From de531f6aa4c7634d81acaffbd96f727130276c32 Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Sun, 28 Jul 2024 23:01:18 +0100 Subject: [PATCH 01/11] add format enforcement --- .editorconfig | 269 ++++++++++++++++++ BatchMap/Program.cs | 20 +- BatchMap/Properties/AssemblyInfo.cs | 2 +- BatchPub/Program.cs | 2 +- BatchPub/Properties/AssemblyInfo.cs | 2 +- BatchPub/frmMain.cs | 38 +-- EOBot/ArgumentsParser.cs | 2 +- EOBot/BotBase.cs | 10 +- EOBot/BotException.cs | 2 +- EOBot/BotFramework.cs | 6 +- EOBot/BotHelper.cs | 2 +- EOBot/ConsoleHelper.cs | 2 +- EOBot/DependencyMaster.cs | 2 +- EOBot/IBot.cs | 2 +- EOBot/Interpreter/BotInterpreter.cs | 2 +- EOBot/Interpreter/BotScriptErrorException.cs | 2 +- EOBot/Interpreter/BotToken.cs | 2 +- EOBot/Interpreter/BotTokenParser.cs | 8 +- EOBot/Interpreter/BotTokenType.cs | 2 +- .../BuiltInIdentifierConfigurator.cs | 5 +- .../Extensions/ProgramStateExtensions.cs | 2 +- .../Extensions/SymbolTableExtensions.cs | 2 +- EOBot/Interpreter/IdentifierBotToken.cs | 2 +- .../Interpreter/States/AssignmentEvaluator.cs | 2 +- EOBot/Interpreter/States/BaseEvaluator.cs | 2 +- EOBot/Interpreter/States/BlockEvaluator.cs | 2 +- EOBot/Interpreter/States/EvalResult.cs | 2 +- .../Interpreter/States/ExpressionEvaluator.cs | 2 +- .../States/ExpressionTailEvaluator.cs | 2 +- EOBot/Interpreter/States/GotoEvaluator.cs | 4 +- EOBot/Interpreter/States/IScriptEvaluator.cs | 2 +- EOBot/Interpreter/States/IfEvaluator.cs | 2 +- EOBot/Interpreter/States/KeywordEvaluator.cs | 2 +- EOBot/Interpreter/States/LabelEvaluator.cs | 2 +- EOBot/Interpreter/States/OperandEvaluator.cs | 2 +- EOBot/Interpreter/States/ProgramState.cs | 4 +- EOBot/Interpreter/States/ScriptEvaluator.cs | 2 +- EOBot/Interpreter/States/VariableEvaluator.cs | 2 +- EOBot/Interpreter/VariableBotToken.cs | 2 +- EOBot/Interpreter/Variables/ArrayVariable.cs | 2 +- EOBot/Interpreter/Variables/AsyncFunction.cs | 2 +- .../Variables/AsyncVoidFunction.cs | 2 +- EOBot/Interpreter/Variables/BoolVariable.cs | 2 +- EOBot/Interpreter/Variables/Function.cs | 2 +- EOBot/Interpreter/Variables/ICallable.cs | 2 +- EOBot/Interpreter/Variables/IIdentifiable.cs | 2 +- EOBot/Interpreter/Variables/IVariable.cs | 2 +- EOBot/Interpreter/Variables/IntVariable.cs | 2 +- EOBot/Interpreter/Variables/ObjectVariable.cs | 2 +- .../Variables/PredefinedIdentifiers.cs | 2 +- EOBot/Interpreter/Variables/StringVariable.cs | 2 +- .../Variables/UndefinedVariable.cs | 2 +- EOBot/Interpreter/Variables/VoidFunction.cs | 2 +- EOBot/NamesList.cs | 2 +- EOBot/Program.cs | 2 +- EOBot/Properties/AssemblyInfo.cs | 2 +- EOBot/ScriptedBot.cs | 2 +- EOBot/ScriptedBotFactory.cs | 2 +- EOBot/TrainerBot.cs | 2 +- EOBot/TrainerBotFactory.cs | 2 +- EOLib.Config.Test/AssemblyInitializer.cs | 2 +- .../ConfigFileLoadActionsTest.cs | 6 +- EOLib.Config.Test/IniReaderTest.cs | 6 +- EOLib.Config.Test/Properties/AssemblyInfo.cs | 2 +- EOLib.Config/ConfigDefaults.cs | 2 +- EOLib.Config/ConfigFileLoadActions.cs | 2 +- EOLib.Config/IConfigFileLoadActions.cs | 2 +- EOLib.Config/IConfigurationRepository.cs | 2 +- EOLib.Config/IniReader.cs | 2 +- EOLib.Config/MalformedConfigException.cs | 2 +- .../GraphicsDeviceTestHelper.cs | 8 +- .../NativeGraphicsLoaderTest.cs | 2 +- .../NativeGraphicsManagerTest.cs | 16 +- EOLib.Graphics.Test/PEFileCollectionTest.cs | 12 +- .../Properties/AssemblyInfo.cs | 2 +- EOLib.Graphics.Test/RectangleExtensionTest.cs | 6 +- EOLib.Graphics/ColorConstants.cs | 2 +- EOLib.Graphics/GFXTypes.cs | 2 +- EOLib.Graphics/IGraphicsDeviceRepository.cs | 2 +- EOLib.Graphics/INativeGraphicsLoader.cs | 2 +- EOLib.Graphics/INativeGraphicsManager.cs | 6 +- EOLib.Graphics/LibraryLoadException.cs | 2 +- EOLib.Graphics/NativeGraphicsLoader.cs | 2 +- EOLib.Graphics/NativeGraphicsManager.cs | 4 +- EOLib.Graphics/PEFileCollection.cs | 8 +- EOLib.IO.Test/EIFRecordExtensionsTest.cs | 6 +- EOLib.IO.Test/Map/MapFilePropertiesTest.cs | 20 +- EOLib.IO.Test/Map/MapFileTest.cs | 14 +- .../Map/MapStringEncoderServiceTest.cs | 12 +- EOLib.IO.Test/Properties/AssemblyInfo.cs | 2 +- EOLib.IO.Test/Pub/BasePubFileTest.cs | 2 +- EOLib.IO.Test/Pub/ECFFileTest.cs | 2 +- EOLib.IO.Test/Pub/ECFRecordTest.cs | 2 +- EOLib.IO.Test/Pub/EIFFileTest.cs | 2 +- EOLib.IO.Test/Pub/EIFRecordTest.cs | 2 +- EOLib.IO.Test/Pub/ENFFileTest.cs | 2 +- EOLib.IO.Test/Pub/ENFRecordTest.cs | 2 +- EOLib.IO.Test/Pub/ESFFileTest.cs | 2 +- EOLib.IO.Test/Pub/ESFRecordTest.cs | 2 +- .../Serializers/PubFileSerializerTest.cs | 2 +- .../Serializers/PubRecordSerializerTest.cs | 2 +- EOLib.IO/Actions/IMapFileLoadActions.cs | 2 +- EOLib.IO/Actions/IPubFileLoadActions.cs | 2 +- EOLib.IO/Actions/MapFileLoadActions.cs | 2 +- EOLib.IO/Caster.cs | 2 +- EOLib.IO/Crc.cs | 4 +- EOLib.IO/Extensions/EIFRecordExtensions.cs | 2 +- EOLib.IO/Extensions/ItemSizeExtensions.cs | 2 +- EOLib.IO/Extensions/PubFileExtensions.cs | 4 +- EOLib.IO/Extensions/TileSpecExtensions.cs | 2 +- EOLib.IO/Map/ChestSpawnMapEntity.cs | 2 +- EOLib.IO/Map/IMapEntity.cs | 2 +- EOLib.IO/Map/IMapFile.cs | 2 +- EOLib.IO/Map/MapFile.cs | 4 +- EOLib.IO/Map/MapFileProperties.cs | 3 +- EOLib.IO/Map/MapPathToIDConverter.cs | 2 +- EOLib.IO/Map/Matrix.cs | 6 +- EOLib.IO/Map/MusicControl.cs | 2 +- EOLib.IO/Map/NPCSpawnMapEntity.cs | 2 +- EOLib.IO/Map/SignMapEntity.cs | 2 +- EOLib.IO/Map/UnknownMapEntity.cs | 2 +- EOLib.IO/Map/WarpMapEntity.cs | 2 +- EOLib.IO/NPCType.cs | 2 +- EOLib.IO/NumericConstants.cs | 4 +- EOLib.IO/Pub/BasePubFile.cs | 2 +- EOLib.IO/Pub/ECFFile.cs | 2 +- EOLib.IO/Pub/ECFRecord.cs | 6 +- EOLib.IO/Pub/EIFFile.cs | 4 +- EOLib.IO/Pub/EIFRecord.cs | 2 +- EOLib.IO/Pub/ENFFile.cs | 2 +- EOLib.IO/Pub/ESFFile.cs | 2 +- EOLib.IO/Pub/IPubFile.cs | 4 +- EOLib.IO/Pub/PubRecord.cs | 6 +- EOLib.IO/Pub/PubRecordProperty.cs | 2 +- EOLib.IO/Pub/RecordData.cs | 2 +- EOLib.IO/Pub/RecordDataAttribute.cs | 2 +- EOLib.IO/PubFileNameConstants.cs | 2 +- EOLib.IO/Repositories/IMapFileRepository.cs | 4 +- EOLib.IO/Repositories/IPubFileProvider.cs | 2 +- EOLib.IO/Repositories/IPubFileRepository.cs | 2 +- EOLib.IO/Services/BasePubLoadService.cs | 4 +- EOLib.IO/Services/ClassFileLoadService.cs | 2 +- EOLib.IO/Services/IMapFileLoadService.cs | 2 +- EOLib.IO/Services/IMapFileSaveService.cs | 2 +- EOLib.IO/Services/IMapStringEncoderService.cs | 2 +- EOLib.IO/Services/INumberEncoderService.cs | 2 +- EOLib.IO/Services/IPubFileSaveService.cs | 2 +- EOLib.IO/Services/IPubLoadService.cs | 2 +- EOLib.IO/Services/ItemFileLoadService.cs | 2 +- EOLib.IO/Services/MapFileLoadService.cs | 6 +- EOLib.IO/Services/MapFileSaveService.cs | 6 +- EOLib.IO/Services/MapStringEncoderService.cs | 2 +- EOLib.IO/Services/NPCFileLoadService.cs | 2 +- EOLib.IO/Services/NumberEncoderService.cs | 2 +- EOLib.IO/Services/PubFileSaveService.cs | 4 +- .../ChestSpawnMapEntitySerializer.cs | 10 +- .../Services/Serializers/IMapDeserializer.cs | 2 +- .../Serializers/IPubFileDeserializer.cs | 2 +- .../Serializers/IPubRecordSerializer.cs | 2 +- .../Services/Serializers/MapFileSerializer.cs | 8 +- .../Serializers/MapPropertiesSerializer.cs | 12 +- .../NPCSpawnMapEntitySerializer.cs | 8 +- .../Services/Serializers/PubFileSerializer.cs | 4 +- .../Serializers/PubRecordSerializer.cs | 2 +- .../Serializers/SignMapEntitySerializer.cs | 8 +- .../Serializers/UnknownMapEntitySerializer.cs | 8 +- .../Serializers/WarpMapEntitySerializer.cs | 10 +- EOLib.IO/Services/SpellFileLoadService.cs | 2 +- .../DataFileLoadActionsTest.cs | 2 +- .../EDFLoaderServiceTest.cs | 6 +- .../LocalizedStringServiceTest.cs | 12 +- .../Properties/AssemblyInfo.cs | 2 +- EOLib.Localization/DataFileConstants.cs | 2 +- EOLib.Localization/DataFileLoadException.cs | 2 +- EOLib.Localization/DataFileRepository.cs | 2 +- EOLib.Localization/EDFFile.cs | 2 +- EOLib.Localization/EOResourceID.cs | 6 +- EOLib.Localization/LocalizedStringFinder.cs | 6 +- .../Services/EDFLoaderService.cs | 4 +- EOLib.Logger/Constants.cs | 2 +- EOLib.Logger/DebugOnlyLogger.cs | 6 +- EOLib.Logger/FileLogger.cs | 2 +- EOLib.Logger/LoggerFactory.cs | 2 +- EOLib.Logger/LoggerProvider.cs | 2 +- EOLib.Logger/NullLogger.cs | 2 +- .../FileTransfer/FileRequestServiceTest.cs | 22 +- EOLib.Test/Properties/AssemblyInfo.cs | 2 +- .../TestHelpers/PacketSendServiceHelpers.cs | 2 +- .../Account/CreateAccountParameterResult.cs | 4 +- .../CreateAccountParameterValidator.cs | 4 +- .../Character/AttackValidationActions.cs | 2 +- .../Domain/Character/CharacterActionState.cs | 2 +- EOLib/Domain/Character/CharacterActions.cs | 2 +- .../Character/CharacterInventoryRepository.cs | 6 +- .../Character/CharacterManagementActions.cs | 2 +- .../Character/CharacterRenderProperties.cs | 8 +- EOLib/Domain/Character/CharacterRepository.cs | 2 +- .../Character/CharacterSessionRepository.cs | 2 +- EOLib/Domain/Character/CharacterStat.cs | 2 +- EOLib/Domain/Character/CharacterStats.cs | 2 +- EOLib/Domain/Character/Emote.cs | 2 +- EOLib/Domain/Character/EquippedItem.cs | 4 +- .../Character/ExperienceTableProvider.cs | 8 +- EOLib/Domain/Character/GhostingRepository.cs | 4 +- EOLib/Domain/Character/IPlayerInfoData.cs | 2 +- EOLib/Domain/Character/InventoryItem.cs | 2 +- EOLib/Domain/Character/PaperdollData.cs | 2 +- EOLib/Domain/Character/PaperdollRepository.cs | 2 +- EOLib/Domain/Character/TrainingActions.cs | 2 +- .../Domain/Character/WalkValidationActions.cs | 5 +- .../Domain/Chat/Builders/ChatPacketBuilder.cs | 6 +- .../Chat/Builders/IChatPacketBuilder.cs | 2 +- EOLib/Domain/Chat/ChatActions.cs | 2 +- EOLib/Domain/Chat/ChatLoggerProvider.cs | 2 +- EOLib/Domain/Chat/ChatProcessor.cs | 20 +- EOLib/Domain/Chat/ChatRepository.cs | 10 +- EOLib/Domain/Chat/ChatTypeCalculator.cs | 4 +- EOLib/Domain/Chat/Commands/IPlayerCommand.cs | 2 +- EOLib/Domain/Chat/Commands/NoWallCommand.cs | 2 +- EOLib/Domain/Chat/Commands/PingCommand.cs | 2 +- EOLib/Domain/Chat/Commands/UsageCommand.cs | 4 +- EOLib/Domain/Chat/LocalCommandHandler.cs | 6 +- EOLib/Domain/Chat/LoggingList.cs | 2 +- .../Domain/Extensions/CharacterExtensions.cs | 2 +- .../CharacterRenderPropertiesExtensions.cs | 6 +- .../Extensions/CharacterStatExtensions.cs | 2 +- EOLib/Domain/Extensions/MapExtensions.cs | 2 +- EOLib/Domain/Extensions/NPCExtensions.cs | 6 +- .../Domain/Extensions/PaperdollExtensions.cs | 2 +- EOLib/Domain/IResetStateAction.cs | 2 +- EOLib/Domain/Interact/Bank/BankActions.cs | 2 +- .../Interact/Bank/BankDataRepository.cs | 2 +- EOLib/Domain/Interact/Barber/BarberActions.cs | 2 +- .../Interact/Barber/BarberDataRepository.cs | 2 +- EOLib/Domain/Interact/Board/BoardActions.cs | 2 +- .../Interact/Board/BoardDataRepository.cs | 2 +- EOLib/Domain/Interact/Board/BoardPostInfo.cs | 2 +- EOLib/Domain/Interact/BookActions.cs | 2 +- .../Domain/Interact/Citizen/CitizenActions.cs | 2 +- .../Interact/Citizen/CitizenDataRepository.cs | 2 +- .../Interact/INPCInteractionNotifier.cs | 2 +- .../Domain/Interact/Jukebox/JukeboxActions.cs | 2 +- .../Interact/Jukebox/JukeboxDataRepository.cs | 2 +- EOLib/Domain/Interact/Law/LawActions.cs | 2 +- .../Interact/Law/LawSessionRepository.cs | 2 +- EOLib/Domain/Interact/MapNPCActions.cs | 2 +- EOLib/Domain/Interact/PaperdollActions.cs | 2 +- EOLib/Domain/Interact/Priest/PriestActions.cs | 2 +- .../Priest/PriestSessionRepository.cs | 2 +- .../Interact/Quest/IStatusLabelNotifier.cs | 2 +- EOLib/Domain/Interact/Quest/QuestActions.cs | 2 +- .../Interact/Quest/QuestDataRepository.cs | 2 +- .../Domain/Interact/Quest/QuestDialogData.cs | 2 +- .../Interact/Quest/QuestProgressData.cs | 2 +- EOLib/Domain/Interact/Shop/ShopActions.cs | 2 +- .../Interact/Shop/ShopCraftIngredient.cs | 2 +- EOLib/Domain/Interact/Shop/ShopCraftItem.cs | 2 +- .../Interact/Shop/ShopDataRepository.cs | 4 +- EOLib/Domain/Interact/Shop/ShopItem.cs | 2 +- EOLib/Domain/Interact/Skill/Skill.cs | 2 +- .../Interact/Skill/SkillDataRepository.cs | 2 +- .../Interact/Skill/SkillmasterActions.cs | 2 +- .../Domain/Interact/Skill/SkillmasterReply.cs | 2 +- EOLib/Domain/Interact/TileSpecMapEntity.cs | 2 +- EOLib/Domain/Item/ItemActions.cs | 2 +- EOLib/Domain/Item/ItemDropResult.cs | 2 +- EOLib/Domain/Item/ItemDropValidator.cs | 2 +- EOLib/Domain/Item/ItemEquipValidator.cs | 2 +- EOLib/Domain/Item/ItemPickupResult.cs | 2 +- EOLib/Domain/Item/ItemPickupValidator.cs | 6 +- EOLib/Domain/Item/ItemStringService.cs | 6 +- .../Login/CharacterSelectorRepository.cs | 2 +- EOLib/Domain/Login/NewsRepository.cs | 6 +- EOLib/Domain/Login/PlayerInfoRepository.cs | 2 +- EOLib/Domain/Map/ChestActions.cs | 2 +- EOLib/Domain/Map/ChestDataRepository.cs | 2 +- EOLib/Domain/Map/ChestItem.cs | 2 +- EOLib/Domain/Map/CurrentMapProvider.cs | 2 +- EOLib/Domain/Map/CurrentMapStateRepository.cs | 4 +- EOLib/Domain/Map/IMapCellState.cs | 6 +- EOLib/Domain/Map/LockerActions.cs | 2 +- EOLib/Domain/Map/LockerDataRepository.cs | 2 +- EOLib/Domain/Map/MapActions.cs | 2 +- EOLib/Domain/Map/MapCellState.cs | 2 +- EOLib/Domain/Map/MapCellStateProvider.cs | 18 +- EOLib/Domain/Map/MapCoordinate.cs | 4 +- .../Domain/Map/MapEntityCollectionHashSet.cs | 2 +- EOLib/Domain/Map/Sign.cs | 2 +- .../Map/UnknownEntitiesRequestActions.cs | 2 +- EOLib/Domain/Map/UnlockChestValidator.cs | 6 +- EOLib/Domain/Map/UnlockDoorValidator.cs | 2 +- EOLib/Domain/Map/Warp.cs | 2 +- EOLib/Domain/Map/WarpState.cs | 2 +- EOLib/Domain/NPC/NPCActionState.cs | 2 +- EOLib/Domain/NPC/NPCFrame.cs | 2 +- EOLib/Domain/Notifiers/IArenaNotifier.cs | 2 +- EOLib/Domain/Notifiers/IChatEventNotifier.cs | 2 +- EOLib/Domain/Notifiers/IChestEventNotifier.cs | 2 +- EOLib/Domain/Notifiers/IEffectNotifier.cs | 2 +- EOLib/Domain/Notifiers/IEmoteNotifier.cs | 2 +- .../Domain/Notifiers/ILockerEventNotifier.cs | 2 +- .../Notifiers/IMainCharacterEventNotifier.cs | 2 +- EOLib/Domain/Notifiers/IMapChangedNotifier.cs | 2 +- EOLib/Domain/Notifiers/INPCActionNotifier.cs | 2 +- .../IOtherCharacterAnimationNotifier.cs | 2 +- .../Notifiers/IOtherCharacterEventNotifier.cs | 2 +- EOLib/Domain/Notifiers/IPartyEventNotifier.cs | 2 +- .../Domain/Notifiers/IServerRebootNotifier.cs | 2 +- EOLib/Domain/Notifiers/ISoundNotifier.cs | 2 +- EOLib/Domain/Notifiers/ITradeEventNotifier.cs | 2 +- .../Notifiers/IUserInterfaceNotifier.cs | 2 +- EOLib/Domain/Online/OnlinePlayerActions.cs | 2 +- EOLib/Domain/Online/OnlinePlayerInfo.cs | 2 +- EOLib/Domain/Online/OnlinePlayerRepository.cs | 4 +- EOLib/Domain/Party/PartyActions.cs | 2 +- EOLib/Domain/Party/PartyMember.cs | 2 +- EOLib/Domain/Party/PartyRepository.cs | 4 +- EOLib/Domain/Protocol/PingTimeRepository.cs | 2 +- EOLib/Domain/Report/ReportActions.cs | 2 +- EOLib/Domain/ResetStateAction.cs | 2 +- EOLib/Domain/Spells/GroupSpellTarget.cs | 2 +- EOLib/Domain/Spells/ISpellTargetable.cs | 2 +- .../Spells/SpellCastValidationActions.cs | 2 +- .../Spells/SpellCastValidationResult.cs | 2 +- EOLib/Domain/Trade/TradeActions.cs | 4 +- EOLib/Domain/Trade/TradeOffer.cs | 2 +- EOLib/Domain/Trade/TradeRepository.cs | 2 +- EOLib/EODirection.cs | 2 +- EOLib/Extensions/ChatIconExtensions.cs | 2 +- EOLib/Extensions/OnlineIconExtensions.cs | 2 +- EOLib/FixedTimeStepRepository.cs | 2 +- EOLib/HDSerialNumberService.cs | 12 +- EOLib/IHDSerialNumberService.cs | 2 +- EOLib/IResettable.cs | 2 +- EOLib/Net/Communication/AsyncSocket.cs | 10 +- EOLib/Net/Communication/IAsyncSocket.cs | 2 +- EOLib/Net/Communication/INetworkClient.cs | 4 +- .../Communication/INetworkClientDisposer.cs | 2 +- .../Communication/INetworkClientFactory.cs | 2 +- .../Communication/INetworkClientRepository.cs | 4 +- EOLib/Net/Communication/IPacketQueue.cs | 2 +- .../Communication/IPacketQueueRepository.cs | 2 +- EOLib/Net/Communication/IPacketSendService.cs | 2 +- .../Communication/ISafeNetworkOperation.cs | 2 +- EOLib/Net/Communication/NetworkClient.cs | 4 +- .../Net/Communication/NetworkClientFactory.cs | 2 +- EOLib/Net/Communication/PacketQueue.cs | 2 +- EOLib/Net/Communication/PacketSendService.cs | 4 +- .../SafeAsyncNetworkOperation.cs | 6 +- .../SafeBlockingNetworkOperation.cs | 6 +- .../Communication/SafeNetworkOperationBase.cs | 6 +- .../SafeNetworkOperationFactory.cs | 8 +- .../Connection/BackgroundReceiveActions.cs | 2 +- .../Connection/IBackgroundReceiveActions.cs | 2 +- .../IBackgroundReceiveTaskRepository.cs | 2 +- .../Connection/INetworkConnectionActions.cs | 6 +- .../Connection/NetworkConnectionActions.cs | 2 +- EOLib/Net/EmptyPacketReceivedException.cs | 2 +- EOLib/Net/FileTransfer/FileRequestService.cs | 2 +- .../LoginFileChecksumRepository.cs | 2 +- .../Net/Handlers/DefaultAsyncPacketHandler.cs | 4 +- EOLib/Net/Handlers/FamilyActionPair.cs | 2 +- EOLib/Net/Handlers/IPacketHandler.cs | 2 +- EOLib/Net/Handlers/InGameOnlyPacketHandler.cs | 2 +- EOLib/Net/Handlers/OutOfBandPacketHandler.cs | 2 +- EOLib/Net/Handlers/PacketHandlerFinder.cs | 8 +- EOLib/Net/Handlers/PacketHandlerProvider.cs | 6 +- .../Net/Handlers/PacketHandlingTypeFinder.cs | 6 +- EOLib/Net/NoDataSentException.cs | 2 +- EOLib/Net/PacketProcessing/HashService.cs | 2 +- .../PacketEncoderRepository.cs | 2 +- .../PacketProcessing/PacketEncoderService.cs | 2 +- EOLib/Net/PacketProcessing/PacketFactory.cs | 2 +- .../PacketProcessing/PacketFactoryFactory.cs | 2 +- .../PacketProcessing/PacketProcessActions.cs | 10 +- .../PacketProcessing/SequenceRepository.cs | 4 +- .../AdminInteract/AdminInteractAgree.cs | 2 +- .../AdminInteract/AdminInteractList.cs | 2 +- .../AdminInteract/AdminInteractRemove.cs | 2 +- .../AdminInteract/AdminInteractReply.cs | 2 +- .../AdminInteract/AdminInteractTell.cs | 6 +- .../Arena/ArenaAcceptHandler.cs | 2 +- .../PacketHandlers/Arena/ArenaDropHandler.cs | 4 +- .../PacketHandlers/Arena/ArenaSpecHandler.cs | 4 +- EOLib/PacketHandlers/Arena/ArenaUseHandler.cs | 4 +- .../Attack/AttackPlayerHandler.cs | 2 +- .../Avatar/AvatarAdminHandler.cs | 2 +- .../Avatar/AvatarAgreeHandler.cs | 2 +- .../Avatar/AvatarChangeHandler.cs | 2 +- .../Avatar/AvatarRemoveHandler.cs | 2 +- .../Avatar/AvatarReplyHandler.cs | 4 +- EOLib/PacketHandlers/Bank/BankOpenHandler.cs | 2 +- EOLib/PacketHandlers/Bank/BankReplyHandler.cs | 2 +- .../Barber/BarberAgreeHandler.cs | 2 +- .../Barber/BarberOpenHandler.cs | 2 +- .../PacketHandlers/Board/BoardOpenHandler.cs | 2 +- .../Board/BoardPlayerHandler.cs | 2 +- EOLib/PacketHandlers/Book/BookReplyHandler.cs | 2 +- .../PacketHandlers/Cast/CastAcceptHandler.cs | 2 +- EOLib/PacketHandlers/Cast/CastReplyHandler.cs | 2 +- EOLib/PacketHandlers/Cast/CastSpecHandler.cs | 2 +- .../PacketHandlers/Chair/ChairCloseHandler.cs | 2 +- .../Chair/ChairPlayerHandler.cs | 2 +- .../Chair/ChairRemoveHandler.cs | 2 +- .../PacketHandlers/Chair/ChairReplyHandler.cs | 2 +- EOLib/PacketHandlers/Chat/GroupChatHandler.cs | 2 +- EOLib/PacketHandlers/Chat/MuteHandler.cs | 2 +- .../Chat/PlayerChatByIDHandler.cs | 2 +- .../Chat/PlayerChatByNameBase.cs | 2 +- .../Chat/PrivateMessageTargetNotFound.cs | 2 +- .../PacketHandlers/Chat/TalkServerHandler.cs | 2 +- .../PacketHandlers/Chest/ChestAgreeHandler.cs | 2 +- .../PacketHandlers/Chest/ChestCloseHandler.cs | 2 +- EOLib/PacketHandlers/Chest/ChestGetHandler.cs | 2 +- .../Chest/ChestItemUpdateHandler.cs | 2 +- .../PacketHandlers/Chest/ChestOpenHandler.cs | 2 +- .../PacketHandlers/Chest/ChestReplyHandler.cs | 2 +- .../Citizen/CitizenAcceptHandler.cs | 2 +- .../Citizen/CitizenOpenHandler.cs | 2 +- .../Citizen/CitizenRemoveHandler.cs | 2 +- .../Citizen/CitizenReplyHandler.cs | 2 +- .../Citizen/CitizenRequestHandler.cs | 2 +- .../Commands/FindCommandHandlerBase.cs | 2 +- .../FindCommandPlayerDifferentMapHandler.cs | 2 +- .../FindCommandPlayerNotFoundHandler.cs | 2 +- .../FindCommandPlayerSameMapHandler.cs | 2 +- .../Commands/PingResponseHandler.cs | 2 +- .../Connection/ConnectionPlayerHandler.cs | 2 +- EOLib/PacketHandlers/Door/DoorOpenHandler.cs | 2 +- .../Effects/EffectAgreeHandler.cs | 2 +- .../Effects/EffectPotionHandler.cs | 2 +- .../Effects/MapDebuffHandler.cs | 2 +- .../Effects/MapHpDrainHandler.cs | 2 +- .../PacketHandlers/Effects/MapQuakeHandler.cs | 2 +- .../Effects/PlayerSpikeDamageHandler.cs | 2 +- .../Effects/TimedSpikeEffectHandler.cs | 2 +- .../Emote/EmotePlayerHandler.cs | 2 +- .../PacketHandlers/Face/FacePlayerHandler.cs | 2 +- .../Init/FriendIgnoreListHandler.cs | 2 +- .../PacketHandlers/Init/IInitPacketHandler.cs | 2 +- .../Init/InGameInitPacketHandler.cs | 2 +- .../PacketHandlers/Init/MapMutationHandler.cs | 2 +- .../Init/MapWarpFileDownloadHandler.cs | 2 +- .../Init/OnlinePlayerListHandler.cs | 2 +- .../PacketHandlers/Items/ItemAcceptHandler.cs | 2 +- EOLib/PacketHandlers/Items/ItemAddHandler.cs | 2 +- .../PacketHandlers/Items/ItemAgreeHandler.cs | 2 +- EOLib/PacketHandlers/Items/ItemDropHandler.cs | 2 +- EOLib/PacketHandlers/Items/ItemGetHandler.cs | 2 +- EOLib/PacketHandlers/Items/ItemJunkHandler.cs | 2 +- EOLib/PacketHandlers/Items/ItemKickHandler.cs | 2 +- .../PacketHandlers/Items/ItemObtainHandler.cs | 2 +- .../PacketHandlers/Items/ItemRemoveHandler.cs | 2 +- .../PacketHandlers/Items/ItemReplyHandler.cs | 2 +- .../Items/QuestItemChangeHandler.cs | 2 +- .../Jukebox/JukeboxAgreeHandler.cs | 2 +- .../Jukebox/JukeboxMessageHandler.cs | 2 +- .../Jukebox/JukeboxOpenHandler.cs | 2 +- .../Jukebox/JukeboxPlayerHandler.cs | 2 +- .../Jukebox/JukeboxReplyHandler.cs | 2 +- .../Jukebox/JukeboxUseHandler.cs | 2 +- .../PacketHandlers/Locker/LockerBuyHandler.cs | 2 +- .../PacketHandlers/Locker/LockerGetHandler.cs | 2 +- .../Locker/LockerModifyHandler.cs | 2 +- .../Locker/LockerOpenHandler.cs | 2 +- .../Locker/LockerReplyHandler.cs | 2 +- .../Locker/LockerSpecHandler.cs | 2 +- .../MapInfo/MapInfoReplyHandler.cs | 2 +- .../Marriage/MarriageOpenHandler.cs | 2 +- .../Marriage/MarriageReplyHandler.cs | 2 +- .../Message/MessageAcceptHandler.cs | 2 +- .../Message/MessageCloseHandler.cs | 4 +- .../Music/MusicPlayerHandler.cs | 2 +- EOLib/PacketHandlers/NPC/NPCAcceptHandler.cs | 2 +- EOLib/PacketHandlers/NPC/NPCAgreeHandler.cs | 2 +- EOLib/PacketHandlers/NPC/NPCDeathHandler.cs | 6 +- EOLib/PacketHandlers/NPC/NPCDialogHandler.cs | 2 +- EOLib/PacketHandlers/NPC/NPCJunkHandler.cs | 2 +- EOLib/PacketHandlers/NPC/NPCPlayerHandler.cs | 2 +- EOLib/PacketHandlers/NPC/NPCReplyHandler.cs | 2 +- EOLib/PacketHandlers/NPC/NPCSpecHandler.cs | 5 +- .../NPC/NPCTakeDamageHandler.cs | 2 +- .../Paperdoll/ItemEquipHandler.cs | 2 +- .../Paperdoll/PaperdollAgreeHandler.cs | 2 +- .../Paperdoll/PaperdollRemoveHandler.cs | 2 +- .../Paperdoll/PaperdollReplyHandler.cs | 2 +- EOLib/PacketHandlers/Party/PartyAddHandler.cs | 2 +- .../PacketHandlers/Party/PartyAgreeHandler.cs | 2 +- .../PacketHandlers/Party/PartyCloseHandler.cs | 2 +- .../Party/PartyCreateHandler.cs | 2 +- .../PacketHandlers/Party/PartyListHandler.cs | 2 +- .../Party/PartyRemoveHandler.cs | 2 +- .../Party/PartyRequestHandler.cs | 2 +- .../Players/PlayersAgreeHandler.cs | 2 +- .../Priest/PriestOpenHandler.cs | 2 +- .../Priest/PriestReplyHandler.cs | 2 +- .../Priest/PriestRequestHandler.cs | 2 +- .../Quest/QuestDialogHandler.cs | 2 +- .../PacketHandlers/Quest/QuestListHandler.cs | 16 +- .../Quest/QuestStatusMessageHandler.cs | 2 +- .../Recover/RecoverAgreeHandler.cs | 2 +- .../Recover/RecoverListHandler.cs | 2 +- .../Recover/RecoverPlayerHandler.cs | 2 +- .../Recover/RecoverReplyHandler.cs | 2 +- .../Refresh/RefreshReplyHandler.cs | 4 +- EOLib/PacketHandlers/Shop/ShopCraftHandler.cs | 2 +- EOLib/PacketHandlers/Shop/ShopOpenHandler.cs | 2 +- EOLib/PacketHandlers/Shop/ShopTradeHandler.cs | 2 +- .../Sit/PlayerSitHandlerBase.cs | 2 +- .../Sit/PlayerStandHandlerBase.cs | 2 +- EOLib/PacketHandlers/Sit/SitCloseHandler.cs | 2 +- EOLib/PacketHandlers/Sit/SitPlayerHandler.cs | 2 +- EOLib/PacketHandlers/Sit/SitRemoveHandler.cs | 2 +- EOLib/PacketHandlers/Sit/SitReplyHandler.cs | 2 +- .../Spell/SpellRequestHandler.cs | 2 +- .../Spell/SpellTargetGroupHandler.cs | 12 +- .../Spell/SpellTargetOtherHandler.cs | 2 +- .../Spell/SpellTargetSelfHandler.cs | 2 +- .../StatSkill/StatskillAcceptHandler.cs | 2 +- .../StatSkill/StatskillJunkHandler.cs | 2 +- .../StatSkill/StatskillOpenHandler.cs | 2 +- .../StatSkill/StatskillPlayerHandler.cs | 2 +- .../StatSkill/StatskillRemoveHandler.cs | 2 +- .../StatSkill/StatskillReplyHandler.cs | 2 +- .../StatSkill/StatskillTakeHandler.cs | 2 +- .../PacketHandlers/Trade/TradeAdminHandler.cs | 2 +- .../PacketHandlers/Trade/TradeAgreeHandler.cs | 2 +- .../PacketHandlers/Trade/TradeCloseHandler.cs | 2 +- .../Trade/TradeOfferUpdateHandler.cs | 2 +- .../PacketHandlers/Trade/TradeOpenHandler.cs | 2 +- .../PacketHandlers/Trade/TradeReplyHandler.cs | 2 +- .../Trade/TradeRequestHandler.cs | 2 +- .../PacketHandlers/Trade/TradeSpecHandler.cs | 2 +- EOLib/PacketHandlers/Trade/TradeUseHandler.cs | 2 +- .../PacketHandlers/Walk/WalkPlayerHandler.cs | 2 +- EOLib/PacketHandlers/Walk/WalkReplyHandler.cs | 2 +- EOLib/PacketHandlers/Warp/WarpAgreeHandler.cs | 2 +- .../PacketHandlers/Warp/WarpRequestHandler.cs | 2 +- EOLib/Win32.cs | 2 +- EOLib/misc.cs | 2 +- EndlessClient/Audio/AudioActions.cs | 2 +- EndlessClient/Audio/MfxPlayer.cs | 2 +- EndlessClient/Audio/SfxPlayer.cs | 2 +- EndlessClient/Audio/SoundEffectID.cs | 2 +- EndlessClient/Audio/WAVFileValidator.cs | 2 +- EndlessClient/Content/ContentProvider.cs | 2 +- .../ControlSets/BackButtonControlSet.cs | 6 +- EndlessClient/ControlSets/BaseControlSet.cs | 10 +- .../ControlSets/ControlSetFactory.cs | 2 +- .../ControlSets/CreateAccountControlSet.cs | 2 +- EndlessClient/ControlSets/EmptyControlSet.cs | 8 +- .../ControlSets/GameControlIdentifier.cs | 2 +- EndlessClient/ControlSets/IControlSet.cs | 8 +- .../ControlSets/IControlSetFactory.cs | 2 +- .../ControlSets/IControlSetRepository.cs | 2 +- .../ControlSets/IHudControlProvider.cs | 4 +- EndlessClient/ControlSets/InGameControlSet.cs | 2 +- .../ControlSets/InitialControlSet.cs | 2 +- .../ControlSets/IntermediateControlSet.cs | 4 +- .../ControlSets/LoggedInControlSet.cs | 2 +- .../ControlSets/LoginPromptControlSet.cs | 2 +- .../ControlSets/ViewCreditsControlSet.cs | 2 +- .../Controllers/ArrowKeyController.cs | 2 +- EndlessClient/Controllers/BardController.cs | 2 +- EndlessClient/Controllers/ChatController.cs | 2 +- .../Controllers/ControlKeyController.cs | 2 +- .../Controllers/FunctionKeyController.cs | 2 +- .../Controllers/InventoryController.cs | 4 +- EndlessClient/Controllers/LoginController.cs | 2 +- .../Controllers/MainButtonController.cs | 2 +- .../Controllers/MapInteractionController.cs | 2 +- .../Controllers/NPCInteractionController.cs | 4 +- EndlessClient/Controllers/NumPadController.cs | 2 +- .../Controllers/TrainingController.cs | 2 +- .../Dialogs/Actions/CharacterDialogActions.cs | 2 +- .../Actions/ErrorDialogDisplayAction.cs | 2 +- .../Dialogs/Actions/FirstTimePlayerActions.cs | 2 +- EndlessClient/Dialogs/Actions/HelpActions.cs | 2 +- .../Actions/IAccountDialogDisplayActions.cs | 6 +- .../Actions/ICharacterDialogActions.cs | 2 +- .../Actions/IErrorDialogDisplayAction.cs | 2 +- .../Dialogs/Actions/InGameDialogActions.cs | 6 +- .../Dialogs/Actions/NpcInteractionActions.cs | 2 +- .../Dialogs/Actions/PartyDialogActions.cs | 2 +- .../Dialogs/Actions/TradeDialogActions.cs | 2 +- .../Dialogs/ActiveDialogRepository.cs | 14 +- EndlessClient/Dialogs/BankAccountDialog.cs | 4 +- EndlessClient/Dialogs/BarberDialog.cs | 20 +- EndlessClient/Dialogs/BardDialog.cs | 2 +- EndlessClient/Dialogs/BaseEODialog.cs | 4 +- EndlessClient/Dialogs/BoardDialog.cs | 2 +- EndlessClient/Dialogs/BookDialog.cs | 2 +- EndlessClient/Dialogs/ChangePasswordDialog.cs | 2 +- EndlessClient/Dialogs/ChestDialog.cs | 2 +- .../Dialogs/CreateCharacterDialog.cs | 8 +- EndlessClient/Dialogs/EODialogButton.cs | 2 +- EndlessClient/Dialogs/EOMessageBox.cs | 2 +- .../Extensions/EquipLocationExtensions.cs | 2 +- .../Factories/BankAccountDialogFactory.cs | 2 +- .../Dialogs/Factories/BarberDialogFactory.cs | 10 +- .../Dialogs/Factories/BardDialogFactory.cs | 2 +- .../Dialogs/Factories/BoardDialogFactory.cs | 2 +- .../Dialogs/Factories/BookDialogFactory.cs | 4 +- .../Dialogs/Factories/ChestDialogFactory.cs | 2 +- .../CreateAccountWarningDialogFactory.cs | 2 +- .../FriendIgnoreListDialogFactory.cs | 2 +- .../Dialogs/Factories/HelpDialogFactory.cs | 2 +- .../Factories/IChangePasswordDialogFactory.cs | 2 +- .../Dialogs/Factories/IEOMessageBoxFactory.cs | 4 +- .../Factories/InnkeeperDialogFactory.cs | 2 +- .../Dialogs/Factories/JukeboxDialogFactory.cs | 2 +- .../Dialogs/Factories/LawDialogFactory.cs | 2 +- .../Dialogs/Factories/LockerDialogFactory.cs | 2 +- .../Factories/PaperdollDialogFactory.cs | 2 +- .../Dialogs/Factories/QuestDialogFactory.cs | 2 +- .../Factories/QuestStatusDialogFactory.cs | 2 +- .../Factories/ScrollingListDialogFactory.cs | 2 +- .../Factories/SessionExpDialogFactory.cs | 2 +- .../Dialogs/Factories/ShopDialogFactory.cs | 2 +- .../Factories/SkillmasterDialogFactory.cs | 2 +- .../Factories/TextInputDialogFactory.cs | 2 +- .../Factories/TextInputMultiDialogFactory.cs | 2 +- .../Dialogs/Factories/TradeDialogFactory.cs | 2 +- .../Dialogs/FriendIgnoreListDialog.cs | 2 +- EndlessClient/Dialogs/GameLoadingDialog.cs | 8 +- EndlessClient/Dialogs/InnkeeperDialog.cs | 2 +- EndlessClient/Dialogs/ItemTransferDialog.cs | 4 +- EndlessClient/Dialogs/JukeboxDialog.cs | 2 +- EndlessClient/Dialogs/LawDialog.cs | 2 +- EndlessClient/Dialogs/ListDialogItem.cs | 2 +- EndlessClient/Dialogs/LockerDialog.cs | 2 +- EndlessClient/Dialogs/PaperdollDialog.cs | 2 +- EndlessClient/Dialogs/PaperdollDialogItem.cs | 2 +- EndlessClient/Dialogs/PlayerInfoDialog.cs | 2 +- EndlessClient/Dialogs/ProgressDialog.cs | 8 +- EndlessClient/Dialogs/QuestDialog.cs | 2 +- EndlessClient/Dialogs/QuestStatusDialog.cs | 2 +- .../Dialogs/QuestStatusListDialogItem.cs | 18 +- EndlessClient/Dialogs/ScrollingListDialog.cs | 50 ++-- .../Dialogs/ScrollingMessageDialog.cs | 8 +- .../Dialogs/Services/EODialogButtonService.cs | 14 +- .../Dialogs/Services/EODialogIconService.cs | 2 +- EndlessClient/Dialogs/SessionExpDialog.cs | 12 +- EndlessClient/Dialogs/ShopDialog.cs | 4 +- EndlessClient/Dialogs/SkillmasterDialog.cs | 14 +- EndlessClient/Dialogs/TextInputDialog.cs | 4 +- EndlessClient/Dialogs/TextMultiInputDialog.cs | 4 +- EndlessClient/Dialogs/TradeDialog.cs | 4 +- .../GameExecution/DebugGameRunner.cs | 2 +- EndlessClient/GameExecution/EndlessGame.cs | 2 +- EndlessClient/GameExecution/GameRunnerBase.cs | 6 +- .../GameExecution/GameStateActions.cs | 18 +- EndlessClient/GameExecution/IEndlessGame.cs | 6 +- .../GameExecution/IEndlessGameProvider.cs | 2 +- EndlessClient/GameExecution/IGameRunner.cs | 2 +- .../GameExecution/IGameStateActions.cs | 2 +- .../GameExecution/IGameStateRepository.cs | 2 +- .../GameExecution/ReleaseGameRunner.cs | 2 +- EndlessClient/HUD/AStarPathFinder.cs | 4 +- EndlessClient/HUD/Chat/ChatModeCalculator.cs | 2 +- .../HUD/Chat/ChatNotificationActions.cs | 10 +- EndlessClient/HUD/Chat/ChatPanelTab.cs | 2 +- EndlessClient/HUD/Chat/IChatModeCalculator.cs | 2 +- EndlessClient/HUD/Chat/IChatTextBoxActions.cs | 2 +- .../HUD/Chat/ServerMessageHandler.cs | 2 +- .../HUD/Controls/DragCompletedEventArgs.cs | 2 +- .../HUD/Controls/DraggablePanelItem.cs | 2 +- .../HUD/Controls/HudBackgroundFrame.cs | 2 +- .../HUD/Controls/HudControlIdentifier.cs | 4 +- .../HUD/Controls/HudControlsFactory.cs | 8 +- .../HUD/Controls/IDraggableItemContainer.cs | 2 +- .../HUD/Controls/IHudControlsFactory.cs | 6 +- .../Controls/PeriodicStatUpdaterComponent.cs | 8 +- EndlessClient/HUD/HudStateActions.cs | 6 +- EndlessClient/HUD/IHudButtonController.cs | 2 +- EndlessClient/HUD/IHudStateActions.cs | 4 +- EndlessClient/HUD/IStatusLabelSetter.cs | 2 +- .../HUD/IStatusLabelTextRepository.cs | 6 +- .../HUD/Inventory/InventoryPanelItem.cs | 4 +- .../HUD/Inventory/InventoryService.cs | 2 +- .../HUD/Inventory/InventorySlotRepository.cs | 2 +- .../HUD/Inventory/InventorySpaceValidator.cs | 2 +- EndlessClient/HUD/ItemNameColorService.cs | 2 +- EndlessClient/HUD/Panels/ChatPanel.cs | 8 +- EndlessClient/HUD/Panels/DraggableHudPanel.cs | 2 +- EndlessClient/HUD/Panels/HudPanelFactory.cs | 18 +- EndlessClient/HUD/Panels/IHudPanel.cs | 2 +- EndlessClient/HUD/Panels/IHudPanelFactory.cs | 2 +- EndlessClient/HUD/Panels/InventoryPanel.cs | 2 +- EndlessClient/HUD/Panels/NewsPanel.cs | 10 +- EndlessClient/HUD/Panels/OnlineListPanel.cs | 4 +- EndlessClient/HUD/Panels/StatsPanel.cs | 16 +- EndlessClient/HUD/Party/PartyPanelMember.cs | 4 +- EndlessClient/HUD/Spells/SpellPanelItem.cs | 4 +- .../HUD/Spells/SpellSelectActions.cs | 2 +- .../HUD/Spells/SpellSlotDataRepository.cs | 2 +- EndlessClient/HUD/StatusBars/HPStatusBar.cs | 2 +- EndlessClient/HUD/StatusBars/SPStatusBar.cs | 2 +- EndlessClient/HUD/StatusBars/StatusBarBase.cs | 2 +- EndlessClient/HUD/StatusBars/TNLStatusBar.cs | 10 +- EndlessClient/HUD/StatusBars/TPStatusBar.cs | 6 +- EndlessClient/HUD/StatusLabelSetter.cs | 2 +- EndlessClient/HUD/UserInterfaceActions.cs | 2 +- .../Initialization/ConfigInitializer.cs | 2 +- .../EndlessClientInitializer.cs | 2 +- .../Initialization/GraphicsInitializer.cs | 2 +- .../Initialization/IGameInitializer.cs | 2 +- .../Initialization/LocalizationInitializer.cs | 2 +- EndlessClient/Input/ArrowKeyHandler.cs | 2 +- EndlessClient/Input/ControlKeyHandler.cs | 2 +- .../Input/CurrentUserInputTracker.cs | 2 +- EndlessClient/Input/FunctionKeyHandler.cs | 2 +- EndlessClient/Input/IUserInputRepository.cs | 2 +- .../Input/IUserInputTimeRepository.cs | 6 +- .../Input/KeyboardStateExtensions.cs | 2 +- EndlessClient/Input/NumPadHandler.cs | 2 +- EndlessClient/Input/PanelShortcutHandler.cs | 4 +- .../Input/PreviousUserInputTracker.cs | 2 +- EndlessClient/Input/UnwalkableTileActions.cs | 2 +- .../Input/UnwalkableTileActionsHandler.cs | 2 +- EndlessClient/Input/UserInputHandler.cs | 2 +- .../Input/UserInputHandlerFactory.cs | 2 +- .../Network/PacketHandlerGameComponent.cs | 4 +- .../Network/UnknownEntitiesRequester.cs | 4 +- EndlessClient/Program.cs | 6 +- EndlessClient/Properties/AssemblyInfo.cs | 2 +- .../Character/CharacterAnimationActions.cs | 6 +- .../Rendering/Character/CharacterAnimator.cs | 6 +- .../Rendering/Character/CharacterRenderer.cs | 10 +- .../Rendering/Character/CharacterTextures.cs | 4 +- .../Rendering/Character/ICharacterRenderer.cs | 2 +- .../Character/ICharacterRendererRepository.cs | 6 +- .../Rendering/Character/ICharacterTextures.cs | 2 +- .../Character/PeriodicEmoteHandler.cs | 2 +- .../CharacterProperties/ArmorRenderer.cs | 6 +- .../BaseCharacterPropertyRenderer.cs | 2 +- .../CharacterProperties/BootsRenderer.cs | 4 +- .../CharacterPropertyRendererBuilder.cs | 8 +- .../CharacterProperties/EmoteRenderer.cs | 2 +- .../CharacterProperties/FaceRenderer.cs | 2 +- .../HairRenderLocationCalculator.cs | 6 +- .../CharacterProperties/HairRenderer.cs | 2 +- .../CharacterProperties/HatRenderer.cs | 2 +- .../ICharacterPropertyRenderer.cs | 2 +- .../ICharacterPropertyRendererBuilder.cs | 2 +- .../CharacterProperties/ShieldRenderer.cs | 2 +- .../SkinRenderLocationCalculator.cs | 4 +- .../CharacterProperties/SkinRenderer.cs | 2 +- .../CharacterProperties/WeaponRenderer.cs | 2 +- .../WeaponSlashRenderer.cs | 2 +- EndlessClient/Rendering/Chat/ChatBubble.cs | 8 +- .../Rendering/Chat/ChatBubbleFactory.cs | 2 +- .../Rendering/Chat/ChatBubbleTexture.cs | 2 +- .../Chat/ChatBubbleTextureProvider.cs | 6 +- .../Rendering/Chat/ChatColorExtensions.cs | 6 +- .../Rendering/Chat/ChatRenderable.cs | 8 +- .../Rendering/Chat/ChatRenderableGenerator.cs | 16 +- .../Chat/IChatRenderableGenerator.cs | 6 +- .../Rendering/ClientWindowSizeRepository.cs | 2 +- .../Rendering/ContextMenuRenderer.cs | 4 +- .../Rendering/ContextMenuRepository.cs | 4 +- .../Rendering/DispatcherGameComponent.cs | 4 +- .../Rendering/Effects/EffectAnimationType.cs | 2 +- .../Rendering/Effects/EffectLayer.cs | 2 +- .../Rendering/Effects/EffectRenderer.cs | 2 +- .../Effects/EffectRendererFactory.cs | 2 +- .../Rendering/Effects/EffectSpriteInfo.cs | 16 +- .../Rendering/Effects/EffectSpriteManager.cs | 4 +- .../Rendering/Effects/HardCodedEffect.cs | 2 +- .../Rendering/Effects/IEffectSpriteInfo.cs | 2 +- .../Effects/PositionOffsetEffectMetadata.cs | 2 +- .../Effects/RandomFlickeringEffectMetadata.cs | 2 +- .../Effects/VerticalSlidingEffectMetadata.cs | 2 +- .../Factories/CharacterRendererFactory.cs | 2 +- .../Factories/ContextMenuRendererFactory.cs | 6 +- .../Factories/HealthBarRendererFactory.cs | 2 +- .../Factories/ICharacterRendererFactory.cs | 2 +- .../Factories/IMapRendererFactory.cs | 2 +- .../Factories/IRenderTargetFactory.cs | 2 +- .../Rendering/Factories/MapRendererFactory.cs | 2 +- .../Factories/MouseCursorRendererFactory.cs | 2 +- .../Factories/RenderTargetFactory.cs | 2 +- .../Rendering/GridDrawCoordinateCalculator.cs | 4 +- EndlessClient/Rendering/HealthBarRenderer.cs | 10 +- EndlessClient/Rendering/IMapActor.cs | 2 +- .../Rendering/Map/ClickDispatcher.cs | 2 +- .../Rendering/Map/ClickDispatcherFactory.cs | 2 +- .../Rendering/Map/DynamicMapObjectUpdater.cs | 2 +- .../Rendering/Map/IMapItemGraphicProvider.cs | 2 +- .../Map/IMapRenderDistanceCalculator.cs | 2 +- EndlessClient/Rendering/Map/IMapRenderer.cs | 2 +- .../Rendering/Map/MapChangedActions.cs | 4 +- .../Map/MapEntityRendererProvider.cs | 2 +- .../Rendering/Map/MapItemGraphicProvider.cs | 4 +- .../Map/MapObjectBoundsCalculator.cs | 2 +- .../Rendering/Map/MapRenderBounds.cs | 2 +- EndlessClient/Rendering/Map/MapRenderer.cs | 6 +- .../Rendering/Map/MiniMapRenderer.cs | 8 +- .../Rendering/Map/MiniMapRendererFactory.cs | 2 +- .../BaseMapEntityRenderer.cs | 8 +- .../MapEntityRenderers/GroundLayerRenderer.cs | 2 +- .../MapEntityRenderers/IMapEntityRenderer.cs | 6 +- .../IMapEntityRendererProvider.cs | 2 +- .../MainCharacterEntityRenderer.cs | 2 +- .../MapItemLayerRenderer.cs | 6 +- .../MapObjectLayerRenderer.cs | 11 +- .../MapEntityRenderers/NPCEntityRenderer.cs | 2 +- .../MapEntityRenderers/OnTopLayerRenderer.cs | 2 +- .../Overlay2LayerRenderer.cs | 2 +- .../OverlayLayerRenderer.cs | 2 +- .../MapEntityRenderers/RoofLayerRenderer.cs | 2 +- .../MapEntityRenderers/ShadowLayerRenderer.cs | 2 +- .../MapEntityRenderers/WallLayerRenderer.cs | 8 +- .../Metadata/EffectMetadataProvider.cs | 2 +- .../Rendering/Metadata/GFXMetadataLoader.cs | 2 +- .../Rendering/Metadata/HatMetadataProvider.cs | 2 +- .../Rendering/Metadata/IMetadataProvider.cs | 2 +- .../Metadata/Models/EffectMetadata.cs | 2 +- .../Rendering/Metadata/Models/HatMetadata.cs | 2 +- .../Rendering/Metadata/Models/IGFXMetadata.cs | 2 +- .../Rendering/Metadata/Models/NPCMetadata.cs | 2 +- .../Metadata/Models/ShieldMetadata.cs | 2 +- .../Metadata/Models/WeaponMetadata.cs | 2 +- .../Rendering/Metadata/NPCMetadataProvider.cs | 2 +- .../Metadata/ShieldMetadataProvider.cs | 2 +- .../Metadata/WeaponMetadataProvider.cs | 2 +- .../Rendering/MouseCursorRenderer.cs | 6 +- EndlessClient/Rendering/NPC/NPCActions.cs | 2 +- EndlessClient/Rendering/NPC/NPCAnimator.cs | 4 +- EndlessClient/Rendering/NPC/NPCCache.cs | 2 +- EndlessClient/Rendering/NPC/NPCRenderer.cs | 2 +- .../Rendering/NPC/NPCRendererFactory.cs | 2 +- .../Rendering/NPC/NPCRendererRepository.cs | 2 +- .../Rendering/NPC/NPCRendererUpdater.cs | 2 +- .../Rendering/PlayerStatusIconRenderer.cs | 8 +- EndlessClient/Rendering/PointComparer.cs | 6 +- .../Rendering/RenderOffsetCalculator.cs | 12 +- .../Rendering/RendererRepositoryResetter.cs | 2 +- .../Sprites/ArmorShieldSpriteType.cs | 4 +- .../Sprites/CharacterSpriteCalculator.cs | 16 +- .../Rendering/Sprites/EmoteSpriteType.cs | 2 +- .../Rendering/Sprites/EmptySpriteSheet.cs | 6 +- .../Sprites/ICharacterSpriteCalculator.cs | 2 +- .../Rendering/Sprites/ISpriteSheet.cs | 2 +- .../Rendering/Sprites/NPCSpriteDataCache.cs | 2 +- .../Rendering/Sprites/SpriteSheet.cs | 2 +- .../Services/FriendIgnoreListService.cs | 2 +- .../Subscribers/ArenaEventSubscriber.cs | 2 +- .../Subscribers/JukeboxEventSubscriber.cs | 2 +- .../Subscribers/LockerEventSubscriber.cs | 2 +- .../MainCharacterEventSubscriber.cs | 4 +- .../OtherCharacterEventSubscriber.cs | 2 +- .../ServerRebootEventSubscriber.cs | 2 +- EndlessClient/Test/CharacterStateTest.cs | 16 +- EndlessClient/Test/TestModeLauncher.cs | 2 +- EndlessClient/UIControls/BlinkingLabel.cs | 6 +- EndlessClient/UIControls/CharacterControl.cs | 2 +- .../UIControls/CharacterInfoPanel.cs | 6 +- .../UIControls/CharacterInfoPanelFactory.cs | 8 +- .../UIControls/ChatModePictureBox.cs | 2 +- EndlessClient/UIControls/ChatTextBox.cs | 2 +- EndlessClient/UIControls/ClickableArea.cs | 2 +- .../UIControls/CreateCharacterControl.cs | 12 +- .../UIControls/ICharacterInfoPanelFactory.cs | 6 +- EndlessClient/UIControls/ScrollBar.cs | 2 +- EndlessClient/UIControls/StatusBarLabel.cs | 6 +- EndlessClient/UIControls/TimeLabel.cs | 6 +- .../UIControls/XnaControlSoundMapper.cs | 2 +- 868 files changed, 1725 insertions(+), 1449 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..696be7353 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,269 @@ +# Remove the line below if you want to inherit .editorconfig settings from higher directories +root = true + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +indent_style = space +tab_width = 4 + +# New line preferences +end_of_line = crlf +insert_final_newline = false + +#### .NET Coding Conventions #### + +# Organize usings +dotnet_separate_import_directive_groups = false +dotnet_sort_system_directives_first = false +file_header_template = unset + +# this. and Me. preferences +dotnet_style_qualification_for_event = false +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false +dotnet_style_qualification_for_property = false + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_operators = never_if_unnecessary +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members + +# Expression-level preferences +dotnet_style_coalesce_expression = true +dotnet_style_collection_initializer = true +dotnet_style_explicit_tuple_names = true +dotnet_style_namespace_match_folder = true +dotnet_style_null_propagation = true +dotnet_style_object_initializer = true +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_prefer_auto_properties = true +dotnet_style_prefer_collection_expression = true +dotnet_style_prefer_compound_assignment = true +dotnet_style_prefer_conditional_expression_over_assignment = true +dotnet_style_prefer_conditional_expression_over_return = true +dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed +dotnet_style_prefer_inferred_anonymous_type_member_names = true +dotnet_style_prefer_inferred_tuple_names = true +dotnet_style_prefer_is_null_check_over_reference_equality_method = true +dotnet_style_prefer_simplified_boolean_expressions = true +dotnet_style_prefer_simplified_interpolation = true + +# Field preferences +dotnet_style_readonly_field = true + +# Parameter preferences +dotnet_code_quality_unused_parameters = all + +# Suppression preferences +dotnet_remove_unnecessary_suppression_exclusions = none + +# New line preferences +dotnet_style_allow_multiple_blank_lines_experimental = true +dotnet_style_allow_statement_immediately_after_block_experimental = true + +#### C# Coding Conventions #### + +# var preferences +csharp_style_var_elsewhere = false:silent +csharp_style_var_for_built_in_types = false:silent +csharp_style_var_when_type_is_apparent = false:silent + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_pattern_matching = true:silent +csharp_style_prefer_switch_expression = true:suggestion + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:suggestion + +# Modifier preferences +csharp_prefer_static_local_function = true:suggestion +csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async +csharp_style_prefer_readonly_struct = true:suggestion +csharp_style_prefer_readonly_struct_member = true:suggestion + +# Code-block preferences +csharp_prefer_braces = true:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_prefer_top_level_statements = true:silent + +# Expression-level preferences +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:silent + +# New line preferences +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent +csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +[*.{cs,vb}] +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_prefer_collection_expression = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_namespace_match_folder = true:suggestion +indent_style = space +dotnet_style_readonly_field = true:suggestion +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true:silent +dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent +dotnet_style_allow_multiple_blank_lines_experimental = true:silent +dotnet_style_allow_statement_immediately_after_block_experimental = true:silent +dotnet_code_quality_unused_parameters = all:suggestion +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_property = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_event = false:silent \ No newline at end of file diff --git a/BatchMap/Program.cs b/BatchMap/Program.cs index 785b6ca18..c88ed8e56 100644 --- a/BatchMap/Program.cs +++ b/BatchMap/Program.cs @@ -1,12 +1,12 @@ -using System; -using System.IO; -using System.Linq; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib; using EOLib.IO.Actions; using EOLib.IO.Map; using EOLib.IO.Repositories; using EOLib.IO.Services; +using System; +using System.IO; +using System.Linq; namespace BatchMap { @@ -34,7 +34,7 @@ private static void Main(string[] args) Console.WriteLine("Invalid: single map cannot be processed into output directory. Specify destination emf file."); return; } - + if (dstFilePath.ToLower().EndsWith(".emf") && !srcFilePath.ToLower().EndsWith(".emf")) { Console.WriteLine("Invalid: map directory cannot be processed into single output map. Specify destination output directory."); @@ -149,7 +149,7 @@ private static void ProcessFiles(string src, string dst, bool singleFile) var mapFileLoadActions = _typeRegistry.Resolve(); var mapFileSaveService = _typeRegistry.Resolve(); - var inFiles = singleFile ? new[] {src} : Directory.GetFiles(src, "*.emf"); + var inFiles = singleFile ? new[] { src } : Directory.GetFiles(src, "*.emf"); for (int mapIndex = 0; mapIndex < inFiles.Length; ++mapIndex) { @@ -157,7 +157,7 @@ private static void ProcessFiles(string src, string dst, bool singleFile) mapFileLoadActions.LoadMapFileByName(inFiles[mapIndex]); var mapFile = _mapFileProvider.MapFiles[mapID]; - + var changesMade = false; //todo: find way to store actual input data, since invalid tiles/warps will be auto-removed @@ -192,7 +192,7 @@ private static void ProcessFiles(string src, string dst, bool singleFile) // } //} - for(int ndx = mapFile.NPCSpawns.Count - 1; ndx >= 0; --ndx) + for (int ndx = mapFile.NPCSpawns.Count - 1; ndx >= 0; --ndx) { var npcSpawn = mapFile.NPCSpawns[ndx]; var npcRec = _pubProvider.ENFFile[npcSpawn.ID]; @@ -239,7 +239,7 @@ private static void ProcessFiles(string src, string dst, bool singleFile) } } - for(int ndx = mapFile.Chests.Count - 1; ndx >= 0; --ndx) + for (int ndx = mapFile.Chests.Count - 1; ndx >= 0; --ndx) { var chestSpawn = mapFile.Chests[ndx]; var rec = _pubProvider.EIFFile[chestSpawn.ItemID]; @@ -313,4 +313,4 @@ private static bool TileIsValidNPCSpawnPoint(IMapFile EMF, int x, int y) return true; } } -} +} \ No newline at end of file diff --git a/BatchMap/Properties/AssemblyInfo.cs b/BatchMap/Properties/AssemblyInfo.cs index 70dd0e423..931aa9d9a 100644 --- a/BatchMap/Properties/AssemblyInfo.cs +++ b/BatchMap/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/BatchPub/Program.cs b/BatchPub/Program.cs index ffbcb081d..78957a790 100644 --- a/BatchPub/Program.cs +++ b/BatchPub/Program.cs @@ -17,4 +17,4 @@ static void Main() Application.Run(new frmMain()); } } -} +} \ No newline at end of file diff --git a/BatchPub/Properties/AssemblyInfo.cs b/BatchPub/Properties/AssemblyInfo.cs index ac1dfe098..36201db71 100644 --- a/BatchPub/Properties/AssemblyInfo.cs +++ b/BatchPub/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/BatchPub/frmMain.cs b/BatchPub/frmMain.cs index 5bf0ea461..da545cc36 100644 --- a/BatchPub/frmMain.cs +++ b/BatchPub/frmMain.cs @@ -1,13 +1,13 @@ -using System; +using EOLib.IO; +using EOLib.IO.Pub; +using EOLib.IO.Services; +using EOLib.IO.Services.Serializers; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; -using EOLib.IO; -using EOLib.IO.Pub; -using EOLib.IO.Services; -using EOLib.IO.Services.Serializers; namespace BatchPub { @@ -49,8 +49,8 @@ private void InitializeMore() cmbStepTwoField.Items.Clear(); cmbStepThreeField.Items.Clear(); - var eifType = typeof (EIFRecord); - foreach(System.Reflection.PropertyInfo prop in eifType.GetProperties()) + var eifType = typeof(EIFRecord); + foreach (System.Reflection.PropertyInfo prop in eifType.GetProperties()) { cmbStepTwoField.Items.Add(new PropInfo(prop)); cmbStepThreeField.Items.Add(new PropInfo(prop)); @@ -85,11 +85,11 @@ private void btnProcess_Click(object sender, EventArgs e) break; } - if(!chkFilterOn.Checked) + if (!chkFilterOn.Checked) { //process the change for EVERY item record. save changes immediately. if (MessageBox.Show( - "This change will be processed for every item immediately. The change is irreversible. Are you sure you want to continue? You may specify a filter by checking the filter option.", "No filter selected", - MessageBoxButtons.YesNo, + "This change will be processed for every item immediately. The change is irreversible. Are you sure you want to continue? You may specify a filter by checking the filter option.", "No filter selected", + MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No ) { @@ -112,7 +112,7 @@ private void btnProcess_Click(object sender, EventArgs e) try { op = (CompareOperator)cmbCompareType.SelectedIndex; - if(op == CompareOperator.REGEX && cmbCompareValue.Enabled) + if (op == CompareOperator.REGEX && cmbCompareValue.Enabled) { MessageBox.Show("You can't use a regex to parse enumerated types"); return; @@ -223,7 +223,7 @@ private void btnProcess_Click(object sender, EventArgs e) setter = Convert.ChangeType(Enum.ToObject(pi.PropertyType, newValue), pi.PropertyType); else setter = Convert.ChangeType(newValue, pi.PropertyType); - + pi.SetValue(rec, setter); //eif.ReplaceRecordAt(index, rec); //todo: way to modify pub files @@ -238,7 +238,7 @@ private void btnExit_Click(object sender, EventArgs e) private void btnBrowse_Click(object sender, EventArgs e) { - using(OpenFileDialog ofd = new OpenFileDialog()) + using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.CheckFileExists = true; ofd.CheckPathExists = true; @@ -266,7 +266,7 @@ private void btnLoad_Click(object sender, EventArgs e) grpStepTwo.Enabled = true; btnReset.Enabled = true; } - catch(Exception ex) + catch (Exception ex) { eif = null; MessageBox.Show("Error loading " + _fname + ":\n" + ex.Message, "Error!"); @@ -305,7 +305,7 @@ private void cmbStepTwoField_SelectedIndexChanged(object sender, EventArgs e) private void LeaveStepTwo(object sender, EventArgs e) { - if(cmbStepTwoField.SelectedIndex >= 0 && + if (cmbStepTwoField.SelectedIndex >= 0 && ((txtStepTwoValue.Enabled && txtStepTwoValue.TextLength > 0) || (cmbStepTwoValue.Enabled && cmbStepTwoValue.SelectedIndex >= 0)) ) { @@ -321,7 +321,7 @@ private void LeaveStepTwo(object sender, EventArgs e) private void chkFilterOn_CheckedChanged(object sender, EventArgs e) { - if(chkFilterOn.Checked) + if (chkFilterOn.Checked) { cmbStepThreeField.Enabled = true; txtCompareValue.Enabled = true; @@ -402,7 +402,7 @@ private void btnClear_Click(object sender, EventArgs e) private void btnSave_Click(object sender, EventArgs e) { - if(changes) + if (changes) { DialogResult dr = MessageBox.Show("WARNING: This will update the pub file you currently have open with any batch changes that have been made. Confirm that this behavior is desired.", "Confirm changes?", MessageBoxButtons.YesNo); if (dr == DialogResult.No) @@ -420,7 +420,7 @@ private void btnSave_Click(object sender, EventArgs e) var serializer = new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); var bytes = serializer.SerializeToByteArray(eif); } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show("Error saving changes to the file:\n" + ex.Message); return; @@ -452,4 +452,4 @@ public override string ToString() return DisplayName; } } -} +} \ No newline at end of file diff --git a/EOBot/ArgumentsParser.cs b/EOBot/ArgumentsParser.cs index 33d48aa32..a0a0c7a6a 100644 --- a/EOBot/ArgumentsParser.cs +++ b/EOBot/ArgumentsParser.cs @@ -213,4 +213,4 @@ private bool ParseInitDelay(string initDelay) return true; } } -} +} \ No newline at end of file diff --git a/EOBot/BotBase.cs b/EOBot/BotBase.cs index 0ec336dd2..731bcded0 100644 --- a/EOBot/BotBase.cs +++ b/EOBot/BotBase.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using EOLib; +using EOLib; using EOLib.Config; using EOLib.Domain.Protocol; using EOLib.Net.Communication; @@ -9,6 +6,9 @@ using EOLib.Net.PacketProcessing; using Moffat.EndlessOnline.SDK.Packet; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; +using System; +using System.Threading; +using System.Threading.Tasks; namespace EOBot { @@ -89,4 +89,4 @@ public async Task RunAsync(CancellationToken ct) /// A cancellation token that will be signalled when Terminate() is called protected abstract Task DoWorkAsync(CancellationToken ct); } -} +} \ No newline at end of file diff --git a/EOBot/BotException.cs b/EOBot/BotException.cs index 8e1f75484..558420ab9 100644 --- a/EOBot/BotException.cs +++ b/EOBot/BotException.cs @@ -6,4 +6,4 @@ public class BotException : Exception { public BotException(string message) : base(message) { } } -} +} \ No newline at end of file diff --git a/EOBot/BotFramework.cs b/EOBot/BotFramework.cs index 49a22e7b8..732455115 100644 --- a/EOBot/BotFramework.cs +++ b/EOBot/BotFramework.cs @@ -66,7 +66,7 @@ public async Task InitializeAsync(IBotFactory botFactory, int delayBetweenInitsM await bot.InitializeAsync(_host, _port); _botsList.Add(bot); } - catch(Exception ex) + catch (Exception ex) { ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, ex.Message, ConsoleColor.DarkRed); numFailed++; @@ -92,7 +92,7 @@ public async Task InitializeAsync(IBotFactory botFactory, int delayBetweenInitsM public async Task RunAsync() { - if(!_initialized) + if (!_initialized) throw new InvalidOperationException("Must call Initialize() before running!"); var botTasks = new List(); @@ -149,4 +149,4 @@ private void Dispose(bool disposing) } } } -} +} \ No newline at end of file diff --git a/EOBot/BotHelper.cs b/EOBot/BotHelper.cs index 991567de6..373f4addd 100644 --- a/EOBot/BotHelper.cs +++ b/EOBot/BotHelper.cs @@ -123,4 +123,4 @@ public async Task DeleteCharacterAsync(string name, bool force) return await characterActions.DeleteCharacter(deleteId); } } -} +} \ No newline at end of file diff --git a/EOBot/ConsoleHelper.cs b/EOBot/ConsoleHelper.cs index a347a4d61..16053186f 100644 --- a/EOBot/ConsoleHelper.cs +++ b/EOBot/ConsoleHelper.cs @@ -77,4 +77,4 @@ public static void WriteMessage(Type messageType, string message, ConsoleColor c Console.ForegroundColor = oldColor; } } -} +} \ No newline at end of file diff --git a/EOBot/DependencyMaster.cs b/EOBot/DependencyMaster.cs index 6a122084e..72ffebcb6 100644 --- a/EOBot/DependencyMaster.cs +++ b/EOBot/DependencyMaster.cs @@ -6,4 +6,4 @@ public static class DependencyMaster { public static ITypeRegistry[] TypeRegistry { get; set; } } -} +} \ No newline at end of file diff --git a/EOBot/IBot.cs b/EOBot/IBot.cs index e6d99de5c..48eca1739 100644 --- a/EOBot/IBot.cs +++ b/EOBot/IBot.cs @@ -22,4 +22,4 @@ public interface IBot /// True to wait until a call to Terminate() is made, false otherwise Task RunAsync(CancellationToken cancellationToken); } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/BotInterpreter.cs b/EOBot/Interpreter/BotInterpreter.cs index a916c5d32..4be01ea55 100644 --- a/EOBot/Interpreter/BotInterpreter.cs +++ b/EOBot/Interpreter/BotInterpreter.cs @@ -88,4 +88,4 @@ public async Task Run(ProgramState programState) } } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/BotScriptErrorException.cs b/EOBot/Interpreter/BotScriptErrorException.cs index b2c54ff09..121d3cb0d 100644 --- a/EOBot/Interpreter/BotScriptErrorException.cs +++ b/EOBot/Interpreter/BotScriptErrorException.cs @@ -10,4 +10,4 @@ public BotScriptErrorException(string message) public BotScriptErrorException(string message, BotToken token) : base($"Error at line {token.LineNumber} column {token.Column}: {message}") { } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/BotToken.cs b/EOBot/Interpreter/BotToken.cs index 3344c7d56..460ddba07 100644 --- a/EOBot/Interpreter/BotToken.cs +++ b/EOBot/Interpreter/BotToken.cs @@ -20,4 +20,4 @@ public BotToken(BotTokenType tokenType, string tokenValue, int line, int col) public override string ToString() => $"{TokenType}: {TokenValue}"; } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/BotTokenParser.cs b/EOBot/Interpreter/BotTokenParser.cs index 78a4fd1eb..69a89ff16 100644 --- a/EOBot/Interpreter/BotTokenParser.cs +++ b/EOBot/Interpreter/BotTokenParser.cs @@ -113,7 +113,7 @@ public BotToken GetNextToken() } else { - switch(inputChar) + switch (inputChar) { case '(': return Token(BotTokenType.LParen, inputChar.ToString()); case ')': return Token(BotTokenType.RParen, inputChar.ToString()); @@ -137,7 +137,7 @@ public BotToken GetNextToken() } case '=': { - switch(Peek()) + switch (Peek()) { case '=': var nextChar = Read(); @@ -148,7 +148,7 @@ public BotToken GetNextToken() } case '!': { - switch(Peek()) + switch (Peek()) { case '=': var nextChar = Read(); @@ -231,4 +231,4 @@ private char Read() return (char)_inputStream.Read(); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/BotTokenType.cs b/EOBot/Interpreter/BotTokenType.cs index 4b3f0a850..e93ed43cd 100644 --- a/EOBot/Interpreter/BotTokenType.cs +++ b/EOBot/Interpreter/BotTokenType.cs @@ -31,4 +31,4 @@ public enum BotTokenType NewLine, Error, } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs b/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs index ae946eaf9..7069b8c51 100644 --- a/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs +++ b/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs @@ -268,7 +268,8 @@ private void Chat(string chatText) statsObj.SymbolTable["tp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.TP])); statsObj.SymbolTable["maxtp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxTP])); return statsObj; - }); + } + ); return Readonly(charObj); } @@ -323,4 +324,4 @@ private IVariable GetMapStateItem(MapItem item) return itemObj; } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs b/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs index 8aae531a2..4a7ec0625 100644 --- a/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs +++ b/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs @@ -25,4 +25,4 @@ public static BotToken Current(this ProgramState input) return input.Program[input.ExecutionIndex]; } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs b/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs index 0bf58ca83..974525d41 100644 --- a/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs +++ b/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs @@ -53,4 +53,4 @@ public static (EvalResult Result, string Reason, T Variable) GetVariable(this return (EvalResult.Ok, string.Empty, variable); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/IdentifierBotToken.cs b/EOBot/Interpreter/IdentifierBotToken.cs index fed0e6c9a..5b59a915e 100644 --- a/EOBot/Interpreter/IdentifierBotToken.cs +++ b/EOBot/Interpreter/IdentifierBotToken.cs @@ -13,4 +13,4 @@ public IdentifierBotToken(BotToken identifier, int? arrayIndex = null, Identifie Member = member; } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/AssignmentEvaluator.cs b/EOBot/Interpreter/States/AssignmentEvaluator.cs index fcad88c8b..4cd58275e 100644 --- a/EOBot/Interpreter/States/AssignmentEvaluator.cs +++ b/EOBot/Interpreter/States/AssignmentEvaluator.cs @@ -96,4 +96,4 @@ public AssignmentEvaluator(IEnumerable evaluators) return Success(); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/BaseEvaluator.cs b/EOBot/Interpreter/States/BaseEvaluator.cs index 428789e1d..39449f0f4 100644 --- a/EOBot/Interpreter/States/BaseEvaluator.cs +++ b/EOBot/Interpreter/States/BaseEvaluator.cs @@ -81,4 +81,4 @@ protected IScriptEvaluator Evaluator() where T : IScriptEvaluator return (EvalResult.Failed, $"Failed to goto label {token.TokenValue}", token); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/BlockEvaluator.cs b/EOBot/Interpreter/States/BlockEvaluator.cs index 5c861c701..eca9cec26 100644 --- a/EOBot/Interpreter/States/BlockEvaluator.cs +++ b/EOBot/Interpreter/States/BlockEvaluator.cs @@ -105,4 +105,4 @@ protected static void RestoreLastNewline(ProgramState input) input.Goto(input.ExecutionIndex - 1); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/EvalResult.cs b/EOBot/Interpreter/States/EvalResult.cs index e8eb6bf20..714f138db 100644 --- a/EOBot/Interpreter/States/EvalResult.cs +++ b/EOBot/Interpreter/States/EvalResult.cs @@ -15,4 +15,4 @@ public enum EvalResult /// NotMatch } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/ExpressionEvaluator.cs b/EOBot/Interpreter/States/ExpressionEvaluator.cs index af3a8dbc7..1df7948e7 100644 --- a/EOBot/Interpreter/States/ExpressionEvaluator.cs +++ b/EOBot/Interpreter/States/ExpressionEvaluator.cs @@ -226,4 +226,4 @@ public ExpressionEvaluator(IEnumerable evaluators) private (IVariable, string) Divide(IntVariable a, IntVariable b) => (new IntVariable(a.Value / b.Value), string.Empty); private (IVariable, string) Divide(object a, object b) => (null, $"Objects {a} and {b} could not be divided (currently the operands must be int)"); } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/ExpressionTailEvaluator.cs b/EOBot/Interpreter/States/ExpressionTailEvaluator.cs index 2ef02d9e6..c24d311dd 100644 --- a/EOBot/Interpreter/States/ExpressionTailEvaluator.cs +++ b/EOBot/Interpreter/States/ExpressionTailEvaluator.cs @@ -24,4 +24,4 @@ public ExpressionTailEvaluator(IEnumerable evaluators) return await Evaluator().EvaluateAsync(input); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/GotoEvaluator.cs b/EOBot/Interpreter/States/GotoEvaluator.cs index 4bb50acd2..71c2d5292 100644 --- a/EOBot/Interpreter/States/GotoEvaluator.cs +++ b/EOBot/Interpreter/States/GotoEvaluator.cs @@ -20,9 +20,9 @@ public class GotoEvaluator : BaseEvaluator var label = input.OperationStack.Pop(); if (!input.Labels.ContainsKey(label.TokenValue)) return Task.FromResult(IdentifierNotFoundError(new IdentifierBotToken(label))); - + var result = input.Goto(input.Labels[label.TokenValue]); return Task.FromResult(result ? Success() : GotoError(label)); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/IScriptEvaluator.cs b/EOBot/Interpreter/States/IScriptEvaluator.cs index 15460e992..db12d2a4a 100644 --- a/EOBot/Interpreter/States/IScriptEvaluator.cs +++ b/EOBot/Interpreter/States/IScriptEvaluator.cs @@ -6,4 +6,4 @@ public interface IScriptEvaluator { Task<(EvalResult Result, string Reason, BotToken Token)> EvaluateAsync(ProgramState input); } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/IfEvaluator.cs b/EOBot/Interpreter/States/IfEvaluator.cs index 74de570f3..1285e7df0 100644 --- a/EOBot/Interpreter/States/IfEvaluator.cs +++ b/EOBot/Interpreter/States/IfEvaluator.cs @@ -77,4 +77,4 @@ private void SkipElseBlocks(ProgramState input) RestoreLastNewline(input); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/KeywordEvaluator.cs b/EOBot/Interpreter/States/KeywordEvaluator.cs index c41c9d9a8..e55c4278c 100644 --- a/EOBot/Interpreter/States/KeywordEvaluator.cs +++ b/EOBot/Interpreter/States/KeywordEvaluator.cs @@ -24,4 +24,4 @@ public KeywordEvaluator(IEnumerable evaluators) return res; } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/LabelEvaluator.cs b/EOBot/Interpreter/States/LabelEvaluator.cs index 50d8eb578..def562c1c 100644 --- a/EOBot/Interpreter/States/LabelEvaluator.cs +++ b/EOBot/Interpreter/States/LabelEvaluator.cs @@ -13,4 +13,4 @@ public class LabelEvaluator : BaseEvaluator return Task.FromResult((result, string.Empty, input.Current())); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/OperandEvaluator.cs b/EOBot/Interpreter/States/OperandEvaluator.cs index 60e70fcc7..058dbb9a3 100644 --- a/EOBot/Interpreter/States/OperandEvaluator.cs +++ b/EOBot/Interpreter/States/OperandEvaluator.cs @@ -24,4 +24,4 @@ public OperandEvaluator(IEnumerable evaluators) return matchRes ? Success() : (EvalResult.NotMatch, string.Empty, input.Current()); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/ProgramState.cs b/EOBot/Interpreter/States/ProgramState.cs index e72cfc107..5ce7906d7 100644 --- a/EOBot/Interpreter/States/ProgramState.cs +++ b/EOBot/Interpreter/States/ProgramState.cs @@ -56,7 +56,7 @@ public bool Expect(BotTokenType tokenType) ExecutionIndex++; return true; } - + return false; } @@ -114,4 +114,4 @@ public bool MatchPair(BotTokenType first, BotTokenType second) return false; } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/ScriptEvaluator.cs b/EOBot/Interpreter/States/ScriptEvaluator.cs index 4a5f08cf4..93cf583c1 100644 --- a/EOBot/Interpreter/States/ScriptEvaluator.cs +++ b/EOBot/Interpreter/States/ScriptEvaluator.cs @@ -21,4 +21,4 @@ public ScriptEvaluator(IEnumerable evaluators) return Success(); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/States/VariableEvaluator.cs b/EOBot/Interpreter/States/VariableEvaluator.cs index 1d406be55..44f2ff5d7 100644 --- a/EOBot/Interpreter/States/VariableEvaluator.cs +++ b/EOBot/Interpreter/States/VariableEvaluator.cs @@ -64,4 +64,4 @@ public VariableEvaluator(IEnumerable evaluators) return Success(); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/VariableBotToken.cs b/EOBot/Interpreter/VariableBotToken.cs index e95a5bec1..953de3f5b 100644 --- a/EOBot/Interpreter/VariableBotToken.cs +++ b/EOBot/Interpreter/VariableBotToken.cs @@ -12,4 +12,4 @@ public VariableBotToken(BotTokenType tokenType, string tokenValue, IVariable var VariableValue = variableValue; } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/ArrayVariable.cs b/EOBot/Interpreter/Variables/ArrayVariable.cs index d2d00d86c..25e01a1a4 100644 --- a/EOBot/Interpreter/Variables/ArrayVariable.cs +++ b/EOBot/Interpreter/Variables/ArrayVariable.cs @@ -25,4 +25,4 @@ public IVariable> WithNewValue(List value) public override string ToString() => StringValue; } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/AsyncFunction.cs b/EOBot/Interpreter/Variables/AsyncFunction.cs index 532136b2a..85a2136c4 100644 --- a/EOBot/Interpreter/Variables/AsyncFunction.cs +++ b/EOBot/Interpreter/Variables/AsyncFunction.cs @@ -129,4 +129,4 @@ public Task CallAsync(params IIdentifiable[] parameters) return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/AsyncVoidFunction.cs b/EOBot/Interpreter/Variables/AsyncVoidFunction.cs index 525782a6f..f4beb6c09 100644 --- a/EOBot/Interpreter/Variables/AsyncVoidFunction.cs +++ b/EOBot/Interpreter/Variables/AsyncVoidFunction.cs @@ -129,4 +129,4 @@ public Task CallAsync(params IIdentifiable[] parameters) return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/BoolVariable.cs b/EOBot/Interpreter/Variables/BoolVariable.cs index 32a98a34c..369537c19 100644 --- a/EOBot/Interpreter/Variables/BoolVariable.cs +++ b/EOBot/Interpreter/Variables/BoolVariable.cs @@ -18,4 +18,4 @@ public class BoolVariable : IVariable public override string ToString() => StringValue; } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/Function.cs b/EOBot/Interpreter/Variables/Function.cs index 9d80a640b..4615850b7 100644 --- a/EOBot/Interpreter/Variables/Function.cs +++ b/EOBot/Interpreter/Variables/Function.cs @@ -128,4 +128,4 @@ public T Call(params IIdentifiable[] parameters) return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/ICallable.cs b/EOBot/Interpreter/Variables/ICallable.cs index 25020ba1e..b82f237fd 100644 --- a/EOBot/Interpreter/Variables/ICallable.cs +++ b/EOBot/Interpreter/Variables/ICallable.cs @@ -24,4 +24,4 @@ public interface IAsyncCallable : IAsyncFunction { Task CallAsync(params IIdentifiable[] parameters); } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/IIdentifiable.cs b/EOBot/Interpreter/Variables/IIdentifiable.cs index 3d21ccd4f..f1c87c708 100644 --- a/EOBot/Interpreter/Variables/IIdentifiable.cs +++ b/EOBot/Interpreter/Variables/IIdentifiable.cs @@ -4,4 +4,4 @@ public interface IIdentifiable { string StringValue { get; } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/IVariable.cs b/EOBot/Interpreter/Variables/IVariable.cs index f3767e5e0..42badf86c 100644 --- a/EOBot/Interpreter/Variables/IVariable.cs +++ b/EOBot/Interpreter/Variables/IVariable.cs @@ -11,4 +11,4 @@ public interface IVariable : IVariable { T Value { get; } } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/IntVariable.cs b/EOBot/Interpreter/Variables/IntVariable.cs index 04fc25b46..397d519aa 100644 --- a/EOBot/Interpreter/Variables/IntVariable.cs +++ b/EOBot/Interpreter/Variables/IntVariable.cs @@ -18,4 +18,4 @@ public class IntVariable : IVariable public override string ToString() => StringValue; } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/ObjectVariable.cs b/EOBot/Interpreter/Variables/ObjectVariable.cs index 99f02669e..099c9a8ca 100644 --- a/EOBot/Interpreter/Variables/ObjectVariable.cs +++ b/EOBot/Interpreter/Variables/ObjectVariable.cs @@ -43,4 +43,4 @@ public class RuntimeEvaluatedMemberObjectVariable : IVariable public override string ToString() => StringValue; } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs b/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs index 7e4dd89d9..977d4dcd1 100644 --- a/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs +++ b/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs @@ -48,4 +48,4 @@ public static class PredefinedIdentifiers public const string JOIN_PARTY = "JoinParty"; public const string CHAT = "Chat"; } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/StringVariable.cs b/EOBot/Interpreter/Variables/StringVariable.cs index 48d7d7b88..7884fd76b 100644 --- a/EOBot/Interpreter/Variables/StringVariable.cs +++ b/EOBot/Interpreter/Variables/StringVariable.cs @@ -18,4 +18,4 @@ public class StringVariable : IVariable public override string ToString() => StringValue; } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/UndefinedVariable.cs b/EOBot/Interpreter/Variables/UndefinedVariable.cs index 16d445a54..95582b946 100644 --- a/EOBot/Interpreter/Variables/UndefinedVariable.cs +++ b/EOBot/Interpreter/Variables/UndefinedVariable.cs @@ -12,4 +12,4 @@ private UndefinedVariable() { } public override string ToString() => StringValue; } -} +} \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/VoidFunction.cs b/EOBot/Interpreter/Variables/VoidFunction.cs index 97c21c506..1429b34ef 100644 --- a/EOBot/Interpreter/Variables/VoidFunction.cs +++ b/EOBot/Interpreter/Variables/VoidFunction.cs @@ -128,4 +128,4 @@ public void Call(params IIdentifiable[] parameters) _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); } } -} +} \ No newline at end of file diff --git a/EOBot/NamesList.cs b/EOBot/NamesList.cs index 9c163a694..0c1a91aea 100644 --- a/EOBot/NamesList.cs +++ b/EOBot/NamesList.cs @@ -52,4 +52,4 @@ public static string Rand() return ret; } } -} +} \ No newline at end of file diff --git a/EOBot/Program.cs b/EOBot/Program.cs index e9fde73ad..48acacfc4 100644 --- a/EOBot/Program.cs +++ b/EOBot/Program.cs @@ -411,4 +411,4 @@ TIME THE SCRIPT FINISHES EXECUTING "); } } -} +} \ No newline at end of file diff --git a/EOBot/Properties/AssemblyInfo.cs b/EOBot/Properties/AssemblyInfo.cs index 8c3480e5f..636611a64 100644 --- a/EOBot/Properties/AssemblyInfo.cs +++ b/EOBot/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/EOBot/ScriptedBot.cs b/EOBot/ScriptedBot.cs index 4d206825e..bd5c2a5d5 100644 --- a/EOBot/ScriptedBot.cs +++ b/EOBot/ScriptedBot.cs @@ -54,4 +54,4 @@ protected override async Task DoWorkAsync(CancellationToken ct) await _interpreter.Run(_programState); } } -} +} \ No newline at end of file diff --git a/EOBot/ScriptedBotFactory.cs b/EOBot/ScriptedBotFactory.cs index cb770ee7d..fa27d634e 100644 --- a/EOBot/ScriptedBotFactory.cs +++ b/EOBot/ScriptedBotFactory.cs @@ -14,4 +14,4 @@ public IBot CreateBot(int index) return new ScriptedBot(index, _parser); } } -} +} \ No newline at end of file diff --git a/EOBot/TrainerBot.cs b/EOBot/TrainerBot.cs index db714494c..ad1245c55 100644 --- a/EOBot/TrainerBot.cs +++ b/EOBot/TrainerBot.cs @@ -409,4 +409,4 @@ private Task Delay(uint milliseconds) return Task.Delay((int)milliseconds); } } -} +} \ No newline at end of file diff --git a/EOBot/TrainerBotFactory.cs b/EOBot/TrainerBotFactory.cs index 9eaa5efce..68df168fa 100644 --- a/EOBot/TrainerBotFactory.cs +++ b/EOBot/TrainerBotFactory.cs @@ -14,4 +14,4 @@ public IBot CreateBot(int index) return new TrainerBot(index, _parser.Account, _parser.Password, _parser.Character); } } -} +} \ No newline at end of file diff --git a/EOLib.Config.Test/AssemblyInitializer.cs b/EOLib.Config.Test/AssemblyInitializer.cs index e29e89d0a..fc78224d8 100644 --- a/EOLib.Config.Test/AssemblyInitializer.cs +++ b/EOLib.Config.Test/AssemblyInitializer.cs @@ -9,4 +9,4 @@ public void OneTimeSetUp() { Directory.SetCurrentDirectory(TestContext.CurrentContext.TestDirectory); } -} +} \ No newline at end of file diff --git a/EOLib.Config.Test/ConfigFileLoadActionsTest.cs b/EOLib.Config.Test/ConfigFileLoadActionsTest.cs index a02aa381e..3b7fa6496 100644 --- a/EOLib.Config.Test/ConfigFileLoadActionsTest.cs +++ b/EOLib.Config.Test/ConfigFileLoadActionsTest.cs @@ -1,6 +1,6 @@ -using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; using System.IO; -using NUnit.Framework; namespace EOLib.Config.Test { @@ -58,7 +58,7 @@ public void InvalidConfigFileThatExists_UsesConfigurationValueDefaults() Assert.IsFalse(_configurationRepository.MusicEnabled); Assert.IsFalse(_configurationRepository.SoundEnabled); - + Assert.IsTrue(_configurationRepository.HearWhispers); Assert.IsTrue(_configurationRepository.Interaction); Assert.IsFalse(_configurationRepository.LogChatToFile); diff --git a/EOLib.Config.Test/IniReaderTest.cs b/EOLib.Config.Test/IniReaderTest.cs index 80ef54d17..3b45a75d1 100644 --- a/EOLib.Config.Test/IniReaderTest.cs +++ b/EOLib.Config.Test/IniReaderTest.cs @@ -1,6 +1,6 @@ -using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; using System.IO; -using NUnit.Framework; namespace EOLib.Config.Test { @@ -307,4 +307,4 @@ private static void CreateTestFileWithData(string contents) File.WriteAllText(FullPath, contents); } } -} +} \ No newline at end of file diff --git a/EOLib.Config.Test/Properties/AssemblyInfo.cs b/EOLib.Config.Test/Properties/AssemblyInfo.cs index 7b512b6d5..89dc4cda2 100644 --- a/EOLib.Config.Test/Properties/AssemblyInfo.cs +++ b/EOLib.Config.Test/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/EOLib.Config/ConfigDefaults.cs b/EOLib.Config/ConfigDefaults.cs index e2ebf8795..aa15f9506 100644 --- a/EOLib.Config/ConfigDefaults.cs +++ b/EOLib.Config/ConfigDefaults.cs @@ -14,4 +14,4 @@ public static class ConfigDefaults public const int AccountCreateTimeout = 2000; } -} +} \ No newline at end of file diff --git a/EOLib.Config/ConfigFileLoadActions.cs b/EOLib.Config/ConfigFileLoadActions.cs index 6f42d1cae..5bedaca3e 100644 --- a/EOLib.Config/ConfigFileLoadActions.cs +++ b/EOLib.Config/ConfigFileLoadActions.cs @@ -74,4 +74,4 @@ public void LoadConfigFile() _configRepository.InGameHeight = configFile.GetValue(ConfigStrings.Settings, ConfigStrings.InGameHeight, out tempInt) ? tempInt : 0; } } -} +} \ No newline at end of file diff --git a/EOLib.Config/IConfigFileLoadActions.cs b/EOLib.Config/IConfigFileLoadActions.cs index 6bbc78a69..b02144c1f 100644 --- a/EOLib.Config/IConfigFileLoadActions.cs +++ b/EOLib.Config/IConfigFileLoadActions.cs @@ -4,4 +4,4 @@ public interface IConfigFileLoadActions { void LoadConfigFile(); } -} +} \ No newline at end of file diff --git a/EOLib.Config/IConfigurationRepository.cs b/EOLib.Config/IConfigurationRepository.cs index da9f9b8b4..46b4e110d 100644 --- a/EOLib.Config/IConfigurationRepository.cs +++ b/EOLib.Config/IConfigurationRepository.cs @@ -114,4 +114,4 @@ public class ConfigurationRepository : IConfigurationRepository, IConfigurationP public bool DebugCrashes { get; set; } } -} +} \ No newline at end of file diff --git a/EOLib.Config/IniReader.cs b/EOLib.Config/IniReader.cs index 33d87eb76..b4022e62c 100644 --- a/EOLib.Config/IniReader.cs +++ b/EOLib.Config/IniReader.cs @@ -192,4 +192,4 @@ private string AddNewHeader(string nextLine) #endregion } -} +} \ No newline at end of file diff --git a/EOLib.Config/MalformedConfigException.cs b/EOLib.Config/MalformedConfigException.cs index 0be9173db..82d2a04f8 100644 --- a/EOLib.Config/MalformedConfigException.cs +++ b/EOLib.Config/MalformedConfigException.cs @@ -12,4 +12,4 @@ public MalformedConfigException(string message, Exception innerException) : base { } } -} +} \ No newline at end of file diff --git a/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs b/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs index 6d5b30ec5..b0d45a271 100644 --- a/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs +++ b/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs @@ -1,8 +1,8 @@ -using System; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using System; using System.ComponentModel.Design; using System.Diagnostics.CodeAnalysis; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; namespace EOLib.Graphics.Test { @@ -40,4 +40,4 @@ private void Dispose(bool disposing) } } } -} +} \ No newline at end of file diff --git a/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs b/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs index 2d6d20331..e0442036c 100644 --- a/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs +++ b/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs @@ -75,4 +75,4 @@ private Mock SetupPEFileForGFXType(GFXTypes type, byte[] array) return peFile; } } -} +} \ No newline at end of file diff --git a/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs b/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs index 69d24a3e7..2373ed3d6 100644 --- a/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs +++ b/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs @@ -1,10 +1,10 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using NUnit.Framework; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Moq; -using Microsoft.Xna.Framework; +using NUnit.Framework; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; namespace EOLib.Graphics.Test { @@ -142,7 +142,7 @@ public void WhenLoadTexture_Transparent_SetsBlackToTransparent() FillBitmapWithColor(bmp, Color.Black); resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, true); - var data = new Microsoft.Xna.Framework.Color[resultTexture.Width*resultTexture.Height]; + var data = new Microsoft.Xna.Framework.Color[resultTexture.Width * resultTexture.Height]; resultTexture.GetData(data); Assert.IsTrue(data.All(x => x.A == 0)); @@ -219,7 +219,7 @@ private Memory LoadGFXReturnsBitmap(GFXTypes whichFile, int requestedResou private static void FillBitmapWithColor(Memory image, Color color) { - for (int i = 54; i < image.Length; i+=4) + for (int i = 54; i < image.Length; i += 4) { image.Span[i] = color.B; image.Span[i + 1] = color.G; @@ -237,4 +237,4 @@ private void GetTextureAgain(GFXTypes whichFile, int requestedResource) _nativeGraphicsManager.TextureFromResource(whichFile, requestedResource); } } -} +} \ No newline at end of file diff --git a/EOLib.Graphics.Test/PEFileCollectionTest.cs b/EOLib.Graphics.Test/PEFileCollectionTest.cs index 2dd542e1d..229246829 100644 --- a/EOLib.Graphics.Test/PEFileCollectionTest.cs +++ b/EOLib.Graphics.Test/PEFileCollectionTest.cs @@ -1,10 +1,10 @@ -using System; +using Moq; +using NUnit.Framework; +using PELoaderLib; +using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; -using NUnit.Framework; -using Moq; -using PELoaderLib; namespace EOLib.Graphics.Test { @@ -63,7 +63,7 @@ public void Dispose_DisposesAllFiles() _collection.Dispose(); - foreach(var file in _collection.Values) + foreach (var file in _collection.Values) Mock.Get(file).Verify(x => x.Dispose(), Times.Once); } @@ -74,4 +74,4 @@ private void CreateExpectedDirectoryWithFiles(int numFiles = 0, string fileNameF File.WriteAllText(string.Format(Path.Combine(ExpectedDirectory, fileNameFormat), i), "test contents"); } } -} +} \ No newline at end of file diff --git a/EOLib.Graphics.Test/Properties/AssemblyInfo.cs b/EOLib.Graphics.Test/Properties/AssemblyInfo.cs index df2478ed1..16e12e6a2 100644 --- a/EOLib.Graphics.Test/Properties/AssemblyInfo.cs +++ b/EOLib.Graphics.Test/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/EOLib.Graphics.Test/RectangleExtensionTest.cs b/EOLib.Graphics.Test/RectangleExtensionTest.cs index a97a9ae9e..173fed9df 100644 --- a/EOLib.Graphics.Test/RectangleExtensionTest.cs +++ b/EOLib.Graphics.Test/RectangleExtensionTest.cs @@ -1,6 +1,6 @@ -using System.Diagnostics.CodeAnalysis; +using Microsoft.Xna.Framework; using NUnit.Framework; -using Microsoft.Xna.Framework; +using System.Diagnostics.CodeAnalysis; namespace EOLib.Graphics.Test { @@ -39,4 +39,4 @@ public void WithPosition_DoesNotModify_OriginalRectangle() Assert.AreNotEqual(newRectangle, rectangle); } } -} +} \ No newline at end of file diff --git a/EOLib.Graphics/ColorConstants.cs b/EOLib.Graphics/ColorConstants.cs index e16585bdb..263e332c4 100644 --- a/EOLib.Graphics/ColorConstants.cs +++ b/EOLib.Graphics/ColorConstants.cs @@ -1,5 +1,5 @@ -using System.Diagnostics.CodeAnalysis; using Microsoft.Xna.Framework; +using System.Diagnostics.CodeAnalysis; namespace EOLib.Graphics { diff --git a/EOLib.Graphics/GFXTypes.cs b/EOLib.Graphics/GFXTypes.cs index a6dfe46b1..7e63789c0 100644 --- a/EOLib.Graphics/GFXTypes.cs +++ b/EOLib.Graphics/GFXTypes.cs @@ -103,4 +103,4 @@ public enum GFXTypes /// SpellIcons } -} +} \ No newline at end of file diff --git a/EOLib.Graphics/IGraphicsDeviceRepository.cs b/EOLib.Graphics/IGraphicsDeviceRepository.cs index 91b67d8ad..994b89848 100644 --- a/EOLib.Graphics/IGraphicsDeviceRepository.cs +++ b/EOLib.Graphics/IGraphicsDeviceRepository.cs @@ -26,4 +26,4 @@ public class GraphicsDeviceRepository : IGraphicsDeviceRepository, IGraphicsDevi public GraphicsDeviceManager GraphicsDeviceManager { get; set; } } -} +} \ No newline at end of file diff --git a/EOLib.Graphics/INativeGraphicsLoader.cs b/EOLib.Graphics/INativeGraphicsLoader.cs index d24b705c7..e1f6b4613 100644 --- a/EOLib.Graphics/INativeGraphicsLoader.cs +++ b/EOLib.Graphics/INativeGraphicsLoader.cs @@ -6,4 +6,4 @@ public interface INativeGraphicsLoader { ReadOnlyMemory LoadGFX(GFXTypes file, int resourceValue); } -} +} \ No newline at end of file diff --git a/EOLib.Graphics/INativeGraphicsManager.cs b/EOLib.Graphics/INativeGraphicsManager.cs index c5f55313f..369272294 100644 --- a/EOLib.Graphics/INativeGraphicsManager.cs +++ b/EOLib.Graphics/INativeGraphicsManager.cs @@ -1,5 +1,5 @@ -using System; -using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Graphics; +using System; namespace EOLib.Graphics { @@ -17,4 +17,4 @@ public interface INativeGraphicsManager : IDisposable /// Texture2D containing the image from the *.egf file Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transparent = false, bool reloadFromFile = false, bool fullTransparent = false); } -} +} \ No newline at end of file diff --git a/EOLib.Graphics/LibraryLoadException.cs b/EOLib.Graphics/LibraryLoadException.cs index 503f33192..313fe9bf5 100644 --- a/EOLib.Graphics/LibraryLoadException.cs +++ b/EOLib.Graphics/LibraryLoadException.cs @@ -16,4 +16,4 @@ public LibraryLoadException(string libraryNumber, GFXTypes which) WhichGFX = which; } } -} +} \ No newline at end of file diff --git a/EOLib.Graphics/NativeGraphicsLoader.cs b/EOLib.Graphics/NativeGraphicsLoader.cs index b201051f0..208c961b4 100644 --- a/EOLib.Graphics/NativeGraphicsLoader.cs +++ b/EOLib.Graphics/NativeGraphicsLoader.cs @@ -39,4 +39,4 @@ public ReadOnlyMemory LoadGFX(GFXTypes file, int resourceValue) return fileBytes; } } -} +} \ No newline at end of file diff --git a/EOLib.Graphics/NativeGraphicsManager.cs b/EOLib.Graphics/NativeGraphicsManager.cs index 4cbcef2d2..9e68c5513 100644 --- a/EOLib.Graphics/NativeGraphicsManager.cs +++ b/EOLib.Graphics/NativeGraphicsManager.cs @@ -136,6 +136,6 @@ public void Dispose() public class GFXLoadException : Exception { public GFXLoadException(int resource, GFXTypes gfx) - : base($"Unable to load graphic {resource + 100} from file gfx{(int) gfx:000}.egf") { } + : base($"Unable to load graphic {resource + 100} from file gfx{(int)gfx:000}.egf") { } } -} +} \ No newline at end of file diff --git a/EOLib.Graphics/PEFileCollection.cs b/EOLib.Graphics/PEFileCollection.cs index f9121d3c1..01671d0d4 100644 --- a/EOLib.Graphics/PEFileCollection.cs +++ b/EOLib.Graphics/PEFileCollection.cs @@ -1,8 +1,8 @@ -using System; +using AutomaticTypeMapper; +using PELoaderLib; +using System; using System.Collections.Generic; using System.IO; -using AutomaticTypeMapper; -using PELoaderLib; namespace EOLib.Graphics { @@ -35,4 +35,4 @@ public interface IPEFileCollection : IDictionary, IDisposable { void PopulateCollectionWithStandardGFX(); } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/EIFRecordExtensionsTest.cs b/EOLib.IO.Test/EIFRecordExtensionsTest.cs index bb14d36a8..d0dc6f4d2 100644 --- a/EOLib.IO.Test/EIFRecordExtensionsTest.cs +++ b/EOLib.IO.Test/EIFRecordExtensionsTest.cs @@ -1,7 +1,7 @@ -using System.Diagnostics.CodeAnalysis; -using EOLib.IO.Extensions; +using EOLib.IO.Extensions; using EOLib.IO.Pub; using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; namespace EOLib.IO.Test { @@ -45,4 +45,4 @@ public void GetEquipLocation_Unsupported_ReturnsPaperdollMax(ItemType type) private static EIFRecord WithItemType(ItemType type) => (EIFRecord)new EIFRecord().WithProperty(PubRecordProperty.ItemType, (int)type); } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Map/MapFilePropertiesTest.cs b/EOLib.IO.Test/Map/MapFilePropertiesTest.cs index 49cfbe460..08a70bc5f 100644 --- a/EOLib.IO.Test/Map/MapFilePropertiesTest.cs +++ b/EOLib.IO.Test/Map/MapFilePropertiesTest.cs @@ -1,14 +1,14 @@ -using System; +using EOLib.IO.Map; +using EOLib.IO.Services; +using EOLib.IO.Services.Serializers; +using NUnit.Framework; +using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Text; -using EOLib.IO.Map; -using EOLib.IO.Services; -using EOLib.IO.Services.Serializers; -using NUnit.Framework; namespace EOLib.IO.Test.Map { @@ -80,20 +80,20 @@ public void MapFileProperties_CustomProperties_NotChangedWhenDeserialized() [Test] public void MapFileProperties_DeserializeFromByteArray_ThrowsExceptionWhenIncorrectSize() { - var bytes = new byte[] {1, 2}; + var bytes = new byte[] { 1, 2 }; Assert.Throws(() => _mapPropertiesSerializer.DeserializeFromByteArray(bytes)); } [Test] public void MapFileProperties_DeserializeFromByteArray_ThrowsExceptionWhenNotEMF() { - var bytes = Enumerable.Repeat((byte) 254, MapFileProperties.DATA_SIZE).ToArray(); + var bytes = Enumerable.Repeat((byte)254, MapFileProperties.DATA_SIZE).ToArray(); Assert.Throws(() => _mapPropertiesSerializer.DeserializeFromByteArray(bytes)); } private static IMapFileProperties CreateMapPropertiesWithSomeTestData(IMapFileProperties props) { - return props.WithChecksum(new List {1, 2}) + return props.WithChecksum(new List { 1, 2 }) .WithName("Some test name") .WithWidth(200) .WithHeight(100) @@ -118,7 +118,7 @@ private static byte[] CreateExpectedBytes(IMapFileProperties props) ret.AddRange(Encoding.ASCII.GetBytes(props.FileType)); ret.AddRange(props.Checksum.SelectMany(x => numberEncoderService.EncodeNumber(x, 2))); - + var fullName = Enumerable.Repeat((byte)0xFF, 24).ToArray(); var encodedName = mapStringEncoderService.EncodeMapString(props.Name, props.Name.Length); Array.Copy(encodedName, 0, fullName, fullName.Length - encodedName.Length, encodedName.Length); @@ -141,4 +141,4 @@ private static byte[] CreateExpectedBytes(IMapFileProperties props) return ret.ToArray(); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Map/MapFileTest.cs b/EOLib.IO.Test/Map/MapFileTest.cs index 4d7265fba..7b4d7e272 100644 --- a/EOLib.IO.Test/Map/MapFileTest.cs +++ b/EOLib.IO.Test/Map/MapFileTest.cs @@ -1,11 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using EOLib.IO.Map; +using EOLib.IO.Map; using EOLib.IO.Services; using EOLib.IO.Services.Serializers; using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; namespace EOLib.IO.Test.Map { @@ -156,7 +156,7 @@ private byte[] CreateDataForMap(IMapFileProperties mapFileProperties, TileSpec s ret.AddRange(nes.EncodeNumber(0, 1)); //count //gfx - foreach (var layer in (MapLayer[]) Enum.GetValues(typeof(MapLayer))) + foreach (var layer in (MapLayer[])Enum.GetValues(typeof(MapLayer))) { ret.AddRange(nes.EncodeNumber(1, 1)); //count ret.AddRange(nes.EncodeNumber(1, 1)); //y @@ -170,4 +170,4 @@ private byte[] CreateDataForMap(IMapFileProperties mapFileProperties, TileSpec s return ret.ToArray(); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs b/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs index abcaf6d8c..c335b98c5 100644 --- a/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs +++ b/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs @@ -1,9 +1,9 @@ -using System; +using EOLib.IO.Services; +using NUnit.Framework; +using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; -using EOLib.IO.Services; -using NUnit.Framework; namespace EOLib.IO.Test.Map { @@ -48,8 +48,8 @@ public void DecodeString_ReturnsExpectedString_FromKnownBytes() { const string expected = "Aeven"; - var bytes = new byte[] {49, 104, 41, 104, 94}; - var fullBytes = Enumerable.Repeat((byte) 255, 24).ToArray(); + var bytes = new byte[] { 49, 104, 41, 104, 94 }; + var fullBytes = Enumerable.Repeat((byte)255, 24).ToArray(); Array.Copy(bytes, 0, fullBytes, fullBytes.Length - bytes.Length, bytes.Length); var actual = _service.DecodeMapString(fullBytes); @@ -91,4 +91,4 @@ public void EncodeString_ExtraLength_DecodesToExpectedValue() Assert.That(original, Is.EqualTo(TestString)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Properties/AssemblyInfo.cs b/EOLib.IO.Test/Properties/AssemblyInfo.cs index 26231ee6d..390ee92dd 100644 --- a/EOLib.IO.Test/Properties/AssemblyInfo.cs +++ b/EOLib.IO.Test/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/BasePubFileTest.cs b/EOLib.IO.Test/Pub/BasePubFileTest.cs index c1effa031..e134471e7 100644 --- a/EOLib.IO.Test/Pub/BasePubFileTest.cs +++ b/EOLib.IO.Test/Pub/BasePubFileTest.cs @@ -172,4 +172,4 @@ public void WithRemovedRecord_IDOutOfrange_ThrowsArgumentException() Assert.That(() => file.WithRemovedRecord((U)record.WithID(2)), Throws.ArgumentException); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ECFFileTest.cs b/EOLib.IO.Test/Pub/ECFFileTest.cs index 88d0622bc..62f571cb2 100644 --- a/EOLib.IO.Test/Pub/ECFFileTest.cs +++ b/EOLib.IO.Test/Pub/ECFFileTest.cs @@ -13,4 +13,4 @@ public void HasCorrectFileType() Assert.That(new ECFFile().FileType, Is.EqualTo("ECF")); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ECFRecordTest.cs b/EOLib.IO.Test/Pub/ECFRecordTest.cs index beb111628..76566a938 100644 --- a/EOLib.IO.Test/Pub/ECFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ECFRecordTest.cs @@ -31,4 +31,4 @@ public void ECFRecord_HasExpectedDataSize() Assert.That(new ECFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/EIFFileTest.cs b/EOLib.IO.Test/Pub/EIFFileTest.cs index 00c1209da..bb2f90cac 100644 --- a/EOLib.IO.Test/Pub/EIFFileTest.cs +++ b/EOLib.IO.Test/Pub/EIFFileTest.cs @@ -13,4 +13,4 @@ public void HasCorrectFileType() Assert.That(new EIFFile().FileType, Is.EqualTo("EIF")); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/EIFRecordTest.cs b/EOLib.IO.Test/Pub/EIFRecordTest.cs index 45710d4cd..e3840beea 100644 --- a/EOLib.IO.Test/Pub/EIFRecordTest.cs +++ b/EOLib.IO.Test/Pub/EIFRecordTest.cs @@ -31,4 +31,4 @@ public void EIFRecord_HasExpectedDataSize() Assert.That(new EIFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ENFFileTest.cs b/EOLib.IO.Test/Pub/ENFFileTest.cs index a9ba82954..89d74be44 100644 --- a/EOLib.IO.Test/Pub/ENFFileTest.cs +++ b/EOLib.IO.Test/Pub/ENFFileTest.cs @@ -13,4 +13,4 @@ public void HasCorrectFileType() Assert.That(new ENFFile().FileType, Is.EqualTo("ENF")); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ENFRecordTest.cs b/EOLib.IO.Test/Pub/ENFRecordTest.cs index c15ba99c1..175effd1c 100644 --- a/EOLib.IO.Test/Pub/ENFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ENFRecordTest.cs @@ -31,4 +31,4 @@ public void ENFRecord_HasExpectedDataSize() Assert.That(new ENFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ESFFileTest.cs b/EOLib.IO.Test/Pub/ESFFileTest.cs index 85715868f..ec0bfca2d 100644 --- a/EOLib.IO.Test/Pub/ESFFileTest.cs +++ b/EOLib.IO.Test/Pub/ESFFileTest.cs @@ -13,4 +13,4 @@ public void HasCorrectFileType() Assert.That(new ESFFile().FileType, Is.EqualTo("ESF")); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ESFRecordTest.cs b/EOLib.IO.Test/Pub/ESFRecordTest.cs index aa2d1dc50..361c8c8b5 100644 --- a/EOLib.IO.Test/Pub/ESFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ESFRecordTest.cs @@ -31,4 +31,4 @@ public void ESFRecord_HasExpectedDataSize() Assert.That(new ESFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs b/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs index 9119c8a7f..d27c0a779 100644 --- a/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs +++ b/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs @@ -140,4 +140,4 @@ private static IPubFileSerializer CreateSerializer() return new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); } } -} +} \ No newline at end of file diff --git a/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs b/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs index 9e61634ec..cc0efb3b0 100644 --- a/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs +++ b/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs @@ -59,4 +59,4 @@ private static IPubRecordSerializer Create() return new PubRecordSerializer(new NumberEncoderService()); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Actions/IMapFileLoadActions.cs b/EOLib.IO/Actions/IMapFileLoadActions.cs index 3cae30785..3810934cd 100644 --- a/EOLib.IO/Actions/IMapFileLoadActions.cs +++ b/EOLib.IO/Actions/IMapFileLoadActions.cs @@ -6,4 +6,4 @@ public interface IMapFileLoadActions void LoadMapFileByName(string fileName); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Actions/IPubFileLoadActions.cs b/EOLib.IO/Actions/IPubFileLoadActions.cs index d633276fc..9a39f3532 100644 --- a/EOLib.IO/Actions/IPubFileLoadActions.cs +++ b/EOLib.IO/Actions/IPubFileLoadActions.cs @@ -20,4 +20,4 @@ public interface IPubFileLoadActions void LoadClassFileByName(string fileName); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Actions/MapFileLoadActions.cs b/EOLib.IO/Actions/MapFileLoadActions.cs index 718b81bea..4bf2165cd 100644 --- a/EOLib.IO/Actions/MapFileLoadActions.cs +++ b/EOLib.IO/Actions/MapFileLoadActions.cs @@ -38,4 +38,4 @@ private void AddMapToCache(IMapFile mapFile) _mapFileRepository.MapFiles.Add(mapFile.Properties.MapID, mapFile); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Caster.cs b/EOLib.IO/Caster.cs index a05496011..6305bac0a 100644 --- a/EOLib.IO/Caster.cs +++ b/EOLib.IO/Caster.cs @@ -34,4 +34,4 @@ private static Func Get() } } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Crc.cs b/EOLib.IO/Crc.cs index 065038db3..bf463607b 100644 --- a/EOLib.IO/Crc.cs +++ b/EOLib.IO/Crc.cs @@ -6,7 +6,7 @@ public static class CRC32 /// This value is used to 'seed' the CRC. It is a polynomial in integer format. It is set to a default when CRC32 is instantiated. /// public static uint Magic { get; set; } - + //lookup table for the CRC private static uint[] lookup = new uint[256]; @@ -75,4 +75,4 @@ public static uint Check(byte[] data, uint offset, uint length) return crc ^ 0xFFFFFFFF; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Extensions/EIFRecordExtensions.cs b/EOLib.IO/Extensions/EIFRecordExtensions.cs index effa61de9..5e596a8b3 100644 --- a/EOLib.IO/Extensions/EIFRecordExtensions.cs +++ b/EOLib.IO/Extensions/EIFRecordExtensions.cs @@ -37,4 +37,4 @@ public static EquipLocation GetEquipLocation(this EIFRecord record) } } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Extensions/ItemSizeExtensions.cs b/EOLib.IO/Extensions/ItemSizeExtensions.cs index 56a14d1aa..807c4f304 100644 --- a/EOLib.IO/Extensions/ItemSizeExtensions.cs +++ b/EOLib.IO/Extensions/ItemSizeExtensions.cs @@ -18,4 +18,4 @@ public static (int Width, int Height) GetDimensions(this ItemSize itemSize) return (width, height); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Extensions/PubFileExtensions.cs b/EOLib.IO/Extensions/PubFileExtensions.cs index 374726d4e..7ab752562 100644 --- a/EOLib.IO/Extensions/PubFileExtensions.cs +++ b/EOLib.IO/Extensions/PubFileExtensions.cs @@ -17,7 +17,7 @@ public static class PubFileExtensions /// The merged pub file. /// Thrown when does not have at least one element. public static IPubFile Merge(IEnumerable> pubFiles) - where TRecord: class, IPubRecord, new() + where TRecord : class, IPubRecord, new() { if (pubFiles.Count() < 1) throw new ArgumentException("pubFiles must have at least 1 element", nameof(pubFiles)); @@ -34,4 +34,4 @@ public static IPubFile Merge(IEnumerable> pu return (IPubFile)mergedFile.WithTotalLength(pubFiles.Select(x => x.Length).Sum()); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Extensions/TileSpecExtensions.cs b/EOLib.IO/Extensions/TileSpecExtensions.cs index b81c00924..60a8c85ed 100644 --- a/EOLib.IO/Extensions/TileSpecExtensions.cs +++ b/EOLib.IO/Extensions/TileSpecExtensions.cs @@ -14,4 +14,4 @@ public static bool IsChair(this TileSpec tileSpec) return tileSpec >= (TileSpec)1 && tileSpec <= (TileSpec)7; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/ChestSpawnMapEntity.cs b/EOLib.IO/Map/ChestSpawnMapEntity.cs index 4ed2984bb..498ea33ca 100644 --- a/EOLib.IO/Map/ChestSpawnMapEntity.cs +++ b/EOLib.IO/Map/ChestSpawnMapEntity.cs @@ -94,4 +94,4 @@ private static ChestSpawnMapEntity MakeCopy(ChestSpawnMapEntity src) src.X, src.Y, src.Key, src.Slot, src.ItemID, src.RespawnTime, src.Amount); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/IMapEntity.cs b/EOLib.IO/Map/IMapEntity.cs index e6a3b91ee..ec75ce875 100644 --- a/EOLib.IO/Map/IMapEntity.cs +++ b/EOLib.IO/Map/IMapEntity.cs @@ -6,4 +6,4 @@ public interface IMapEntity int Y { get; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/IMapFile.cs b/EOLib.IO/Map/IMapFile.cs index c5292854d..045008daa 100644 --- a/EOLib.IO/Map/IMapFile.cs +++ b/EOLib.IO/Map/IMapFile.cs @@ -45,4 +45,4 @@ public interface IMapFile IMapFile RemoveWarpAt(int x, int y); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/MapFile.cs b/EOLib.IO/Map/MapFile.cs index 9aae4c7ea..7ce13f7c7 100644 --- a/EOLib.IO/Map/MapFile.cs +++ b/EOLib.IO/Map/MapFile.cs @@ -47,7 +47,7 @@ public MapFile() new List(), new List()) { - foreach (var layer in (MapLayer[]) Enum.GetValues(typeof(MapLayer))) + foreach (var layer in (MapLayer[])Enum.GetValues(typeof(MapLayer))) _mutableGFX.Add(layer, Matrix.Empty); SetReadOnlyGFX(); } @@ -211,4 +211,4 @@ private void SetReadOnlyGFX() _readOnlyEmptyGFXRows = _mutableEmptyGFXRows.ToDictionary(k => k.Key, v => (IReadOnlyList)v.Value); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/MapFileProperties.cs b/EOLib.IO/Map/MapFileProperties.cs index 94d9a4fdf..01dd91b4a 100644 --- a/EOLib.IO/Map/MapFileProperties.cs +++ b/EOLib.IO/Map/MapFileProperties.cs @@ -194,5 +194,4 @@ private MapFileProperties Clone() }; } } -} - +} \ No newline at end of file diff --git a/EOLib.IO/Map/MapPathToIDConverter.cs b/EOLib.IO/Map/MapPathToIDConverter.cs index a0e711785..c8c81cc34 100644 --- a/EOLib.IO/Map/MapPathToIDConverter.cs +++ b/EOLib.IO/Map/MapPathToIDConverter.cs @@ -14,4 +14,4 @@ public int ConvertFromPathToID(string pathToMapFile) return int.Parse(strID); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/Matrix.cs b/EOLib.IO/Map/Matrix.cs index b58856456..e70d2cc49 100644 --- a/EOLib.IO/Map/Matrix.cs +++ b/EOLib.IO/Map/Matrix.cs @@ -6,7 +6,7 @@ namespace EOLib.IO.Map { public class Matrix : IReadOnlyMatrix { - private static readonly Matrix _empty = new Matrix(new T[0,0]); + private static readonly Matrix _empty = new Matrix(new T[0, 0]); public static Matrix Empty => _empty; private readonly T[,] _arr; @@ -28,7 +28,7 @@ public Matrix(int rows, int cols, T defaultValue) { _default = defaultValue; Fill(defaultValue); - } + } public Matrix(IReadOnlyMatrix other) : this(new T[other.Rows, other.Cols]) @@ -124,4 +124,4 @@ public void Reset() object IEnumerator.Current => Current; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/MusicControl.cs b/EOLib.IO/Map/MusicControl.cs index e09769803..2bed57c80 100644 --- a/EOLib.IO/Map/MusicControl.cs +++ b/EOLib.IO/Map/MusicControl.cs @@ -31,4 +31,4 @@ public enum MusicControl : byte // * Interrupt all music and does not play music for this map. TurnOff = 6, } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/NPCSpawnMapEntity.cs b/EOLib.IO/Map/NPCSpawnMapEntity.cs index dcc250087..fa3bc2ef9 100644 --- a/EOLib.IO/Map/NPCSpawnMapEntity.cs +++ b/EOLib.IO/Map/NPCSpawnMapEntity.cs @@ -83,4 +83,4 @@ private static NPCSpawnMapEntity MakeCopy(NPCSpawnMapEntity src) src.X, src.Y, src.ID, src.SpawnType, src.RespawnTime, src.Amount); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/SignMapEntity.cs b/EOLib.IO/Map/SignMapEntity.cs index 6e83a82df..821ecdddc 100644 --- a/EOLib.IO/Map/SignMapEntity.cs +++ b/EOLib.IO/Map/SignMapEntity.cs @@ -69,4 +69,4 @@ private static SignMapEntity MakeCopy(SignMapEntity src) return new SignMapEntity(src.X, src.Y, src.Title, src.Message, src.RawLength); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/UnknownMapEntity.cs b/EOLib.IO/Map/UnknownMapEntity.cs index 2097a4415..7b1b61de5 100644 --- a/EOLib.IO/Map/UnknownMapEntity.cs +++ b/EOLib.IO/Map/UnknownMapEntity.cs @@ -51,4 +51,4 @@ private static UnknownMapEntity MakeCopy(UnknownMapEntity src) return new UnknownMapEntity(src.X, src.Y, copy); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Map/WarpMapEntity.cs b/EOLib.IO/Map/WarpMapEntity.cs index 809f026c4..7ad39b1b8 100644 --- a/EOLib.IO/Map/WarpMapEntity.cs +++ b/EOLib.IO/Map/WarpMapEntity.cs @@ -100,4 +100,4 @@ private static WarpMapEntity MakeCopy(WarpMapEntity src) src.DoorType); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/NPCType.cs b/EOLib.IO/NPCType.cs index b84d73073..e2a975e88 100644 --- a/EOLib.IO/NPCType.cs +++ b/EOLib.IO/NPCType.cs @@ -20,4 +20,4 @@ public enum NPCType Quest, NONE } -} +} \ No newline at end of file diff --git a/EOLib.IO/NumericConstants.cs b/EOLib.IO/NumericConstants.cs index c82c4f856..1e17c1dcf 100644 --- a/EOLib.IO/NumericConstants.cs +++ b/EOLib.IO/NumericConstants.cs @@ -10,6 +10,6 @@ public static class NumericConstants public const uint THREE_BYTE_MAX = ONE_BYTE_MAX * ONE_BYTE_MAX * ONE_BYTE_MAX; public const uint FOUR_BYTE_MAX = ONE_BYTE_MAX * ONE_BYTE_MAX * ONE_BYTE_MAX * ONE_BYTE_MAX; - public static readonly uint[] NUMERIC_MAXIMUM = {ONE_BYTE_MAX, TWO_BYTE_MAX, THREE_BYTE_MAX, FOUR_BYTE_MAX }; + public static readonly uint[] NUMERIC_MAXIMUM = { ONE_BYTE_MAX, TWO_BYTE_MAX, THREE_BYTE_MAX, FOUR_BYTE_MAX }; } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/BasePubFile.cs b/EOLib.IO/Pub/BasePubFile.cs index 18c9d5f9d..fd7e09517 100644 --- a/EOLib.IO/Pub/BasePubFile.cs +++ b/EOLib.IO/Pub/BasePubFile.cs @@ -143,4 +143,4 @@ private static void AdjustIDs(List data) data[i] = (TRecord)data[i].WithID(i + 1); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/ECFFile.cs b/EOLib.IO/Pub/ECFFile.cs index b5fabf506..50ce25396 100644 --- a/EOLib.IO/Pub/ECFFile.cs +++ b/EOLib.IO/Pub/ECFFile.cs @@ -21,4 +21,4 @@ protected override BasePubFile MakeCopy() return new ECFFile(ID, CheckSum, TotalLength, new List(this)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/ECFRecord.cs b/EOLib.IO/Pub/ECFRecord.cs index 84019807b..685156c8c 100644 --- a/EOLib.IO/Pub/ECFRecord.cs +++ b/EOLib.IO/Pub/ECFRecord.cs @@ -1,10 +1,10 @@ -using System; +using EOLib.IO.Services; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; -using EOLib.IO.Services; namespace EOLib.IO.Pub { @@ -40,4 +40,4 @@ protected override PubRecord MakeCopy(List names, Dictionary(names), new Dictionary(propertyBag)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/EIFFile.cs b/EOLib.IO/Pub/EIFFile.cs index 499a3c644..653af4111 100644 --- a/EOLib.IO/Pub/EIFFile.cs +++ b/EOLib.IO/Pub/EIFFile.cs @@ -12,7 +12,7 @@ public EIFFile() } public EIFFile(int id, IReadOnlyList checksum, int totalLength, List data) - : base (id, checksum, totalLength, data) + : base(id, checksum, totalLength, data) { } @@ -21,4 +21,4 @@ protected override BasePubFile MakeCopy() return new EIFFile(ID, CheckSum, TotalLength, new List(this)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/EIFRecord.cs b/EOLib.IO/Pub/EIFRecord.cs index 61e3e1af5..d18253f34 100644 --- a/EOLib.IO/Pub/EIFRecord.cs +++ b/EOLib.IO/Pub/EIFRecord.cs @@ -72,7 +72,7 @@ public EIFRecord() } public EIFRecord(int id, string name) - : base (id, name, PubRecordProperty.Item) + : base(id, name, PubRecordProperty.Item) { } diff --git a/EOLib.IO/Pub/ENFFile.cs b/EOLib.IO/Pub/ENFFile.cs index a6f9dcc23..fe0cb8a38 100644 --- a/EOLib.IO/Pub/ENFFile.cs +++ b/EOLib.IO/Pub/ENFFile.cs @@ -21,4 +21,4 @@ protected override BasePubFile MakeCopy() return new ENFFile(ID, CheckSum, TotalLength, new List(this)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/ESFFile.cs b/EOLib.IO/Pub/ESFFile.cs index e49601565..765271c4a 100644 --- a/EOLib.IO/Pub/ESFFile.cs +++ b/EOLib.IO/Pub/ESFFile.cs @@ -21,4 +21,4 @@ protected override BasePubFile MakeCopy() return new ESFFile(ID, CheckSum, TotalLength, new List(this)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/IPubFile.cs b/EOLib.IO/Pub/IPubFile.cs index 15cd71368..e43d09da4 100644 --- a/EOLib.IO/Pub/IPubFile.cs +++ b/EOLib.IO/Pub/IPubFile.cs @@ -47,7 +47,7 @@ public interface IPubFile /// /// The file ID. Typically this will be set to 1, but will increase incrementally for chunked pub files. /// - int ID { get; } + int ID { get; } /// /// The type of the file, usually a 3-character string e.g. EIF/ENF/ESF/ECF @@ -91,4 +91,4 @@ public interface IPubFile /// The updated pub file. IPubFile WithTotalLength(int totalLength); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/PubRecord.cs b/EOLib.IO/Pub/PubRecord.cs index a23f88d53..e9d92c026 100644 --- a/EOLib.IO/Pub/PubRecord.cs +++ b/EOLib.IO/Pub/PubRecord.cs @@ -47,7 +47,7 @@ public PubRecord(int id, List names, Dictionary(() => _propertyBag.Values .GroupBy(x => x.Offset) .Select(x => x.First().Length) @@ -116,7 +116,7 @@ public override bool Equals(object obj) var namesMatch = true; for (int i = 0; i < NumberOfNames; i++) namesMatch &= Names[i] == pr.Names[i]; - + return namesMatch && Bag.Intersect(pr.Bag).Count() == Bag.Count; } @@ -157,4 +157,4 @@ private static Dictionary GetPropertiesWithFlag(P .ToDictionary(k => k.Key, v => new RecordData(v.Value.Offset, v.Value.Length, 0)); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/PubRecordProperty.cs b/EOLib.IO/Pub/PubRecordProperty.cs index 00f74bfbe..63c135460 100644 --- a/EOLib.IO/Pub/PubRecordProperty.cs +++ b/EOLib.IO/Pub/PubRecordProperty.cs @@ -265,4 +265,4 @@ public enum PubRecordProperty : uint [RecordData(12, 2)] ClassCha } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/RecordData.cs b/EOLib.IO/Pub/RecordData.cs index e07b4f5c4..5869f2852 100644 --- a/EOLib.IO/Pub/RecordData.cs +++ b/EOLib.IO/Pub/RecordData.cs @@ -43,4 +43,4 @@ public override string ToString() return $"{Offset} {Length} {Value}"; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Pub/RecordDataAttribute.cs b/EOLib.IO/Pub/RecordDataAttribute.cs index 664604e95..3c2bc2e01 100644 --- a/EOLib.IO/Pub/RecordDataAttribute.cs +++ b/EOLib.IO/Pub/RecordDataAttribute.cs @@ -15,4 +15,4 @@ public RecordDataAttribute(int offset, int length) Length = length; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/PubFileNameConstants.cs b/EOLib.IO/PubFileNameConstants.cs index 28708da13..1a0da2d6b 100644 --- a/EOLib.IO/PubFileNameConstants.cs +++ b/EOLib.IO/PubFileNameConstants.cs @@ -16,4 +16,4 @@ public static class PubFileNameConstants public const string ECFFormat = "pub/dat{0,3:D3}.ecf"; public const string ECFFilter = "dat*.ecf"; } -} +} \ No newline at end of file diff --git a/EOLib.IO/Repositories/IMapFileRepository.cs b/EOLib.IO/Repositories/IMapFileRepository.cs index 1fb62752d..b28d9d189 100644 --- a/EOLib.IO/Repositories/IMapFileRepository.cs +++ b/EOLib.IO/Repositories/IMapFileRepository.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.IO.Map; +using System.Collections.Generic; namespace EOLib.IO.Repositories { diff --git a/EOLib.IO/Repositories/IPubFileProvider.cs b/EOLib.IO/Repositories/IPubFileProvider.cs index b3a215a05..7dc2c834f 100644 --- a/EOLib.IO/Repositories/IPubFileProvider.cs +++ b/EOLib.IO/Repositories/IPubFileProvider.cs @@ -25,4 +25,4 @@ public interface IECFFileProvider { IPubFile ECFFile { get; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Repositories/IPubFileRepository.cs b/EOLib.IO/Repositories/IPubFileRepository.cs index c8489df5e..be3485cf9 100644 --- a/EOLib.IO/Repositories/IPubFileRepository.cs +++ b/EOLib.IO/Repositories/IPubFileRepository.cs @@ -30,4 +30,4 @@ public interface IECFFileRepository IPubFile ECFFile { get; set; } List> ECFFiles { get; set; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/BasePubLoadService.cs b/EOLib.IO/Services/BasePubLoadService.cs index 80cd6f0d8..0e0667ddf 100644 --- a/EOLib.IO/Services/BasePubLoadService.cs +++ b/EOLib.IO/Services/BasePubLoadService.cs @@ -1,8 +1,8 @@ using EOLib.IO.Pub; using EOLib.IO.Services.Serializers; +using System; using System.Collections.Generic; using System.IO; -using System; namespace EOLib.IO.Services { @@ -41,4 +41,4 @@ public IEnumerable> LoadPubFromExplicitFile(string directory, protected abstract IPubFile Factory(); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/ClassFileLoadService.cs b/EOLib.IO/Services/ClassFileLoadService.cs index 3b1478861..6373797de 100644 --- a/EOLib.IO/Services/ClassFileLoadService.cs +++ b/EOLib.IO/Services/ClassFileLoadService.cs @@ -16,4 +16,4 @@ public ClassFileLoadService(IPubFileDeserializer pubFileDeserializer) protected override IPubFile Factory() => new ECFFile(); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/IMapFileLoadService.cs b/EOLib.IO/Services/IMapFileLoadService.cs index 8cfa46a0d..52dc47f01 100644 --- a/EOLib.IO/Services/IMapFileLoadService.cs +++ b/EOLib.IO/Services/IMapFileLoadService.cs @@ -8,4 +8,4 @@ public interface IMapFileLoadService IMapFile LoadMapByPath(string pathToMapFile); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/IMapFileSaveService.cs b/EOLib.IO/Services/IMapFileSaveService.cs index 13831ce1d..fb1cc8f7e 100644 --- a/EOLib.IO/Services/IMapFileSaveService.cs +++ b/EOLib.IO/Services/IMapFileSaveService.cs @@ -8,4 +8,4 @@ public interface IMapFileSaveService void SaveFile(string path, IMapFile pubFile, bool rewriteChecksum = true); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/IMapStringEncoderService.cs b/EOLib.IO/Services/IMapStringEncoderService.cs index 15749a993..d98591075 100644 --- a/EOLib.IO/Services/IMapStringEncoderService.cs +++ b/EOLib.IO/Services/IMapStringEncoderService.cs @@ -6,4 +6,4 @@ public interface IMapStringEncoderService byte[] EncodeMapString(string s, int length); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/INumberEncoderService.cs b/EOLib.IO/Services/INumberEncoderService.cs index d9379bfff..179811eb8 100644 --- a/EOLib.IO/Services/INumberEncoderService.cs +++ b/EOLib.IO/Services/INumberEncoderService.cs @@ -6,4 +6,4 @@ public interface INumberEncoderService int DecodeNumber(params byte[] b); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/IPubFileSaveService.cs b/EOLib.IO/Services/IPubFileSaveService.cs index f0add58e8..7f335dd5f 100644 --- a/EOLib.IO/Services/IPubFileSaveService.cs +++ b/EOLib.IO/Services/IPubFileSaveService.cs @@ -7,4 +7,4 @@ public interface IPubFileSaveService void SaveFile(string path, IPubFile pubFile, bool rewriteChecksum = true) where TRecord : class, IPubRecord, new(); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/IPubLoadService.cs b/EOLib.IO/Services/IPubLoadService.cs index 11aa7ff3e..9cdc07737 100644 --- a/EOLib.IO/Services/IPubLoadService.cs +++ b/EOLib.IO/Services/IPubLoadService.cs @@ -10,4 +10,4 @@ public interface IPubLoadService IEnumerable> LoadPubFromExplicitFile(string directory, string fileName); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/ItemFileLoadService.cs b/EOLib.IO/Services/ItemFileLoadService.cs index 432bc3e9e..5f889c4cf 100644 --- a/EOLib.IO/Services/ItemFileLoadService.cs +++ b/EOLib.IO/Services/ItemFileLoadService.cs @@ -16,4 +16,4 @@ public ItemFileLoadService(IPubFileDeserializer pubFileDeserializer) protected override IPubFile Factory() => new EIFFile(); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/MapFileLoadService.cs b/EOLib.IO/Services/MapFileLoadService.cs index ac859dcf9..7632e56b0 100644 --- a/EOLib.IO/Services/MapFileLoadService.cs +++ b/EOLib.IO/Services/MapFileLoadService.cs @@ -1,7 +1,7 @@ -using System.IO; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.IO.Map; using EOLib.IO.Services.Serializers; +using System.IO; namespace EOLib.IO.Services { @@ -38,4 +38,4 @@ public IMapFile LoadMapByPath(string pathToMapFile) return mapFile; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/MapFileSaveService.cs b/EOLib.IO/Services/MapFileSaveService.cs index 77aa5011a..fbb2790a4 100644 --- a/EOLib.IO/Services/MapFileSaveService.cs +++ b/EOLib.IO/Services/MapFileSaveService.cs @@ -1,8 +1,8 @@ -using System; -using System.IO; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.IO.Map; using EOLib.IO.Services.Serializers; +using System; +using System.IO; namespace EOLib.IO.Services { diff --git a/EOLib.IO/Services/MapStringEncoderService.cs b/EOLib.IO/Services/MapStringEncoderService.cs index 2f2c19c0a..db9c82a77 100644 --- a/EOLib.IO/Services/MapStringEncoderService.cs +++ b/EOLib.IO/Services/MapStringEncoderService.cs @@ -83,4 +83,4 @@ public byte[] EncodeMapString(string s, int length) return chars; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/NPCFileLoadService.cs b/EOLib.IO/Services/NPCFileLoadService.cs index 6ca58027c..7f4c5b81c 100644 --- a/EOLib.IO/Services/NPCFileLoadService.cs +++ b/EOLib.IO/Services/NPCFileLoadService.cs @@ -16,4 +16,4 @@ public NPCFileLoadService(IPubFileDeserializer pubFileDeserializer) protected override IPubFile Factory() => new ENFFile(); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/NumberEncoderService.cs b/EOLib.IO/Services/NumberEncoderService.cs index 83d915bf7..e86a863de 100644 --- a/EOLib.IO/Services/NumberEncoderService.cs +++ b/EOLib.IO/Services/NumberEncoderService.cs @@ -11,4 +11,4 @@ public class NumberEncoderService : INumberEncoderService public int DecodeNumber(params byte[] b) => NumberEncoder.DecodeNumber(b); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/PubFileSaveService.cs b/EOLib.IO/Services/PubFileSaveService.cs index 8c5094c37..024dfc9ec 100644 --- a/EOLib.IO/Services/PubFileSaveService.cs +++ b/EOLib.IO/Services/PubFileSaveService.cs @@ -1,7 +1,7 @@ -using System.IO; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.IO.Pub; using EOLib.IO.Services.Serializers; +using System.IO; namespace EOLib.IO.Services { diff --git a/EOLib.IO/Services/Serializers/ChestSpawnMapEntitySerializer.cs b/EOLib.IO/Services/Serializers/ChestSpawnMapEntitySerializer.cs index 126169fd7..dad2f552a 100644 --- a/EOLib.IO/Services/Serializers/ChestSpawnMapEntitySerializer.cs +++ b/EOLib.IO/Services/Serializers/ChestSpawnMapEntitySerializer.cs @@ -1,7 +1,7 @@ -using System; -using System.Collections.Generic; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.IO.Map; +using System; +using System.Collections.Generic; namespace EOLib.IO.Services.Serializers { @@ -39,11 +39,11 @@ public ChestSpawnMapEntity DeserializeFromByteArray(byte[] data) return new ChestSpawnMapEntity() .WithX(_numberEncoderService.DecodeNumber(data[0])) .WithY(_numberEncoderService.DecodeNumber(data[1])) - .WithKey((ChestKey) _numberEncoderService.DecodeNumber(data[2], data[3])) + .WithKey((ChestKey)_numberEncoderService.DecodeNumber(data[2], data[3])) .WithSlot(_numberEncoderService.DecodeNumber(data[4])) .WithItemID(_numberEncoderService.DecodeNumber(data[5], data[6])) .WithRespawnTime(_numberEncoderService.DecodeNumber(data[7], data[8])) .WithAmount(_numberEncoderService.DecodeNumber(data[9], data[10], data[11])); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/IMapDeserializer.cs b/EOLib.IO/Services/Serializers/IMapDeserializer.cs index 01f9ed058..ca0608a18 100644 --- a/EOLib.IO/Services/Serializers/IMapDeserializer.cs +++ b/EOLib.IO/Services/Serializers/IMapDeserializer.cs @@ -16,4 +16,4 @@ public interface IMapEntitySerializer : IMapDeserializer { byte[] SerializeToByteArray(T mapEntity); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/IPubFileDeserializer.cs b/EOLib.IO/Services/Serializers/IPubFileDeserializer.cs index 9f9c685be..064e50308 100644 --- a/EOLib.IO/Services/Serializers/IPubFileDeserializer.cs +++ b/EOLib.IO/Services/Serializers/IPubFileDeserializer.cs @@ -14,4 +14,4 @@ public interface IPubFileSerializer : IPubFileDeserializer byte[] SerializeToByteArray(IPubFile file, bool rewriteChecksum = true) where TRecord : class, IPubRecord, new(); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/IPubRecordSerializer.cs b/EOLib.IO/Services/Serializers/IPubRecordSerializer.cs index 5643e64c9..2663bf14d 100644 --- a/EOLib.IO/Services/Serializers/IPubRecordSerializer.cs +++ b/EOLib.IO/Services/Serializers/IPubRecordSerializer.cs @@ -9,4 +9,4 @@ public interface IPubRecordSerializer byte[] SerializeToByteArray(IPubRecord record); } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/MapFileSerializer.cs b/EOLib.IO/Services/Serializers/MapFileSerializer.cs index ac333f553..3ed94b47c 100644 --- a/EOLib.IO/Services/Serializers/MapFileSerializer.cs +++ b/EOLib.IO/Services/Serializers/MapFileSerializer.cs @@ -1,9 +1,9 @@ -using System; +using AutomaticTypeMapper; +using EOLib.IO.Map; +using System; using System.Collections.Generic; using System.IO; using System.Linq; -using AutomaticTypeMapper; -using EOLib.IO.Map; namespace EOLib.IO.Services.Serializers { @@ -428,4 +428,4 @@ private List WriteMapSigns(IMapFile mapFile) #endregion } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/MapPropertiesSerializer.cs b/EOLib.IO/Services/Serializers/MapPropertiesSerializer.cs index 51c92c8f0..bc98c8e80 100644 --- a/EOLib.IO/Services/Serializers/MapPropertiesSerializer.cs +++ b/EOLib.IO/Services/Serializers/MapPropertiesSerializer.cs @@ -1,10 +1,10 @@ -using System; +using AutomaticTypeMapper; +using EOLib.IO.Map; +using Moffat.EndlessOnline.SDK.Data; +using System; using System.Collections.Generic; using System.Linq; using System.Text; -using AutomaticTypeMapper; -using EOLib.IO.Map; -using Moffat.EndlessOnline.SDK.Data; namespace EOLib.IO.Services.Serializers { @@ -72,7 +72,7 @@ public IMapFileProperties DeserializeFromByteArray(byte[] data) .WithName(mapName) .WithPKAvailable(_numberEncoderService.DecodeNumber(data[31]) == 3 || (mapNameArray[0] == 0xFF && mapNameArray[1] == 0x01)) - .WithEffect((MapEffect) _numberEncoderService.DecodeNumber(data[32])) + .WithEffect((MapEffect)_numberEncoderService.DecodeNumber(data[32])) .WithMusic(_numberEncoderService.DecodeNumber(data[33])) .WithControl((MusicControl)_numberEncoderService.DecodeNumber(data[34])) .WithAmbientNoise(_numberEncoderService.DecodeNumber(data[35], data[36])) @@ -101,4 +101,4 @@ private byte[] EncodeMapName(IMapFileProperties mapEntity) return formattedName; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/NPCSpawnMapEntitySerializer.cs b/EOLib.IO/Services/Serializers/NPCSpawnMapEntitySerializer.cs index 0c59c1ac4..a404f8ecb 100644 --- a/EOLib.IO/Services/Serializers/NPCSpawnMapEntitySerializer.cs +++ b/EOLib.IO/Services/Serializers/NPCSpawnMapEntitySerializer.cs @@ -1,7 +1,7 @@ -using System; -using System.Collections.Generic; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.IO.Map; +using System; +using System.Collections.Generic; namespace EOLib.IO.Services.Serializers { @@ -44,4 +44,4 @@ public NPCSpawnMapEntity DeserializeFromByteArray(byte[] data) .WithAmount(_numberEncoderService.DecodeNumber(data[7])); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/PubFileSerializer.cs b/EOLib.IO/Services/Serializers/PubFileSerializer.cs index 2817711f1..bd1977398 100644 --- a/EOLib.IO/Services/Serializers/PubFileSerializer.cs +++ b/EOLib.IO/Services/Serializers/PubFileSerializer.cs @@ -95,7 +95,7 @@ public byte[] SerializeToByteArray(IPubFile file, bool rewrite var checksumBytes = new List(); for (int i = 0; i < file.CheckSum.Count; i++) checksumBytes.AddRange(_numberEncoderService.EncodeNumber(file.CheckSum[i], 2)); - + if (rewriteChecksum) { var checksum = CRC32.Check(fileBytes); @@ -106,4 +106,4 @@ public byte[] SerializeToByteArray(IPubFile file, bool rewrite return fileBytes; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/PubRecordSerializer.cs b/EOLib.IO/Services/Serializers/PubRecordSerializer.cs index d589792d3..94fc7d1ab 100644 --- a/EOLib.IO/Services/Serializers/PubRecordSerializer.cs +++ b/EOLib.IO/Services/Serializers/PubRecordSerializer.cs @@ -75,4 +75,4 @@ public byte[] SerializeToByteArray(IPubRecord record) return retList.ToArray(); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/SignMapEntitySerializer.cs b/EOLib.IO/Services/Serializers/SignMapEntitySerializer.cs index 13b9815a5..c837fc340 100644 --- a/EOLib.IO/Services/Serializers/SignMapEntitySerializer.cs +++ b/EOLib.IO/Services/Serializers/SignMapEntitySerializer.cs @@ -1,8 +1,8 @@ -using System; +using AutomaticTypeMapper; +using EOLib.IO.Map; +using System; using System.Collections.Generic; using System.Linq; -using AutomaticTypeMapper; -using EOLib.IO.Map; namespace EOLib.IO.Services.Serializers { @@ -60,4 +60,4 @@ public SignMapEntity DeserializeFromByteArray(byte[] data) return sign; } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/UnknownMapEntitySerializer.cs b/EOLib.IO/Services/Serializers/UnknownMapEntitySerializer.cs index 55bac9cb3..9ddc299a2 100644 --- a/EOLib.IO/Services/Serializers/UnknownMapEntitySerializer.cs +++ b/EOLib.IO/Services/Serializers/UnknownMapEntitySerializer.cs @@ -1,6 +1,6 @@ -using System; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.IO.Map; +using System; namespace EOLib.IO.Services.Serializers { @@ -18,7 +18,7 @@ public UnknownMapEntitySerializer(INumberEncoderService numberEncoderService) public byte[] SerializeToByteArray(UnknownMapEntity mapEntity) { - if(mapEntity.RawData.Length != UnknownMapEntity.DATA_SIZE) + if (mapEntity.RawData.Length != UnknownMapEntity.DATA_SIZE) throw new ArgumentException("Data is improperly sized for serialization", nameof(mapEntity)); return mapEntity.RawData; @@ -35,4 +35,4 @@ public UnknownMapEntity DeserializeFromByteArray(byte[] data) .WithRawData(data); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/Serializers/WarpMapEntitySerializer.cs b/EOLib.IO/Services/Serializers/WarpMapEntitySerializer.cs index 41c7a8a0d..3afe54795 100644 --- a/EOLib.IO/Services/Serializers/WarpMapEntitySerializer.cs +++ b/EOLib.IO/Services/Serializers/WarpMapEntitySerializer.cs @@ -1,7 +1,7 @@ -using System; -using System.Collections.Generic; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.IO.Map; +using System; +using System.Collections.Generic; namespace EOLib.IO.Services.Serializers { @@ -41,7 +41,7 @@ public WarpMapEntity DeserializeFromByteArray(byte[] data) .WithDestinationMapX(_numberEncoderService.DecodeNumber(data[3])) .WithDestinationMapY(_numberEncoderService.DecodeNumber(data[4])) .WithLevelRequirement(_numberEncoderService.DecodeNumber(data[5])) - .WithDoorType((DoorSpec) _numberEncoderService.DecodeNumber(data[6], data[7])); + .WithDoorType((DoorSpec)_numberEncoderService.DecodeNumber(data[6], data[7])); } } -} +} \ No newline at end of file diff --git a/EOLib.IO/Services/SpellFileLoadService.cs b/EOLib.IO/Services/SpellFileLoadService.cs index 0eb60642f..b03cecf65 100644 --- a/EOLib.IO/Services/SpellFileLoadService.cs +++ b/EOLib.IO/Services/SpellFileLoadService.cs @@ -16,4 +16,4 @@ public SpellFileLoadService(IPubFileDeserializer pubFileDeserializer) protected override IPubFile Factory() => new ESFFile(); } -} +} \ No newline at end of file diff --git a/EOLib.Localization.Test/DataFileLoadActionsTest.cs b/EOLib.Localization.Test/DataFileLoadActionsTest.cs index dd79760b1..ae1b6cb45 100644 --- a/EOLib.Localization.Test/DataFileLoadActionsTest.cs +++ b/EOLib.Localization.Test/DataFileLoadActionsTest.cs @@ -75,4 +75,4 @@ private void GivenEDFFilesInRequiredDirectory(int numberOfFiles = DataFileConsta File.Create(string.Format(Path.Combine(DataFileConstants.DataFilePath, nameFormat), i)).Close(); } } -} +} \ No newline at end of file diff --git a/EOLib.Localization.Test/EDFLoaderServiceTest.cs b/EOLib.Localization.Test/EDFLoaderServiceTest.cs index 9c7a12a0a..763494618 100644 --- a/EOLib.Localization.Test/EDFLoaderServiceTest.cs +++ b/EOLib.Localization.Test/EDFLoaderServiceTest.cs @@ -117,7 +117,7 @@ public void NonSpecialDataFiles_AreDecodedCorrectly(DataFiles whichFile) public void NonSpecialDataFiles_AreDecodedCorrectly_MultipleLines(DataFiles whichFile) { const string fileData = "a7b6cg1f2e3d4 5\na7b6cg1f2e3d4 5"; - var expectedStrings = new[] { "abc12345 defg67", "abc12345 defg67"}; + var expectedStrings = new[] { "abc12345 defg67", "abc12345 defg67" }; GivenDataFileWithContents(FILE_NAME, fileData); @@ -181,7 +181,7 @@ public void NonSpecialDataFiles_Encode_SwapAdjacentCharacterValues_MultiplesOfSe public static DataFiles[] GetStandardEDFFiles() { - return new [] + return new[] { DataFiles.JukeBoxSongs, DataFiles.EnglishStatus1, @@ -206,4 +206,4 @@ private void AssertFileContent(string fileName, string fileData) Assert.That(text, Is.EqualTo(fileData)); } } -} +} \ No newline at end of file diff --git a/EOLib.Localization.Test/LocalizedStringServiceTest.cs b/EOLib.Localization.Test/LocalizedStringServiceTest.cs index 03ccebe97..389b1ef31 100644 --- a/EOLib.Localization.Test/LocalizedStringServiceTest.cs +++ b/EOLib.Localization.Test/LocalizedStringServiceTest.cs @@ -1,9 +1,9 @@ -using System; +using EOLib.Config; +using Moq; +using NUnit.Framework; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using EOLib.Config; -using NUnit.Framework; -using Moq; namespace EOLib.Localization.Test { @@ -29,7 +29,7 @@ public void SetUp() [Test] public void GetString_Dialog_InvalidLanguage_ThrowsArgumentOutOfRangeException() { - Assert.Throws(() => _localizedStringFinder.GetString((EOLanguage) 50, DialogResourceID.ACCOUNT_CREATE_ACCEPTED)); + Assert.Throws(() => _localizedStringFinder.GetString((EOLanguage)50, DialogResourceID.ACCOUNT_CREATE_ACCEPTED)); } [Test] @@ -131,4 +131,4 @@ private void GivenLanguageSetInConfig(EOLanguage language) .Returns(language); } } -} +} \ No newline at end of file diff --git a/EOLib.Localization.Test/Properties/AssemblyInfo.cs b/EOLib.Localization.Test/Properties/AssemblyInfo.cs index 50865fc94..7eb5e6783 100644 --- a/EOLib.Localization.Test/Properties/AssemblyInfo.cs +++ b/EOLib.Localization.Test/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/EOLib.Localization/DataFileConstants.cs b/EOLib.Localization/DataFileConstants.cs index d65a64d24..bcae69818 100644 --- a/EOLib.Localization/DataFileConstants.cs +++ b/EOLib.Localization/DataFileConstants.cs @@ -5,4 +5,4 @@ public static class DataFileConstants public const string DataFilePath = "data/"; public const int ExpectedNumberOfDataFiles = 12; } -} +} \ No newline at end of file diff --git a/EOLib.Localization/DataFileLoadException.cs b/EOLib.Localization/DataFileLoadException.cs index 176e73990..fcef3e680 100644 --- a/EOLib.Localization/DataFileLoadException.cs +++ b/EOLib.Localization/DataFileLoadException.cs @@ -9,4 +9,4 @@ public class DataFileLoadException : Exception public DataFileLoadException() : base(ExceptionMessage) { } } -} +} \ No newline at end of file diff --git a/EOLib.Localization/DataFileRepository.cs b/EOLib.Localization/DataFileRepository.cs index 01bb5966e..c0ac4ebb8 100644 --- a/EOLib.Localization/DataFileRepository.cs +++ b/EOLib.Localization/DataFileRepository.cs @@ -27,4 +27,4 @@ public interface IDataFileProvider { IReadOnlyDictionary DataFiles { get; } } -} +} \ No newline at end of file diff --git a/EOLib.Localization/EDFFile.cs b/EOLib.Localization/EDFFile.cs index 1ca39e8d1..e8cddc425 100644 --- a/EOLib.Localization/EDFFile.cs +++ b/EOLib.Localization/EDFFile.cs @@ -40,4 +40,4 @@ public interface IEDFFile IEDFFile WithDataEntry(int key, string data); } -} +} \ No newline at end of file diff --git a/EOLib.Localization/EOResourceID.cs b/EOLib.Localization/EOResourceID.cs index 2eb7e9a70..f1a70586c 100644 --- a/EOLib.Localization/EOResourceID.cs +++ b/EOLib.Localization/EOResourceID.cs @@ -157,8 +157,8 @@ public enum EOResourceID DIALOG_BARBER_BUY_HAIRSTYLE = 162, DIALOG_WORD_CURRENT = 163, DIALOG_BARBER_DO_YOU_WANT_TO_BUY_A_NEW_HAIRSTYLE = 164, - - + + DIALOG_TRADE_BOTH_PLAYERS_OFFER_ONE_ITEM = 165, DIALOG_TRANSFER_TRANSFER = 176, @@ -349,4 +349,4 @@ public enum EOResourceID DIALOG_BANK_MORE_SPACE = 432, STATUS_LABEL_LOCKER_SPACE_INCREASED = 433, } -} +} \ No newline at end of file diff --git a/EOLib.Localization/LocalizedStringFinder.cs b/EOLib.Localization/LocalizedStringFinder.cs index 12787618c..57dab15ae 100644 --- a/EOLib.Localization/LocalizedStringFinder.cs +++ b/EOLib.Localization/LocalizedStringFinder.cs @@ -1,6 +1,6 @@ -using System; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.Config; +using System; namespace EOLib.Localization { @@ -74,4 +74,4 @@ public interface ILocalizedStringFinder string GetString(DialogResourceID dataConstant); string GetString(EOResourceID dataConstant); } -} +} \ No newline at end of file diff --git a/EOLib.Localization/Services/EDFLoaderService.cs b/EOLib.Localization/Services/EDFLoaderService.cs index e51fa2fd1..b22d9b010 100644 --- a/EOLib.Localization/Services/EDFLoaderService.cs +++ b/EOLib.Localization/Services/EDFLoaderService.cs @@ -27,7 +27,7 @@ public IEDFFile LoadFile(string fileName, DataFiles whichFile) public void SaveFile(string fileName, IEDFFile file) { - switch(file.WhichFile) + switch (file.WhichFile) { case DataFiles.CurseFilter: { @@ -116,4 +116,4 @@ private string EncodeDatString(string content, DataFiles whichFile) return Encoding.ASCII.GetString(res); } } -} +} \ No newline at end of file diff --git a/EOLib.Logger/Constants.cs b/EOLib.Logger/Constants.cs index 3df2bbe1b..749be2d19 100644 --- a/EOLib.Logger/Constants.cs +++ b/EOLib.Logger/Constants.cs @@ -11,4 +11,4 @@ internal static class Constants internal const string LOG_FILE_PATH = LOG_DIRECTORY + "/debug.log"; internal const string LOG_FILE_FMT = LOG_DIRECTORY + "/{0}-debug.log"; } -} +} \ No newline at end of file diff --git a/EOLib.Logger/DebugOnlyLogger.cs b/EOLib.Logger/DebugOnlyLogger.cs index c232609b8..1f40f26ba 100644 --- a/EOLib.Logger/DebugOnlyLogger.cs +++ b/EOLib.Logger/DebugOnlyLogger.cs @@ -1,8 +1,8 @@ -using System; +using EOLib.Config; +using System; using System.Diagnostics; using System.IO; using System.Threading; -using EOLib.Config; namespace EOLib.Logger { @@ -120,4 +120,4 @@ protected virtual void Dispose(bool disposing) } } } -} +} \ No newline at end of file diff --git a/EOLib.Logger/FileLogger.cs b/EOLib.Logger/FileLogger.cs index 00595543e..d7779fdfc 100644 --- a/EOLib.Logger/FileLogger.cs +++ b/EOLib.Logger/FileLogger.cs @@ -31,4 +31,4 @@ public void Dispose() } } } -} +} \ No newline at end of file diff --git a/EOLib.Logger/LoggerFactory.cs b/EOLib.Logger/LoggerFactory.cs index fcbf232ee..7055a9339 100644 --- a/EOLib.Logger/LoggerFactory.cs +++ b/EOLib.Logger/LoggerFactory.cs @@ -36,4 +36,4 @@ public interface ILoggerFactory ILogger CreateLogger(string fileName = "") where TLogger : class, ILogger, new(); } -} +} \ No newline at end of file diff --git a/EOLib.Logger/LoggerProvider.cs b/EOLib.Logger/LoggerProvider.cs index b54ea7230..f0e490d43 100644 --- a/EOLib.Logger/LoggerProvider.cs +++ b/EOLib.Logger/LoggerProvider.cs @@ -32,4 +32,4 @@ public interface ILoggerProvider : IDisposable { ILogger Logger { get; } } -} +} \ No newline at end of file diff --git a/EOLib.Logger/NullLogger.cs b/EOLib.Logger/NullLogger.cs index b48f46945..89ce2101e 100644 --- a/EOLib.Logger/NullLogger.cs +++ b/EOLib.Logger/NullLogger.cs @@ -6,4 +6,4 @@ public void Dispose() { } public void Log(string format, params object[] parameters) { } } -} +} \ No newline at end of file diff --git a/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs b/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs index 5a2ce8a44..390f36ff0 100644 --- a/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs +++ b/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs @@ -1,7 +1,4 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using EOLib.Domain.Protocol; +using EOLib.Domain.Protocol; using EOLib.IO.Map; using EOLib.IO.Pub; using EOLib.IO.Services; @@ -10,14 +7,17 @@ using EOLib.Net.Communication; using EOLib.Net.FileTransfer; using EOLib.Test.TestHelpers; -using NUnit.Framework; -using Moq; -using System.Collections.Generic; +using Moffat.EndlessOnline.SDK.Data; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; +using Moq; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Text; -using Moffat.EndlessOnline.SDK.Data; namespace EOLib.Test.Net.FileTransfer { @@ -133,7 +133,7 @@ public void RequestMapFile_ResponsePacketHasInvalidHeader_ThrowsEmptyPacketRecei [Test] public void RequestMapFile_ResponsePacketHasIncorrectFileType_ThrowsMalformedPacketException() { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader((byte) InitReply.FileEsf, 33); + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader((byte)InitReply.FileEsf, 33); Assert.ThrowsAsync(async () => await _fileRequestService.RequestMapFile(1, 1)); } @@ -172,7 +172,7 @@ private static bool IsCorrectFileRequestPacket(IPacket packet, FileType type, sh { var waPacket = packet as WelcomeAgreeClientPacket; var correctTyping = waPacket.FileType == type; - + var correctData = true; if (mapId > 0 && sessionId > 0) { @@ -278,4 +278,4 @@ private static byte[] CreateFilePacket(FileType type) #endregion } -} +} \ No newline at end of file diff --git a/EOLib.Test/Properties/AssemblyInfo.cs b/EOLib.Test/Properties/AssemblyInfo.cs index f1e9caf90..50ba5aeac 100644 --- a/EOLib.Test/Properties/AssemblyInfo.cs +++ b/EOLib.Test/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs b/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs index 4a0629c98..ad022e3dd 100644 --- a/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs +++ b/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs @@ -25,4 +25,4 @@ internal static void SetupReceivedPacketHasHeader(this Mock(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/CharacterManagementActions.cs b/EOLib/Domain/Character/CharacterManagementActions.cs index 7a352a40a..5bba07018 100644 --- a/EOLib/Domain/Character/CharacterManagementActions.cs +++ b/EOLib/Domain/Character/CharacterManagementActions.cs @@ -49,7 +49,7 @@ public async Task CreateCharacter(ICharacterCreateParameters par var response = await _packetSendService.SendEncodedPacketAndWaitAsync(packet); if (!(response is CharacterReplyServerPacket responsePacket)) throw new EmptyPacketReceivedException(); - + if (responsePacket.ReplyCodeData is CharacterReplyServerPacket.ReplyCodeDataOk dataOk && dataOk.Characters.Any()) { _characterSelectorRepository.Characters = dataOk.Characters diff --git a/EOLib/Domain/Character/CharacterRenderProperties.cs b/EOLib/Domain/Character/CharacterRenderProperties.cs index f01a1f734..0346887ea 100644 --- a/EOLib/Domain/Character/CharacterRenderProperties.cs +++ b/EOLib/Domain/Character/CharacterRenderProperties.cs @@ -7,10 +7,10 @@ namespace EOLib.Domain.Character [Record] public sealed partial class CharacterRenderProperties { - public const int MAX_NUMBER_OF_WALK_FRAMES = 5; - public const int MAX_NUMBER_OF_ATTACK_FRAMES = 3; + public const int MAX_NUMBER_OF_WALK_FRAMES = 5; + public const int MAX_NUMBER_OF_ATTACK_FRAMES = 3; public const int MAX_NUMBER_OF_RANGED_ATTACK_FRAMES = 2; - public const int MAX_NUMBER_OF_EMOTE_FRAMES = 3; + public const int MAX_NUMBER_OF_EMOTE_FRAMES = 3; public CharacterActionState CurrentAction { get; } @@ -67,4 +67,4 @@ public static CharacterRenderProperties FromCharacterMapInfo(CharacterMapInfo ch }.ToImmutable(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/CharacterRepository.cs b/EOLib/Domain/Character/CharacterRepository.cs index 09db284f9..9df3edb0a 100644 --- a/EOLib/Domain/Character/CharacterRepository.cs +++ b/EOLib/Domain/Character/CharacterRepository.cs @@ -23,4 +23,4 @@ public class CharacterRepository : ICharacterRepository, ICharacterProvider public Character MainCharacter { get; set; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/CharacterSessionRepository.cs b/EOLib/Domain/Character/CharacterSessionRepository.cs index 13b1b7207..688862021 100644 --- a/EOLib/Domain/Character/CharacterSessionRepository.cs +++ b/EOLib/Domain/Character/CharacterSessionRepository.cs @@ -49,4 +49,4 @@ public void ResetState() TodayTotalExp = 0; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/CharacterStat.cs b/EOLib/Domain/Character/CharacterStat.cs index e89b9a0ad..f2d1a9e05 100644 --- a/EOLib/Domain/Character/CharacterStat.cs +++ b/EOLib/Domain/Character/CharacterStat.cs @@ -39,4 +39,4 @@ public enum CharacterStat Earth, Wind, } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/CharacterStats.cs b/EOLib/Domain/Character/CharacterStats.cs index 506718e28..ee067d0dc 100644 --- a/EOLib/Domain/Character/CharacterStats.cs +++ b/EOLib/Domain/Character/CharacterStats.cs @@ -123,4 +123,4 @@ public static CharacterStats FromStatReset(CharacterStatsReset characterStatsUpd }); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/Emote.cs b/EOLib/Domain/Character/Emote.cs index 7cacde529..f23ac77a0 100644 --- a/EOLib/Domain/Character/Emote.cs +++ b/EOLib/Domain/Character/Emote.cs @@ -25,4 +25,4 @@ public enum Emote Playful = 14, MusicNotes = 15, } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/EquippedItem.cs b/EOLib/Domain/Character/EquippedItem.cs index d0c199d0c..7d4ecf209 100644 --- a/EOLib/Domain/Character/EquippedItem.cs +++ b/EOLib/Domain/Character/EquippedItem.cs @@ -1,7 +1,7 @@ -using System; -using EOLib.IO; +using EOLib.IO; using EOLib.IO.Extensions; using EOLib.IO.Pub; +using System; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/ExperienceTableProvider.cs b/EOLib/Domain/Character/ExperienceTableProvider.cs index 0fbd1a293..3dc73df4a 100644 --- a/EOLib/Domain/Character/ExperienceTableProvider.cs +++ b/EOLib/Domain/Character/ExperienceTableProvider.cs @@ -1,6 +1,6 @@ -using System; +using AutomaticTypeMapper; +using System; using System.Collections.Generic; -using AutomaticTypeMapper; namespace EOLib.Domain.Character { @@ -13,7 +13,7 @@ public ExperienceTableProvider() { var exp_table = new List { 0 }; for (int i = 1; i < byte.MaxValue - 1; ++i) - exp_table.Add((int) Math.Round(Math.Pow(i, 3)*133.1)); + exp_table.Add((int)Math.Round(Math.Pow(i, 3) * 133.1)); ExperienceByLevel = exp_table; } @@ -23,4 +23,4 @@ public interface IExperienceTableProvider { IReadOnlyList ExperienceByLevel { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/GhostingRepository.cs b/EOLib/Domain/Character/GhostingRepository.cs index f7126cd60..83b0d27d7 100644 --- a/EOLib/Domain/Character/GhostingRepository.cs +++ b/EOLib/Domain/Character/GhostingRepository.cs @@ -5,7 +5,7 @@ namespace EOLib.Domain.Character { [AutoMappedType(IsSingleton = true)] - public sealed class GhostingRepository: IGhostingProvider, IGhostingRepository + public sealed class GhostingRepository : IGhostingProvider, IGhostingRepository { public bool GhostedRecently => GhostStartTime.Elapsed.TotalMilliseconds > 0 && !GhostStartTime.IsRunning; @@ -47,4 +47,4 @@ public interface IGhostingProvider : IResettable Option GhostTarget { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/IPlayerInfoData.cs b/EOLib/Domain/Character/IPlayerInfoData.cs index ae162a5d1..2990acec4 100644 --- a/EOLib/Domain/Character/IPlayerInfoData.cs +++ b/EOLib/Domain/Character/IPlayerInfoData.cs @@ -24,4 +24,4 @@ public interface IPlayerInfoData CharacterIcon Icon { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/InventoryItem.cs b/EOLib/Domain/Character/InventoryItem.cs index cb5b26e9c..8a24d11d2 100644 --- a/EOLib/Domain/Character/InventoryItem.cs +++ b/EOLib/Domain/Character/InventoryItem.cs @@ -9,7 +9,7 @@ namespace EOLib.Domain.Character public sealed partial class InventoryItem { public int ItemID { get; } - + public int Amount { get; } public static InventoryItem FromNet(NetItem source) => new InventoryItem(source.Id, source.Amount); diff --git a/EOLib/Domain/Character/PaperdollData.cs b/EOLib/Domain/Character/PaperdollData.cs index 3ded396da..d827ff52a 100644 --- a/EOLib/Domain/Character/PaperdollData.cs +++ b/EOLib/Domain/Character/PaperdollData.cs @@ -41,4 +41,4 @@ public PaperdollData() QuestNames = new List(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/PaperdollRepository.cs b/EOLib/Domain/Character/PaperdollRepository.cs index 87eb64a98..8d0f48cda 100644 --- a/EOLib/Domain/Character/PaperdollRepository.cs +++ b/EOLib/Domain/Character/PaperdollRepository.cs @@ -20,4 +20,4 @@ public class PaperdollRepository : IPaperdollRepository, IPaperdollProvider IReadOnlyDictionary IPaperdollProvider.VisibleCharacterPaperdolls => VisibleCharacterPaperdolls; } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/TrainingActions.cs b/EOLib/Domain/Character/TrainingActions.cs index 6d4014ba2..1f66d9c01 100644 --- a/EOLib/Domain/Character/TrainingActions.cs +++ b/EOLib/Domain/Character/TrainingActions.cs @@ -79,4 +79,4 @@ public interface ITrainingActions void LevelUpSkill(int spellId); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Character/WalkValidationActions.cs b/EOLib/Domain/Character/WalkValidationActions.cs index d02a7f17a..7a42c7fa6 100644 --- a/EOLib/Domain/Character/WalkValidationActions.cs +++ b/EOLib/Domain/Character/WalkValidationActions.cs @@ -70,7 +70,8 @@ public WalkValidationResult IsCellStateWalkable(IMapCellState cellState) var cellChar = cellState.Character.FlatMap(c => c.SomeWhen(cc => cc != mc)); return cellChar.Match( - some: c => { + some: c => + { if (mc.NoWall) return WalkValidationResult.Walkable; @@ -199,4 +200,4 @@ public interface IWalkValidationActions WalkValidationResult IsCellStateWalkable(IMapCellState cellState); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Chat/Builders/ChatPacketBuilder.cs b/EOLib/Domain/Chat/Builders/ChatPacketBuilder.cs index ff643914f..1cac74e42 100644 --- a/EOLib/Domain/Chat/Builders/ChatPacketBuilder.cs +++ b/EOLib/Domain/Chat/Builders/ChatPacketBuilder.cs @@ -1,7 +1,7 @@ -using System; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; +using System; namespace EOLib.Domain.Chat.Builders { @@ -31,4 +31,4 @@ public IPacket BuildChatPacket(ChatType chatType, string chat, string targetChar return packet; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Chat/Builders/IChatPacketBuilder.cs b/EOLib/Domain/Chat/Builders/IChatPacketBuilder.cs index 8768ed773..e9bd22fbb 100644 --- a/EOLib/Domain/Chat/Builders/IChatPacketBuilder.cs +++ b/EOLib/Domain/Chat/Builders/IChatPacketBuilder.cs @@ -6,4 +6,4 @@ public interface IChatPacketBuilder { IPacket BuildChatPacket(ChatType chatType, string chat, string targetCharacter); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Chat/ChatActions.cs b/EOLib/Domain/Chat/ChatActions.cs index adeb17eea..1221d89bd 100644 --- a/EOLib/Domain/Chat/ChatActions.cs +++ b/EOLib/Domain/Chat/ChatActions.cs @@ -155,7 +155,7 @@ private void AddChatForLocalDisplay(ChatType chatType, string chat, string targe _chatRepository.AllChat[ChatTab.Group].Add(new ChatData(ChatTab.Group, who, chat, ChatIcon.HGM, ChatColor.Admin)); break; case ChatType.PM: - if(targetCharacter == _chatRepository.PMTarget1) + if (targetCharacter == _chatRepository.PMTarget1) _chatRepository.AllChat[ChatTab.Private1].Add(new ChatData(ChatTab.Private1, who, chat, ChatIcon.Note, ChatColor.PM)); else if (targetCharacter == _chatRepository.PMTarget2) _chatRepository.AllChat[ChatTab.Private2].Add(new ChatData(ChatTab.Private2, who, chat, ChatIcon.Note, ChatColor.PM)); diff --git a/EOLib/Domain/Chat/ChatLoggerProvider.cs b/EOLib/Domain/Chat/ChatLoggerProvider.cs index c6cc93bc2..eaf2e1734 100644 --- a/EOLib/Domain/Chat/ChatLoggerProvider.cs +++ b/EOLib/Domain/Chat/ChatLoggerProvider.cs @@ -28,4 +28,4 @@ public void Dispose() ChatLogger.Dispose(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Chat/ChatProcessor.cs b/EOLib/Domain/Chat/ChatProcessor.cs index 0a64f255b..b2539eff6 100644 --- a/EOLib/Domain/Chat/ChatProcessor.cs +++ b/EOLib/Domain/Chat/ChatProcessor.cs @@ -1,9 +1,9 @@ -using System; -using System.Linq; -using System.Text; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.Config; using EOLib.Localization; +using System; +using System.Linq; +using System.Text; namespace EOLib.Domain.Chat { @@ -67,21 +67,21 @@ public string MakeDrunk(string input) if (char.ToLower(c) == 'e' || char.ToLower(c) == 'a') { if (_random.Next(100) < 70) - ret.Insert(i+1, 'j'); + ret.Insert(i + 1, 'j'); } else if (char.ToLower(c) == 'u' || char.ToLower(c) == 'o') { if (_random.Next(100) < 70) - ret.Insert(i+1, 'w'); + ret.Insert(i + 1, 'w'); } else if (c == 'i') { if (_random.Next(100) < 40) - ret.Insert(i+1, 'u'); + ret.Insert(i + 1, 'u'); } else if (c != ' ' && _random.Next(100) < 40) { - ret.Insert(i+1, c); + ret.Insert(i + 1, c); } } @@ -105,7 +105,7 @@ public string MakeDrunk(string input) { if (ret[i] == ' ' && _random.Next(100) < 30) { - ret.Insert(i+1, "*hic* "); + ret.Insert(i + 1, "*hic* "); i += 6; } } @@ -154,4 +154,4 @@ public interface IChatProcessor (bool ShowChat, string FilteredMessage) FilterCurses(string input); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Chat/ChatRepository.cs b/EOLib/Domain/Chat/ChatRepository.cs index 16e7508ae..99b529390 100644 --- a/EOLib/Domain/Chat/ChatRepository.cs +++ b/EOLib/Domain/Chat/ChatRepository.cs @@ -1,8 +1,8 @@ -using System; +using AutomaticTypeMapper; +using EOLib.Config; +using System; using System.Collections.Generic; using System.Linq; -using AutomaticTypeMapper; -using EOLib.Config; namespace EOLib.Domain.Chat { @@ -61,10 +61,10 @@ public ChatRepository(IConfigurationProvider configurationProvider, public void ResetState() { var chat = new Dictionary>(); - foreach (var tab in (ChatTab[]) Enum.GetValues(typeof(ChatTab))) + foreach (var tab in (ChatTab[])Enum.GetValues(typeof(ChatTab))) chat.Add(tab, new LoggingList(_configurationProvider, _chatLoggerProvider, _chatProcessor)); AllChat = chat; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Chat/ChatTypeCalculator.cs b/EOLib/Domain/Chat/ChatTypeCalculator.cs index 4bfea9423..b0737cfb0 100644 --- a/EOLib/Domain/Chat/ChatTypeCalculator.cs +++ b/EOLib/Domain/Chat/ChatTypeCalculator.cs @@ -16,10 +16,10 @@ public ChatTypeCalculator(ICharacterProvider characterProvider) public ChatType CalculateChatType(string input) { - if(string.IsNullOrEmpty(input)) + if (string.IsNullOrEmpty(input)) return ChatType.Local; - if(!CharacterIsAdmin && (input[0] == '+' || input[0] == '@')) + if (!CharacterIsAdmin && (input[0] == '+' || input[0] == '@')) return ChatType.Local; return input[0] switch diff --git a/EOLib/Domain/Chat/Commands/IPlayerCommand.cs b/EOLib/Domain/Chat/Commands/IPlayerCommand.cs index 4c867bc28..52400e771 100644 --- a/EOLib/Domain/Chat/Commands/IPlayerCommand.cs +++ b/EOLib/Domain/Chat/Commands/IPlayerCommand.cs @@ -6,4 +6,4 @@ public interface IPlayerCommand bool Execute(string parameter); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Chat/Commands/NoWallCommand.cs b/EOLib/Domain/Chat/Commands/NoWallCommand.cs index 1a29ee7a0..293e61677 100644 --- a/EOLib/Domain/Chat/Commands/NoWallCommand.cs +++ b/EOLib/Domain/Chat/Commands/NoWallCommand.cs @@ -30,4 +30,4 @@ public bool Execute(string parameter) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Chat/Commands/PingCommand.cs b/EOLib/Domain/Chat/Commands/PingCommand.cs index 53b2be141..4b6fbc501 100644 --- a/EOLib/Domain/Chat/Commands/PingCommand.cs +++ b/EOLib/Domain/Chat/Commands/PingCommand.cs @@ -29,4 +29,4 @@ public bool Execute(string parameter) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Chat/Commands/UsageCommand.cs b/EOLib/Domain/Chat/Commands/UsageCommand.cs index 9c487c1ec..16ef26e12 100644 --- a/EOLib/Domain/Chat/Commands/UsageCommand.cs +++ b/EOLib/Domain/Chat/Commands/UsageCommand.cs @@ -21,7 +21,7 @@ public UsageCommand(ICharacterProvider characterProvider, public bool Execute(string parameter) { var usage = _characterProvider.MainCharacter.Stats[CharacterStat.Usage]; - var message = $"[x] usage: {usage/60}hrs. {usage%60}min."; + var message = $"[x] usage: {usage / 60}hrs. {usage % 60}min."; var chatData = new ChatData(ChatTab.Local, "System", message, ChatIcon.LookingDude); _chatRepository.AllChat[ChatTab.Local].Add(chatData); @@ -29,4 +29,4 @@ public bool Execute(string parameter) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Chat/LocalCommandHandler.cs b/EOLib/Domain/Chat/LocalCommandHandler.cs index db2755b8b..7cdbbe470 100644 --- a/EOLib/Domain/Chat/LocalCommandHandler.cs +++ b/EOLib/Domain/Chat/LocalCommandHandler.cs @@ -1,8 +1,8 @@ -using System; +using AutomaticTypeMapper; +using EOLib.Domain.Chat.Commands; +using System; using System.Collections.Generic; using System.Linq; -using AutomaticTypeMapper; -using EOLib.Domain.Chat.Commands; namespace EOLib.Domain.Chat { diff --git a/EOLib/Domain/Chat/LoggingList.cs b/EOLib/Domain/Chat/LoggingList.cs index 849d61fbe..e8f5d0703 100644 --- a/EOLib/Domain/Chat/LoggingList.cs +++ b/EOLib/Domain/Chat/LoggingList.cs @@ -95,4 +95,4 @@ private string GetChatTabString(ChatTab tab) #endregion } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Extensions/CharacterExtensions.cs b/EOLib/Domain/Extensions/CharacterExtensions.cs index fc5b251d0..91b46d4ba 100644 --- a/EOLib/Domain/Extensions/CharacterExtensions.cs +++ b/EOLib/Domain/Extensions/CharacterExtensions.cs @@ -44,4 +44,4 @@ public static Character.Character WithDamage(this Character.Character original, return original.WithStats(stats).WithRenderProperties(props); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Extensions/CharacterRenderPropertiesExtensions.cs b/EOLib/Domain/Extensions/CharacterRenderPropertiesExtensions.cs index e22612879..67c68e555 100644 --- a/EOLib/Domain/Extensions/CharacterRenderPropertiesExtensions.cs +++ b/EOLib/Domain/Extensions/CharacterRenderPropertiesExtensions.cs @@ -1,6 +1,6 @@ -using System.Linq; -using EOLib.Domain.Character; +using EOLib.Domain.Character; using EOLib.Domain.Map; +using System.Linq; namespace EOLib.Domain.Extensions { @@ -121,4 +121,4 @@ public static CharacterRenderProperties ResetAnimationFrames(this CharacterRende public static MapCoordinate DestinationCoordinates(this CharacterRenderProperties rp) => new MapCoordinate(rp.GetDestinationX(), rp.GetDestinationY()); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Extensions/CharacterStatExtensions.cs b/EOLib/Domain/Extensions/CharacterStatExtensions.cs index 4cbbd9487..505cb8b2f 100644 --- a/EOLib/Domain/Extensions/CharacterStatExtensions.cs +++ b/EOLib/Domain/Extensions/CharacterStatExtensions.cs @@ -44,4 +44,4 @@ public static string GetKarmaString(this CharacterStats characterStats) return string.Empty; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Extensions/MapExtensions.cs b/EOLib/Domain/Extensions/MapExtensions.cs index ee102fded..327fbc066 100644 --- a/EOLib/Domain/Extensions/MapExtensions.cs +++ b/EOLib/Domain/Extensions/MapExtensions.cs @@ -45,4 +45,4 @@ public static IEnumerable GetTileSpecs(this IMapFile map, params } } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Extensions/NPCExtensions.cs b/EOLib/Domain/Extensions/NPCExtensions.cs index 566735522..3c006da89 100644 --- a/EOLib/Domain/Extensions/NPCExtensions.cs +++ b/EOLib/Domain/Extensions/NPCExtensions.cs @@ -1,6 +1,6 @@ -using System; +using EOLib.Domain.NPC; +using System; using System.Linq; -using EOLib.Domain.NPC; namespace EOLib.Domain.Extensions { @@ -94,4 +94,4 @@ private static int GetYOffset(EODirection direction) direction == EODirection.Up ? -1 : 0; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Extensions/PaperdollExtensions.cs b/EOLib/Domain/Extensions/PaperdollExtensions.cs index 59bd16f3b..c83737373 100644 --- a/EOLib/Domain/Extensions/PaperdollExtensions.cs +++ b/EOLib/Domain/Extensions/PaperdollExtensions.cs @@ -50,4 +50,4 @@ public static IReadOnlyDictionary GetPaperdoll(this Equipmen }; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/IResetStateAction.cs b/EOLib/Domain/IResetStateAction.cs index 2cd328c78..a28e3844d 100644 --- a/EOLib/Domain/IResetStateAction.cs +++ b/EOLib/Domain/IResetStateAction.cs @@ -4,4 +4,4 @@ public interface IResetStateAction { void ResetState(); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Bank/BankActions.cs b/EOLib/Domain/Interact/Bank/BankActions.cs index fd221e1d5..94df4b762 100644 --- a/EOLib/Domain/Interact/Bank/BankActions.cs +++ b/EOLib/Domain/Interact/Bank/BankActions.cs @@ -41,4 +41,4 @@ public interface IBankActions void BuyStorageUpgrade(); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Bank/BankDataRepository.cs b/EOLib/Domain/Interact/Bank/BankDataRepository.cs index 2a6bd49c4..3306be242 100644 --- a/EOLib/Domain/Interact/Bank/BankDataRepository.cs +++ b/EOLib/Domain/Interact/Bank/BankDataRepository.cs @@ -42,4 +42,4 @@ public void ResetState() LockerUpgrades = Option.None(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Barber/BarberActions.cs b/EOLib/Domain/Interact/Barber/BarberActions.cs index 9624ca394..26af9f499 100644 --- a/EOLib/Domain/Interact/Barber/BarberActions.cs +++ b/EOLib/Domain/Interact/Barber/BarberActions.cs @@ -31,4 +31,4 @@ public interface IBarberActions { void Purchase(int hairStyle, int hairColor); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Barber/BarberDataRepository.cs b/EOLib/Domain/Interact/Barber/BarberDataRepository.cs index d88e0a335..38ebe3c5a 100644 --- a/EOLib/Domain/Interact/Barber/BarberDataRepository.cs +++ b/EOLib/Domain/Interact/Barber/BarberDataRepository.cs @@ -27,4 +27,4 @@ public void ResetState() SessionID = 0; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Board/BoardActions.cs b/EOLib/Domain/Interact/Board/BoardActions.cs index 42802b0ad..9a86e287b 100644 --- a/EOLib/Domain/Interact/Board/BoardActions.cs +++ b/EOLib/Domain/Interact/Board/BoardActions.cs @@ -67,4 +67,4 @@ public interface IBoardActions void DeletePost(int postId); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Board/BoardDataRepository.cs b/EOLib/Domain/Interact/Board/BoardDataRepository.cs index cc09ddaa3..4e9d80921 100644 --- a/EOLib/Domain/Interact/Board/BoardDataRepository.cs +++ b/EOLib/Domain/Interact/Board/BoardDataRepository.cs @@ -52,4 +52,4 @@ public void ResetState() ActivePostMessage = Option.None(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Board/BoardPostInfo.cs b/EOLib/Domain/Interact/Board/BoardPostInfo.cs index 41a368abd..f695633f7 100644 --- a/EOLib/Domain/Interact/Board/BoardPostInfo.cs +++ b/EOLib/Domain/Interact/Board/BoardPostInfo.cs @@ -11,4 +11,4 @@ public sealed partial class BoardPostInfo public string Subject { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/BookActions.cs b/EOLib/Domain/Interact/BookActions.cs index 3108ac140..57b0aa731 100644 --- a/EOLib/Domain/Interact/BookActions.cs +++ b/EOLib/Domain/Interact/BookActions.cs @@ -25,4 +25,4 @@ public interface IBookActions { void RequestBook(int characterId); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Citizen/CitizenActions.cs b/EOLib/Domain/Interact/Citizen/CitizenActions.cs index c2d769932..a4464f11b 100644 --- a/EOLib/Domain/Interact/Citizen/CitizenActions.cs +++ b/EOLib/Domain/Interact/Citizen/CitizenActions.cs @@ -75,4 +75,4 @@ public interface ICitizenActions void Unsubscribe(); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Citizen/CitizenDataRepository.cs b/EOLib/Domain/Interact/Citizen/CitizenDataRepository.cs index f4d131ed2..f771942bf 100644 --- a/EOLib/Domain/Interact/Citizen/CitizenDataRepository.cs +++ b/EOLib/Domain/Interact/Citizen/CitizenDataRepository.cs @@ -38,4 +38,4 @@ public CitizenDataRepository() Questions = new List(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/INPCInteractionNotifier.cs b/EOLib/Domain/Interact/INPCInteractionNotifier.cs index b340b801a..064d1b011 100644 --- a/EOLib/Domain/Interact/INPCInteractionNotifier.cs +++ b/EOLib/Domain/Interact/INPCInteractionNotifier.cs @@ -55,4 +55,4 @@ public void NotifyPriestRequest(string partnerName) { } public void NotifyMarriageReply(MarriageReply reply) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Jukebox/JukeboxActions.cs b/EOLib/Domain/Interact/Jukebox/JukeboxActions.cs index 2aa3c265b..5505bdf7b 100644 --- a/EOLib/Domain/Interact/Jukebox/JukeboxActions.cs +++ b/EOLib/Domain/Interact/Jukebox/JukeboxActions.cs @@ -57,4 +57,4 @@ public interface IJukeboxActions void RequestSong(int songIndex); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Jukebox/JukeboxDataRepository.cs b/EOLib/Domain/Interact/Jukebox/JukeboxDataRepository.cs index de7a4a3e1..8e8c97160 100644 --- a/EOLib/Domain/Interact/Jukebox/JukeboxDataRepository.cs +++ b/EOLib/Domain/Interact/Jukebox/JukeboxDataRepository.cs @@ -29,4 +29,4 @@ public void ResetState() PlayingRequestName = Option.None(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Law/LawActions.cs b/EOLib/Domain/Interact/Law/LawActions.cs index 61f0ba62b..0c66cfcb7 100644 --- a/EOLib/Domain/Interact/Law/LawActions.cs +++ b/EOLib/Domain/Interact/Law/LawActions.cs @@ -45,4 +45,4 @@ public interface ILawActions void RequestDivorce(string partner); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Law/LawSessionRepository.cs b/EOLib/Domain/Interact/Law/LawSessionRepository.cs index e3a882691..99bb236ff 100644 --- a/EOLib/Domain/Interact/Law/LawSessionRepository.cs +++ b/EOLib/Domain/Interact/Law/LawSessionRepository.cs @@ -22,4 +22,4 @@ public LawSessionRepository() SessionID = 0; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/MapNPCActions.cs b/EOLib/Domain/Interact/MapNPCActions.cs index 2a80472f3..6e738efae 100644 --- a/EOLib/Domain/Interact/MapNPCActions.cs +++ b/EOLib/Domain/Interact/MapNPCActions.cs @@ -89,4 +89,4 @@ public interface IMapNPCActions void RequestBarber(NPC.NPC npc); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/PaperdollActions.cs b/EOLib/Domain/Interact/PaperdollActions.cs index f510dac80..388db9ee5 100644 --- a/EOLib/Domain/Interact/PaperdollActions.cs +++ b/EOLib/Domain/Interact/PaperdollActions.cs @@ -25,4 +25,4 @@ public interface IPaperdollActions { void RequestPaperdoll(int characterId); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Priest/PriestActions.cs b/EOLib/Domain/Interact/Priest/PriestActions.cs index d9d0e195d..5d83d4608 100644 --- a/EOLib/Domain/Interact/Priest/PriestActions.cs +++ b/EOLib/Domain/Interact/Priest/PriestActions.cs @@ -44,4 +44,4 @@ public interface IPriestActions void ConfirmMarriage(); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Priest/PriestSessionRepository.cs b/EOLib/Domain/Interact/Priest/PriestSessionRepository.cs index b2a5ce82e..6f4056c82 100644 --- a/EOLib/Domain/Interact/Priest/PriestSessionRepository.cs +++ b/EOLib/Domain/Interact/Priest/PriestSessionRepository.cs @@ -22,4 +22,4 @@ public PriestSessionRepository() SessionID = 0; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Quest/IStatusLabelNotifier.cs b/EOLib/Domain/Interact/Quest/IStatusLabelNotifier.cs index de069a688..6cebaf2ad 100644 --- a/EOLib/Domain/Interact/Quest/IStatusLabelNotifier.cs +++ b/EOLib/Domain/Interact/Quest/IStatusLabelNotifier.cs @@ -12,4 +12,4 @@ public class NoOpStatusLabelNotifier : IStatusLabelNotifier { public void ShowWarning(string message) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Quest/QuestActions.cs b/EOLib/Domain/Interact/Quest/QuestActions.cs index a483a982a..e378bf797 100644 --- a/EOLib/Domain/Interact/Quest/QuestActions.cs +++ b/EOLib/Domain/Interact/Quest/QuestActions.cs @@ -53,4 +53,4 @@ public interface IQuestActions void RequestQuestHistory(QuestPage page); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Quest/QuestDataRepository.cs b/EOLib/Domain/Interact/Quest/QuestDataRepository.cs index 417e8aa60..57eefe423 100644 --- a/EOLib/Domain/Interact/Quest/QuestDataRepository.cs +++ b/EOLib/Domain/Interact/Quest/QuestDataRepository.cs @@ -54,4 +54,4 @@ public void ResetState() QuestHistory = new List(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Quest/QuestDialogData.cs b/EOLib/Domain/Interact/Quest/QuestDialogData.cs index d42214876..6126d5a7f 100644 --- a/EOLib/Domain/Interact/Quest/QuestDialogData.cs +++ b/EOLib/Domain/Interact/Quest/QuestDialogData.cs @@ -27,4 +27,4 @@ public QuestDialogData() Actions = new List<(int, string)>(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Quest/QuestProgressData.cs b/EOLib/Domain/Interact/Quest/QuestProgressData.cs index d1cffcc24..8d502b3b2 100644 --- a/EOLib/Domain/Interact/Quest/QuestProgressData.cs +++ b/EOLib/Domain/Interact/Quest/QuestProgressData.cs @@ -29,4 +29,4 @@ public sealed partial class QuestProgressData public int Target { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Shop/ShopActions.cs b/EOLib/Domain/Interact/Shop/ShopActions.cs index 1df130e86..6c1fc51d9 100644 --- a/EOLib/Domain/Interact/Shop/ShopActions.cs +++ b/EOLib/Domain/Interact/Shop/ShopActions.cs @@ -64,4 +64,4 @@ public interface IShopActions void CraftItem(int itemId); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Shop/ShopCraftIngredient.cs b/EOLib/Domain/Interact/Shop/ShopCraftIngredient.cs index 3c2f11542..65ae47b1e 100644 --- a/EOLib/Domain/Interact/Shop/ShopCraftIngredient.cs +++ b/EOLib/Domain/Interact/Shop/ShopCraftIngredient.cs @@ -19,4 +19,4 @@ public interface IShopCraftIngredient int Amount { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Shop/ShopCraftItem.cs b/EOLib/Domain/Interact/Shop/ShopCraftItem.cs index ccc574ebc..c5ee0512d 100644 --- a/EOLib/Domain/Interact/Shop/ShopCraftItem.cs +++ b/EOLib/Domain/Interact/Shop/ShopCraftItem.cs @@ -21,4 +21,4 @@ public interface IShopCraftItem IReadOnlyList Ingredients { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Shop/ShopDataRepository.cs b/EOLib/Domain/Interact/Shop/ShopDataRepository.cs index fc4b5d047..906271510 100644 --- a/EOLib/Domain/Interact/Shop/ShopDataRepository.cs +++ b/EOLib/Domain/Interact/Shop/ShopDataRepository.cs @@ -32,7 +32,7 @@ public class ShopDataRepository : IShopDataProvider, IShopDataRepository public string ShopName { get; set; } public List TradeItems { get; set; } - + public List CraftItems { get; set; } IReadOnlyList IShopDataProvider.TradeItems => TradeItems; @@ -52,4 +52,4 @@ public void ResetState() CraftItems = new List(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Shop/ShopItem.cs b/EOLib/Domain/Interact/Shop/ShopItem.cs index 4a2de6f57..2b491afb2 100644 --- a/EOLib/Domain/Interact/Shop/ShopItem.cs +++ b/EOLib/Domain/Interact/Shop/ShopItem.cs @@ -29,4 +29,4 @@ public interface IShopItem int MaxBuy { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Skill/Skill.cs b/EOLib/Domain/Interact/Skill/Skill.cs index 9eca63b3b..d607c49f4 100644 --- a/EOLib/Domain/Interact/Skill/Skill.cs +++ b/EOLib/Domain/Interact/Skill/Skill.cs @@ -29,4 +29,4 @@ public sealed partial class Skill public int ChaRequirement { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Skill/SkillDataRepository.cs b/EOLib/Domain/Interact/Skill/SkillDataRepository.cs index 9b6068439..c5d523cd6 100644 --- a/EOLib/Domain/Interact/Skill/SkillDataRepository.cs +++ b/EOLib/Domain/Interact/Skill/SkillDataRepository.cs @@ -44,4 +44,4 @@ public void ResetState() Skills = new HashSet(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Skill/SkillmasterActions.cs b/EOLib/Domain/Interact/Skill/SkillmasterActions.cs index 2eac1fa5d..1f10f2bd1 100644 --- a/EOLib/Domain/Interact/Skill/SkillmasterActions.cs +++ b/EOLib/Domain/Interact/Skill/SkillmasterActions.cs @@ -55,4 +55,4 @@ public interface ISkillmasterActions void ResetCharacter(); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/Skill/SkillmasterReply.cs b/EOLib/Domain/Interact/Skill/SkillmasterReply.cs index afe01aafe..b281929ef 100644 --- a/EOLib/Domain/Interact/Skill/SkillmasterReply.cs +++ b/EOLib/Domain/Interact/Skill/SkillmasterReply.cs @@ -9,4 +9,4 @@ public enum SkillmasterReply ErrorRemoveItems = 1, ErrorWrongClass = 2 } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Interact/TileSpecMapEntity.cs b/EOLib/Domain/Interact/TileSpecMapEntity.cs index 832cd1c01..0bd43fdc1 100644 --- a/EOLib/Domain/Interact/TileSpecMapEntity.cs +++ b/EOLib/Domain/Interact/TileSpecMapEntity.cs @@ -10,4 +10,4 @@ public sealed partial class TileSpecMapEntity : IMapEntity public int Y { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Item/ItemActions.cs b/EOLib/Domain/Item/ItemActions.cs index 784011137..b70f57e85 100644 --- a/EOLib/Domain/Item/ItemActions.cs +++ b/EOLib/Domain/Item/ItemActions.cs @@ -88,4 +88,4 @@ public interface IItemActions void JunkItem(int itemId, int amount); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Item/ItemDropResult.cs b/EOLib/Domain/Item/ItemDropResult.cs index eb32175e8..158a85dbc 100644 --- a/EOLib/Domain/Item/ItemDropResult.cs +++ b/EOLib/Domain/Item/ItemDropResult.cs @@ -7,4 +7,4 @@ public enum ItemDropResult Jail, TooFar } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Item/ItemDropValidator.cs b/EOLib/Domain/Item/ItemDropValidator.cs index d131479e4..dc2f50a65 100644 --- a/EOLib/Domain/Item/ItemDropValidator.cs +++ b/EOLib/Domain/Item/ItemDropValidator.cs @@ -53,4 +53,4 @@ public interface IItemDropValidator ItemDropResult ValidateItemDrop(Character.Character mainCharacter, InventoryItem item, MapCoordinate dropPoint); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Item/ItemEquipValidator.cs b/EOLib/Domain/Item/ItemEquipValidator.cs index 58613711b..ad2f104a5 100644 --- a/EOLib/Domain/Item/ItemEquipValidator.cs +++ b/EOLib/Domain/Item/ItemEquipValidator.cs @@ -82,4 +82,4 @@ public interface IItemEquipValidator { (ItemEquipResult Result, string Detail, bool IsAlternateEquipLocation) ValidateItemEquip(Character.Character mainCharacter, EIFRecord itemData); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Item/ItemPickupResult.cs b/EOLib/Domain/Item/ItemPickupResult.cs index 61870647e..32aa1e442 100644 --- a/EOLib/Domain/Item/ItemPickupResult.cs +++ b/EOLib/Domain/Item/ItemPickupResult.cs @@ -7,4 +7,4 @@ public enum ItemPickupResult DropProtection, TooHeavy } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Item/ItemPickupValidator.cs b/EOLib/Domain/Item/ItemPickupValidator.cs index 5ce014970..29fdc1797 100644 --- a/EOLib/Domain/Item/ItemPickupValidator.cs +++ b/EOLib/Domain/Item/ItemPickupValidator.cs @@ -1,10 +1,10 @@ -using System; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.Config; using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.IO.Repositories; using Optional; +using System; namespace EOLib.Domain.Item { @@ -60,4 +60,4 @@ public interface IItemPickupValidator { ItemPickupResult ValidateItemPickup(Character.Character mainCharacter, MapItem item); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Item/ItemStringService.cs b/EOLib/Domain/Item/ItemStringService.cs index b51b64905..0b31b0c69 100644 --- a/EOLib/Domain/Item/ItemStringService.cs +++ b/EOLib/Domain/Item/ItemStringService.cs @@ -1,6 +1,6 @@ -using System; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.IO.Pub; +using System; namespace EOLib.Domain.Item { @@ -30,4 +30,4 @@ public interface IItemStringService string GetStringForInventoryDisplay(EIFRecord record, int amount); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Login/CharacterSelectorRepository.cs b/EOLib/Domain/Login/CharacterSelectorRepository.cs index 4c6f302d0..4cd4714de 100644 --- a/EOLib/Domain/Login/CharacterSelectorRepository.cs +++ b/EOLib/Domain/Login/CharacterSelectorRepository.cs @@ -25,4 +25,4 @@ public class CharacterSelectorRepository : ICharacterSelectorRepository, ICharac public Option CharacterForDelete { get; set; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Login/NewsRepository.cs b/EOLib/Domain/Login/NewsRepository.cs index 5fed0d4f9..ba4cc1d6b 100644 --- a/EOLib/Domain/Login/NewsRepository.cs +++ b/EOLib/Domain/Login/NewsRepository.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; -using AutomaticTypeMapper; +using AutomaticTypeMapper; +using System.Collections.Generic; namespace EOLib.Domain.Login { @@ -26,4 +26,4 @@ public class NewsRepository : INewsRepository, INewsProvider IReadOnlyList INewsProvider.NewsText => NewsText; } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Login/PlayerInfoRepository.cs b/EOLib/Domain/Login/PlayerInfoRepository.cs index 8b03b51d6..cb6cfe1d0 100644 --- a/EOLib/Domain/Login/PlayerInfoRepository.cs +++ b/EOLib/Domain/Login/PlayerInfoRepository.cs @@ -66,4 +66,4 @@ public void ResetState() PlayerHasAdminCharacter = false; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/ChestActions.cs b/EOLib/Domain/Map/ChestActions.cs index c9928544f..74ce06dd0 100644 --- a/EOLib/Domain/Map/ChestActions.cs +++ b/EOLib/Domain/Map/ChestActions.cs @@ -60,4 +60,4 @@ public interface IChestActions void TakeItemFromChest(int itemId); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/ChestDataRepository.cs b/EOLib/Domain/Map/ChestDataRepository.cs index edb3bdaff..d498d0c38 100644 --- a/EOLib/Domain/Map/ChestDataRepository.cs +++ b/EOLib/Domain/Map/ChestDataRepository.cs @@ -38,4 +38,4 @@ public void ResetState() Items = new HashSet(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/ChestItem.cs b/EOLib/Domain/Map/ChestItem.cs index 747abb3f3..12b104a84 100644 --- a/EOLib/Domain/Map/ChestItem.cs +++ b/EOLib/Domain/Map/ChestItem.cs @@ -11,4 +11,4 @@ public sealed partial class ChestItem public int Slot { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/CurrentMapProvider.cs b/EOLib/Domain/Map/CurrentMapProvider.cs index 9181cc718..f8c9354f4 100644 --- a/EOLib/Domain/Map/CurrentMapProvider.cs +++ b/EOLib/Domain/Map/CurrentMapProvider.cs @@ -24,4 +24,4 @@ public interface ICurrentMapProvider { IMapFile CurrentMap { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/CurrentMapStateRepository.cs b/EOLib/Domain/Map/CurrentMapStateRepository.cs index e599d0cb8..aa12a166e 100644 --- a/EOLib/Domain/Map/CurrentMapStateRepository.cs +++ b/EOLib/Domain/Map/CurrentMapStateRepository.cs @@ -21,7 +21,7 @@ public interface ICurrentMapStateRepository MapEntityCollectionHashSet MapItems { get; set; } - HashSet OpenDoors { get; set; } + HashSet OpenDoors { get; set; } HashSet PendingDoors { get; set; } @@ -156,4 +156,4 @@ public void ResetState() IsSleepWarp = false; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/IMapCellState.cs b/EOLib/Domain/Map/IMapCellState.cs index b14801373..c0e60a27d 100644 --- a/EOLib/Domain/Map/IMapCellState.cs +++ b/EOLib/Domain/Map/IMapCellState.cs @@ -9,7 +9,7 @@ public interface IMapCellState { bool InBounds { get; } - MapCoordinate Coordinate { get; } + MapCoordinate Coordinate { get; } IReadOnlyList Items { get; } @@ -20,11 +20,11 @@ public interface IMapCellState Option Character { get; } IReadOnlyList Characters { get; } - + Option ChestKey { get; } Option Warp { get; } Option Sign { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/LockerActions.cs b/EOLib/Domain/Map/LockerActions.cs index 4a1eb6475..350767dff 100644 --- a/EOLib/Domain/Map/LockerActions.cs +++ b/EOLib/Domain/Map/LockerActions.cs @@ -69,4 +69,4 @@ public interface ILockerActions int GetNewItemAmount(int itemId, int amount); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/LockerDataRepository.cs b/EOLib/Domain/Map/LockerDataRepository.cs index c653933ab..b2c98aad6 100644 --- a/EOLib/Domain/Map/LockerDataRepository.cs +++ b/EOLib/Domain/Map/LockerDataRepository.cs @@ -38,4 +38,4 @@ public void ResetState() Items = new HashSet(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/MapActions.cs b/EOLib/Domain/Map/MapActions.cs index 9c41b90c2..707ce286a 100644 --- a/EOLib/Domain/Map/MapActions.cs +++ b/EOLib/Domain/Map/MapActions.cs @@ -92,4 +92,4 @@ public interface IMapActions void OpenJukebox(MapCoordinate location); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/MapCellState.cs b/EOLib/Domain/Map/MapCellState.cs index 5edcdce2a..4de0fa620 100644 --- a/EOLib/Domain/Map/MapCellState.cs +++ b/EOLib/Domain/Map/MapCellState.cs @@ -39,4 +39,4 @@ public MapCellState() Sign = Option.None(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/MapCellStateProvider.cs b/EOLib/Domain/Map/MapCellStateProvider.cs index 65b0de3da..26604c047 100644 --- a/EOLib/Domain/Map/MapCellStateProvider.cs +++ b/EOLib/Domain/Map/MapCellStateProvider.cs @@ -40,7 +40,7 @@ public IMapCellState GetCellStateAt(int x, int y) var sign = CurrentMap.Signs.FirstOrDefault(s => s.X == x && s.Y == y); var characters = new List(); - if (_mapStateProvider.Characters.ContainsKey(new MapCoordinate(x,y))) + if (_mapStateProvider.Characters.ContainsKey(new MapCoordinate(x, y))) characters = _mapStateProvider.Characters[new MapCoordinate(x, y)].ToList(); if (_characterProvider.MainCharacter.X == x && _characterProvider.MainCharacter.Y == y) characters.Add(_characterProvider.MainCharacter); @@ -59,16 +59,16 @@ public IMapCellState GetCellStateAt(int x, int y) return new MapCellState { - InBounds = true, + InBounds = true, Coordinate = new MapCoordinate(x, y), - Items = items, - TileSpec = tileSpec, - Warp = warp.SomeNotNull().Map(w => new Warp(w)), - ChestKey = chest.SomeNotNull(), - Sign = sign.SomeNotNull().Map(s => new Sign(s)), - Character = characters.FirstOrNone(), + Items = items, + TileSpec = tileSpec, + Warp = warp.SomeNotNull().Map(w => new Warp(w)), + ChestKey = chest.SomeNotNull(), + Sign = sign.SomeNotNull().Map(s => new Sign(s)), + Character = characters.FirstOrNone(), Characters = characters, - NPC = npc + NPC = npc }; } diff --git a/EOLib/Domain/Map/MapCoordinate.cs b/EOLib/Domain/Map/MapCoordinate.cs index 53f9abc52..7e8d21464 100644 --- a/EOLib/Domain/Map/MapCoordinate.cs +++ b/EOLib/Domain/Map/MapCoordinate.cs @@ -47,7 +47,7 @@ public override bool Equals(object obj) if (!(obj is MapCoordinate)) return false; - var other = (MapCoordinate) obj; + var other = (MapCoordinate)obj; return X == other.X && Y == other.Y; } @@ -72,4 +72,4 @@ public int CompareTo(MapCoordinate other) return 0; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/MapEntityCollectionHashSet.cs b/EOLib/Domain/Map/MapEntityCollectionHashSet.cs index 3ca5bc1f8..0513fc735 100644 --- a/EOLib/Domain/Map/MapEntityCollectionHashSet.cs +++ b/EOLib/Domain/Map/MapEntityCollectionHashSet.cs @@ -128,4 +128,4 @@ public interface IReadOnlyMapEntityCollection : IEnumerable bool TryGetValue(int key1, out TValue value); bool TryGetValues(MapCoordinate key2, out HashSet values); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/Sign.cs b/EOLib/Domain/Map/Sign.cs index 407dc9a6c..19823a3f8 100644 --- a/EOLib/Domain/Map/Sign.cs +++ b/EOLib/Domain/Map/Sign.cs @@ -28,4 +28,4 @@ private static string Filter(string input) return new string(input.Where(x => !char.IsControl(x)).ToArray()); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/UnknownEntitiesRequestActions.cs b/EOLib/Domain/Map/UnknownEntitiesRequestActions.cs index 7b63dd48f..322b625b6 100644 --- a/EOLib/Domain/Map/UnknownEntitiesRequestActions.cs +++ b/EOLib/Domain/Map/UnknownEntitiesRequestActions.cs @@ -59,4 +59,4 @@ public interface IUnknownEntitiesRequestActions void RequestAll(); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/UnlockChestValidator.cs b/EOLib/Domain/Map/UnlockChestValidator.cs index 938f1f48f..3baefd5bf 100644 --- a/EOLib/Domain/Map/UnlockChestValidator.cs +++ b/EOLib/Domain/Map/UnlockChestValidator.cs @@ -1,10 +1,10 @@ -using System.Linq; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.IO.Map; using EOLib.IO.Repositories; using Optional; using Optional.Collections; +using System.Linq; namespace EOLib.Domain.Map { @@ -42,4 +42,4 @@ public interface IUnlockChestValidator Option GetRequiredKeyName(ChestKey requiredKey); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/UnlockDoorValidator.cs b/EOLib/Domain/Map/UnlockDoorValidator.cs index 2482093d8..dd348c27e 100644 --- a/EOLib/Domain/Map/UnlockDoorValidator.cs +++ b/EOLib/Domain/Map/UnlockDoorValidator.cs @@ -45,4 +45,4 @@ public interface IUnlockDoorValidator Option GetRequiredKey(Warp warp); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/Warp.cs b/EOLib/Domain/Map/Warp.cs index c322943f9..c2071b15d 100644 --- a/EOLib/Domain/Map/Warp.cs +++ b/EOLib/Domain/Map/Warp.cs @@ -21,4 +21,4 @@ public Warp(WarpMapEntity warpEntity) _warpEntity = warpEntity; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Map/WarpState.cs b/EOLib/Domain/Map/WarpState.cs index 870a6adeb..e6e5cbe24 100644 --- a/EOLib/Domain/Map/WarpState.cs +++ b/EOLib/Domain/Map/WarpState.cs @@ -6,4 +6,4 @@ public enum WarpState WarpStarted, WarpCompleting } -} +} \ No newline at end of file diff --git a/EOLib/Domain/NPC/NPCActionState.cs b/EOLib/Domain/NPC/NPCActionState.cs index 95fafa24c..1828320c1 100644 --- a/EOLib/Domain/NPC/NPCActionState.cs +++ b/EOLib/Domain/NPC/NPCActionState.cs @@ -6,4 +6,4 @@ public enum NPCActionState Walking, Attacking } -} +} \ No newline at end of file diff --git a/EOLib/Domain/NPC/NPCFrame.cs b/EOLib/Domain/NPC/NPCFrame.cs index 5ef86cdac..b66cbb918 100644 --- a/EOLib/Domain/NPC/NPCFrame.cs +++ b/EOLib/Domain/NPC/NPCFrame.cs @@ -13,4 +13,4 @@ public enum NPCFrame Attack2, //354, 356 //there may be an Attack3 frame, there are 2 extra graphics at this point } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IArenaNotifier.cs b/EOLib/Domain/Notifiers/IArenaNotifier.cs index 5ec443a4c..dae45b10c 100644 --- a/EOLib/Domain/Notifiers/IArenaNotifier.cs +++ b/EOLib/Domain/Notifiers/IArenaNotifier.cs @@ -24,4 +24,4 @@ public void NotifyArenaKill(int killCount, string killer, string victim) { } public void NotifyArenaWin(string winner) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IChatEventNotifier.cs b/EOLib/Domain/Notifiers/IChatEventNotifier.cs index 64ad7149c..09290e28d 100644 --- a/EOLib/Domain/Notifiers/IChatEventNotifier.cs +++ b/EOLib/Domain/Notifiers/IChatEventNotifier.cs @@ -35,4 +35,4 @@ public void NotifyServerMessage(string serverMessage) { } public void NotifyServerPing(int timeInMS) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IChestEventNotifier.cs b/EOLib/Domain/Notifiers/IChestEventNotifier.cs index 462ebe9f2..b68b0b383 100644 --- a/EOLib/Domain/Notifiers/IChestEventNotifier.cs +++ b/EOLib/Domain/Notifiers/IChestEventNotifier.cs @@ -15,4 +15,4 @@ public void NotifyChestLocked(ChestKey key) { } public void NotifyChestBroken() { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IEffectNotifier.cs b/EOLib/Domain/Notifiers/IEffectNotifier.cs index e4d51ee76..34646c2a0 100644 --- a/EOLib/Domain/Notifiers/IEffectNotifier.cs +++ b/EOLib/Domain/Notifiers/IEffectNotifier.cs @@ -34,4 +34,4 @@ public void NotifyEffectAtLocation(MapCoordinate location, int effectId) { } public void NotifyAdminHideEffect(int playerId) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IEmoteNotifier.cs b/EOLib/Domain/Notifiers/IEmoteNotifier.cs index 633150fff..3a7aa8095 100644 --- a/EOLib/Domain/Notifiers/IEmoteNotifier.cs +++ b/EOLib/Domain/Notifiers/IEmoteNotifier.cs @@ -17,4 +17,4 @@ public void NotifyEmote(int playerId, Emote emote) { } public void MakeMainPlayerDrunk() { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/ILockerEventNotifier.cs b/EOLib/Domain/Notifiers/ILockerEventNotifier.cs index 01516f84e..1fcbc8381 100644 --- a/EOLib/Domain/Notifiers/ILockerEventNotifier.cs +++ b/EOLib/Domain/Notifiers/ILockerEventNotifier.cs @@ -12,4 +12,4 @@ public class NoOpLockerEventNotifier : ILockerEventNotifier { public void NotifyLockerFull(int maxItems) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IMainCharacterEventNotifier.cs b/EOLib/Domain/Notifiers/IMainCharacterEventNotifier.cs index b20867128..498d3b1e7 100644 --- a/EOLib/Domain/Notifiers/IMainCharacterEventNotifier.cs +++ b/EOLib/Domain/Notifiers/IMainCharacterEventNotifier.cs @@ -29,4 +29,4 @@ public void DropItem(int id, int amountDropped) { } public void JunkItem(int id, int amountTaken) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IMapChangedNotifier.cs b/EOLib/Domain/Notifiers/IMapChangedNotifier.cs index 4ee0256fe..1d866780d 100644 --- a/EOLib/Domain/Notifiers/IMapChangedNotifier.cs +++ b/EOLib/Domain/Notifiers/IMapChangedNotifier.cs @@ -17,4 +17,4 @@ public void NotifyMapChanged(WarpEffect warpEffect, bool differentMapID) { } public void NotifyMapMutation() { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/INPCActionNotifier.cs b/EOLib/Domain/Notifiers/INPCActionNotifier.cs index 63df65f7c..0a4c1ae77 100644 --- a/EOLib/Domain/Notifiers/INPCActionNotifier.cs +++ b/EOLib/Domain/Notifiers/INPCActionNotifier.cs @@ -34,4 +34,4 @@ public void NPCTakeDamage(int npcIndex, int fromPlayerId, int damageToNpc, int n public void NPCDropItem(MapItem item) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IOtherCharacterAnimationNotifier.cs b/EOLib/Domain/Notifiers/IOtherCharacterAnimationNotifier.cs index 6e6c5e743..85fe5365a 100644 --- a/EOLib/Domain/Notifiers/IOtherCharacterAnimationNotifier.cs +++ b/EOLib/Domain/Notifiers/IOtherCharacterAnimationNotifier.cs @@ -39,4 +39,4 @@ public void NotifyTargetOtherSpellCast(int sourcePlayerID, int targetPlayerID, i public void NotifyGroupSpellCast(int playerId, int spellId, int spellHp, List spellTargets) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IOtherCharacterEventNotifier.cs b/EOLib/Domain/Notifiers/IOtherCharacterEventNotifier.cs index f42022e28..ea066dca6 100644 --- a/EOLib/Domain/Notifiers/IOtherCharacterEventNotifier.cs +++ b/EOLib/Domain/Notifiers/IOtherCharacterEventNotifier.cs @@ -24,4 +24,4 @@ public void OtherCharacterSaySomethingToGroup(int characterID, string message) { public void AdminAnnounce(string message) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IPartyEventNotifier.cs b/EOLib/Domain/Notifiers/IPartyEventNotifier.cs index a4567f4c5..afea7c603 100644 --- a/EOLib/Domain/Notifiers/IPartyEventNotifier.cs +++ b/EOLib/Domain/Notifiers/IPartyEventNotifier.cs @@ -25,4 +25,4 @@ public void NotifyPartyMemberAdd(string name) { } public void NotifyPartyMemberRemove(string name) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IServerRebootNotifier.cs b/EOLib/Domain/Notifiers/IServerRebootNotifier.cs index 51fe93f7c..950170bec 100644 --- a/EOLib/Domain/Notifiers/IServerRebootNotifier.cs +++ b/EOLib/Domain/Notifiers/IServerRebootNotifier.cs @@ -12,4 +12,4 @@ public class NoOpServerRebootNotifier : IServerRebootNotifier { public void NotifyServerReboot() { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/ISoundNotifier.cs b/EOLib/Domain/Notifiers/ISoundNotifier.cs index 6cc702636..f698f996e 100644 --- a/EOLib/Domain/Notifiers/ISoundNotifier.cs +++ b/EOLib/Domain/Notifiers/ISoundNotifier.cs @@ -16,4 +16,4 @@ public void NotifySoundEffect(int soundEffectId) { } public void NotifyMusic(int musicEffectId, bool isJukebox) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/ITradeEventNotifier.cs b/EOLib/Domain/Notifiers/ITradeEventNotifier.cs index e45cbd451..b3fc62cf2 100644 --- a/EOLib/Domain/Notifiers/ITradeEventNotifier.cs +++ b/EOLib/Domain/Notifiers/ITradeEventNotifier.cs @@ -20,4 +20,4 @@ public void NotifyTradeAccepted() { } public void NotifyTradeClose(bool cancel) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Notifiers/IUserInterfaceNotifier.cs b/EOLib/Domain/Notifiers/IUserInterfaceNotifier.cs index ae2533207..df280ff03 100644 --- a/EOLib/Domain/Notifiers/IUserInterfaceNotifier.cs +++ b/EOLib/Domain/Notifiers/IUserInterfaceNotifier.cs @@ -28,4 +28,4 @@ public void NotifyCharacterInfo(string name, int mapId, MapCoordinate mapCoords, public void NotifyCharacterInventory(string name, int usage, int gold, IReadOnlyList inventory, IReadOnlyList bank) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Online/OnlinePlayerActions.cs b/EOLib/Domain/Online/OnlinePlayerActions.cs index 5febe33fd..5231d91d3 100644 --- a/EOLib/Domain/Online/OnlinePlayerActions.cs +++ b/EOLib/Domain/Online/OnlinePlayerActions.cs @@ -25,4 +25,4 @@ public interface IOnlinePlayerActions { void RequestOnlinePlayers(bool fullList); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Online/OnlinePlayerInfo.cs b/EOLib/Domain/Online/OnlinePlayerInfo.cs index 01ff54eae..0cba01ca9 100644 --- a/EOLib/Domain/Online/OnlinePlayerInfo.cs +++ b/EOLib/Domain/Online/OnlinePlayerInfo.cs @@ -21,4 +21,4 @@ public OnlinePlayerInfo(string name) { } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Online/OnlinePlayerRepository.cs b/EOLib/Domain/Online/OnlinePlayerRepository.cs index 4f271f538..8bf27d4a5 100644 --- a/EOLib/Domain/Online/OnlinePlayerRepository.cs +++ b/EOLib/Domain/Online/OnlinePlayerRepository.cs @@ -5,7 +5,7 @@ namespace EOLib.Domain.Online { public interface IOnlinePlayerRepository : IResettable { - HashSet OnlinePlayers { get; set; } + HashSet OnlinePlayers { get; set; } } public interface IOnlinePlayerProvider @@ -30,4 +30,4 @@ public void ResetState() OnlinePlayers = new HashSet(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Party/PartyActions.cs b/EOLib/Domain/Party/PartyActions.cs index 2f6f8b843..3dd08b0ea 100644 --- a/EOLib/Domain/Party/PartyActions.cs +++ b/EOLib/Domain/Party/PartyActions.cs @@ -60,4 +60,4 @@ public interface IPartyActions void RemovePartyMember(int targetCharacterId); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Party/PartyMember.cs b/EOLib/Domain/Party/PartyMember.cs index 8e0a4e7e2..e927f4e0f 100644 --- a/EOLib/Domain/Party/PartyMember.cs +++ b/EOLib/Domain/Party/PartyMember.cs @@ -15,4 +15,4 @@ public sealed partial class PartyMember public string Name { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Party/PartyRepository.cs b/EOLib/Domain/Party/PartyRepository.cs index 6f39e3702..0406caad7 100644 --- a/EOLib/Domain/Party/PartyRepository.cs +++ b/EOLib/Domain/Party/PartyRepository.cs @@ -8,7 +8,7 @@ public interface IPartyDataRepository List Members { get; } } - public interface IPartyDataProvider + public interface IPartyDataProvider { IReadOnlyList Members { get; } } @@ -25,4 +25,4 @@ public PartyDataRepository() Members = new List(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Protocol/PingTimeRepository.cs b/EOLib/Domain/Protocol/PingTimeRepository.cs index f50454169..d96e60976 100644 --- a/EOLib/Domain/Protocol/PingTimeRepository.cs +++ b/EOLib/Domain/Protocol/PingTimeRepository.cs @@ -18,4 +18,4 @@ public PingTimeRepository() RequestTimer = new Stopwatch(); } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Report/ReportActions.cs b/EOLib/Domain/Report/ReportActions.cs index fb86fc0cd..8d1b0d5c1 100644 --- a/EOLib/Domain/Report/ReportActions.cs +++ b/EOLib/Domain/Report/ReportActions.cs @@ -37,4 +37,4 @@ public interface IReportActions void SpeakToAdmin(string message); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/ResetStateAction.cs b/EOLib/Domain/ResetStateAction.cs index e66f6214c..00aafc9af 100644 --- a/EOLib/Domain/ResetStateAction.cs +++ b/EOLib/Domain/ResetStateAction.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; using AutomaticTypeMapper; +using System.Collections.Generic; namespace EOLib.Domain { diff --git a/EOLib/Domain/Spells/GroupSpellTarget.cs b/EOLib/Domain/Spells/GroupSpellTarget.cs index 49cefc465..dc721d6ba 100644 --- a/EOLib/Domain/Spells/GroupSpellTarget.cs +++ b/EOLib/Domain/Spells/GroupSpellTarget.cs @@ -11,4 +11,4 @@ public sealed partial class GroupSpellTarget public int TargetHp { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Spells/ISpellTargetable.cs b/EOLib/Domain/Spells/ISpellTargetable.cs index 1da2033de..a919b666a 100644 --- a/EOLib/Domain/Spells/ISpellTargetable.cs +++ b/EOLib/Domain/Spells/ISpellTargetable.cs @@ -8,4 +8,4 @@ public interface ISpellTargetable : IMapEntity int Index { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Spells/SpellCastValidationActions.cs b/EOLib/Domain/Spells/SpellCastValidationActions.cs index 2382a869e..76829b55b 100644 --- a/EOLib/Domain/Spells/SpellCastValidationActions.cs +++ b/EOLib/Domain/Spells/SpellCastValidationActions.cs @@ -88,4 +88,4 @@ public interface ISpellCastValidationActions bool ValidateBard(); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Spells/SpellCastValidationResult.cs b/EOLib/Domain/Spells/SpellCastValidationResult.cs index 0be33f540..1a3e456ec 100644 --- a/EOLib/Domain/Spells/SpellCastValidationResult.cs +++ b/EOLib/Domain/Spells/SpellCastValidationResult.cs @@ -8,4 +8,4 @@ public enum SpellCastValidationResult ExhaustedNoSp, ExhaustedNoTp, } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Trade/TradeActions.cs b/EOLib/Domain/Trade/TradeActions.cs index 96e61aad8..d0f754f07 100644 --- a/EOLib/Domain/Trade/TradeActions.cs +++ b/EOLib/Domain/Trade/TradeActions.cs @@ -28,7 +28,7 @@ public void AcceptTradeRequest(int characterID) public void RemoveItemFromOffer(int itemID) { - var packet = new TradeRemoveClientPacket { ItemId = itemID }; + var packet = new TradeRemoveClientPacket { ItemId = itemID }; _packetSendService.SendPacket(packet); } @@ -68,4 +68,4 @@ public interface ITradeActions void CancelTrade(); } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Trade/TradeOffer.cs b/EOLib/Domain/Trade/TradeOffer.cs index 71e2d219d..fb967c410 100644 --- a/EOLib/Domain/Trade/TradeOffer.cs +++ b/EOLib/Domain/Trade/TradeOffer.cs @@ -15,4 +15,4 @@ public sealed partial class TradeOffer public IReadOnlyList Items { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Domain/Trade/TradeRepository.cs b/EOLib/Domain/Trade/TradeRepository.cs index 124ac54dc..fb69fb78b 100644 --- a/EOLib/Domain/Trade/TradeRepository.cs +++ b/EOLib/Domain/Trade/TradeRepository.cs @@ -36,4 +36,4 @@ public void ResetState() PlayerTwoOffer = new TradeOffer(false, 0, string.Empty, new List()); } } -} +} \ No newline at end of file diff --git a/EOLib/EODirection.cs b/EOLib/EODirection.cs index a5de40f19..025f1ed1a 100644 --- a/EOLib/EODirection.cs +++ b/EOLib/EODirection.cs @@ -18,7 +18,7 @@ public static EODirection Opposite(this EODirection direction) switch (direction) { case EODirection.Invalid: return EODirection.Invalid; - default: return (EODirection) ((int) (direction + 2) % 4); + default: return (EODirection)((int)(direction + 2) % 4); } } } diff --git a/EOLib/Extensions/ChatIconExtensions.cs b/EOLib/Extensions/ChatIconExtensions.cs index 671c41ea3..e9ec826e8 100644 --- a/EOLib/Extensions/ChatIconExtensions.cs +++ b/EOLib/Extensions/ChatIconExtensions.cs @@ -10,4 +10,4 @@ public static class ChatIconExtensions return icon == ChatIcon.None ? Option.None<(int, int, int, int)>() : Option.Some((0, (int)icon * 13, 13, 13)); } } -} +} \ No newline at end of file diff --git a/EOLib/Extensions/OnlineIconExtensions.cs b/EOLib/Extensions/OnlineIconExtensions.cs index d498859a5..b5ce79a78 100644 --- a/EOLib/Extensions/OnlineIconExtensions.cs +++ b/EOLib/Extensions/OnlineIconExtensions.cs @@ -20,4 +20,4 @@ public static ChatIcon ToChatIcon(this CharacterIcon icon) }; } } -} +} \ No newline at end of file diff --git a/EOLib/FixedTimeStepRepository.cs b/EOLib/FixedTimeStepRepository.cs index 81cbe0ec5..1e8a3d47f 100644 --- a/EOLib/FixedTimeStepRepository.cs +++ b/EOLib/FixedTimeStepRepository.cs @@ -25,4 +25,4 @@ public interface IFixedTimeStepRepository void Tick(uint ticks = 1); } -} +} \ No newline at end of file diff --git a/EOLib/HDSerialNumberService.cs b/EOLib/HDSerialNumberService.cs index d077e8998..d5d5d72b8 100644 --- a/EOLib/HDSerialNumberService.cs +++ b/EOLib/HDSerialNumberService.cs @@ -1,11 +1,11 @@ -using System; +using AutomaticTypeMapper; +using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; -using AutomaticTypeMapper; namespace EOLib { @@ -36,12 +36,12 @@ private static string GetHDSerialNumberWindows() return Win32.GetVolumeInformation( strDriveLetter, volumeLabel, - (uint) volumeLabel.Capacity, + (uint)volumeLabel.Capacity, ref serNum, ref maxCompLen, ref VolFlags, fileSystemName, - (uint) fileSystemName.Capacity) != 0 + (uint)fileSystemName.Capacity) != 0 ? Convert.ToString(serNum) : string.Empty; } @@ -119,7 +119,7 @@ private static string GetHDSerialNumberOSX() } // replace letters with their corresponding numbers - serialNumber = Regex.Replace(serialNumber, "[A-Z]", m => ((int) m.Value[0] - 55).ToString()); + serialNumber = Regex.Replace(serialNumber, "[A-Z]", m => ((int)m.Value[0] - 55).ToString()); // make the serial number shorted so eoserv can handle it while (ulong.TryParse(serialNumber, out var sn) && sn > uint.MaxValue) @@ -136,4 +136,4 @@ private static string GetHDSerialNumberOSX() } } } -} +} \ No newline at end of file diff --git a/EOLib/IHDSerialNumberService.cs b/EOLib/IHDSerialNumberService.cs index 70973c1ef..37dfe6981 100644 --- a/EOLib/IHDSerialNumberService.cs +++ b/EOLib/IHDSerialNumberService.cs @@ -4,4 +4,4 @@ public interface IHDSerialNumberService { string GetHDSerialNumber(); } -} +} \ No newline at end of file diff --git a/EOLib/IResettable.cs b/EOLib/IResettable.cs index c9ac50b22..9fa23f70a 100644 --- a/EOLib/IResettable.cs +++ b/EOLib/IResettable.cs @@ -4,4 +4,4 @@ public interface IResettable { void ResetState(); } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/AsyncSocket.cs b/EOLib/Net/Communication/AsyncSocket.cs index a5fa860d0..26fde0eeb 100644 --- a/EOLib/Net/Communication/AsyncSocket.cs +++ b/EOLib/Net/Communication/AsyncSocket.cs @@ -138,19 +138,19 @@ private ConnectResult BlockingConnect(EndPoint endPoint) result = ConnectResult.Success; _connected = true; } - catch(ArgumentNullException) + catch (ArgumentNullException) { result = ConnectResult.InvalidEndpoint; } - catch(SocketException sex) + catch (SocketException sex) { result = ConnectResult.SocketError | (ConnectResult)sex.ErrorCode; } - catch(ObjectDisposedException) + catch (ObjectDisposedException) { result = ConnectResult.InvalidSocket; } - catch(InvalidOperationException) + catch (InvalidOperationException) { result = ConnectResult.InvalidSocket; } @@ -198,4 +198,4 @@ protected virtual void Dispose(bool disposing) #endregion } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/IAsyncSocket.cs b/EOLib/Net/Communication/IAsyncSocket.cs index b2df17594..73fbf9f2a 100644 --- a/EOLib/Net/Communication/IAsyncSocket.cs +++ b/EOLib/Net/Communication/IAsyncSocket.cs @@ -19,4 +19,4 @@ public interface IAsyncSocket : IDisposable Task DisconnectAsync(CancellationToken ct); } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/INetworkClient.cs b/EOLib/Net/Communication/INetworkClient.cs index 0d857d723..687534710 100644 --- a/EOLib/Net/Communication/INetworkClient.cs +++ b/EOLib/Net/Communication/INetworkClient.cs @@ -22,7 +22,7 @@ public interface INetworkClient : IDisposable int Send(IPacket packet); Task SendAsync(IPacket packet, int timeout = 1500); - + Task SendRawPacketAsync(IPacket packet, int timeout = 1500); } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/INetworkClientDisposer.cs b/EOLib/Net/Communication/INetworkClientDisposer.cs index beb54c36e..df6de1c22 100644 --- a/EOLib/Net/Communication/INetworkClientDisposer.cs +++ b/EOLib/Net/Communication/INetworkClientDisposer.cs @@ -5,4 +5,4 @@ namespace EOLib.Net.Communication public interface INetworkClientDisposer : IDisposable { } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/INetworkClientFactory.cs b/EOLib/Net/Communication/INetworkClientFactory.cs index ea701ed98..790817c49 100644 --- a/EOLib/Net/Communication/INetworkClientFactory.cs +++ b/EOLib/Net/Communication/INetworkClientFactory.cs @@ -4,4 +4,4 @@ public interface INetworkClientFactory { INetworkClient CreateNetworkClient(int timeout = Constants.ResponseTimeout); } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/INetworkClientRepository.cs b/EOLib/Net/Communication/INetworkClientRepository.cs index 62a86ba2b..0220d59b9 100644 --- a/EOLib/Net/Communication/INetworkClientRepository.cs +++ b/EOLib/Net/Communication/INetworkClientRepository.cs @@ -16,11 +16,11 @@ public interface INetworkClientProvider public sealed class NetworkClientRepository : INetworkClientProvider, INetworkClientRepository, INetworkClientDisposer { public INetworkClient NetworkClient { get; set; } - + public void Dispose() { if (NetworkClient != null) NetworkClient.Dispose(); } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/IPacketQueue.cs b/EOLib/Net/Communication/IPacketQueue.cs index 45fae7cdd..b333ee0ce 100644 --- a/EOLib/Net/Communication/IPacketQueue.cs +++ b/EOLib/Net/Communication/IPacketQueue.cs @@ -15,4 +15,4 @@ public interface IPacketQueue IEnumerable DequeueAllPackets(); } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/IPacketQueueRepository.cs b/EOLib/Net/Communication/IPacketQueueRepository.cs index 67a172f01..00ef92cdd 100644 --- a/EOLib/Net/Communication/IPacketQueueRepository.cs +++ b/EOLib/Net/Communication/IPacketQueueRepository.cs @@ -36,4 +36,4 @@ public PacketQueueRepository() HandleOutOfBandPacketQueue = new PacketQueue(); } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/IPacketSendService.cs b/EOLib/Net/Communication/IPacketSendService.cs index cb8588548..8070f377e 100644 --- a/EOLib/Net/Communication/IPacketSendService.cs +++ b/EOLib/Net/Communication/IPacketSendService.cs @@ -13,4 +13,4 @@ public interface IPacketSendService Task SendEncodedPacketAndWaitAsync(IPacket packet); } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/ISafeNetworkOperation.cs b/EOLib/Net/Communication/ISafeNetworkOperation.cs index 5750287cd..4b11e7053 100644 --- a/EOLib/Net/Communication/ISafeNetworkOperation.cs +++ b/EOLib/Net/Communication/ISafeNetworkOperation.cs @@ -11,4 +11,4 @@ public interface ISafeNetworkOperation : ISafeNetworkOperation { T Result { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/NetworkClient.cs b/EOLib/Net/Communication/NetworkClient.cs index 2c1472bf0..514555f72 100644 --- a/EOLib/Net/Communication/NetworkClient.cs +++ b/EOLib/Net/Communication/NetworkClient.cs @@ -17,7 +17,7 @@ public class NetworkClient : INetworkClient private readonly INumberEncoderService _numberEncoderService; private readonly IAsyncSocket _socket; - + public bool Connected => _socket.Connected; public bool Started { get; private set; } @@ -141,4 +141,4 @@ protected virtual void Dispose(bool disposing) } } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/NetworkClientFactory.cs b/EOLib/Net/Communication/NetworkClientFactory.cs index cd8370d92..ac3de85df 100644 --- a/EOLib/Net/Communication/NetworkClientFactory.cs +++ b/EOLib/Net/Communication/NetworkClientFactory.cs @@ -28,4 +28,4 @@ public INetworkClient CreateNetworkClient(int timeout = Constants.ResponseTimeou return new NetworkClient(_packetProcessActions, _packetHandlingActions, _numberEncoderService, TimeSpan.FromMilliseconds(timeout)); } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/PacketQueue.cs b/EOLib/Net/Communication/PacketQueue.cs index 2c0e59ce6..654a554da 100644 --- a/EOLib/Net/Communication/PacketQueue.cs +++ b/EOLib/Net/Communication/PacketQueue.cs @@ -96,4 +96,4 @@ private void SetSignalResult(bool result) Task.Run(() => _enqueuedTaskCompletionSource.SetResult(result)); } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/PacketSendService.cs b/EOLib/Net/Communication/PacketSendService.cs index ea225b6f2..7e53c29c0 100644 --- a/EOLib/Net/Communication/PacketSendService.cs +++ b/EOLib/Net/Communication/PacketSendService.cs @@ -1,6 +1,6 @@ -using System.Threading.Tasks; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using Moffat.EndlessOnline.SDK.Protocol.Net; +using System.Threading.Tasks; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/SafeAsyncNetworkOperation.cs b/EOLib/Net/Communication/SafeAsyncNetworkOperation.cs index 1cfcff5c6..82462da21 100644 --- a/EOLib/Net/Communication/SafeAsyncNetworkOperation.cs +++ b/EOLib/Net/Communication/SafeAsyncNetworkOperation.cs @@ -1,6 +1,6 @@ -using System; +using EOLib.Net.Connection; +using System; using System.Threading.Tasks; -using EOLib.Net.Connection; namespace EOLib.Net.Communication { @@ -25,4 +25,4 @@ protected override async Task DoOperation() await _networkOperation(); } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/SafeBlockingNetworkOperation.cs b/EOLib/Net/Communication/SafeBlockingNetworkOperation.cs index 2e0799c68..f8362e57a 100644 --- a/EOLib/Net/Communication/SafeBlockingNetworkOperation.cs +++ b/EOLib/Net/Communication/SafeBlockingNetworkOperation.cs @@ -1,6 +1,6 @@ -using System; +using EOLib.Net.Connection; +using System; using System.Threading.Tasks; -using EOLib.Net.Connection; namespace EOLib.Net.Communication { @@ -55,4 +55,4 @@ protected override async Task DoOperation() Result = await _operation(); } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/SafeNetworkOperationBase.cs b/EOLib/Net/Communication/SafeNetworkOperationBase.cs index b71f2ebc7..3f701550f 100644 --- a/EOLib/Net/Communication/SafeNetworkOperationBase.cs +++ b/EOLib/Net/Communication/SafeNetworkOperationBase.cs @@ -1,6 +1,6 @@ -using System; +using EOLib.Net.Connection; +using System; using System.Threading.Tasks; -using EOLib.Net.Connection; namespace EOLib.Net.Communication { @@ -44,4 +44,4 @@ private void DisconnectAndStopReceiving() _networkConnectionActions.DisconnectFromServer(); } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Communication/SafeNetworkOperationFactory.cs b/EOLib/Net/Communication/SafeNetworkOperationFactory.cs index 398877631..dfa78f277 100644 --- a/EOLib/Net/Communication/SafeNetworkOperationFactory.cs +++ b/EOLib/Net/Communication/SafeNetworkOperationFactory.cs @@ -1,7 +1,7 @@ -using System; -using System.Threading.Tasks; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EOLib.Net.Connection; +using System; +using System.Threading.Tasks; namespace EOLib.Net.Communication { @@ -53,4 +53,4 @@ public ISafeNetworkOperation CreateSafeAsyncOperation(Func networkOperatio sendErrorAction); } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Connection/BackgroundReceiveActions.cs b/EOLib/Net/Connection/BackgroundReceiveActions.cs index 40035fc1d..83483ef4f 100644 --- a/EOLib/Net/Connection/BackgroundReceiveActions.cs +++ b/EOLib/Net/Connection/BackgroundReceiveActions.cs @@ -41,4 +41,4 @@ private Task RunLoop() return _clientProvider.NetworkClient.RunReceiveLoopAsync(_backgroundReceiveTaskRepository.BackgroundCancellationTokenSource.Token); } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Connection/IBackgroundReceiveActions.cs b/EOLib/Net/Connection/IBackgroundReceiveActions.cs index 884aa0256..c26a6b3c9 100644 --- a/EOLib/Net/Connection/IBackgroundReceiveActions.cs +++ b/EOLib/Net/Connection/IBackgroundReceiveActions.cs @@ -6,4 +6,4 @@ public interface IBackgroundReceiveActions void CancelBackgroundReceiveLoop(); } -} +} \ No newline at end of file diff --git a/EOLib/Net/Connection/IBackgroundReceiveTaskRepository.cs b/EOLib/Net/Connection/IBackgroundReceiveTaskRepository.cs index 698958101..ec10cb704 100644 --- a/EOLib/Net/Connection/IBackgroundReceiveTaskRepository.cs +++ b/EOLib/Net/Connection/IBackgroundReceiveTaskRepository.cs @@ -18,4 +18,4 @@ public class BackgroundReceiveThreadRepository : IBackgroundReceiveTaskRepositor public CancellationTokenSource BackgroundCancellationTokenSource { get; set; } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Connection/INetworkConnectionActions.cs b/EOLib/Net/Connection/INetworkConnectionActions.cs index eb0ffcbe6..ab9335098 100644 --- a/EOLib/Net/Connection/INetworkConnectionActions.cs +++ b/EOLib/Net/Connection/INetworkConnectionActions.cs @@ -1,6 +1,6 @@ -using System.Threading.Tasks; -using EOLib.Net.Communication; +using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; +using System.Threading.Tasks; namespace EOLib.Net.Connection { @@ -14,4 +14,4 @@ public interface INetworkConnectionActions void CompleteHandshake(InitInitServerPacket initializationData); } -} +} \ No newline at end of file diff --git a/EOLib/Net/Connection/NetworkConnectionActions.cs b/EOLib/Net/Connection/NetworkConnectionActions.cs index db84e5e71..548248936 100644 --- a/EOLib/Net/Connection/NetworkConnectionActions.cs +++ b/EOLib/Net/Connection/NetworkConnectionActions.cs @@ -116,4 +116,4 @@ private static bool IsInvalidInitPacket(IPacket responsePacket, out InitInitServ private INetworkClient Client => _networkClientRepository.NetworkClient; } -} +} \ No newline at end of file diff --git a/EOLib/Net/EmptyPacketReceivedException.cs b/EOLib/Net/EmptyPacketReceivedException.cs index 2dffd25c4..5b28388d2 100644 --- a/EOLib/Net/EmptyPacketReceivedException.cs +++ b/EOLib/Net/EmptyPacketReceivedException.cs @@ -7,4 +7,4 @@ public class EmptyPacketReceivedException : Exception public EmptyPacketReceivedException() : base("No data was received from the server") { } } -} +} \ No newline at end of file diff --git a/EOLib/Net/FileTransfer/FileRequestService.cs b/EOLib/Net/FileTransfer/FileRequestService.cs index 017627042..a7d7aca84 100644 --- a/EOLib/Net/FileTransfer/FileRequestService.cs +++ b/EOLib/Net/FileTransfer/FileRequestService.cs @@ -156,7 +156,7 @@ private static WelcomeAgreeClientPacket.IFileTypeData GetPubRequestData(FileType _ => throw new ArgumentOutOfRangeException(nameof(fileType)), }; } - + private static bool PubFileIdMatches(int requestedFileId, InitInitServerPacket.IReplyCodeData replyCodeData, out int responseFileId) { if (replyCodeData is InitInitServerPacket.ReplyCodeDataFileEif eif) diff --git a/EOLib/Net/FileTransfer/LoginFileChecksumRepository.cs b/EOLib/Net/FileTransfer/LoginFileChecksumRepository.cs index c98dd70a5..a352471df 100644 --- a/EOLib/Net/FileTransfer/LoginFileChecksumRepository.cs +++ b/EOLib/Net/FileTransfer/LoginFileChecksumRepository.cs @@ -91,4 +91,4 @@ public class LoginFileChecksumRepository : ILoginFileChecksumRepository, ILoginF IReadOnlyList ILoginFileChecksumProvider.MapChecksum => MapChecksum; } -} +} \ No newline at end of file diff --git a/EOLib/Net/Handlers/DefaultAsyncPacketHandler.cs b/EOLib/Net/Handlers/DefaultAsyncPacketHandler.cs index 26f669da4..45a406fef 100644 --- a/EOLib/Net/Handlers/DefaultAsyncPacketHandler.cs +++ b/EOLib/Net/Handlers/DefaultAsyncPacketHandler.cs @@ -4,7 +4,7 @@ namespace EOLib.Net.Handlers { public abstract class DefaultAsyncPacketHandler : IPacketHandler - where TPacket: IPacket + where TPacket : IPacket { public abstract PacketFamily Family { get; } @@ -29,4 +29,4 @@ public async Task HandlePacketAsync(TPacket packet) return await Task.Run(() => HandlePacket(packet)); } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Handlers/FamilyActionPair.cs b/EOLib/Net/Handlers/FamilyActionPair.cs index 3ea13eb9e..9eaca0888 100644 --- a/EOLib/Net/Handlers/FamilyActionPair.cs +++ b/EOLib/Net/Handlers/FamilyActionPair.cs @@ -20,7 +20,7 @@ bool IEqualityComparer.Equals(object obj1, object obj2) if (!(obj1 is FamilyActionPair) || !(obj2 is FamilyActionPair)) return false; - var fap1 = (FamilyActionPair) obj1; + var fap1 = (FamilyActionPair)obj1; var fap2 = (FamilyActionPair)obj2; return fap1.Family == fap2.Family && fap1.Action == fap2.Action; } diff --git a/EOLib/Net/Handlers/IPacketHandler.cs b/EOLib/Net/Handlers/IPacketHandler.cs index 9bffa66e4..f938f0a9e 100644 --- a/EOLib/Net/Handlers/IPacketHandler.cs +++ b/EOLib/Net/Handlers/IPacketHandler.cs @@ -23,4 +23,4 @@ public interface IPacketHandler : IPacketHandler //todo: method to determine whether a packet should be handled asynchronously or not Task HandlePacketAsync(TPacket packet); } -} +} \ No newline at end of file diff --git a/EOLib/Net/Handlers/InGameOnlyPacketHandler.cs b/EOLib/Net/Handlers/InGameOnlyPacketHandler.cs index e691960c4..f6a6da670 100644 --- a/EOLib/Net/Handlers/InGameOnlyPacketHandler.cs +++ b/EOLib/Net/Handlers/InGameOnlyPacketHandler.cs @@ -15,4 +15,4 @@ protected InGameOnlyPacketHandler(IPlayerInfoProvider playerInfoProvider) _playerInfoProvider = playerInfoProvider; } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Handlers/OutOfBandPacketHandler.cs b/EOLib/Net/Handlers/OutOfBandPacketHandler.cs index ce5abab16..c0bdbdfa3 100644 --- a/EOLib/Net/Handlers/OutOfBandPacketHandler.cs +++ b/EOLib/Net/Handlers/OutOfBandPacketHandler.cs @@ -60,4 +60,4 @@ public interface IOutOfBandPacketHandler { void PollForPacketsAndHandle(); } -} +} \ No newline at end of file diff --git a/EOLib/Net/Handlers/PacketHandlerFinder.cs b/EOLib/Net/Handlers/PacketHandlerFinder.cs index 9ade14f55..b1f79e609 100644 --- a/EOLib/Net/Handlers/PacketHandlerFinder.cs +++ b/EOLib/Net/Handlers/PacketHandlerFinder.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; -using System.Linq; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using Moffat.EndlessOnline.SDK.Protocol.Net; +using System.Collections.Generic; +using System.Linq; namespace EOLib.Net.Handlers { @@ -9,7 +9,7 @@ namespace EOLib.Net.Handlers public class PacketHandlerFinder : IPacketHandlerFinder { private readonly IReadOnlyDictionary _handlers; - + public PacketHandlerFinder(IPacketHandlerProvider packetHandlerProvider) { _handlers = packetHandlerProvider.PacketHandlers diff --git a/EOLib/Net/Handlers/PacketHandlerProvider.cs b/EOLib/Net/Handlers/PacketHandlerProvider.cs index 1f5111b0e..d6d4284e0 100644 --- a/EOLib/Net/Handlers/PacketHandlerProvider.cs +++ b/EOLib/Net/Handlers/PacketHandlerProvider.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; -using AutomaticTypeMapper; +using AutomaticTypeMapper; +using System.Collections.Generic; namespace EOLib.Net.Handlers { @@ -18,4 +18,4 @@ public interface IPacketHandlerProvider { IEnumerable PacketHandlers { get; } } -} +} \ No newline at end of file diff --git a/EOLib/Net/Handlers/PacketHandlingTypeFinder.cs b/EOLib/Net/Handlers/PacketHandlingTypeFinder.cs index e5d4ac478..e144850cc 100644 --- a/EOLib/Net/Handlers/PacketHandlingTypeFinder.cs +++ b/EOLib/Net/Handlers/PacketHandlingTypeFinder.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; -using System.Linq; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using Moffat.EndlessOnline.SDK.Protocol.Net; +using System.Collections.Generic; +using System.Linq; namespace EOLib.Net.Handlers { diff --git a/EOLib/Net/NoDataSentException.cs b/EOLib/Net/NoDataSentException.cs index 491dc0579..2b39b9332 100644 --- a/EOLib/Net/NoDataSentException.cs +++ b/EOLib/Net/NoDataSentException.cs @@ -7,4 +7,4 @@ public class NoDataSentException : Exception public NoDataSentException() : base("No data was sent to the server.") { } } -} +} \ No newline at end of file diff --git a/EOLib/Net/PacketProcessing/HashService.cs b/EOLib/Net/PacketProcessing/HashService.cs index 0c587a5cb..ddf3c1672 100644 --- a/EOLib/Net/PacketProcessing/HashService.cs +++ b/EOLib/Net/PacketProcessing/HashService.cs @@ -13,4 +13,4 @@ public interface IHashService { int StupidHash(int challenge); } -} +} \ No newline at end of file diff --git a/EOLib/Net/PacketProcessing/PacketEncoderRepository.cs b/EOLib/Net/PacketProcessing/PacketEncoderRepository.cs index fb2b500b0..5611138b6 100644 --- a/EOLib/Net/PacketProcessing/PacketEncoderRepository.cs +++ b/EOLib/Net/PacketProcessing/PacketEncoderRepository.cs @@ -14,4 +14,4 @@ public interface IPacketEncoderRepository int ReceiveMultiplier { get; set; } int SendMultiplier { get; set; } } -} +} \ No newline at end of file diff --git a/EOLib/Net/PacketProcessing/PacketEncoderService.cs b/EOLib/Net/PacketProcessing/PacketEncoderService.cs index faf59c731..b31819dbd 100644 --- a/EOLib/Net/PacketProcessing/PacketEncoderService.cs +++ b/EOLib/Net/PacketProcessing/PacketEncoderService.cs @@ -77,4 +77,4 @@ public interface IPacketEncoderService Option Decode(byte[] original, int decodeMultiplier); } -} +} \ No newline at end of file diff --git a/EOLib/Net/PacketProcessing/PacketFactory.cs b/EOLib/Net/PacketProcessing/PacketFactory.cs index cbba7cee7..bef27f7bf 100644 --- a/EOLib/Net/PacketProcessing/PacketFactory.cs +++ b/EOLib/Net/PacketProcessing/PacketFactory.cs @@ -68,4 +68,4 @@ public interface IPacketFactory { Option Create(byte[] array); } -} +} \ No newline at end of file diff --git a/EOLib/Net/PacketProcessing/PacketFactoryFactory.cs b/EOLib/Net/PacketProcessing/PacketFactoryFactory.cs index 0423485bd..1eda01c51 100644 --- a/EOLib/Net/PacketProcessing/PacketFactoryFactory.cs +++ b/EOLib/Net/PacketProcessing/PacketFactoryFactory.cs @@ -15,4 +15,4 @@ public interface IPacketFactoryFactory { IPacketFactory Create(string name_space); } -} +} \ No newline at end of file diff --git a/EOLib/Net/PacketProcessing/PacketProcessActions.cs b/EOLib/Net/PacketProcessing/PacketProcessActions.cs index e69f0f2b3..aa7e887bb 100644 --- a/EOLib/Net/PacketProcessing/PacketProcessActions.cs +++ b/EOLib/Net/PacketProcessing/PacketProcessActions.cs @@ -1,11 +1,11 @@ -using System; -using AutomaticTypeMapper; -using Moffat.EndlessOnline.SDK.Data; +using AutomaticTypeMapper; using EOLib.Logger; +using Moffat.EndlessOnline.SDK.Data; using Moffat.EndlessOnline.SDK.Packet; using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Net.Sockets; using Optional; +using System; +using System.Net.Sockets; namespace EOLib.Net.PacketProcessing { @@ -89,4 +89,4 @@ public interface IPacketProcessActions Option DecodeData(byte[] rawData); } -} +} \ No newline at end of file diff --git a/EOLib/Net/PacketProcessing/SequenceRepository.cs b/EOLib/Net/PacketProcessing/SequenceRepository.cs index 38fdcbbd6..b341b9d40 100644 --- a/EOLib/Net/PacketProcessing/SequenceRepository.cs +++ b/EOLib/Net/PacketProcessing/SequenceRepository.cs @@ -12,7 +12,7 @@ public class SequenceRepository : ISequenceRepository public void ResetState() { - Sequencer = new PacketSequencer(ZeroSequence.Instance); + Sequencer = new PacketSequencer(ZeroSequence.Instance); } } @@ -20,4 +20,4 @@ public interface ISequenceRepository : IResettable { PacketSequencer Sequencer { get; set; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/AdminInteract/AdminInteractAgree.cs b/EOLib/PacketHandlers/AdminInteract/AdminInteractAgree.cs index f5585c72a..0ff814945 100644 --- a/EOLib/PacketHandlers/AdminInteract/AdminInteractAgree.cs +++ b/EOLib/PacketHandlers/AdminInteract/AdminInteractAgree.cs @@ -66,4 +66,4 @@ private static Character Shown(Character input) return input.WithRenderProperties(renderProps); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/AdminInteract/AdminInteractList.cs b/EOLib/PacketHandlers/AdminInteract/AdminInteractList.cs index 6d61ef0a0..c3cf5253a 100644 --- a/EOLib/PacketHandlers/AdminInteract/AdminInteractList.cs +++ b/EOLib/PacketHandlers/AdminInteract/AdminInteractList.cs @@ -41,4 +41,4 @@ public override bool HandlePacket(AdminInteractListServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/AdminInteract/AdminInteractRemove.cs b/EOLib/PacketHandlers/AdminInteract/AdminInteractRemove.cs index 6d1cdffc5..45c1cf94d 100644 --- a/EOLib/PacketHandlers/AdminInteract/AdminInteractRemove.cs +++ b/EOLib/PacketHandlers/AdminInteract/AdminInteractRemove.cs @@ -66,4 +66,4 @@ private static Character Hidden(Character input) return input.WithRenderProperties(renderProps); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/AdminInteract/AdminInteractReply.cs b/EOLib/PacketHandlers/AdminInteract/AdminInteractReply.cs index 11e688494..555a9f834 100644 --- a/EOLib/PacketHandlers/AdminInteract/AdminInteractReply.cs +++ b/EOLib/PacketHandlers/AdminInteract/AdminInteractReply.cs @@ -52,4 +52,4 @@ public override bool HandlePacket(AdminInteractReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/AdminInteract/AdminInteractTell.cs b/EOLib/PacketHandlers/AdminInteract/AdminInteractTell.cs index e4d05358c..9ea95f012 100644 --- a/EOLib/PacketHandlers/AdminInteract/AdminInteractTell.cs +++ b/EOLib/PacketHandlers/AdminInteract/AdminInteractTell.cs @@ -3,8 +3,8 @@ using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Domain.Notifiers; -using Moffat.EndlessOnline.SDK.Protocol.Net; using EOLib.Net.Handlers; +using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using System.Collections.Generic; @@ -14,7 +14,7 @@ namespace EOLib.PacketHandlers.AdminInteract /// Response to $info command. /// [AutoMappedType] - public class AdminInteractTell: InGameOnlyPacketHandler + public class AdminInteractTell : InGameOnlyPacketHandler { private readonly IEnumerable _userInterfaceNotifiers; @@ -75,4 +75,4 @@ public override bool HandlePacket(AdminInteractTellServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Arena/ArenaAcceptHandler.cs b/EOLib/PacketHandlers/Arena/ArenaAcceptHandler.cs index 61de6d005..d25e359aa 100644 --- a/EOLib/PacketHandlers/Arena/ArenaAcceptHandler.cs +++ b/EOLib/PacketHandlers/Arena/ArenaAcceptHandler.cs @@ -38,4 +38,4 @@ public override bool HandlePacket(ArenaAcceptServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Arena/ArenaDropHandler.cs b/EOLib/PacketHandlers/Arena/ArenaDropHandler.cs index e74f3bc27..57b1b6c7b 100644 --- a/EOLib/PacketHandlers/Arena/ArenaDropHandler.cs +++ b/EOLib/PacketHandlers/Arena/ArenaDropHandler.cs @@ -29,7 +29,7 @@ public ArenaDropHandler(IPlayerInfoProvider playerInfoProvider, public override bool HandlePacket(ArenaDropServerPacket packet) { - foreach (var notifier in _arenaNotifiers) + foreach (var notifier in _arenaNotifiers) { notifier.NotifyArenaBusy(); } @@ -37,4 +37,4 @@ public override bool HandlePacket(ArenaDropServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Arena/ArenaSpecHandler.cs b/EOLib/PacketHandlers/Arena/ArenaSpecHandler.cs index 5985e609f..dbcadd350 100644 --- a/EOLib/PacketHandlers/Arena/ArenaSpecHandler.cs +++ b/EOLib/PacketHandlers/Arena/ArenaSpecHandler.cs @@ -54,7 +54,7 @@ public override bool HandlePacket(ArenaSpecServerPacket packet) _currentMapStateRepository.UnknownPlayerIDs.Add(packet.PlayerId); } - foreach (var notifier in _arenaNotifiers) + foreach (var notifier in _arenaNotifiers) { notifier.NotifyArenaKill(packet.KillsCount, packet.KillerName, packet.VictimName); } @@ -62,4 +62,4 @@ public override bool HandlePacket(ArenaSpecServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Arena/ArenaUseHandler.cs b/EOLib/PacketHandlers/Arena/ArenaUseHandler.cs index a55ddaae8..8170f87b2 100644 --- a/EOLib/PacketHandlers/Arena/ArenaUseHandler.cs +++ b/EOLib/PacketHandlers/Arena/ArenaUseHandler.cs @@ -29,7 +29,7 @@ public ArenaUseHandler(IPlayerInfoProvider playerInfoProvider, public override bool HandlePacket(ArenaUseServerPacket packet) { - foreach (var notifier in _arenaNotifiers) + foreach (var notifier in _arenaNotifiers) { notifier.NotifyArenaStart(packet.PlayersCount); } @@ -37,4 +37,4 @@ public override bool HandlePacket(ArenaUseServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Attack/AttackPlayerHandler.cs b/EOLib/PacketHandlers/Attack/AttackPlayerHandler.cs index 55ab5bf7d..fc7901488 100644 --- a/EOLib/PacketHandlers/Attack/AttackPlayerHandler.cs +++ b/EOLib/PacketHandlers/Attack/AttackPlayerHandler.cs @@ -52,4 +52,4 @@ public override bool HandlePacket(AttackPlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Avatar/AvatarAdminHandler.cs b/EOLib/PacketHandlers/Avatar/AvatarAdminHandler.cs index aef2c89f9..1a839f5c4 100644 --- a/EOLib/PacketHandlers/Avatar/AvatarAdminHandler.cs +++ b/EOLib/PacketHandlers/Avatar/AvatarAdminHandler.cs @@ -93,4 +93,4 @@ public override bool HandlePacket(AvatarAdminServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Avatar/AvatarAgreeHandler.cs b/EOLib/PacketHandlers/Avatar/AvatarAgreeHandler.cs index 29d8a95c3..097a894fc 100644 --- a/EOLib/PacketHandlers/Avatar/AvatarAgreeHandler.cs +++ b/EOLib/PacketHandlers/Avatar/AvatarAgreeHandler.cs @@ -30,4 +30,4 @@ public override bool HandlePacket(AvatarAgreeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Avatar/AvatarChangeHandler.cs b/EOLib/PacketHandlers/Avatar/AvatarChangeHandler.cs index 899e3654b..2047e489e 100644 --- a/EOLib/PacketHandlers/Avatar/AvatarChangeHandler.cs +++ b/EOLib/PacketHandlers/Avatar/AvatarChangeHandler.cs @@ -80,4 +80,4 @@ protected void Handle(AvatarChange change) } } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Avatar/AvatarRemoveHandler.cs b/EOLib/PacketHandlers/Avatar/AvatarRemoveHandler.cs index f95d05552..6e5b86834 100644 --- a/EOLib/PacketHandlers/Avatar/AvatarRemoveHandler.cs +++ b/EOLib/PacketHandlers/Avatar/AvatarRemoveHandler.cs @@ -55,4 +55,4 @@ public override bool HandlePacket(AvatarRemoveServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Avatar/AvatarReplyHandler.cs b/EOLib/PacketHandlers/Avatar/AvatarReplyHandler.cs index 49777336b..16eaaa0cf 100644 --- a/EOLib/PacketHandlers/Avatar/AvatarReplyHandler.cs +++ b/EOLib/PacketHandlers/Avatar/AvatarReplyHandler.cs @@ -21,7 +21,7 @@ public class AvatarReplyHandler : InGameOnlyPacketHandler PacketFamily.Avatar; - + public override PacketAction Action => PacketAction.Reply; public AvatarReplyHandler(IPlayerInfoProvider playerInfoProvider, @@ -87,4 +87,4 @@ public override bool HandlePacket(AvatarReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Bank/BankOpenHandler.cs b/EOLib/PacketHandlers/Bank/BankOpenHandler.cs index c31491d1b..d28096e1e 100644 --- a/EOLib/PacketHandlers/Bank/BankOpenHandler.cs +++ b/EOLib/PacketHandlers/Bank/BankOpenHandler.cs @@ -33,4 +33,4 @@ public override bool HandlePacket(BankOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Bank/BankReplyHandler.cs b/EOLib/PacketHandlers/Bank/BankReplyHandler.cs index bcb761267..a90c85f84 100644 --- a/EOLib/PacketHandlers/Bank/BankReplyHandler.cs +++ b/EOLib/PacketHandlers/Bank/BankReplyHandler.cs @@ -47,4 +47,4 @@ public override bool HandlePacket(BankReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Barber/BarberAgreeHandler.cs b/EOLib/PacketHandlers/Barber/BarberAgreeHandler.cs index 1b4dd2f5c..5eef396aa 100644 --- a/EOLib/PacketHandlers/Barber/BarberAgreeHandler.cs +++ b/EOLib/PacketHandlers/Barber/BarberAgreeHandler.cs @@ -74,4 +74,4 @@ private CharacterRenderProperties UpdateRenderProperties(Character currentCharac return currentRenderProps; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Barber/BarberOpenHandler.cs b/EOLib/PacketHandlers/Barber/BarberOpenHandler.cs index 505e1438d..678c5e506 100644 --- a/EOLib/PacketHandlers/Barber/BarberOpenHandler.cs +++ b/EOLib/PacketHandlers/Barber/BarberOpenHandler.cs @@ -41,4 +41,4 @@ public override bool HandlePacket(BarberOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Board/BoardOpenHandler.cs b/EOLib/PacketHandlers/Board/BoardOpenHandler.cs index 32bf5c0f3..f980932ae 100644 --- a/EOLib/PacketHandlers/Board/BoardOpenHandler.cs +++ b/EOLib/PacketHandlers/Board/BoardOpenHandler.cs @@ -52,4 +52,4 @@ public override bool HandlePacket(BoardOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Board/BoardPlayerHandler.cs b/EOLib/PacketHandlers/Board/BoardPlayerHandler.cs index e1b771808..aaf6986ff 100644 --- a/EOLib/PacketHandlers/Board/BoardPlayerHandler.cs +++ b/EOLib/PacketHandlers/Board/BoardPlayerHandler.cs @@ -41,4 +41,4 @@ public override bool HandlePacket(BoardPlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Book/BookReplyHandler.cs b/EOLib/PacketHandlers/Book/BookReplyHandler.cs index 86c69aade..93f249f49 100644 --- a/EOLib/PacketHandlers/Book/BookReplyHandler.cs +++ b/EOLib/PacketHandlers/Book/BookReplyHandler.cs @@ -51,4 +51,4 @@ public override bool HandlePacket(BookReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Cast/CastAcceptHandler.cs b/EOLib/PacketHandlers/Cast/CastAcceptHandler.cs index a0b6312d8..41d6131ef 100644 --- a/EOLib/PacketHandlers/Cast/CastAcceptHandler.cs +++ b/EOLib/PacketHandlers/Cast/CastAcceptHandler.cs @@ -48,4 +48,4 @@ public override bool HandlePacket(CastAcceptServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Cast/CastReplyHandler.cs b/EOLib/PacketHandlers/Cast/CastReplyHandler.cs index cce7feaea..ba2588fc6 100644 --- a/EOLib/PacketHandlers/Cast/CastReplyHandler.cs +++ b/EOLib/PacketHandlers/Cast/CastReplyHandler.cs @@ -33,4 +33,4 @@ public override bool HandlePacket(CastReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Cast/CastSpecHandler.cs b/EOLib/PacketHandlers/Cast/CastSpecHandler.cs index c29e5b49a..e4b7c99fa 100644 --- a/EOLib/PacketHandlers/Cast/CastSpecHandler.cs +++ b/EOLib/PacketHandlers/Cast/CastSpecHandler.cs @@ -41,4 +41,4 @@ public override bool HandlePacket(CastSpecServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chair/ChairCloseHandler.cs b/EOLib/PacketHandlers/Chair/ChairCloseHandler.cs index a157f2543..7ff9e68d4 100644 --- a/EOLib/PacketHandlers/Chair/ChairCloseHandler.cs +++ b/EOLib/PacketHandlers/Chair/ChairCloseHandler.cs @@ -29,4 +29,4 @@ public override bool HandlePacket(ChairCloseServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chair/ChairPlayerHandler.cs b/EOLib/PacketHandlers/Chair/ChairPlayerHandler.cs index 8434bc759..05706c0c2 100644 --- a/EOLib/PacketHandlers/Chair/ChairPlayerHandler.cs +++ b/EOLib/PacketHandlers/Chair/ChairPlayerHandler.cs @@ -27,4 +27,4 @@ public override bool HandlePacket(ChairPlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chair/ChairRemoveHandler.cs b/EOLib/PacketHandlers/Chair/ChairRemoveHandler.cs index 3c1be6003..c0b4a5e91 100644 --- a/EOLib/PacketHandlers/Chair/ChairRemoveHandler.cs +++ b/EOLib/PacketHandlers/Chair/ChairRemoveHandler.cs @@ -29,4 +29,4 @@ public override bool HandlePacket(ChairRemoveServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chair/ChairReplyHandler.cs b/EOLib/PacketHandlers/Chair/ChairReplyHandler.cs index 4b53e494e..8cbed737b 100644 --- a/EOLib/PacketHandlers/Chair/ChairReplyHandler.cs +++ b/EOLib/PacketHandlers/Chair/ChairReplyHandler.cs @@ -29,4 +29,4 @@ public override bool HandlePacket(ChairReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chat/GroupChatHandler.cs b/EOLib/PacketHandlers/Chat/GroupChatHandler.cs index aa14e4adb..6650f25ef 100644 --- a/EOLib/PacketHandlers/Chat/GroupChatHandler.cs +++ b/EOLib/PacketHandlers/Chat/GroupChatHandler.cs @@ -52,4 +52,4 @@ protected override void DoTalk(TalkOpenServerPacket packet, Character character) notifier.NotifyChatReceived(ChatEventType.Group); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chat/MuteHandler.cs b/EOLib/PacketHandlers/Chat/MuteHandler.cs index 4ae521879..dc315aa5a 100644 --- a/EOLib/PacketHandlers/Chat/MuteHandler.cs +++ b/EOLib/PacketHandlers/Chat/MuteHandler.cs @@ -35,4 +35,4 @@ public override bool HandlePacket(TalkSpecServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chat/PlayerChatByIDHandler.cs b/EOLib/PacketHandlers/Chat/PlayerChatByIDHandler.cs index 6921dbb51..f0330cd26 100644 --- a/EOLib/PacketHandlers/Chat/PlayerChatByIDHandler.cs +++ b/EOLib/PacketHandlers/Chat/PlayerChatByIDHandler.cs @@ -42,4 +42,4 @@ protected bool Handle(TPacket packet, int fromPlayerID) protected abstract void DoTalk(TPacket packet, Character character); } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chat/PlayerChatByNameBase.cs b/EOLib/PacketHandlers/Chat/PlayerChatByNameBase.cs index 3f81df9c4..51dcfc675 100644 --- a/EOLib/PacketHandlers/Chat/PlayerChatByNameBase.cs +++ b/EOLib/PacketHandlers/Chat/PlayerChatByNameBase.cs @@ -22,4 +22,4 @@ protected bool Handle(string name, string message) protected abstract void PostChat(string name, string message); } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chat/PrivateMessageTargetNotFound.cs b/EOLib/PacketHandlers/Chat/PrivateMessageTargetNotFound.cs index 0b7bc046b..d428fbc52 100644 --- a/EOLib/PacketHandlers/Chat/PrivateMessageTargetNotFound.cs +++ b/EOLib/PacketHandlers/Chat/PrivateMessageTargetNotFound.cs @@ -51,4 +51,4 @@ public override bool HandlePacket(TalkReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chat/TalkServerHandler.cs b/EOLib/PacketHandlers/Chat/TalkServerHandler.cs index 82c871a8c..7a32c987f 100644 --- a/EOLib/PacketHandlers/Chat/TalkServerHandler.cs +++ b/EOLib/PacketHandlers/Chat/TalkServerHandler.cs @@ -34,4 +34,4 @@ public override bool HandlePacket(TalkServerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chest/ChestAgreeHandler.cs b/EOLib/PacketHandlers/Chest/ChestAgreeHandler.cs index f6f1fdd72..e68c90278 100644 --- a/EOLib/PacketHandlers/Chest/ChestAgreeHandler.cs +++ b/EOLib/PacketHandlers/Chest/ChestAgreeHandler.cs @@ -31,4 +31,4 @@ public override bool HandlePacket(ChestAgreeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chest/ChestCloseHandler.cs b/EOLib/PacketHandlers/Chest/ChestCloseHandler.cs index 75caeae5b..311fb7eb0 100644 --- a/EOLib/PacketHandlers/Chest/ChestCloseHandler.cs +++ b/EOLib/PacketHandlers/Chest/ChestCloseHandler.cs @@ -39,4 +39,4 @@ public override bool HandlePacket(ChestCloseServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chest/ChestGetHandler.cs b/EOLib/PacketHandlers/Chest/ChestGetHandler.cs index 4cf31b4a9..3a3905b22 100644 --- a/EOLib/PacketHandlers/Chest/ChestGetHandler.cs +++ b/EOLib/PacketHandlers/Chest/ChestGetHandler.cs @@ -31,4 +31,4 @@ public override bool HandlePacket(ChestGetServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chest/ChestItemUpdateHandler.cs b/EOLib/PacketHandlers/Chest/ChestItemUpdateHandler.cs index a7fe35b4e..adb0b9720 100644 --- a/EOLib/PacketHandlers/Chest/ChestItemUpdateHandler.cs +++ b/EOLib/PacketHandlers/Chest/ChestItemUpdateHandler.cs @@ -65,4 +65,4 @@ protected void Handle(List items, ThreeItem item, Weight weight, bool _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithStats(stats); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chest/ChestOpenHandler.cs b/EOLib/PacketHandlers/Chest/ChestOpenHandler.cs index 30841cdc6..69e5aed3c 100644 --- a/EOLib/PacketHandlers/Chest/ChestOpenHandler.cs +++ b/EOLib/PacketHandlers/Chest/ChestOpenHandler.cs @@ -41,4 +41,4 @@ public override bool HandlePacket(ChestOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Chest/ChestReplyHandler.cs b/EOLib/PacketHandlers/Chest/ChestReplyHandler.cs index d3a564f8b..c6e78397d 100644 --- a/EOLib/PacketHandlers/Chest/ChestReplyHandler.cs +++ b/EOLib/PacketHandlers/Chest/ChestReplyHandler.cs @@ -36,4 +36,4 @@ public override bool HandlePacket(ChestReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Citizen/CitizenAcceptHandler.cs b/EOLib/PacketHandlers/Citizen/CitizenAcceptHandler.cs index a17f0da5c..7965079d4 100644 --- a/EOLib/PacketHandlers/Citizen/CitizenAcceptHandler.cs +++ b/EOLib/PacketHandlers/Citizen/CitizenAcceptHandler.cs @@ -48,4 +48,4 @@ public override bool HandlePacket(CitizenAcceptServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Citizen/CitizenOpenHandler.cs b/EOLib/PacketHandlers/Citizen/CitizenOpenHandler.cs index fb90f1a84..bcd7a2d60 100644 --- a/EOLib/PacketHandlers/Citizen/CitizenOpenHandler.cs +++ b/EOLib/PacketHandlers/Citizen/CitizenOpenHandler.cs @@ -50,4 +50,4 @@ public override bool HandlePacket(CitizenOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Citizen/CitizenRemoveHandler.cs b/EOLib/PacketHandlers/Citizen/CitizenRemoveHandler.cs index 731769c67..4fec1b1d9 100644 --- a/EOLib/PacketHandlers/Citizen/CitizenRemoveHandler.cs +++ b/EOLib/PacketHandlers/Citizen/CitizenRemoveHandler.cs @@ -43,4 +43,4 @@ public override bool HandlePacket(CitizenRemoveServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Citizen/CitizenReplyHandler.cs b/EOLib/PacketHandlers/Citizen/CitizenReplyHandler.cs index 7aac1825c..4516a3a5f 100644 --- a/EOLib/PacketHandlers/Citizen/CitizenReplyHandler.cs +++ b/EOLib/PacketHandlers/Citizen/CitizenReplyHandler.cs @@ -35,4 +35,4 @@ public override bool HandlePacket(CitizenReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Citizen/CitizenRequestHandler.cs b/EOLib/PacketHandlers/Citizen/CitizenRequestHandler.cs index 7fa284201..ca0a44b10 100644 --- a/EOLib/PacketHandlers/Citizen/CitizenRequestHandler.cs +++ b/EOLib/PacketHandlers/Citizen/CitizenRequestHandler.cs @@ -35,4 +35,4 @@ public override bool HandlePacket(CitizenRequestServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Commands/FindCommandHandlerBase.cs b/EOLib/PacketHandlers/Commands/FindCommandHandlerBase.cs index 81c076fc2..978961345 100644 --- a/EOLib/PacketHandlers/Commands/FindCommandHandlerBase.cs +++ b/EOLib/PacketHandlers/Commands/FindCommandHandlerBase.cs @@ -30,4 +30,4 @@ protected void Handle(string playerName, EOResourceID resourceId) _chatRespository.AllChat[ChatTab.Local].Add(chatData); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Commands/FindCommandPlayerDifferentMapHandler.cs b/EOLib/PacketHandlers/Commands/FindCommandPlayerDifferentMapHandler.cs index c61604f80..df72b3462 100644 --- a/EOLib/PacketHandlers/Commands/FindCommandPlayerDifferentMapHandler.cs +++ b/EOLib/PacketHandlers/Commands/FindCommandPlayerDifferentMapHandler.cs @@ -25,4 +25,4 @@ public override bool HandlePacket(PlayersNet242ServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Commands/FindCommandPlayerNotFoundHandler.cs b/EOLib/PacketHandlers/Commands/FindCommandPlayerNotFoundHandler.cs index 4887ed977..256a9332c 100644 --- a/EOLib/PacketHandlers/Commands/FindCommandPlayerNotFoundHandler.cs +++ b/EOLib/PacketHandlers/Commands/FindCommandPlayerNotFoundHandler.cs @@ -25,4 +25,4 @@ public override bool HandlePacket(PlayersPingServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Commands/FindCommandPlayerSameMapHandler.cs b/EOLib/PacketHandlers/Commands/FindCommandPlayerSameMapHandler.cs index e941cffe1..3d59d340b 100644 --- a/EOLib/PacketHandlers/Commands/FindCommandPlayerSameMapHandler.cs +++ b/EOLib/PacketHandlers/Commands/FindCommandPlayerSameMapHandler.cs @@ -25,4 +25,4 @@ public override bool HandlePacket(PlayersPongServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Commands/PingResponseHandler.cs b/EOLib/PacketHandlers/Commands/PingResponseHandler.cs index 53310700b..6ea95ede5 100644 --- a/EOLib/PacketHandlers/Commands/PingResponseHandler.cs +++ b/EOLib/PacketHandlers/Commands/PingResponseHandler.cs @@ -42,4 +42,4 @@ public override bool HandlePacket(MessagePongServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Connection/ConnectionPlayerHandler.cs b/EOLib/PacketHandlers/Connection/ConnectionPlayerHandler.cs index 66ab01a83..93ae62f4c 100644 --- a/EOLib/PacketHandlers/Connection/ConnectionPlayerHandler.cs +++ b/EOLib/PacketHandlers/Connection/ConnectionPlayerHandler.cs @@ -48,4 +48,4 @@ public override bool HandlePacket(ConnectionPlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Door/DoorOpenHandler.cs b/EOLib/PacketHandlers/Door/DoorOpenHandler.cs index 4a669810f..debe7e5d3 100644 --- a/EOLib/PacketHandlers/Door/DoorOpenHandler.cs +++ b/EOLib/PacketHandlers/Door/DoorOpenHandler.cs @@ -56,4 +56,4 @@ public override bool HandlePacket(DoorOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Effects/EffectAgreeHandler.cs b/EOLib/PacketHandlers/Effects/EffectAgreeHandler.cs index 352d45b98..5c7deb250 100644 --- a/EOLib/PacketHandlers/Effects/EffectAgreeHandler.cs +++ b/EOLib/PacketHandlers/Effects/EffectAgreeHandler.cs @@ -35,4 +35,4 @@ public override bool HandlePacket(EffectAgreeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Effects/EffectPotionHandler.cs b/EOLib/PacketHandlers/Effects/EffectPotionHandler.cs index 567481f33..dfebc201b 100644 --- a/EOLib/PacketHandlers/Effects/EffectPotionHandler.cs +++ b/EOLib/PacketHandlers/Effects/EffectPotionHandler.cs @@ -34,4 +34,4 @@ public override bool HandlePacket(EffectPlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Effects/MapDebuffHandler.cs b/EOLib/PacketHandlers/Effects/MapDebuffHandler.cs index ee386077f..cb9634a43 100644 --- a/EOLib/PacketHandlers/Effects/MapDebuffHandler.cs +++ b/EOLib/PacketHandlers/Effects/MapDebuffHandler.cs @@ -87,4 +87,4 @@ public override bool HandlePacket(EffectSpecServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Effects/MapHpDrainHandler.cs b/EOLib/PacketHandlers/Effects/MapHpDrainHandler.cs index 2d6b5cc27..35b6c73f4 100644 --- a/EOLib/PacketHandlers/Effects/MapHpDrainHandler.cs +++ b/EOLib/PacketHandlers/Effects/MapHpDrainHandler.cs @@ -60,4 +60,4 @@ public override bool HandlePacket(EffectTargetOtherServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Effects/MapQuakeHandler.cs b/EOLib/PacketHandlers/Effects/MapQuakeHandler.cs index ff3a19023..da85a63a8 100644 --- a/EOLib/PacketHandlers/Effects/MapQuakeHandler.cs +++ b/EOLib/PacketHandlers/Effects/MapQuakeHandler.cs @@ -34,4 +34,4 @@ public override bool HandlePacket(EffectUseServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Effects/PlayerSpikeDamageHandler.cs b/EOLib/PacketHandlers/Effects/PlayerSpikeDamageHandler.cs index f069fb0ac..7829f00a1 100644 --- a/EOLib/PacketHandlers/Effects/PlayerSpikeDamageHandler.cs +++ b/EOLib/PacketHandlers/Effects/PlayerSpikeDamageHandler.cs @@ -49,4 +49,4 @@ public override bool HandlePacket(EffectAdminServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Effects/TimedSpikeEffectHandler.cs b/EOLib/PacketHandlers/Effects/TimedSpikeEffectHandler.cs index 65fb871b7..c267894aa 100644 --- a/EOLib/PacketHandlers/Effects/TimedSpikeEffectHandler.cs +++ b/EOLib/PacketHandlers/Effects/TimedSpikeEffectHandler.cs @@ -55,4 +55,4 @@ public override bool HandlePacket(EffectReportServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Emote/EmotePlayerHandler.cs b/EOLib/PacketHandlers/Emote/EmotePlayerHandler.cs index a5fdbe1cf..dccf7a6d5 100644 --- a/EOLib/PacketHandlers/Emote/EmotePlayerHandler.cs +++ b/EOLib/PacketHandlers/Emote/EmotePlayerHandler.cs @@ -35,4 +35,4 @@ public override bool HandlePacket(EmotePlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Face/FacePlayerHandler.cs b/EOLib/PacketHandlers/Face/FacePlayerHandler.cs index 53b7ee521..750c45f56 100644 --- a/EOLib/PacketHandlers/Face/FacePlayerHandler.cs +++ b/EOLib/PacketHandlers/Face/FacePlayerHandler.cs @@ -44,4 +44,4 @@ public override bool HandlePacket(FacePlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Init/FriendIgnoreListHandler.cs b/EOLib/PacketHandlers/Init/FriendIgnoreListHandler.cs index a17805da7..abd0a303f 100644 --- a/EOLib/PacketHandlers/Init/FriendIgnoreListHandler.cs +++ b/EOLib/PacketHandlers/Init/FriendIgnoreListHandler.cs @@ -27,4 +27,4 @@ public override bool HandleData(InitInitServerPacket.ReplyCodeDataPlayersListFri return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Init/IInitPacketHandler.cs b/EOLib/PacketHandlers/Init/IInitPacketHandler.cs index 42a65f18f..cf3606904 100644 --- a/EOLib/PacketHandlers/Init/IInitPacketHandler.cs +++ b/EOLib/PacketHandlers/Init/IInitPacketHandler.cs @@ -25,4 +25,4 @@ public bool HandleData(InitInitServerPacket.IReplyCodeData data) public abstract bool HandleData(TData data); } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Init/InGameInitPacketHandler.cs b/EOLib/PacketHandlers/Init/InGameInitPacketHandler.cs index 23ee8469d..0a9737d9e 100644 --- a/EOLib/PacketHandlers/Init/InGameInitPacketHandler.cs +++ b/EOLib/PacketHandlers/Init/InGameInitPacketHandler.cs @@ -30,4 +30,4 @@ public override bool HandlePacket(InitInitServerPacket packet) .Match(x => x.HandleData(packet.ReplyCodeData), () => false); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Init/MapMutationHandler.cs b/EOLib/PacketHandlers/Init/MapMutationHandler.cs index e8832887c..6a7d6e43b 100644 --- a/EOLib/PacketHandlers/Init/MapMutationHandler.cs +++ b/EOLib/PacketHandlers/Init/MapMutationHandler.cs @@ -50,4 +50,4 @@ public override bool HandleData(InitInitServerPacket.ReplyCodeDataMapMutation pa return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Init/MapWarpFileDownloadHandler.cs b/EOLib/PacketHandlers/Init/MapWarpFileDownloadHandler.cs index 0e6d71211..28a05b2d2 100644 --- a/EOLib/PacketHandlers/Init/MapWarpFileDownloadHandler.cs +++ b/EOLib/PacketHandlers/Init/MapWarpFileDownloadHandler.cs @@ -68,4 +68,4 @@ private void SendWarpAcceptToServer(int mapID, int sessionID) }); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Init/OnlinePlayerListHandler.cs b/EOLib/PacketHandlers/Init/OnlinePlayerListHandler.cs index 51567a18b..4024bd429 100644 --- a/EOLib/PacketHandlers/Init/OnlinePlayerListHandler.cs +++ b/EOLib/PacketHandlers/Init/OnlinePlayerListHandler.cs @@ -46,4 +46,4 @@ public override bool HandleData(InitInitServerPacket.ReplyCodeDataPlayersList pa return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/ItemAcceptHandler.cs b/EOLib/PacketHandlers/Items/ItemAcceptHandler.cs index 92a0cb2d2..4212475b8 100644 --- a/EOLib/PacketHandlers/Items/ItemAcceptHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemAcceptHandler.cs @@ -35,4 +35,4 @@ public override bool HandlePacket(ItemAcceptServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/ItemAddHandler.cs b/EOLib/PacketHandlers/Items/ItemAddHandler.cs index 2ae3bf71e..e2571b93f 100644 --- a/EOLib/PacketHandlers/Items/ItemAddHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemAddHandler.cs @@ -37,4 +37,4 @@ public override bool HandlePacket(ItemAddServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/ItemAgreeHandler.cs b/EOLib/PacketHandlers/Items/ItemAgreeHandler.cs index 23589e30d..ab8dd5014 100644 --- a/EOLib/PacketHandlers/Items/ItemAgreeHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemAgreeHandler.cs @@ -29,4 +29,4 @@ public override bool HandlePacket(ItemAgreeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/ItemDropHandler.cs b/EOLib/PacketHandlers/Items/ItemDropHandler.cs index 649daea80..2ed349ffa 100644 --- a/EOLib/PacketHandlers/Items/ItemDropHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemDropHandler.cs @@ -61,4 +61,4 @@ public override bool HandlePacket(ItemDropServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/ItemGetHandler.cs b/EOLib/PacketHandlers/Items/ItemGetHandler.cs index 25e987221..b199602fb 100644 --- a/EOLib/PacketHandlers/Items/ItemGetHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemGetHandler.cs @@ -65,4 +65,4 @@ public override bool HandlePacket(ItemGetServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/ItemJunkHandler.cs b/EOLib/PacketHandlers/Items/ItemJunkHandler.cs index c2947e7d3..b236ef9ef 100644 --- a/EOLib/PacketHandlers/Items/ItemJunkHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemJunkHandler.cs @@ -58,4 +58,4 @@ public override bool HandlePacket(ItemJunkServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/ItemKickHandler.cs b/EOLib/PacketHandlers/Items/ItemKickHandler.cs index 6622d1ac8..aac48dc86 100644 --- a/EOLib/PacketHandlers/Items/ItemKickHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemKickHandler.cs @@ -27,4 +27,4 @@ public override bool HandlePacket(ItemKickServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/ItemObtainHandler.cs b/EOLib/PacketHandlers/Items/ItemObtainHandler.cs index 2823250e5..ce2c85275 100644 --- a/EOLib/PacketHandlers/Items/ItemObtainHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemObtainHandler.cs @@ -27,4 +27,4 @@ public override bool HandlePacket(ItemObtainServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/ItemRemoveHandler.cs b/EOLib/PacketHandlers/Items/ItemRemoveHandler.cs index a335d0c39..27c8b165f 100644 --- a/EOLib/PacketHandlers/Items/ItemRemoveHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemRemoveHandler.cs @@ -33,4 +33,4 @@ public override bool HandlePacket(ItemRemoveServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/ItemReplyHandler.cs b/EOLib/PacketHandlers/Items/ItemReplyHandler.cs index 2175f08c0..f9a6ce975 100644 --- a/EOLib/PacketHandlers/Items/ItemReplyHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemReplyHandler.cs @@ -174,4 +174,4 @@ public override bool HandlePacket(ItemReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Items/QuestItemChangeHandler.cs b/EOLib/PacketHandlers/Items/QuestItemChangeHandler.cs index 129aa409a..52ff637d9 100644 --- a/EOLib/PacketHandlers/Items/QuestItemChangeHandler.cs +++ b/EOLib/PacketHandlers/Items/QuestItemChangeHandler.cs @@ -45,4 +45,4 @@ protected void Handle(int id, int amount, int weight) _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithStats(stats); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxAgreeHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxAgreeHandler.cs index c2da3b1c9..0530d9d01 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxAgreeHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxAgreeHandler.cs @@ -35,4 +35,4 @@ public override bool HandlePacket(JukeboxAgreeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxMessageHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxMessageHandler.cs index dcc101c58..6736f9868 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxMessageHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxMessageHandler.cs @@ -49,4 +49,4 @@ public override bool HandlePacket(JukeboxMsgServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxOpenHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxOpenHandler.cs index 70d270898..cc3868b55 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxOpenHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxOpenHandler.cs @@ -39,4 +39,4 @@ public override bool HandlePacket(JukeboxOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxPlayerHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxPlayerHandler.cs index 6feb8f16f..dbe30102d 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxPlayerHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxPlayerHandler.cs @@ -34,4 +34,4 @@ public override bool HandlePacket(JukeboxPlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxReplyHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxReplyHandler.cs index 76dbb3bd5..71bc1a6af 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxReplyHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxReplyHandler.cs @@ -31,4 +31,4 @@ public override bool HandlePacket(JukeboxReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxUseHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxUseHandler.cs index ac6147b05..9a2dd932f 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxUseHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxUseHandler.cs @@ -42,4 +42,4 @@ public override bool HandlePacket(JukeboxUseServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Locker/LockerBuyHandler.cs b/EOLib/PacketHandlers/Locker/LockerBuyHandler.cs index 441290903..1ee22bcc9 100644 --- a/EOLib/PacketHandlers/Locker/LockerBuyHandler.cs +++ b/EOLib/PacketHandlers/Locker/LockerBuyHandler.cs @@ -48,4 +48,4 @@ public override bool HandlePacket(LockerBuyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Locker/LockerGetHandler.cs b/EOLib/PacketHandlers/Locker/LockerGetHandler.cs index c6c0aa019..d1bca1aa3 100644 --- a/EOLib/PacketHandlers/Locker/LockerGetHandler.cs +++ b/EOLib/PacketHandlers/Locker/LockerGetHandler.cs @@ -30,4 +30,4 @@ public override bool HandlePacket(LockerGetServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Locker/LockerModifyHandler.cs b/EOLib/PacketHandlers/Locker/LockerModifyHandler.cs index 3e0c48fc8..77e59102c 100644 --- a/EOLib/PacketHandlers/Locker/LockerModifyHandler.cs +++ b/EOLib/PacketHandlers/Locker/LockerModifyHandler.cs @@ -57,4 +57,4 @@ protected void Handle(int itemId, int amount, Weight weight, IReadOnlyList mainCharacterEventNotifiers, IEnumerable otherCharacterAnimationNotifiers) : base(playerInfoProvider, characterRepository, currentMapStateRepository, characterSessionRepository, - npcActionNotifiers, mainCharacterEventNotifiers, otherCharacterAnimationNotifiers) { } + npcActionNotifiers, mainCharacterEventNotifiers, otherCharacterAnimationNotifiers) + { } public override bool HandlePacket(NpcSpecServerPacket packet) { @@ -37,4 +38,4 @@ public override bool HandlePacket(NpcSpecServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/NPC/NPCTakeDamageHandler.cs b/EOLib/PacketHandlers/NPC/NPCTakeDamageHandler.cs index aadcbe2f7..35e2f92b8 100644 --- a/EOLib/PacketHandlers/NPC/NPCTakeDamageHandler.cs +++ b/EOLib/PacketHandlers/NPC/NPCTakeDamageHandler.cs @@ -89,4 +89,4 @@ protected void Handle(int fromPlayerId, EODirection fromDirection, }); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Paperdoll/ItemEquipHandler.cs b/EOLib/PacketHandlers/Paperdoll/ItemEquipHandler.cs index 63ae34d9d..5d2cbdc4a 100644 --- a/EOLib/PacketHandlers/Paperdoll/ItemEquipHandler.cs +++ b/EOLib/PacketHandlers/Paperdoll/ItemEquipHandler.cs @@ -105,4 +105,4 @@ protected bool HandlePaperdollPacket(AvatarChange change, int itemId, int amount return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Paperdoll/PaperdollAgreeHandler.cs b/EOLib/PacketHandlers/Paperdoll/PaperdollAgreeHandler.cs index 0378152a8..e37a1ffd9 100644 --- a/EOLib/PacketHandlers/Paperdoll/PaperdollAgreeHandler.cs +++ b/EOLib/PacketHandlers/Paperdoll/PaperdollAgreeHandler.cs @@ -33,4 +33,4 @@ public override bool HandlePacket(PaperdollAgreeServerPacket packet) return HandlePaperdollPacket(packet.Change, packet.ItemId, packet.RemainingAmount, packet.SubLoc, packet.Stats); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Paperdoll/PaperdollRemoveHandler.cs b/EOLib/PacketHandlers/Paperdoll/PaperdollRemoveHandler.cs index 30089fce3..92debdbcf 100644 --- a/EOLib/PacketHandlers/Paperdoll/PaperdollRemoveHandler.cs +++ b/EOLib/PacketHandlers/Paperdoll/PaperdollRemoveHandler.cs @@ -33,4 +33,4 @@ public override bool HandlePacket(PaperdollRemoveServerPacket packet) return HandlePaperdollPacket(packet.Change, packet.ItemId, 1, packet.SubLoc, packet.Stats); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Paperdoll/PaperdollReplyHandler.cs b/EOLib/PacketHandlers/Paperdoll/PaperdollReplyHandler.cs index c4d2650bf..b72fd9687 100644 --- a/EOLib/PacketHandlers/Paperdoll/PaperdollReplyHandler.cs +++ b/EOLib/PacketHandlers/Paperdoll/PaperdollReplyHandler.cs @@ -69,4 +69,4 @@ public override bool HandlePacket(PaperdollReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Party/PartyAddHandler.cs b/EOLib/PacketHandlers/Party/PartyAddHandler.cs index 06297ac57..d6059216e 100644 --- a/EOLib/PacketHandlers/Party/PartyAddHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyAddHandler.cs @@ -50,4 +50,4 @@ public override bool HandlePacket(PartyAddServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Party/PartyAgreeHandler.cs b/EOLib/PacketHandlers/Party/PartyAgreeHandler.cs index 8305bee4d..ed978a2aa 100644 --- a/EOLib/PacketHandlers/Party/PartyAgreeHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyAgreeHandler.cs @@ -45,4 +45,4 @@ public override bool HandlePacket(PartyAgreeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Party/PartyCloseHandler.cs b/EOLib/PacketHandlers/Party/PartyCloseHandler.cs index 52f284bbd..a15da9d3f 100644 --- a/EOLib/PacketHandlers/Party/PartyCloseHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyCloseHandler.cs @@ -32,4 +32,4 @@ public override bool HandlePacket(PartyCloseServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Party/PartyCreateHandler.cs b/EOLib/PacketHandlers/Party/PartyCreateHandler.cs index 67f1c3b23..9b2737117 100644 --- a/EOLib/PacketHandlers/Party/PartyCreateHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyCreateHandler.cs @@ -53,4 +53,4 @@ public override bool HandlePacket(PartyCreateServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Party/PartyListHandler.cs b/EOLib/PacketHandlers/Party/PartyListHandler.cs index 392866582..2bafd4947 100644 --- a/EOLib/PacketHandlers/Party/PartyListHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyListHandler.cs @@ -45,4 +45,4 @@ public override bool HandlePacket(PartyListServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Party/PartyRemoveHandler.cs b/EOLib/PacketHandlers/Party/PartyRemoveHandler.cs index 5ae585670..8bb7fb5d2 100644 --- a/EOLib/PacketHandlers/Party/PartyRemoveHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyRemoveHandler.cs @@ -45,4 +45,4 @@ public override bool HandlePacket(PartyRemoveServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Party/PartyRequestHandler.cs b/EOLib/PacketHandlers/Party/PartyRequestHandler.cs index 539cb3787..6a6e4d80f 100644 --- a/EOLib/PacketHandlers/Party/PartyRequestHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyRequestHandler.cs @@ -35,4 +35,4 @@ public override bool HandlePacket(PartyRequestServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Players/PlayersAgreeHandler.cs b/EOLib/PacketHandlers/Players/PlayersAgreeHandler.cs index 8e88df0e6..a08827987 100644 --- a/EOLib/PacketHandlers/Players/PlayersAgreeHandler.cs +++ b/EOLib/PacketHandlers/Players/PlayersAgreeHandler.cs @@ -92,4 +92,4 @@ public override bool HandlePacket(PlayersAgreeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Priest/PriestOpenHandler.cs b/EOLib/PacketHandlers/Priest/PriestOpenHandler.cs index a787b8e93..25fe5b7b0 100644 --- a/EOLib/PacketHandlers/Priest/PriestOpenHandler.cs +++ b/EOLib/PacketHandlers/Priest/PriestOpenHandler.cs @@ -38,4 +38,4 @@ public override bool HandlePacket(PriestOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Priest/PriestReplyHandler.cs b/EOLib/PacketHandlers/Priest/PriestReplyHandler.cs index c1241ab36..dd241fe3e 100644 --- a/EOLib/PacketHandlers/Priest/PriestReplyHandler.cs +++ b/EOLib/PacketHandlers/Priest/PriestReplyHandler.cs @@ -32,4 +32,4 @@ public override bool HandlePacket(PriestReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Priest/PriestRequestHandler.cs b/EOLib/PacketHandlers/Priest/PriestRequestHandler.cs index 4db7646a8..e88647d95 100644 --- a/EOLib/PacketHandlers/Priest/PriestRequestHandler.cs +++ b/EOLib/PacketHandlers/Priest/PriestRequestHandler.cs @@ -38,4 +38,4 @@ public override bool HandlePacket(PriestRequestServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Quest/QuestDialogHandler.cs b/EOLib/PacketHandlers/Quest/QuestDialogHandler.cs index c4f1c368c..25f64220c 100644 --- a/EOLib/PacketHandlers/Quest/QuestDialogHandler.cs +++ b/EOLib/PacketHandlers/Quest/QuestDialogHandler.cs @@ -66,4 +66,4 @@ public override bool HandlePacket(QuestDialogServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Quest/QuestListHandler.cs b/EOLib/PacketHandlers/Quest/QuestListHandler.cs index 509492d59..d63bd1823 100644 --- a/EOLib/PacketHandlers/Quest/QuestListHandler.cs +++ b/EOLib/PacketHandlers/Quest/QuestListHandler.cs @@ -32,13 +32,13 @@ public override bool HandlePacket(QuestListServerPacket packet) _questDataRepository.QuestProgress = ((QuestListServerPacket.PageDataProgress)packet.PageData) .QuestProgressEntries .Select(x => new QuestProgressData.Builder - { - Name = x.Name, - Description = x.Description, - Icon = x.Icon, - Progress = x.Progress, - Target = x.Target, - }.ToImmutable()) + { + Name = x.Name, + Description = x.Description, + Icon = x.Icon, + Progress = x.Progress, + Target = x.Target, + }.ToImmutable()) .ToList(); break; case QuestPage.History: @@ -49,4 +49,4 @@ public override bool HandlePacket(QuestListServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Quest/QuestStatusMessageHandler.cs b/EOLib/PacketHandlers/Quest/QuestStatusMessageHandler.cs index eaa05780b..2fa34af49 100644 --- a/EOLib/PacketHandlers/Quest/QuestStatusMessageHandler.cs +++ b/EOLib/PacketHandlers/Quest/QuestStatusMessageHandler.cs @@ -39,4 +39,4 @@ public override bool HandlePacket(MessageOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Recover/RecoverAgreeHandler.cs b/EOLib/PacketHandlers/Recover/RecoverAgreeHandler.cs index 3cb204f9b..df88300ea 100644 --- a/EOLib/PacketHandlers/Recover/RecoverAgreeHandler.cs +++ b/EOLib/PacketHandlers/Recover/RecoverAgreeHandler.cs @@ -64,4 +64,4 @@ public override bool HandlePacket(RecoverAgreeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Recover/RecoverListHandler.cs b/EOLib/PacketHandlers/Recover/RecoverListHandler.cs index 20c346c69..ad3ef341a 100644 --- a/EOLib/PacketHandlers/Recover/RecoverListHandler.cs +++ b/EOLib/PacketHandlers/Recover/RecoverListHandler.cs @@ -37,4 +37,4 @@ public override bool HandlePacket(RecoverListServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Recover/RecoverPlayerHandler.cs b/EOLib/PacketHandlers/Recover/RecoverPlayerHandler.cs index 7f9f7d380..fd0e14fa0 100644 --- a/EOLib/PacketHandlers/Recover/RecoverPlayerHandler.cs +++ b/EOLib/PacketHandlers/Recover/RecoverPlayerHandler.cs @@ -36,4 +36,4 @@ public override bool HandlePacket(RecoverPlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Recover/RecoverReplyHandler.cs b/EOLib/PacketHandlers/Recover/RecoverReplyHandler.cs index ed6be1d5e..ec35fe928 100644 --- a/EOLib/PacketHandlers/Recover/RecoverReplyHandler.cs +++ b/EOLib/PacketHandlers/Recover/RecoverReplyHandler.cs @@ -59,4 +59,4 @@ public override bool HandlePacket(RecoverReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Refresh/RefreshReplyHandler.cs b/EOLib/PacketHandlers/Refresh/RefreshReplyHandler.cs index 482a1018f..35c76421e 100644 --- a/EOLib/PacketHandlers/Refresh/RefreshReplyHandler.cs +++ b/EOLib/PacketHandlers/Refresh/RefreshReplyHandler.cs @@ -53,7 +53,7 @@ public override bool HandlePacket(RefreshReplyServerPacket packet) .WithRenderProperties(updatedRenderProperties); var withoutMainCharacter = characters.Where(x => !MainCharacterIDMatches(x)); - _currentMapStateRepository.Characters = new MapEntityCollectionHashSet(c => c.ID, c => new MapCoordinate(c.X, c.Y), withoutMainCharacter); + _currentMapStateRepository.Characters = new MapEntityCollectionHashSet(c => c.ID, c => new MapCoordinate(c.X, c.Y), withoutMainCharacter); _currentMapStateRepository.NPCs = new MapEntityCollectionHashSet(n => n.Index, n => new MapCoordinate(n.X, n.Y), packet.Nearby.Npcs.Select(DomainNPC.FromNearby)); _currentMapStateRepository.MapItems = new MapEntityCollectionHashSet(item => item.UniqueID, item => new MapCoordinate(item.X, item.Y), packet.Nearby.Items.Select(MapItem.FromNearby)); @@ -73,4 +73,4 @@ private bool MainCharacterIDMatches(Character x) return x.ID == _characterRepository.MainCharacter.ID; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Shop/ShopCraftHandler.cs b/EOLib/PacketHandlers/Shop/ShopCraftHandler.cs index 1fe6b2b74..f4ee90a2b 100644 --- a/EOLib/PacketHandlers/Shop/ShopCraftHandler.cs +++ b/EOLib/PacketHandlers/Shop/ShopCraftHandler.cs @@ -77,4 +77,4 @@ public override bool HandlePacket(ShopCreateServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Shop/ShopOpenHandler.cs b/EOLib/PacketHandlers/Shop/ShopOpenHandler.cs index d44740a35..1b7496f9f 100644 --- a/EOLib/PacketHandlers/Shop/ShopOpenHandler.cs +++ b/EOLib/PacketHandlers/Shop/ShopOpenHandler.cs @@ -52,4 +52,4 @@ public override bool HandlePacket(ShopOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Shop/ShopTradeHandler.cs b/EOLib/PacketHandlers/Shop/ShopTradeHandler.cs index 17ac815fd..253ed14a1 100644 --- a/EOLib/PacketHandlers/Shop/ShopTradeHandler.cs +++ b/EOLib/PacketHandlers/Shop/ShopTradeHandler.cs @@ -116,4 +116,4 @@ public override bool HandlePacket(ShopSellServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Sit/PlayerSitHandlerBase.cs b/EOLib/PacketHandlers/Sit/PlayerSitHandlerBase.cs index 4a8347427..cca851d87 100644 --- a/EOLib/PacketHandlers/Sit/PlayerSitHandlerBase.cs +++ b/EOLib/PacketHandlers/Sit/PlayerSitHandlerBase.cs @@ -56,4 +56,4 @@ protected void Handle(int playerId, int x, int y, EODirection direction) } } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Sit/PlayerStandHandlerBase.cs b/EOLib/PacketHandlers/Sit/PlayerStandHandlerBase.cs index ca14b8a93..d961a4f5c 100644 --- a/EOLib/PacketHandlers/Sit/PlayerStandHandlerBase.cs +++ b/EOLib/PacketHandlers/Sit/PlayerStandHandlerBase.cs @@ -52,4 +52,4 @@ protected void Handle(int playerId, int x, int y) } } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Sit/SitCloseHandler.cs b/EOLib/PacketHandlers/Sit/SitCloseHandler.cs index 58b5643da..0ddc86913 100644 --- a/EOLib/PacketHandlers/Sit/SitCloseHandler.cs +++ b/EOLib/PacketHandlers/Sit/SitCloseHandler.cs @@ -26,4 +26,4 @@ public override bool HandlePacket(SitCloseServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Sit/SitPlayerHandler.cs b/EOLib/PacketHandlers/Sit/SitPlayerHandler.cs index f4dbd5cda..27a823c39 100644 --- a/EOLib/PacketHandlers/Sit/SitPlayerHandler.cs +++ b/EOLib/PacketHandlers/Sit/SitPlayerHandler.cs @@ -26,4 +26,4 @@ public override bool HandlePacket(SitPlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Sit/SitRemoveHandler.cs b/EOLib/PacketHandlers/Sit/SitRemoveHandler.cs index f9e652e45..934e9aa49 100644 --- a/EOLib/PacketHandlers/Sit/SitRemoveHandler.cs +++ b/EOLib/PacketHandlers/Sit/SitRemoveHandler.cs @@ -26,4 +26,4 @@ public override bool HandlePacket(SitRemoveServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Sit/SitReplyHandler.cs b/EOLib/PacketHandlers/Sit/SitReplyHandler.cs index d4e532bf2..e4569e998 100644 --- a/EOLib/PacketHandlers/Sit/SitReplyHandler.cs +++ b/EOLib/PacketHandlers/Sit/SitReplyHandler.cs @@ -28,4 +28,4 @@ public override bool HandlePacket(SitReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Spell/SpellRequestHandler.cs b/EOLib/PacketHandlers/Spell/SpellRequestHandler.cs index 7c102a36e..585dc200a 100644 --- a/EOLib/PacketHandlers/Spell/SpellRequestHandler.cs +++ b/EOLib/PacketHandlers/Spell/SpellRequestHandler.cs @@ -34,4 +34,4 @@ public override bool HandlePacket(SpellRequestServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Spell/SpellTargetGroupHandler.cs b/EOLib/PacketHandlers/Spell/SpellTargetGroupHandler.cs index 79525bea7..a4dc29e34 100644 --- a/EOLib/PacketHandlers/Spell/SpellTargetGroupHandler.cs +++ b/EOLib/PacketHandlers/Spell/SpellTargetGroupHandler.cs @@ -48,11 +48,11 @@ public override bool HandlePacket(SpellTargetGroupServerPacket packet) var spellTargets = packet.Players .Select(x => new GroupSpellTarget.Builder - { - TargetId = x.PlayerId, - TargetHp = x.Hp, - PercentHealth = x.HpPercentage, - }.ToImmutable()) + { + TargetId = x.PlayerId, + TargetHp = x.Hp, + PercentHealth = x.HpPercentage, + }.ToImmutable()) .ToList(); // todo: eoserv potentially sends garbage 255 bytes in packet.Players @@ -80,4 +80,4 @@ public override bool HandlePacket(SpellTargetGroupServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Spell/SpellTargetOtherHandler.cs b/EOLib/PacketHandlers/Spell/SpellTargetOtherHandler.cs index eda20f4b9..bd6a6b329 100644 --- a/EOLib/PacketHandlers/Spell/SpellTargetOtherHandler.cs +++ b/EOLib/PacketHandlers/Spell/SpellTargetOtherHandler.cs @@ -64,4 +64,4 @@ public override bool HandlePacket(SpellTargetOtherServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Spell/SpellTargetSelfHandler.cs b/EOLib/PacketHandlers/Spell/SpellTargetSelfHandler.cs index 060b71c65..d798fad89 100644 --- a/EOLib/PacketHandlers/Spell/SpellTargetSelfHandler.cs +++ b/EOLib/PacketHandlers/Spell/SpellTargetSelfHandler.cs @@ -52,4 +52,4 @@ public override bool HandlePacket(SpellTargetSelfServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/StatSkill/StatskillAcceptHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillAcceptHandler.cs index de80c6c61..d2a9a3d4a 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillAcceptHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillAcceptHandler.cs @@ -43,4 +43,4 @@ public override bool HandlePacket(StatSkillAcceptServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/StatSkill/StatskillJunkHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillJunkHandler.cs index 7108a2924..11a1d0ce1 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillJunkHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillJunkHandler.cs @@ -47,4 +47,4 @@ public override bool HandlePacket(StatSkillJunkServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/StatSkill/StatskillOpenHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillOpenHandler.cs index 52dcf4f6b..5c238d6ae 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillOpenHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillOpenHandler.cs @@ -58,4 +58,4 @@ public override bool HandlePacket(StatSkillOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/StatSkill/StatskillPlayerHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillPlayerHandler.cs index 150fed9ef..8f79a0a98 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillPlayerHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillPlayerHandler.cs @@ -36,4 +36,4 @@ public override bool HandlePacket(StatSkillPlayerServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/StatSkill/StatskillRemoveHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillRemoveHandler.cs index aeb7b1964..59f69d042 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillRemoveHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillRemoveHandler.cs @@ -41,4 +41,4 @@ public override bool HandlePacket(StatSkillRemoveServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/StatSkill/StatskillReplyHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillReplyHandler.cs index d60fdb338..df9267e84 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillReplyHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillReplyHandler.cs @@ -41,4 +41,4 @@ public override bool HandlePacket(StatSkillReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/StatSkill/StatskillTakeHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillTakeHandler.cs index 7c7aab8f6..7f89ccb59 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillTakeHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillTakeHandler.cs @@ -49,4 +49,4 @@ public override bool HandlePacket(StatSkillTakeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Trade/TradeAdminHandler.cs b/EOLib/PacketHandlers/Trade/TradeAdminHandler.cs index 90df7e008..809a84e0b 100644 --- a/EOLib/PacketHandlers/Trade/TradeAdminHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeAdminHandler.cs @@ -25,4 +25,4 @@ public override bool HandlePacket(TradeAdminServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Trade/TradeAgreeHandler.cs b/EOLib/PacketHandlers/Trade/TradeAgreeHandler.cs index 6ac83c4ca..60a67910f 100644 --- a/EOLib/PacketHandlers/Trade/TradeAgreeHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeAgreeHandler.cs @@ -37,4 +37,4 @@ public override bool HandlePacket(TradeAgreeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Trade/TradeCloseHandler.cs b/EOLib/PacketHandlers/Trade/TradeCloseHandler.cs index e0824090a..41302db77 100644 --- a/EOLib/PacketHandlers/Trade/TradeCloseHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeCloseHandler.cs @@ -41,4 +41,4 @@ public override bool HandlePacket(TradeCloseServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Trade/TradeOfferUpdateHandler.cs b/EOLib/PacketHandlers/Trade/TradeOfferUpdateHandler.cs index fb9d0495d..0e5929b38 100644 --- a/EOLib/PacketHandlers/Trade/TradeOfferUpdateHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeOfferUpdateHandler.cs @@ -48,4 +48,4 @@ protected void Handle(TradeItemData data) _tradeRepository.PlayerTwoOffer = _tradeRepository.PlayerTwoOffer.WithAgrees(false); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Trade/TradeOpenHandler.cs b/EOLib/PacketHandlers/Trade/TradeOpenHandler.cs index 798a2a230..362019b71 100644 --- a/EOLib/PacketHandlers/Trade/TradeOpenHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeOpenHandler.cs @@ -52,4 +52,4 @@ public override bool HandlePacket(TradeOpenServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Trade/TradeReplyHandler.cs b/EOLib/PacketHandlers/Trade/TradeReplyHandler.cs index 1f9ef1b94..d7154fc65 100644 --- a/EOLib/PacketHandlers/Trade/TradeReplyHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeReplyHandler.cs @@ -26,4 +26,4 @@ public override bool HandlePacket(TradeReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Trade/TradeRequestHandler.cs b/EOLib/PacketHandlers/Trade/TradeRequestHandler.cs index 363a4912d..c3e7d56fd 100644 --- a/EOLib/PacketHandlers/Trade/TradeRequestHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeRequestHandler.cs @@ -35,4 +35,4 @@ public override bool HandlePacket(TradeRequestServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Trade/TradeSpecHandler.cs b/EOLib/PacketHandlers/Trade/TradeSpecHandler.cs index 7fb3fbb01..5b99d1c22 100644 --- a/EOLib/PacketHandlers/Trade/TradeSpecHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeSpecHandler.cs @@ -38,4 +38,4 @@ public override bool HandlePacket(TradeSpecServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Trade/TradeUseHandler.cs b/EOLib/PacketHandlers/Trade/TradeUseHandler.cs index f7212b673..03cbc8f87 100644 --- a/EOLib/PacketHandlers/Trade/TradeUseHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeUseHandler.cs @@ -91,4 +91,4 @@ public override bool HandlePacket(TradeUseServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Walk/WalkPlayerHandler.cs b/EOLib/PacketHandlers/Walk/WalkPlayerHandler.cs index c8f4cc7cd..60476a544 100644 --- a/EOLib/PacketHandlers/Walk/WalkPlayerHandler.cs +++ b/EOLib/PacketHandlers/Walk/WalkPlayerHandler.cs @@ -70,4 +70,4 @@ private static CharacterRenderProperties EnsureCorrectXAndY(CharacterRenderPrope .WithMapY(tempRenderProperties.GetDestinationY()); } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Walk/WalkReplyHandler.cs b/EOLib/PacketHandlers/Walk/WalkReplyHandler.cs index e2d7e8db1..f6ad66578 100644 --- a/EOLib/PacketHandlers/Walk/WalkReplyHandler.cs +++ b/EOLib/PacketHandlers/Walk/WalkReplyHandler.cs @@ -48,4 +48,4 @@ public override bool HandlePacket(WalkReplyServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Warp/WarpAgreeHandler.cs b/EOLib/PacketHandlers/Warp/WarpAgreeHandler.cs index b17d758b0..b47d6ec91 100644 --- a/EOLib/PacketHandlers/Warp/WarpAgreeHandler.cs +++ b/EOLib/PacketHandlers/Warp/WarpAgreeHandler.cs @@ -93,4 +93,4 @@ public override bool HandlePacket(WarpAgreeServerPacket packet) return true; } } -} +} \ No newline at end of file diff --git a/EOLib/PacketHandlers/Warp/WarpRequestHandler.cs b/EOLib/PacketHandlers/Warp/WarpRequestHandler.cs index 92d0c9657..5648d560a 100644 --- a/EOLib/PacketHandlers/Warp/WarpRequestHandler.cs +++ b/EOLib/PacketHandlers/Warp/WarpRequestHandler.cs @@ -99,4 +99,4 @@ private void SendWarpAcceptToServer(int mapID, int sessionID) }); } } -} +} \ No newline at end of file diff --git a/EOLib/Win32.cs b/EOLib/Win32.cs index 0b1dd7141..60cf2e1d3 100644 --- a/EOLib/Win32.cs +++ b/EOLib/Win32.cs @@ -16,4 +16,4 @@ internal static extern int GetVolumeInformation(string PathName, StringBuilder FileSystemNameBuffer, UInt32 FileSystemNameSize); } -} +} \ No newline at end of file diff --git a/EOLib/misc.cs b/EOLib/misc.cs index 8f975832d..6f242f2d1 100644 --- a/EOLib/misc.cs +++ b/EOLib/misc.cs @@ -64,4 +64,4 @@ Copyright Vult-R public const string VersionInfoFormat = "{0}.{1:000}.{2:000} - {3}:{4}"; } -} +} \ No newline at end of file diff --git a/EndlessClient/Audio/AudioActions.cs b/EndlessClient/Audio/AudioActions.cs index b67791c13..17ead27e8 100644 --- a/EndlessClient/Audio/AudioActions.cs +++ b/EndlessClient/Audio/AudioActions.cs @@ -73,4 +73,4 @@ public interface IAudioActions void ToggleSound(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Audio/MfxPlayer.cs b/EndlessClient/Audio/MfxPlayer.cs index c6ef520db..fd3cd231f 100644 --- a/EndlessClient/Audio/MfxPlayer.cs +++ b/EndlessClient/Audio/MfxPlayer.cs @@ -135,4 +135,4 @@ public interface IMfxPlayer : IDisposable void StopBackgroundMusic(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Audio/SfxPlayer.cs b/EndlessClient/Audio/SfxPlayer.cs index fb7fd0362..4ae6db01d 100644 --- a/EndlessClient/Audio/SfxPlayer.cs +++ b/EndlessClient/Audio/SfxPlayer.cs @@ -93,4 +93,4 @@ public interface ISfxPlayer : IDisposable void StopLoopingSfx(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Audio/SoundEffectID.cs b/EndlessClient/Audio/SoundEffectID.cs index e115d387f..16ad15708 100644 --- a/EndlessClient/Audio/SoundEffectID.cs +++ b/EndlessClient/Audio/SoundEffectID.cs @@ -101,4 +101,4 @@ public enum SoundEffectID FireBlastSpell = 80, MapAmbientNoiseLavaBubbles2, } -} +} \ No newline at end of file diff --git a/EndlessClient/Audio/WAVFileValidator.cs b/EndlessClient/Audio/WAVFileValidator.cs index caee40ade..23a3ad59a 100644 --- a/EndlessClient/Audio/WAVFileValidator.cs +++ b/EndlessClient/Audio/WAVFileValidator.cs @@ -30,4 +30,4 @@ public static Stream GetStreamWithCorrectLengthHeader(string filename) return new MemoryStream(wavBuffer); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Content/ContentProvider.cs b/EndlessClient/Content/ContentProvider.cs index 8f4827b6c..a7aacd0e4 100644 --- a/EndlessClient/Content/ContentProvider.cs +++ b/EndlessClient/Content/ContentProvider.cs @@ -164,4 +164,4 @@ private static IEnumerable GetSoundEffects(string filter) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/BackButtonControlSet.cs b/EndlessClient/ControlSets/BackButtonControlSet.cs index 640982d81..c4ad0cd9f 100644 --- a/EndlessClient/ControlSets/BackButtonControlSet.cs +++ b/EndlessClient/ControlSets/BackButtonControlSet.cs @@ -1,10 +1,10 @@ -using System; -using EndlessClient.Content; +using EndlessClient.Content; using EndlessClient.Controllers; using EndlessClient.Rendering; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; using XNAControls; namespace EndlessClient.ControlSets @@ -65,4 +65,4 @@ protected virtual void DoBackButtonClick(object sender, EventArgs e) _mainButtonController.GoToInitialState(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/BaseControlSet.cs b/EndlessClient/ControlSets/BaseControlSet.cs index f8efc399e..c0e9e109e 100644 --- a/EndlessClient/ControlSets/BaseControlSet.cs +++ b/EndlessClient/ControlSets/BaseControlSet.cs @@ -1,11 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using EndlessClient.Content; +using EndlessClient.Content; using EndlessClient.GameExecution; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; +using System.Collections.Generic; +using System.Linq; using XNAControls; namespace EndlessClient.ControlSets @@ -124,4 +124,4 @@ public void Dispose() protected virtual void Dispose(bool disposing) { } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/ControlSetFactory.cs b/EndlessClient/ControlSets/ControlSetFactory.cs index 4e5bf2dfb..ea25b2924 100644 --- a/EndlessClient/ControlSets/ControlSetFactory.cs +++ b/EndlessClient/ControlSets/ControlSetFactory.cs @@ -109,4 +109,4 @@ private IControlSet GetSetBasedOnState(GameStates newState) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/CreateAccountControlSet.cs b/EndlessClient/ControlSets/CreateAccountControlSet.cs index 8a1bf3fec..51bda50cc 100644 --- a/EndlessClient/ControlSets/CreateAccountControlSet.cs +++ b/EndlessClient/ControlSets/CreateAccountControlSet.cs @@ -211,4 +211,4 @@ private void DoCreateAccount(object sender, EventArgs e) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/EmptyControlSet.cs b/EndlessClient/ControlSets/EmptyControlSet.cs index 2318b7edb..1fe96ebbe 100644 --- a/EndlessClient/ControlSets/EmptyControlSet.cs +++ b/EndlessClient/ControlSets/EmptyControlSet.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; -using System.Linq; -using EndlessClient.Content; +using EndlessClient.Content; using EndlessClient.GameExecution; using EOLib.Graphics; using Microsoft.Xna.Framework; +using System.Collections.Generic; +using System.Linq; using XNAControls; namespace EndlessClient.ControlSets @@ -36,4 +36,4 @@ public void Dispose() { } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/GameControlIdentifier.cs b/EndlessClient/ControlSets/GameControlIdentifier.cs index b4bcbf5c2..19f429449 100644 --- a/EndlessClient/ControlSets/GameControlIdentifier.cs +++ b/EndlessClient/ControlSets/GameControlIdentifier.cs @@ -38,4 +38,4 @@ public enum GameControlIdentifier Character2Panel, Character3Panel } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/IControlSet.cs b/EndlessClient/ControlSets/IControlSet.cs index 59e344c63..c77c536a4 100644 --- a/EndlessClient/ControlSets/IControlSet.cs +++ b/EndlessClient/ControlSets/IControlSet.cs @@ -1,9 +1,9 @@ -using System; -using System.Collections.Generic; -using EndlessClient.Content; +using EndlessClient.Content; using EndlessClient.GameExecution; using EOLib.Graphics; using Microsoft.Xna.Framework; +using System; +using System.Collections.Generic; using XNAControls; namespace EndlessClient.ControlSets @@ -45,4 +45,4 @@ public interface IControlSet : IDisposable /// The matching control IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control); } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/IControlSetFactory.cs b/EndlessClient/ControlSets/IControlSetFactory.cs index 8f4b5b1ee..7117fc67f 100644 --- a/EndlessClient/ControlSets/IControlSetFactory.cs +++ b/EndlessClient/ControlSets/IControlSetFactory.cs @@ -12,4 +12,4 @@ void InjectControllers(IMainButtonController mainButtonController, ILoginController loginController, ICharacterManagementController characterManagementController); } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/IControlSetRepository.cs b/EndlessClient/ControlSets/IControlSetRepository.cs index 2ac6fe6cc..efddacb41 100644 --- a/EndlessClient/ControlSets/IControlSetRepository.cs +++ b/EndlessClient/ControlSets/IControlSetRepository.cs @@ -23,4 +23,4 @@ public ControlSetRepository() CurrentControlSet = new EmptyControlSet(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/IHudControlProvider.cs b/EndlessClient/ControlSets/IHudControlProvider.cs index 5e84d7f6e..c6693c135 100644 --- a/EndlessClient/ControlSets/IHudControlProvider.cs +++ b/EndlessClient/ControlSets/IHudControlProvider.cs @@ -33,7 +33,7 @@ public InGameControlSet ControlSet { get { - if(!IsInGame) + if (!IsInGame) throw new InvalidOperationException("Not currently in game, in game control set does not exist"); return (InGameControlSet)_controlSetProvider.CurrentControlSet; @@ -67,4 +67,4 @@ public T GetComponent(HudControlIdentifier identifier) where T : IGameCompone return ControlSet.GetHudComponent(identifier); } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/InGameControlSet.cs b/EndlessClient/ControlSets/InGameControlSet.cs index 7d0c33e3b..12bb0dfd6 100644 --- a/EndlessClient/ControlSets/InGameControlSet.cs +++ b/EndlessClient/ControlSets/InGameControlSet.cs @@ -70,4 +70,4 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/InitialControlSet.cs b/EndlessClient/ControlSets/InitialControlSet.cs index ce093267c..11c4d8a31 100644 --- a/EndlessClient/ControlSets/InitialControlSet.cs +++ b/EndlessClient/ControlSets/InitialControlSet.cs @@ -172,4 +172,4 @@ protected void ExcludePersonPicture1() _allComponents.Remove(_personPicture); } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/IntermediateControlSet.cs b/EndlessClient/ControlSets/IntermediateControlSet.cs index e553e2780..63ebe9f95 100644 --- a/EndlessClient/ControlSets/IntermediateControlSet.cs +++ b/EndlessClient/ControlSets/IntermediateControlSet.cs @@ -1,4 +1,3 @@ -using System; using EndlessClient.Content; using EndlessClient.Controllers; using EndlessClient.GameExecution; @@ -6,6 +5,7 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; using XNAControls; namespace EndlessClient.ControlSets @@ -36,7 +36,7 @@ public override void InitializeResources(INativeGraphicsManager gfxManager, ICon protected override void InitializeControlsHelper(IControlSet currentControlSet) { - _btnCreate = GetControl(currentControlSet, + _btnCreate = GetControl(currentControlSet, GameState == GameStates.LoggedIn ? GameControlIdentifier.CreateCharacterButton : GameControlIdentifier.CreateAccountButton, GetCreateButton); _person2Picture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay2, GetPerson2Picture); diff --git a/EndlessClient/ControlSets/LoggedInControlSet.cs b/EndlessClient/ControlSets/LoggedInControlSet.cs index 1a6cd2dd4..325b4895b 100644 --- a/EndlessClient/ControlSets/LoggedInControlSet.cs +++ b/EndlessClient/ControlSets/LoggedInControlSet.cs @@ -103,4 +103,4 @@ private void AsyncButtonAction(Func clickHandler) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/LoginPromptControlSet.cs b/EndlessClient/ControlSets/LoginPromptControlSet.cs index 643a067e9..2da2d5452 100644 --- a/EndlessClient/ControlSets/LoginPromptControlSet.cs +++ b/EndlessClient/ControlSets/LoginPromptControlSet.cs @@ -163,4 +163,4 @@ private XNAButton GetLoginCancelButton() return button; } } -} +} \ No newline at end of file diff --git a/EndlessClient/ControlSets/ViewCreditsControlSet.cs b/EndlessClient/ControlSets/ViewCreditsControlSet.cs index ff814bce3..e6b37e55a 100644 --- a/EndlessClient/ControlSets/ViewCreditsControlSet.cs +++ b/EndlessClient/ControlSets/ViewCreditsControlSet.cs @@ -45,4 +45,4 @@ private XNALabel GetCreditsLabel() }; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Controllers/ArrowKeyController.cs b/EndlessClient/Controllers/ArrowKeyController.cs index 123c9fd98..d42bd8ac6 100644 --- a/EndlessClient/Controllers/ArrowKeyController.cs +++ b/EndlessClient/Controllers/ArrowKeyController.cs @@ -149,4 +149,4 @@ public interface IArrowKeyController void KeysUp(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Controllers/BardController.cs b/EndlessClient/Controllers/BardController.cs index c7796dbfa..6cf4c2e8e 100644 --- a/EndlessClient/Controllers/BardController.cs +++ b/EndlessClient/Controllers/BardController.cs @@ -40,4 +40,4 @@ public interface IBardController { void PlayInstrumentNote(int noteIndex); } -} +} \ No newline at end of file diff --git a/EndlessClient/Controllers/ChatController.cs b/EndlessClient/Controllers/ChatController.cs index 2e9b94b05..4e84953b2 100644 --- a/EndlessClient/Controllers/ChatController.cs +++ b/EndlessClient/Controllers/ChatController.cs @@ -109,4 +109,4 @@ public interface IChatController void ClearAndWarnIfJailAndGlobal(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Controllers/ControlKeyController.cs b/EndlessClient/Controllers/ControlKeyController.cs index 6c4e3878f..6b8c06ff8 100644 --- a/EndlessClient/Controllers/ControlKeyController.cs +++ b/EndlessClient/Controllers/ControlKeyController.cs @@ -94,4 +94,4 @@ public interface IControlKeyController { bool Attack(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Controllers/FunctionKeyController.cs b/EndlessClient/Controllers/FunctionKeyController.cs index 8a1f5d7fc..ffc5ed050 100644 --- a/EndlessClient/Controllers/FunctionKeyController.cs +++ b/EndlessClient/Controllers/FunctionKeyController.cs @@ -124,4 +124,4 @@ public interface IFunctionKeyController bool RefreshMapState(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Controllers/InventoryController.cs b/EndlessClient/Controllers/InventoryController.cs index 94a9b1730..34ccb0ba6 100644 --- a/EndlessClient/Controllers/InventoryController.cs +++ b/EndlessClient/Controllers/InventoryController.cs @@ -348,7 +348,7 @@ public void TradeItem(EIFRecord itemData, InventoryItem inventoryItem) EOResourceID.DIALOG_TRANSFER_OFFER); } } - + private void DoItemDrop(EIFRecord itemData, InventoryItem inventoryItem, Action dropAction, ItemTransferDialog.TransferType transferType = ItemTransferDialog.TransferType.DropItems, EOResourceID message = EOResourceID.DIALOG_TRANSFER_DROP) @@ -360,7 +360,7 @@ private void DoItemDrop(EIFRecord itemData, InventoryItem inventoryItem, Action< transferType, inventoryItem.Amount, message); - + transferDialog.DialogClosing += (sender, e) => { if (e.Result == XNADialogResult.OK) diff --git a/EndlessClient/Controllers/LoginController.cs b/EndlessClient/Controllers/LoginController.cs index d46fcc03f..b8fc7b40f 100644 --- a/EndlessClient/Controllers/LoginController.cs +++ b/EndlessClient/Controllers/LoginController.cs @@ -286,7 +286,7 @@ private async Task SafeGetFile(Func operation) private void ClearChat() { - foreach(var chat in _chatRepository.AllChat.Values) + foreach (var chat in _chatRepository.AllChat.Values) { chat.Clear(); } diff --git a/EndlessClient/Controllers/MainButtonController.cs b/EndlessClient/Controllers/MainButtonController.cs index 1ac85b5f1..4f68aa7ff 100644 --- a/EndlessClient/Controllers/MainButtonController.cs +++ b/EndlessClient/Controllers/MainButtonController.cs @@ -177,4 +177,4 @@ public interface IMainButtonController void ClickExit(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Controllers/MapInteractionController.cs b/EndlessClient/Controllers/MapInteractionController.cs index 4e1fc6c71..b64509482 100644 --- a/EndlessClient/Controllers/MapInteractionController.cs +++ b/EndlessClient/Controllers/MapInteractionController.cs @@ -315,4 +315,4 @@ public interface IMapInteractionController void RightClick(ISpellTargetable target); } -} +} \ No newline at end of file diff --git a/EndlessClient/Controllers/NPCInteractionController.cs b/EndlessClient/Controllers/NPCInteractionController.cs index 2731d4d04..f031b3596 100644 --- a/EndlessClient/Controllers/NPCInteractionController.cs +++ b/EndlessClient/Controllers/NPCInteractionController.cs @@ -43,7 +43,7 @@ public void ShowNPCDialog(NPC npc) // there is no "NPC" text in the localized files _statusLabelSetter.SetStatusLabel($"[ NPC ] {data.Name}"); - switch(data.Type) + switch (data.Type) { case EOLib.IO.NPCType.Shop: _mapNpcActions.RequestShop(npc); @@ -81,4 +81,4 @@ public interface INPCInteractionController { void ShowNPCDialog(NPC npc); } -} +} \ No newline at end of file diff --git a/EndlessClient/Controllers/NumPadController.cs b/EndlessClient/Controllers/NumPadController.cs index a2c390b11..5661d14a2 100644 --- a/EndlessClient/Controllers/NumPadController.cs +++ b/EndlessClient/Controllers/NumPadController.cs @@ -35,4 +35,4 @@ public interface INumPadController { void Emote(Emote whichEmote); } -} +} \ No newline at end of file diff --git a/EndlessClient/Controllers/TrainingController.cs b/EndlessClient/Controllers/TrainingController.cs index e8034da11..4968f9f29 100644 --- a/EndlessClient/Controllers/TrainingController.cs +++ b/EndlessClient/Controllers/TrainingController.cs @@ -53,4 +53,4 @@ public interface ITrainingController void AddSkillPoint(int spellId); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs b/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs index b56924c36..ee99390e4 100644 --- a/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs @@ -79,4 +79,4 @@ public void ShowCharacterDeleteError() messageBox.ShowDialog(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs b/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs index 2cc8d2c64..430d84281 100644 --- a/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs +++ b/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs @@ -171,4 +171,4 @@ public void ShowConnectionLost(bool isInGame) messageBox.ShowDialog(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs b/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs index d11226e1c..162da9453 100644 --- a/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs +++ b/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs @@ -32,4 +32,4 @@ public interface IFirstTimePlayerActions { void WarnFirstTimePlayers(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/HelpActions.cs b/EndlessClient/Dialogs/Actions/HelpActions.cs index b56c3eca5..ee018a1d0 100644 --- a/EndlessClient/Dialogs/Actions/HelpActions.cs +++ b/EndlessClient/Dialogs/Actions/HelpActions.cs @@ -106,4 +106,4 @@ public interface IHelpActions void SpeakToAdmin(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs b/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs index 141c30b39..b394df971 100644 --- a/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs +++ b/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs @@ -15,9 +15,9 @@ public interface IAccountDialogDisplayActions Task> ShowChangePasswordDialog(); void ShowCreateParameterValidationError(CreateAccountParameterResult validationResult); - + void ShowCreateAccountServerError(AccountReply serverError); - + void ShowSuccessMessage(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs b/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs index d09480307..c681896cc 100644 --- a/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs @@ -18,4 +18,4 @@ public interface ICharacterDialogActions void ShowCharacterDeleteError(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs b/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs index 9022280ce..49707b8a1 100644 --- a/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs +++ b/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs @@ -18,4 +18,4 @@ public interface IErrorDialogDisplayAction void ShowConnectionLost(bool isIngame); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/InGameDialogActions.cs b/EndlessClient/Dialogs/Actions/InGameDialogActions.cs index 7ca9f1014..58562eea9 100644 --- a/EndlessClient/Dialogs/Actions/InGameDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/InGameDialogActions.cs @@ -70,7 +70,7 @@ public InGameDialogActions(IFriendIgnoreListDialogFactory friendIgnoreListDialog IHelpDialogFactory helpDialogFactory, ISfxPlayer sfxPlayer, IStatusLabelSetter statusLabelSetter, - IBarberDialogFactory barberDialogFactory) + IBarberDialogFactory barberDialogFactory) { _friendIgnoreListDialogFactory = friendIgnoreListDialogFactory; _paperdollDialogFactory = paperdollDialogFactory; @@ -451,7 +451,7 @@ public void ShowHelpDialog() UseDefaultDialogSounds(dlg); }); } - + public void ShowBarberDialog() { _activeDialogRepository.BarberDialog.MatchNone(() => @@ -544,4 +544,4 @@ public interface IInGameDialogActions void ShowBarberDialog(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs b/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs index be39af7c0..d6ebec130 100644 --- a/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs +++ b/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs @@ -230,4 +230,4 @@ private void ShowPriestDialog() dlg.ShowDialog(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/PartyDialogActions.cs b/EndlessClient/Dialogs/Actions/PartyDialogActions.cs index ece65ae9e..5c911ccf6 100644 --- a/EndlessClient/Dialogs/Actions/PartyDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/PartyDialogActions.cs @@ -83,4 +83,4 @@ public void NotifyPartyMemberRemove(string name) _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_LEFT_YOUR), ChatIcon.PlayerPartyDark, ChatColor.PM)); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/TradeDialogActions.cs b/EndlessClient/Dialogs/Actions/TradeDialogActions.cs index ca1d0b284..c1be94edf 100644 --- a/EndlessClient/Dialogs/Actions/TradeDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/TradeDialogActions.cs @@ -85,4 +85,4 @@ public void NotifyTradeClose(bool cancel) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/ActiveDialogRepository.cs b/EndlessClient/Dialogs/ActiveDialogRepository.cs index d0764cd7d..b8932eee4 100644 --- a/EndlessClient/Dialogs/ActiveDialogRepository.cs +++ b/EndlessClient/Dialogs/ActiveDialogRepository.cs @@ -58,9 +58,9 @@ public interface IActiveDialogRepository : IDisposable { Option FriendIgnoreDialog { get; set; } - Option SessionExpDialog { get; set; } + Option SessionExpDialog { get; set; } - Option QuestStatusDialog { get; set; } + Option QuestStatusDialog { get; set; } Option PaperdollDialog { get; set; } @@ -72,7 +72,7 @@ public interface IActiveDialogRepository : IDisposable Option ChestDialog { get; set; } - Option LockerDialog { get; set; } + Option LockerDialog { get; set; } Option BankAccountDialog { get; set; } @@ -95,7 +95,7 @@ public interface IActiveDialogRepository : IDisposable Option LawDialog { get; set; } Option BarberDialog { get; set; } - + Option HelpDialog { get; set; } IReadOnlyList> ActiveDialogs { get; } @@ -143,8 +143,8 @@ public class ActiveDialogRepository : IActiveDialogRepository, IActiveDialogProv public Option LawDialog { get; set; } public Option BarberDialog { get; set; } - - public Option HelpDialog { get; set; } + + public Option HelpDialog { get; set; } IReadOnlyList> ActiveDialogs { @@ -214,4 +214,4 @@ public void Dispose() HelpDialog = Option.None(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/BankAccountDialog.cs b/EndlessClient/Dialogs/BankAccountDialog.cs index eceeee19c..f6d9f22bc 100644 --- a/EndlessClient/Dialogs/BankAccountDialog.cs +++ b/EndlessClient/Dialogs/BankAccountDialog.cs @@ -33,7 +33,7 @@ public class BankAccountDialog : ScrollingListDialog private int _cachedValue; private Option _cachedUpgrades; - public BankAccountDialog(INativeGraphicsManager nativeGraphicsManager, + public BankAccountDialog(INativeGraphicsManager nativeGraphicsManager, IBankActions bankActions, IEODialogButtonService dialogButtonService, IEODialogIconService dialogIconService, @@ -247,4 +247,4 @@ private void Upgrade(object sender, EventArgs e) }); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/BarberDialog.cs b/EndlessClient/Dialogs/BarberDialog.cs index d29a13c52..f730de83f 100644 --- a/EndlessClient/Dialogs/BarberDialog.cs +++ b/EndlessClient/Dialogs/BarberDialog.cs @@ -1,17 +1,17 @@ -using System; +using EndlessClient.Audio; +using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; -using EOLib.Graphics; -using EndlessClient.UIControls; using EndlessClient.Rendering.Factories; -using Microsoft.Xna.Framework; -using XNAControls; +using EndlessClient.UIControls; using EOLib.Domain.Character; -using EOLib.Localization; using EOLib.Domain.Interact.Barber; -using EndlessClient.Dialogs.Factories; -using Optional.Collections; +using EOLib.Graphics; using EOLib.IO.Repositories; -using EndlessClient.Audio; +using EOLib.Localization; +using Microsoft.Xna.Framework; +using Optional.Collections; +using System; +using XNAControls; namespace EndlessClient.Dialogs { @@ -194,4 +194,4 @@ private XNAButton CreateButton(IEODialogButtonService dialogButtonService, Vecto return button; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/BardDialog.cs b/EndlessClient/Dialogs/BardDialog.cs index 737dd771f..b2ba3498d 100644 --- a/EndlessClient/Dialogs/BardDialog.cs +++ b/EndlessClient/Dialogs/BardDialog.cs @@ -108,4 +108,4 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/BaseEODialog.cs b/EndlessClient/Dialogs/BaseEODialog.cs index b480929e8..52d39c3d8 100644 --- a/EndlessClient/Dialogs/BaseEODialog.cs +++ b/EndlessClient/Dialogs/BaseEODialog.cs @@ -30,7 +30,7 @@ public override void CenterInGameView() base.CenterInGameView(); if (_isInGame() && !Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, (330 - DrawArea.Height)/2f); + DrawPosition = new Vector2(DrawPosition.X, (330 - DrawArea.Height) / 2f); } public void Close() @@ -38,4 +38,4 @@ public void Close() Close(XNADialogResult.NO_BUTTON_PRESSED); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/BoardDialog.cs b/EndlessClient/Dialogs/BoardDialog.cs index 961fde98f..e648db10b 100644 --- a/EndlessClient/Dialogs/BoardDialog.cs +++ b/EndlessClient/Dialogs/BoardDialog.cs @@ -312,4 +312,4 @@ private void ChildItem_Click(object sender, MouseEventArgs e) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/BookDialog.cs b/EndlessClient/Dialogs/BookDialog.cs index 5a5aaee18..fef42d67f 100644 --- a/EndlessClient/Dialogs/BookDialog.cs +++ b/EndlessClient/Dialogs/BookDialog.cs @@ -127,4 +127,4 @@ private static Rectangle GetIconSourceRectangle(QuestStatusIcon index) return new Rectangle((int)index * 15, 0, 15, 15); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/ChangePasswordDialog.cs b/EndlessClient/Dialogs/ChangePasswordDialog.cs index 5af8f6989..37089edbe 100644 --- a/EndlessClient/Dialogs/ChangePasswordDialog.cs +++ b/EndlessClient/Dialogs/ChangePasswordDialog.cs @@ -140,4 +140,4 @@ private void OnButtonPressed(object sender, EventArgs e) Close(XNADialogResult.OK); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/ChestDialog.cs b/EndlessClient/Dialogs/ChestDialog.cs index 4fa1fed24..7cd10cab2 100644 --- a/EndlessClient/Dialogs/ChestDialog.cs +++ b/EndlessClient/Dialogs/ChestDialog.cs @@ -120,4 +120,4 @@ private void TakeItem(ChestItem item, EIFRecord itemData) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/CreateCharacterDialog.cs b/EndlessClient/Dialogs/CreateCharacterDialog.cs index 8b64f87ec..3a46497ff 100644 --- a/EndlessClient/Dialogs/CreateCharacterDialog.cs +++ b/EndlessClient/Dialogs/CreateCharacterDialog.cs @@ -1,5 +1,4 @@ -using System; -using EndlessClient.Content; +using EndlessClient.Content; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.GameExecution; @@ -12,6 +11,7 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Optional; +using System; using XNAControls; namespace EndlessClient.Dialogs @@ -140,7 +140,7 @@ protected override void OnDrawControl(GameTime gt) { _spriteBatch.Draw(_charCreateSheet, new Vector2(170 + DrawPositionWithParentOffset.X, - 84 + i*27 + DrawPositionWithParentOffset.Y), + 84 + i * 27 + DrawPositionWithParentOffset.Y), _srcRectangles[i], Color.White); } @@ -189,4 +189,4 @@ private void ClickOk() } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/EODialogButton.cs b/EndlessClient/Dialogs/EODialogButton.cs index c6c2f7e17..e065433f5 100644 --- a/EndlessClient/Dialogs/EODialogButton.cs +++ b/EndlessClient/Dialogs/EODialogButton.cs @@ -6,4 +6,4 @@ public enum EODialogButtons Cancel, OkCancel, } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/EOMessageBox.cs b/EndlessClient/Dialogs/EOMessageBox.cs index 1ce9d4918..a5889e812 100644 --- a/EndlessClient/Dialogs/EOMessageBox.cs +++ b/EndlessClient/Dialogs/EOMessageBox.cs @@ -126,4 +126,4 @@ public override void Initialize() base.Initialize(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs b/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs index b9e269763..fe2f63539 100644 --- a/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs +++ b/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs @@ -29,4 +29,4 @@ public static Rectangle GetEquipLocationRectangle(this EquipLocation loc) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs b/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs index 908bbc221..ca9207f4d 100644 --- a/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs @@ -74,4 +74,4 @@ public interface IBankAccountDialogFactory { BankAccountDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs b/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs index a446b06d7..ec9055cb3 100644 --- a/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs @@ -1,17 +1,17 @@ using AutomaticTypeMapper; +using EndlessClient.Audio; +using EndlessClient.Content; using EndlessClient.Controllers; using EndlessClient.Dialogs.Services; using EndlessClient.Rendering.Character; -using EOLib.Graphics; -using EndlessClient.Content; using EndlessClient.Rendering.Factories; using EOLib.Domain.Character; -using EOLib.Localization; using EOLib.Domain.Interact.Barber; -using EOLib.IO.Repositories; using EOLib.Domain.Notifiers; +using EOLib.Graphics; +using EOLib.IO.Repositories; +using EOLib.Localization; using System.Collections.Generic; -using EndlessClient.Audio; namespace EndlessClient.Dialogs.Factories { diff --git a/EndlessClient/Dialogs/Factories/BardDialogFactory.cs b/EndlessClient/Dialogs/Factories/BardDialogFactory.cs index 64e81da46..9be90b362 100644 --- a/EndlessClient/Dialogs/Factories/BardDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BardDialogFactory.cs @@ -33,4 +33,4 @@ public interface IBardDialogFactory { BardDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs b/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs index ebfd4628e..167d2cbd5 100644 --- a/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs @@ -66,4 +66,4 @@ public interface IBoardDialogFactory { BoardDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BookDialogFactory.cs b/EndlessClient/Dialogs/Factories/BookDialogFactory.cs index cc78bd1f6..0ab0c369f 100644 --- a/EndlessClient/Dialogs/Factories/BookDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BookDialogFactory.cs @@ -19,7 +19,7 @@ public BookDialogFactory(INativeGraphicsManager nativeGraphicsManager, IPubFileProvider pubFileProvider, IPaperdollProvider paperdollProvider) { - + _nativeGraphicsManager = nativeGraphicsManager; _eoDialogButtonService = eoDialogButtonService; _pubFileProvider = pubFileProvider; @@ -41,4 +41,4 @@ public interface IBookDialogFactory { BookDialog Create(Character character, bool isMainCharacter); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs b/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs index 731a80f84..7326a6b18 100644 --- a/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs @@ -72,4 +72,4 @@ public interface IChestDialogFactory { ChestDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs b/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs index 614ae0ac0..4342a1a98 100644 --- a/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs @@ -47,4 +47,4 @@ public interface ICreateAccountWarningDialogFactory { IXNADialog ShowCreateAccountWarningDialog(string warningMessage); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs b/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs index 1e212c732..d46c7c18a 100644 --- a/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs @@ -137,4 +137,4 @@ public interface IFriendIgnoreListDialogFactory { FriendIgnoreListDialog Create(bool isFriendList); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs b/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs index 5e424db3d..5560d1b46 100644 --- a/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs @@ -78,4 +78,4 @@ public interface IHelpDialogFactory { ScrollingListDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs b/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs index e333d839c..80054bf4e 100644 --- a/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs @@ -4,4 +4,4 @@ public interface IChangePasswordDialogFactory { ChangePasswordDialog BuildChangePasswordDialog(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs b/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs index 96decb462..aa345a1e1 100644 --- a/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs +++ b/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs @@ -5,7 +5,7 @@ namespace EndlessClient.Dialogs.Factories { public interface IEOMessageBoxFactory { - IXNADialog CreateMessageBox(string message, + IXNADialog CreateMessageBox(string message, string caption = "", EODialogButtons whichButtons = EODialogButtons.Ok, EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); @@ -29,4 +29,4 @@ IXNADialog CreateMessageBox(EOResourceID message, EODialogButtons whichButtons = EODialogButtons.Ok, EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs b/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs index 774ae41ec..15a389ce4 100644 --- a/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs @@ -64,4 +64,4 @@ public interface IInnkeeperDialogFactory { InnkeeperDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs b/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs index a0228e152..926646a63 100644 --- a/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs @@ -64,4 +64,4 @@ public interface IJukeboxDialogFactory { JukeboxDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/LawDialogFactory.cs b/EndlessClient/Dialogs/Factories/LawDialogFactory.cs index 349aac6a0..0a9538435 100644 --- a/EndlessClient/Dialogs/Factories/LawDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/LawDialogFactory.cs @@ -61,4 +61,4 @@ public interface ILawDialogFactory { LawDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs b/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs index e5a699335..fc9065bee 100644 --- a/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs @@ -71,4 +71,4 @@ public interface ILockerDialogFactory { LockerDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs b/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs index 7ed0c4499..b1ec454e0 100644 --- a/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs @@ -74,4 +74,4 @@ public interface IPaperdollDialogFactory void InjectInventoryController(IInventoryController inventoryController); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs b/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs index 0fdc86289..73b9e7d77 100644 --- a/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs @@ -47,4 +47,4 @@ public interface IQuestDialogFactory { QuestDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs b/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs index ecdb3f1c2..18ca65f3a 100644 --- a/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs @@ -43,4 +43,4 @@ public interface IQuestStatusDialogFactory { QuestStatusDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs b/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs index 2641bdd86..5bf061e6a 100644 --- a/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs @@ -27,4 +27,4 @@ public interface IScrollingListDialogFactory { ScrollingListDialog Create(DialogType size); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs b/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs index 6eb6e954c..548c7a48b 100644 --- a/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs @@ -46,4 +46,4 @@ public interface ISessionExpDialogFactory { SessionExpDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs b/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs index b2f0cbea0..ed7d589d5 100644 --- a/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs @@ -74,4 +74,4 @@ public interface IShopDialogFactory { ShopDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs b/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs index 917decb76..e17ff74c8 100644 --- a/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs @@ -78,4 +78,4 @@ public interface ISkillmasterDialogFactory { SkillmasterDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs b/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs index 6718eaece..b72776cd5 100644 --- a/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs @@ -46,4 +46,4 @@ public interface ITextInputDialogFactory { TextInputDialog Create(string prompt, int maxInputChars = 12); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs b/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs index 60caa456a..111ddbda3 100644 --- a/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs @@ -51,4 +51,4 @@ TextMultiInputDialog Create(string title, TextMultiInputDialog.DialogSize size, params TextMultiInputDialog.InputInfo[] inputInfo); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs b/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs index 83d56ab88..bfd49b8b4 100644 --- a/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs @@ -76,4 +76,4 @@ public interface ITradeDialogFactory { TradeDialog Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/FriendIgnoreListDialog.cs b/EndlessClient/Dialogs/FriendIgnoreListDialog.cs index 590766826..ba481f3c8 100644 --- a/EndlessClient/Dialogs/FriendIgnoreListDialog.cs +++ b/EndlessClient/Dialogs/FriendIgnoreListDialog.cs @@ -35,4 +35,4 @@ protected override void OnUpdateControl(GameTime gameTime) base.OnUpdateControl(gameTime); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/GameLoadingDialog.cs b/EndlessClient/Dialogs/GameLoadingDialog.cs index 2a126af6c..67fde1c75 100644 --- a/EndlessClient/Dialogs/GameLoadingDialog.cs +++ b/EndlessClient/Dialogs/GameLoadingDialog.cs @@ -1,11 +1,11 @@ -using System; -using EndlessClient.GameExecution; +using EndlessClient.GameExecution; using EndlessClient.Rendering; using EOLib; using EOLib.Graphics; using EOLib.Localization; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; using XNAControls; namespace EndlessClient.Dialogs @@ -70,7 +70,7 @@ public override void Initialize() protected override void OnUpdateControl(GameTime gt) { - if ((int) (DateTime.Now - _lastBackgroundUpdate).TotalMilliseconds > 500) + if ((int)(DateTime.Now - _lastBackgroundUpdate).TotalMilliseconds > 500) { _bgSrcIndex = _bgSrcIndex == 3 ? 0 : _bgSrcIndex + 1; _lastBackgroundUpdate = DateTime.Now; @@ -133,4 +133,4 @@ public enum GameLoadingDialogState Class, LoadingGame } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/InnkeeperDialog.cs b/EndlessClient/Dialogs/InnkeeperDialog.cs index b72bfc8b0..22bd4d0cb 100644 --- a/EndlessClient/Dialogs/InnkeeperDialog.cs +++ b/EndlessClient/Dialogs/InnkeeperDialog.cs @@ -251,4 +251,4 @@ private void SetState(InnkeeperDialogState state) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/ItemTransferDialog.cs b/EndlessClient/Dialogs/ItemTransferDialog.cs index 39494171f..838106e9f 100644 --- a/EndlessClient/Dialogs/ItemTransferDialog.cs +++ b/EndlessClient/Dialogs/ItemTransferDialog.cs @@ -68,7 +68,7 @@ public ItemTransferDialog(INativeGraphicsManager nativeGraphicsManager, } _okButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(60, 125), + new Vector2(60, 125), eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)) { @@ -220,4 +220,4 @@ private static bool IsValidMessage(EOResourceID msg) } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/JukeboxDialog.cs b/EndlessClient/Dialogs/JukeboxDialog.cs index aa8af76ce..f6df54d5a 100644 --- a/EndlessClient/Dialogs/JukeboxDialog.cs +++ b/EndlessClient/Dialogs/JukeboxDialog.cs @@ -172,4 +172,4 @@ private string FormatSubtitle(string additionalText) return _localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT) + " : " + additionalText; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/LawDialog.cs b/EndlessClient/Dialogs/LawDialog.cs index 2469efa12..1a8a8f950 100644 --- a/EndlessClient/Dialogs/LawDialog.cs +++ b/EndlessClient/Dialogs/LawDialog.cs @@ -195,4 +195,4 @@ private void SetState(LawDialogState state) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/ListDialogItem.cs b/EndlessClient/Dialogs/ListDialogItem.cs index 77874114f..ffa4f2e5d 100644 --- a/EndlessClient/Dialogs/ListDialogItem.cs +++ b/EndlessClient/Dialogs/ListDialogItem.cs @@ -297,4 +297,4 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/LockerDialog.cs b/EndlessClient/Dialogs/LockerDialog.cs index 92114f376..accc1eb83 100644 --- a/EndlessClient/Dialogs/LockerDialog.cs +++ b/EndlessClient/Dialogs/LockerDialog.cs @@ -121,4 +121,4 @@ private string GetDialogTitle() return _characterProvider.MainCharacter.Name + "'s " + _localizedStringFinder.GetString(EOResourceID.DIALOG_TITLE_PRIVATE_LOCKER) + $" [{_lockerDataProvider.Items.Count}]"; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/PaperdollDialog.cs b/EndlessClient/Dialogs/PaperdollDialog.cs index e9d513b31..5d102b03d 100644 --- a/EndlessClient/Dialogs/PaperdollDialog.cs +++ b/EndlessClient/Dialogs/PaperdollDialog.cs @@ -155,4 +155,4 @@ protected override void UpdateDisplayedData(PaperdollData paperdollData) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/PaperdollDialogItem.cs b/EndlessClient/Dialogs/PaperdollDialogItem.cs index 9c753acfc..5209495bf 100644 --- a/EndlessClient/Dialogs/PaperdollDialogItem.cs +++ b/EndlessClient/Dialogs/PaperdollDialogItem.cs @@ -121,4 +121,4 @@ private void StopDragging() _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/PlayerInfoDialog.cs b/EndlessClient/Dialogs/PlayerInfoDialog.cs index 8d1ff2939..ca98e9f21 100644 --- a/EndlessClient/Dialogs/PlayerInfoDialog.cs +++ b/EndlessClient/Dialogs/PlayerInfoDialog.cs @@ -162,4 +162,4 @@ private static Rectangle GetOnlineIconSourceRectangle(CharacterIcon icon) return new Rectangle(x, y, width, height); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/ProgressDialog.cs b/EndlessClient/Dialogs/ProgressDialog.cs index 5a698f105..1bcf03e12 100644 --- a/EndlessClient/Dialogs/ProgressDialog.cs +++ b/EndlessClient/Dialogs/ProgressDialog.cs @@ -1,12 +1,12 @@ -using System; -using System.Threading; -using EndlessClient.Dialogs.Services; +using EndlessClient.Dialogs.Services; using EndlessClient.GameExecution; using EOLib; using EOLib.Config; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; +using System.Threading; using XNAControls; namespace EndlessClient.Dialogs @@ -122,4 +122,4 @@ private void DoCancel(object sender, EventArgs e) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/QuestDialog.cs b/EndlessClient/Dialogs/QuestDialog.cs index 538fb1123..de1328595 100644 --- a/EndlessClient/Dialogs/QuestDialog.cs +++ b/EndlessClient/Dialogs/QuestDialog.cs @@ -188,4 +188,4 @@ private void PreviousPage(object sender, EventArgs e) }); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/QuestStatusDialog.cs b/EndlessClient/Dialogs/QuestStatusDialog.cs index 6acff69be..2d3b4e65f 100644 --- a/EndlessClient/Dialogs/QuestStatusDialog.cs +++ b/EndlessClient/Dialogs/QuestStatusDialog.cs @@ -131,4 +131,4 @@ private void SetTitle(QuestPage page) Title = $"{_characterProvider.MainCharacter.Name}'s {description}"; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/QuestStatusListDialogItem.cs b/EndlessClient/Dialogs/QuestStatusListDialogItem.cs index c708eea4a..2e3f99dfc 100644 --- a/EndlessClient/Dialogs/QuestStatusListDialogItem.cs +++ b/EndlessClient/Dialogs/QuestStatusListDialogItem.cs @@ -11,14 +11,14 @@ public class QuestStatusListDialogItem : ListDialogItem { public enum QuestStatusIcon { - None = 0, - Talk = 1, - Item = 2, - Kill = 3, - Step = 4, - Complete = 5, - None2 = 6, // ? - None3 = 7, // ? + None = 0, + Talk = 1, + Item = 2, + Kill = 3, + Step = 4, + Complete = 5, + None2 = 6, // ? + None3 = 7, // ? }; private static readonly Vector2 _firstIconPosition = new Vector2(6, 0); @@ -131,4 +131,4 @@ private static Rectangle GetSignalSourceRectangle() return new Rectangle(0, 15, 15, 15); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/ScrollingListDialog.cs b/EndlessClient/Dialogs/ScrollingListDialog.cs index 56f598ffb..d4eb5596c 100644 --- a/EndlessClient/Dialogs/ScrollingListDialog.cs +++ b/EndlessClient/Dialogs/ScrollingListDialog.cs @@ -18,28 +18,28 @@ namespace EndlessClient.Dialogs [Flags] public enum ScrollingListDialogButtons { - None = 0x00, - Add = 0x01, - Cancel = 0x02, - Back = 0x04, - Next = 0x08, - Ok = 0x10, - History = 0x20, - Progress = 0x40, - Delete = 0x80, - DualButtons = 0x800, + None = 0x00, + Add = 0x01, + Cancel = 0x02, + Back = 0x04, + Next = 0x08, + Ok = 0x10, + History = 0x20, + Progress = 0x40, + Delete = 0x80, + DualButtons = 0x800, // indicates a configuration in which a pairing of DualButtons is already defined, but the order is reversed - Alternate = 0x1000, - - AddCancel = DualButtons | Add | Cancel, - BackCancel = DualButtons | Back | Cancel, - BackOk = DualButtons | Back | Ok, - CancelOk = DualButtons | Cancel | Ok, - OkCancel = DualButtons | Cancel | Ok | Alternate, - BackNext = DualButtons | Back | Next, - CancelNext = DualButtons | Cancel | Next, - HistoryOk = DualButtons | History | Ok, - ProgressOk = DualButtons | Progress | Ok, + Alternate = 0x1000, + + AddCancel = DualButtons | Add | Cancel, + BackCancel = DualButtons | Back | Cancel, + BackOk = DualButtons | Back | Ok, + CancelOk = DualButtons | Cancel | Ok, + OkCancel = DualButtons | Cancel | Ok | Alternate, + BackNext = DualButtons | Back | Next, + CancelNext = DualButtons | Cancel | Next, + HistoryOk = DualButtons | History | Ok, + ProgressOk = DualButtons | Progress | Ok, DeleteCancel = DualButtons | Delete | Cancel, // There is only one button, but we want it to show on the right side as if it were a dual button setting @@ -228,7 +228,7 @@ public ScrollingListDialog(INativeGraphicsManager nativeGraphicsManager, _add = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Add), dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Add)) - { + { Visible = false, UpdateOrder = 1, }; @@ -483,7 +483,7 @@ protected override void OnUpdateControl(GameTime gameTime) protected static Rectangle GetTitleDrawArea(DialogType size) { - switch(size) + switch (size) { case DialogType.Shop: case DialogType.Help: @@ -539,7 +539,7 @@ private static int GetBackgroundTexture(DialogType size) return new Rectangle(0, 0, backgroundTexture.Width, backgroundTexture.Height / 2); case DialogType.Jukebox: case DialogType.NpcQuestDialog: - case DialogType.BankAccountDialog: return null; + case DialogType.BankAccountDialog: return null; default: throw new NotImplementedException(); } } @@ -606,4 +606,4 @@ private static int GetButtonYCoordinate(Rectangle dialogArea) return dialogArea.Height - 38; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/ScrollingMessageDialog.cs b/EndlessClient/Dialogs/ScrollingMessageDialog.cs index 0387095eb..26d4762e5 100644 --- a/EndlessClient/Dialogs/ScrollingMessageDialog.cs +++ b/EndlessClient/Dialogs/ScrollingMessageDialog.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using EndlessClient.Content; +using EndlessClient.Content; using EndlessClient.Dialogs.Services; using EndlessClient.GameExecution; using EndlessClient.UIControls; @@ -8,6 +6,8 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using MonoGame.Extended.BitmapFonts; +using System; +using System.Collections.Generic; using XNAControls; namespace EndlessClient.Dialogs @@ -114,4 +114,4 @@ protected override void OnDrawControl(GameTime gt) _spriteBatch.End(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Services/EODialogButtonService.cs b/EndlessClient/Dialogs/Services/EODialogButtonService.cs index 150da078c..84ee583cc 100644 --- a/EndlessClient/Dialogs/Services/EODialogButtonService.cs +++ b/EndlessClient/Dialogs/Services/EODialogButtonService.cs @@ -34,16 +34,16 @@ public EODialogButtonService(INativeGraphicsManager nativeGraphicsManager) public Rectangle GetSmallDialogButtonOutSource(SmallButton whichButton) { - var widthDelta = SmallButtonSheet.Width/2; - var heightDelta = SmallButtonSheet.Height/(int) SmallButton.NUM_BUTTONS; - return new Rectangle(0, heightDelta*(int) whichButton, widthDelta, heightDelta); + var widthDelta = SmallButtonSheet.Width / 2; + var heightDelta = SmallButtonSheet.Height / (int)SmallButton.NUM_BUTTONS; + return new Rectangle(0, heightDelta * (int)whichButton, widthDelta, heightDelta); } public Rectangle GetSmallDialogButtonOverSource(SmallButton whichButton) { - var widthDelta = SmallButtonSheet.Width/2; - var heightDelta = SmallButtonSheet.Height/(int) SmallButton.NUM_BUTTONS; - return new Rectangle(widthDelta, heightDelta*(int) whichButton, widthDelta, heightDelta); + var widthDelta = SmallButtonSheet.Width / 2; + var heightDelta = SmallButtonSheet.Height / (int)SmallButton.NUM_BUTTONS; + return new Rectangle(widthDelta, heightDelta * (int)whichButton, widthDelta, heightDelta); } } @@ -54,4 +54,4 @@ public interface IEODialogButtonService Rectangle GetSmallDialogButtonOutSource(SmallButton whichButton); Rectangle GetSmallDialogButtonOverSource(SmallButton whichButton); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/Services/EODialogIconService.cs b/EndlessClient/Dialogs/Services/EODialogIconService.cs index f5a1072bb..09f0d4dea 100644 --- a/EndlessClient/Dialogs/Services/EODialogIconService.cs +++ b/EndlessClient/Dialogs/Services/EODialogIconService.cs @@ -56,4 +56,4 @@ public interface IEODialogIconService Rectangle GetDialogIconSource(DialogIcon whichIcon); } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/SessionExpDialog.cs b/EndlessClient/Dialogs/SessionExpDialog.cs index 4f85b5354..f24dfda7b 100644 --- a/EndlessClient/Dialogs/SessionExpDialog.cs +++ b/EndlessClient/Dialogs/SessionExpDialog.cs @@ -1,11 +1,11 @@ -using System; -using EndlessClient.Dialogs.Services; +using EndlessClient.Dialogs.Services; using EOLib; using EOLib.Domain.Character; using EOLib.Graphics; using EOLib.Localization; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; using XNAControls; namespace EndlessClient.Dialogs @@ -93,9 +93,9 @@ public SessionExpDialog(INativeGraphicsManager nativeGraphicsManager, rightSide[1].Text = $"{expTableProvider.ExperienceByLevel[level + 1]}"; rightSide[2].Text = $"{expTableProvider.ExperienceByLevel[level + 1] - exp}"; rightSide[3].Text = $"{characterSessionProvider.TodayTotalExp}"; - rightSide[4].Text = $"{(int)(exp / (usage/60.0))}"; + rightSide[4].Text = $"{(int)(exp / (usage / 60.0))}"; int sessionTimeMinutes = (int)(DateTime.Now - characterSessionProvider.SessionStartTime).TotalMinutes; - rightSide[5].Text = $"{(sessionTimeMinutes > 0 ? (int)(characterSessionProvider.TodayTotalExp / (sessionTimeMinutes/60.0)) : 0)}"; + rightSide[5].Text = $"{(sessionTimeMinutes > 0 ? (int)(characterSessionProvider.TodayTotalExp / (sessionTimeMinutes / 60.0)) : 0)}"; rightSide[6].Text = $"{characterSessionProvider.BestKillExp}"; rightSide[7].Text = $"{characterSessionProvider.LastKillExp}"; @@ -117,10 +117,10 @@ protected override void OnDrawControl(GameTime gameTime) for (int i = 0; i < 8; i++) _spriteBatch.Draw(_icons, new Vector2(DrawPositionWithParentOffset.X + 18, DrawPositionWithParentOffset.Y + 47 + 16 * i), _iconSource, Color.White); - for(int i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) _spriteBatch.Draw(_icons, new Vector2(DrawPositionWithParentOffset.X + 142, DrawPositionWithParentOffset.Y + 48 + 16 * i), _signalSource, Color.White); _spriteBatch.End(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/ShopDialog.cs b/EndlessClient/Dialogs/ShopDialog.cs index 469b06bf4..29e5c7efc 100644 --- a/EndlessClient/Dialogs/ShopDialog.cs +++ b/EndlessClient/Dialogs/ShopDialog.cs @@ -364,7 +364,7 @@ private void CraftItem(object sender, EventArgs e) { var message = BuildMessage(EOResourceID.DIALOG_SHOP_CRAFT_MISSING_INGREDIENTS); var caption = BuildCaption(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS); - + var dlg = _messageBoxFactory.CreateMessageBox(message, caption, EODialogButtons.Cancel, EOMessageBoxStyle.LargeDialogSmallHeader); dlg.ShowDialog(); @@ -411,4 +411,4 @@ string BuildCaption(EOResourceID resource) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/SkillmasterDialog.cs b/EndlessClient/Dialogs/SkillmasterDialog.cs index 2ceb60820..3f58ec8f2 100644 --- a/EndlessClient/Dialogs/SkillmasterDialog.cs +++ b/EndlessClient/Dialogs/SkillmasterDialog.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using EndlessClient.Content; +using EndlessClient.Content; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.HUD; @@ -14,6 +10,10 @@ using EOLib.Localization; using Microsoft.Xna.Framework; using Optional.Collections; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; using XNAControls; namespace EndlessClient.Dialogs @@ -332,7 +332,7 @@ from req in skill.SkillRequirements if (skill.WisRequirement > 0) drawStrings.Add($"{skill.WisRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_WISDOM)}"); if (skill.AgiRequirement > 0) - drawStrings.Add($"{skill.AgiRequirement} { _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_AGILITY)}"); + drawStrings.Add($"{skill.AgiRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_AGILITY)}"); if (skill.ConRequirement > 0) drawStrings.Add($"{skill.ConRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CONSTITUTION)}"); if (skill.ChaRequirement > 0) @@ -398,4 +398,4 @@ private void ConfirmResetCharacter() dlg.ShowDialog(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/TextInputDialog.cs b/EndlessClient/Dialogs/TextInputDialog.cs index 67bb93890..4e6bea597 100644 --- a/EndlessClient/Dialogs/TextInputDialog.cs +++ b/EndlessClient/Dialogs/TextInputDialog.cs @@ -43,7 +43,7 @@ public TextInputDialog(INativeGraphicsManager nativeGraphicsManager, TextColor = ColorConstants.LightBeigeText, }; _inputBox.SetParentControl(this); - + var ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, new Vector2(41, 103), eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), @@ -73,4 +73,4 @@ public override void Initialize() base.Initialize(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/TextMultiInputDialog.cs b/EndlessClient/Dialogs/TextMultiInputDialog.cs index fc11fd872..73af29c43 100644 --- a/EndlessClient/Dialogs/TextMultiInputDialog.cs +++ b/EndlessClient/Dialogs/TextMultiInputDialog.cs @@ -51,7 +51,7 @@ public TextMultiInputDialog(INativeGraphicsManager nativeGraphicsManager, : base(nativeGraphicsManager, isInGame: true) { _background = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 57); - + switch (size) { case DialogSize.Two: @@ -159,4 +159,4 @@ protected override void OnDrawControl(GameTime gameTime) base.OnDrawControl(gameTime); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Dialogs/TradeDialog.cs b/EndlessClient/Dialogs/TradeDialog.cs index 33822db05..3a4f56235 100644 --- a/EndlessClient/Dialogs/TradeDialog.cs +++ b/EndlessClient/Dialogs/TradeDialog.cs @@ -309,7 +309,7 @@ private void UpdateOffer(TradeOffer actualOffer, TradeOffer cachedOffer, { var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_OTHER_PLAYER_TRICK_YOU); dlg.ShowDialog(); - + // this will prevent the message from showing more than once per trade (I'm too lazy to find something more elegant) _recentPartnerItemChanges = -1000; } @@ -401,4 +401,4 @@ private void CancelButtonClicked(object sender, EventArgs e) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/GameExecution/DebugGameRunner.cs b/EndlessClient/GameExecution/DebugGameRunner.cs index 922665e93..80eb2abab 100644 --- a/EndlessClient/GameExecution/DebugGameRunner.cs +++ b/EndlessClient/GameExecution/DebugGameRunner.cs @@ -10,4 +10,4 @@ public class DebugGameRunner : GameRunnerBase public DebugGameRunner(ITypeRegistry registry, string[] args) : base(registry, args) { } } -} +} \ No newline at end of file diff --git a/EndlessClient/GameExecution/EndlessGame.cs b/EndlessClient/GameExecution/EndlessGame.cs index 8f0db67f2..2cb41e3e2 100644 --- a/EndlessClient/GameExecution/EndlessGame.cs +++ b/EndlessClient/GameExecution/EndlessGame.cs @@ -297,4 +297,4 @@ private void SetUpInitialControlSet() xnaControl.Initialize(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/GameExecution/GameRunnerBase.cs b/EndlessClient/GameExecution/GameRunnerBase.cs index 832f7d37d..5d9eaf43f 100644 --- a/EndlessClient/GameExecution/GameRunnerBase.cs +++ b/EndlessClient/GameExecution/GameRunnerBase.cs @@ -60,7 +60,7 @@ public virtual bool SetupDependencies() catch (LibraryLoadException lle) { var message = - $"There was an error loading GFX{(int) lle.WhichGFX:000}.EGF : {lle.WhichGFX}. Place all .GFX files in .\\gfx\\. The error message is:\n\n\"{lle.Message}\""; + $"There was an error loading GFX{(int)lle.WhichGFX:000}.EGF : {lle.WhichGFX}. Place all .GFX files in .\\gfx\\. The error message is:\n\n\"{lle.Message}\""; ShowErrorMessage(message, "GFX Load Error"); return false; } @@ -76,7 +76,7 @@ public virtual bool SetupDependencies() i++; } - else if(string.Equals(arg, "--port") && i < _args.Length - 1) + else if (string.Equals(arg, "--port") && i < _args.Length - 1) { var port = _args[i + 1]; @@ -145,4 +145,4 @@ public virtual void RunGame() game.Run(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/GameExecution/GameStateActions.cs b/EndlessClient/GameExecution/GameStateActions.cs index 95a4bb011..2673b7105 100644 --- a/EndlessClient/GameExecution/GameStateActions.cs +++ b/EndlessClient/GameExecution/GameStateActions.cs @@ -1,18 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.ControlSets; +using EndlessClient.HUD.Panels; using EndlessClient.Network; +using EndlessClient.Rendering; +using EOLib; +using EOLib.Config; using EOLib.Domain.Character; using EOLib.Domain.Login; -using EndlessClient.Rendering; using Microsoft.Xna.Framework; +using System; +using System.Collections.Generic; +using System.Linq; using XNAControls.Input; -using EndlessClient.HUD.Panels; -using EOLib; -using EOLib.Config; namespace EndlessClient.GameExecution { @@ -159,4 +159,4 @@ private void StorePanelLayout(object sender, EventArgs e) private IEndlessGame Game => _endlessGameProvider.Game; } -} +} \ No newline at end of file diff --git a/EndlessClient/GameExecution/IEndlessGame.cs b/EndlessClient/GameExecution/IEndlessGame.cs index 682eb62e1..d9066581d 100644 --- a/EndlessClient/GameExecution/IEndlessGame.cs +++ b/EndlessClient/GameExecution/IEndlessGame.cs @@ -1,6 +1,6 @@ -using System; -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; +using System; namespace EndlessClient.GameExecution { @@ -20,4 +20,4 @@ public interface IEndlessGame : IDisposable void Exit(); } -} +} \ No newline at end of file diff --git a/EndlessClient/GameExecution/IEndlessGameProvider.cs b/EndlessClient/GameExecution/IEndlessGameProvider.cs index 47f16f20d..5320faa60 100644 --- a/EndlessClient/GameExecution/IEndlessGameProvider.cs +++ b/EndlessClient/GameExecution/IEndlessGameProvider.cs @@ -18,4 +18,4 @@ public class EndlessGameRepository : IEndlessGameRepository, IEndlessGameProvide { public IEndlessGame Game { get; set; } } -} +} \ No newline at end of file diff --git a/EndlessClient/GameExecution/IGameRunner.cs b/EndlessClient/GameExecution/IGameRunner.cs index fa75ed940..48347f597 100644 --- a/EndlessClient/GameExecution/IGameRunner.cs +++ b/EndlessClient/GameExecution/IGameRunner.cs @@ -6,4 +6,4 @@ public interface IGameRunner void RunGame(); } -} +} \ No newline at end of file diff --git a/EndlessClient/GameExecution/IGameStateActions.cs b/EndlessClient/GameExecution/IGameStateActions.cs index ec73a464e..cf109642b 100644 --- a/EndlessClient/GameExecution/IGameStateActions.cs +++ b/EndlessClient/GameExecution/IGameStateActions.cs @@ -8,4 +8,4 @@ public interface IGameStateActions void ExitGame(); } -} +} \ No newline at end of file diff --git a/EndlessClient/GameExecution/IGameStateRepository.cs b/EndlessClient/GameExecution/IGameStateRepository.cs index d983c5142..288123615 100644 --- a/EndlessClient/GameExecution/IGameStateRepository.cs +++ b/EndlessClient/GameExecution/IGameStateRepository.cs @@ -18,4 +18,4 @@ public class GameStateRepository : IGameStateRepository, IGameStateProvider { public GameStates CurrentState { get; set; } } -} +} \ No newline at end of file diff --git a/EndlessClient/GameExecution/ReleaseGameRunner.cs b/EndlessClient/GameExecution/ReleaseGameRunner.cs index 2164c63b0..a03d47224 100644 --- a/EndlessClient/GameExecution/ReleaseGameRunner.cs +++ b/EndlessClient/GameExecution/ReleaseGameRunner.cs @@ -111,4 +111,4 @@ private static void ShowExceptionDialog(Exception ex) #endif } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/AStarPathFinder.cs b/EndlessClient/HUD/AStarPathFinder.cs index 5ecd0c205..c3902916c 100644 --- a/EndlessClient/HUD/AStarPathFinder.cs +++ b/EndlessClient/HUD/AStarPathFinder.cs @@ -97,7 +97,7 @@ private IEnumerable getNeighbors(MapCoordinate current) }; foreach (var coordinateOffset in points) - { + { if (_walkValidationActions.CanMoveToCoordinates(current.X + coordinateOffset.X, current.Y + coordinateOffset.Y) == WalkValidationResult.Walkable) yield return new MapCoordinate(current.X + coordinateOffset.X, current.Y + coordinateOffset.Y); } @@ -108,4 +108,4 @@ public interface IPathFinder { Queue FindPath(MapCoordinate start, MapCoordinate finish); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatModeCalculator.cs b/EndlessClient/HUD/Chat/ChatModeCalculator.cs index ea75ac74d..39dde4b17 100644 --- a/EndlessClient/HUD/Chat/ChatModeCalculator.cs +++ b/EndlessClient/HUD/Chat/ChatModeCalculator.cs @@ -31,7 +31,7 @@ public ChatModePictureBox.ChatMode CalculateMode(string fullTextString) { case '!': return ChatModePictureBox.ChatMode.Private; case '@': - case '~': return ChatModePictureBox.ChatMode.Global; + case '~': return ChatModePictureBox.ChatMode.Global; case '+': return ChatModePictureBox.ChatMode.Admin; case '\'': return ChatModePictureBox.ChatMode.Group; case '&': return ChatModePictureBox.ChatMode.Guild; diff --git a/EndlessClient/HUD/Chat/ChatNotificationActions.cs b/EndlessClient/HUD/Chat/ChatNotificationActions.cs index 9cc3d0283..ab8d4d06b 100644 --- a/EndlessClient/HUD/Chat/ChatNotificationActions.cs +++ b/EndlessClient/HUD/Chat/ChatNotificationActions.cs @@ -1,7 +1,4 @@ -using System; -using System.Globalization; -using System.Windows; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.ControlSets; using EndlessClient.HUD.Controls; @@ -12,6 +9,9 @@ using EOLib.Domain.Notifiers; using EOLib.Localization; using Optional; +using System; +using System.Globalization; +using System.Windows; namespace EndlessClient.HUD.Chat { @@ -108,4 +108,4 @@ public void NotifyServerPing(int timeInMS) _chatRepository.AllChat[ChatTab.Local].Add(chatData); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatPanelTab.cs b/EndlessClient/HUD/Chat/ChatPanelTab.cs index 4af986b75..382c57040 100644 --- a/EndlessClient/HUD/Chat/ChatPanelTab.cs +++ b/EndlessClient/HUD/Chat/ChatPanelTab.cs @@ -244,4 +244,4 @@ ChatTab.Private1 or }; } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/IChatModeCalculator.cs b/EndlessClient/HUD/Chat/IChatModeCalculator.cs index 9c7c20875..5ae7f3286 100644 --- a/EndlessClient/HUD/Chat/IChatModeCalculator.cs +++ b/EndlessClient/HUD/Chat/IChatModeCalculator.cs @@ -6,4 +6,4 @@ public interface IChatModeCalculator { ChatModePictureBox.ChatMode CalculateMode(string fullTextString); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/IChatTextBoxActions.cs b/EndlessClient/HUD/Chat/IChatTextBoxActions.cs index 734a443e8..e5c61e4ec 100644 --- a/EndlessClient/HUD/Chat/IChatTextBoxActions.cs +++ b/EndlessClient/HUD/Chat/IChatTextBoxActions.cs @@ -6,4 +6,4 @@ public interface IChatTextBoxActions void FocusChatTextBox(); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ServerMessageHandler.cs b/EndlessClient/HUD/Chat/ServerMessageHandler.cs index 00f409b44..89e66123c 100644 --- a/EndlessClient/HUD/Chat/ServerMessageHandler.cs +++ b/EndlessClient/HUD/Chat/ServerMessageHandler.cs @@ -41,4 +41,4 @@ public interface IServerMessageHandler { void AddServerMessage(string message, SoundEffectID soundEffect = SoundEffectID.ServerMessage, ChatIcon icon = ChatIcon.Exclamation); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs b/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs index 5e7d5f497..741bbb32f 100644 --- a/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs +++ b/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs @@ -20,4 +20,4 @@ public DragCompletedEventArgs(TRecord data, bool isChainedDrag) IsChainedDrag = isChainedDrag; } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/DraggablePanelItem.cs b/EndlessClient/HUD/Controls/DraggablePanelItem.cs index 33c5c0886..7632e5fce 100644 --- a/EndlessClient/HUD/Controls/DraggablePanelItem.cs +++ b/EndlessClient/HUD/Controls/DraggablePanelItem.cs @@ -132,4 +132,4 @@ private void StopDragging(MouseEventArgs mouseEventArgs) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/HudBackgroundFrame.cs b/EndlessClient/HUD/Controls/HudBackgroundFrame.cs index 728acbc9d..c9dde9fd6 100644 --- a/EndlessClient/HUD/Controls/HudBackgroundFrame.cs +++ b/EndlessClient/HUD/Controls/HudBackgroundFrame.cs @@ -68,4 +68,4 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/HudControlIdentifier.cs b/EndlessClient/HUD/Controls/HudControlIdentifier.cs index bd1938bc2..19824f396 100644 --- a/EndlessClient/HUD/Controls/HudControlIdentifier.cs +++ b/EndlessClient/HUD/Controls/HudControlIdentifier.cs @@ -39,7 +39,7 @@ public enum HudControlIdentifier PartyPanel, MacroButton, - + SettingsButton, SettingsPanel, @@ -78,4 +78,4 @@ public enum HudControlIdentifier PreviousUserInputTracker = Int32.MaxValue, //this should always be last! } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/HudControlsFactory.cs b/EndlessClient/HUD/Controls/HudControlsFactory.cs index 4d522d28e..793f450de 100644 --- a/EndlessClient/HUD/Controls/HudControlsFactory.cs +++ b/EndlessClient/HUD/Controls/HudControlsFactory.cs @@ -253,11 +253,11 @@ private IXNAButton CreateStateChangeButton(InGameStates whichState) { if (whichState == InGameStates.News) throw new ArgumentOutOfRangeException(nameof(whichState), "News state does not have a button associated with it"); - var buttonIndex = (int) whichState; + var buttonIndex = (int)whichState; var mainButtonTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 25); - var widthDelta = mainButtonTexture.Width/2; - var heightDelta = mainButtonTexture.Height/11; + var widthDelta = mainButtonTexture.Width / 2; + var heightDelta = mainButtonTexture.Height / 11; IXNAButton retButton; if (!_clientWindowSizeRepository.Resizable) @@ -359,7 +359,7 @@ private void DoHudStateChangeClick(InGameStates whichState) case InGameStates.ViewMapToggle: _hudButtonController.ClickViewMapToggle(); break; case InGameStates.ActiveSpells: _hudButtonController.ClickActiveSpells(); break; case InGameStates.PassiveSpells: _hudButtonController.ClickPassiveSpells(); break; - case InGameStates.Chat: + case InGameStates.Chat: _hudButtonController.ClickChat(); _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_CHAT_PANEL_NOW_VIEWED); break; diff --git a/EndlessClient/HUD/Controls/IDraggableItemContainer.cs b/EndlessClient/HUD/Controls/IDraggableItemContainer.cs index c2387a469..39713bef4 100644 --- a/EndlessClient/HUD/Controls/IDraggableItemContainer.cs +++ b/EndlessClient/HUD/Controls/IDraggableItemContainer.cs @@ -6,4 +6,4 @@ public interface IDraggableItemContainer : IXNAControl { bool NoItemsDragging(); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/IHudControlsFactory.cs b/EndlessClient/HUD/Controls/IHudControlsFactory.cs index 2b7c2d115..dc788bcdb 100644 --- a/EndlessClient/HUD/Controls/IHudControlsFactory.cs +++ b/EndlessClient/HUD/Controls/IHudControlsFactory.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; -using EndlessClient.Controllers; +using EndlessClient.Controllers; using Microsoft.Xna.Framework; +using System.Collections.Generic; namespace EndlessClient.HUD.Controls { @@ -10,4 +10,4 @@ public interface IHudControlsFactory IReadOnlyDictionary CreateHud(); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs b/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs index e437a3c12..02baaf161 100644 --- a/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs +++ b/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs @@ -1,9 +1,9 @@ -using System; -using System.Diagnostics; -using EndlessClient.GameExecution; +using EndlessClient.GameExecution; using EOLib.Domain.Character; using Microsoft.Xna.Framework; using Optional; +using System; +using System.Diagnostics; namespace EndlessClient.HUD.Controls { @@ -69,4 +69,4 @@ public override void Update(GameTime gameTime) base.Update(gameTime); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/HudStateActions.cs b/EndlessClient/HUD/HudStateActions.cs index cb77610f0..1b2d78473 100644 --- a/EndlessClient/HUD/HudStateActions.cs +++ b/EndlessClient/HUD/HudStateActions.cs @@ -1,12 +1,12 @@ -using System; -using System.Linq; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EndlessClient.ControlSets; using EndlessClient.HUD.Panels; using EndlessClient.Rendering; using EOLib.Domain.Map; using EOLib.IO.Repositories; using EOLib.Localization; +using System; +using System.Linq; namespace EndlessClient.HUD { diff --git a/EndlessClient/HUD/IHudButtonController.cs b/EndlessClient/HUD/IHudButtonController.cs index acf078f09..47a5e8ad8 100644 --- a/EndlessClient/HUD/IHudButtonController.cs +++ b/EndlessClient/HUD/IHudButtonController.cs @@ -32,4 +32,4 @@ public interface IHudButtonController void ClickQuestStatus(); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/IHudStateActions.cs b/EndlessClient/HUD/IHudStateActions.cs index 755e063bd..83e06dba3 100644 --- a/EndlessClient/HUD/IHudStateActions.cs +++ b/EndlessClient/HUD/IHudStateActions.cs @@ -3,7 +3,7 @@ public interface IHudStateActions { void SwitchToState(InGameStates newState); - + void ToggleMapView(); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/IStatusLabelSetter.cs b/EndlessClient/HUD/IStatusLabelSetter.cs index 8f6b3aa59..b28839090 100644 --- a/EndlessClient/HUD/IStatusLabelSetter.cs +++ b/EndlessClient/HUD/IStatusLabelSetter.cs @@ -13,4 +13,4 @@ public interface IStatusLabelSetter : IStatusLabelNotifier void SetStatusLabel(string text); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/IStatusLabelTextRepository.cs b/EndlessClient/HUD/IStatusLabelTextRepository.cs index 6b0ee57bd..59eb2d9ca 100644 --- a/EndlessClient/HUD/IStatusLabelTextRepository.cs +++ b/EndlessClient/HUD/IStatusLabelTextRepository.cs @@ -1,5 +1,5 @@ -using System; -using AutomaticTypeMapper; +using AutomaticTypeMapper; +using System; namespace EndlessClient.HUD { @@ -31,4 +31,4 @@ public StatusLabelTextRepository() SetTime = DateTime.Now; } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventoryPanelItem.cs b/EndlessClient/HUD/Inventory/InventoryPanelItem.cs index eb9b75a88..10400ca73 100644 --- a/EndlessClient/HUD/Inventory/InventoryPanelItem.cs +++ b/EndlessClient/HUD/Inventory/InventoryPanelItem.cs @@ -56,7 +56,7 @@ public string Text public event EventHandler DoubleClick; public override Rectangle EventArea => IsDragging ? DrawArea : DrawAreaWithParentOffset; - + // uses absolute coordinates protected override Rectangle GridArea => new Rectangle( _parentContainer.DrawPositionWithParentOffset.ToPoint() + new Point(12, 8), @@ -232,4 +232,4 @@ private static Vector2 GetPosition(int slot) return new Vector2(13 + 26 * (slot % InventoryPanel.InventoryRowSlots), 9 + 26 * (slot / InventoryPanel.InventoryRowSlots)); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventoryService.cs b/EndlessClient/HUD/Inventory/InventoryService.cs index f111b8af1..c1b43937a 100644 --- a/EndlessClient/HUD/Inventory/InventoryService.cs +++ b/EndlessClient/HUD/Inventory/InventoryService.cs @@ -110,4 +110,4 @@ public interface IInventoryService bool FitsInSlot(bool[,] usedSlots, int newSlot, ItemSize size); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventorySlotRepository.cs b/EndlessClient/HUD/Inventory/InventorySlotRepository.cs index b3da1b47a..aa4be9371 100644 --- a/EndlessClient/HUD/Inventory/InventorySlotRepository.cs +++ b/EndlessClient/HUD/Inventory/InventorySlotRepository.cs @@ -42,4 +42,4 @@ public void ResetState() SlotMap = new Dictionary(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs b/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs index 66f4e2a55..4cbeac495 100644 --- a/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs +++ b/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs @@ -86,4 +86,4 @@ public interface IInventorySpaceValidator bool ItemsFit(IReadOnlyList outItems, IReadOnlyList inItems); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/ItemNameColorService.cs b/EndlessClient/HUD/ItemNameColorService.cs index d37a3217c..c41fe4a20 100644 --- a/EndlessClient/HUD/ItemNameColorService.cs +++ b/EndlessClient/HUD/ItemNameColorService.cs @@ -34,4 +34,4 @@ public interface IItemNameColorService Color GetColorForInventoryDisplay(EIFRecord itemData); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/ChatPanel.cs b/EndlessClient/HUD/Panels/ChatPanel.cs index 63e39c657..856db4f09 100644 --- a/EndlessClient/HUD/Panels/ChatPanel.cs +++ b/EndlessClient/HUD/Panels/ChatPanel.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using EndlessClient.ControlSets; +using EndlessClient.ControlSets; using EndlessClient.HUD.Chat; using EndlessClient.Rendering; using EndlessClient.Rendering.Chat; @@ -11,6 +8,9 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using MonoGame.Extended.BitmapFonts; +using System; +using System.Collections.Generic; +using System.Linq; using XNAControls; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Panels/DraggableHudPanel.cs b/EndlessClient/HUD/Panels/DraggableHudPanel.cs index e33c7bb96..3a3316c3e 100644 --- a/EndlessClient/HUD/Panels/DraggableHudPanel.cs +++ b/EndlessClient/HUD/Panels/DraggableHudPanel.cs @@ -63,4 +63,4 @@ protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventA return true; } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/HudPanelFactory.cs b/EndlessClient/HUD/Panels/HudPanelFactory.cs index 0f89149e7..0a1f045de 100644 --- a/EndlessClient/HUD/Panels/HudPanelFactory.cs +++ b/EndlessClient/HUD/Panels/HudPanelFactory.cs @@ -134,7 +134,8 @@ public NewsPanel CreateNewsPanel() new ChatRenderableGenerator(_nativeGraphicsManager, _friendIgnoreListService, chatFont), _newsProvider, chatFont, - _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; } public InventoryPanel CreateInventoryPanel() @@ -154,7 +155,8 @@ public InventoryPanel CreateInventoryPanel() _activeDialogProvider, _sfxPlayer, _configurationProvider, - _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; } public ActiveSpellsPanel CreateActiveSpellsPanel() @@ -171,7 +173,8 @@ public ActiveSpellsPanel CreateActiveSpellsPanel() _hudControlProvider, _sfxPlayer, _configurationProvider, - _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; } public PassiveSpellsPanel CreatePassiveSpellsPanel() @@ -189,7 +192,8 @@ public ChatPanel CreateChatPanel() _chatProvider, _hudControlProvider, chatFont, - _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; } public StatsPanel CreateStatsPanel() @@ -200,7 +204,8 @@ public StatsPanel CreateStatsPanel() _experienceTableProvider, _messageBoxFactory, _trainingController, - _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; } public OnlineListPanel CreateOnlineListPanel() @@ -224,7 +229,8 @@ public SettingsPanel CreateSettingsPanel() _messageBoxFactory, _configurationRepository, _sfxPlayer, - _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; } public HelpPanel CreateHelpPanel() diff --git a/EndlessClient/HUD/Panels/IHudPanel.cs b/EndlessClient/HUD/Panels/IHudPanel.cs index 8e915163a..e380c4618 100644 --- a/EndlessClient/HUD/Panels/IHudPanel.cs +++ b/EndlessClient/HUD/Panels/IHudPanel.cs @@ -20,4 +20,4 @@ public interface IHudPanel : IGameComponent event Action DragCompleted; } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/IHudPanelFactory.cs b/EndlessClient/HUD/Panels/IHudPanelFactory.cs index 04f1a847d..eec471e9d 100644 --- a/EndlessClient/HUD/Panels/IHudPanelFactory.cs +++ b/EndlessClient/HUD/Panels/IHudPanelFactory.cs @@ -22,4 +22,4 @@ public interface IHudPanelFactory HelpPanel CreateHelpPanel(); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/InventoryPanel.cs b/EndlessClient/HUD/Panels/InventoryPanel.cs index b2956f8b7..aa3abf31d 100644 --- a/EndlessClient/HUD/Panels/InventoryPanel.cs +++ b/EndlessClient/HUD/Panels/InventoryPanel.cs @@ -565,4 +565,4 @@ private static IEnumerable GetOverlappingTakenSlots(int newSlot, ItemSize s } } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/NewsPanel.cs b/EndlessClient/HUD/Panels/NewsPanel.cs index 1a0e51cea..ad983b417 100644 --- a/EndlessClient/HUD/Panels/NewsPanel.cs +++ b/EndlessClient/HUD/Panels/NewsPanel.cs @@ -1,14 +1,14 @@ -using EndlessClient.Rendering.Chat; +using EndlessClient.Rendering; +using EndlessClient.Rendering.Chat; using EndlessClient.UIControls; using EOLib.Domain.Login; using EOLib.Graphics; using Microsoft.Xna.Framework; -using MonoGame.Extended.BitmapFonts; -using XNAControls; using Microsoft.Xna.Framework.Graphics; +using MonoGame.Extended.BitmapFonts; using System.Collections.Generic; using System.Linq; -using EndlessClient.Rendering; +using XNAControls; namespace EndlessClient.HUD.Panels { @@ -129,4 +129,4 @@ private void SetupRenderablesFromCachedValues(IReadOnlyList ren _scrollBar.UpdateDimensions(renderables.Count); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/OnlineListPanel.cs b/EndlessClient/HUD/Panels/OnlineListPanel.cs index d58d9c7bc..6f892ebb2 100644 --- a/EndlessClient/HUD/Panels/OnlineListPanel.cs +++ b/EndlessClient/HUD/Panels/OnlineListPanel.cs @@ -130,7 +130,7 @@ protected override void OnUpdateControl(GameTime gameTime) if (!_cachedList.SetEquals(_onlinePlayerProvider.OnlinePlayers)) { _cachedList = _onlinePlayerProvider.OnlinePlayers.ToHashSet(); - + // keep the friends list data from overriding the displayed data in this panel // it will be friends list data if all titles (or any field other than name) are empty if (!_cachedList.All(x => x.Title == string.Empty)) @@ -217,7 +217,7 @@ private void ApplyFilter() { case Filter.Friends: _filteredList = _onlineList.Where(x => _friendList.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase)).ToList(); break; case Filter.Admins: _filteredList = _onlineList.Where(IsAdminIcon).ToList(); break; - case Filter.Party: _filteredList = _onlineList.Where(x => _partyDataProvider.Members.Any(y => string.Equals(y.Name, x.Name, StringComparison.InvariantCultureIgnoreCase))).ToList(); break; + case Filter.Party: _filteredList = _onlineList.Where(x => _partyDataProvider.Members.Any(y => string.Equals(y.Name, x.Name, StringComparison.InvariantCultureIgnoreCase))).ToList(); break; case Filter.All: default: _filteredList = new List(_onlineList); break; } diff --git a/EndlessClient/HUD/Panels/StatsPanel.cs b/EndlessClient/HUD/Panels/StatsPanel.cs index cdb3d288e..9106f5563 100644 --- a/EndlessClient/HUD/Panels/StatsPanel.cs +++ b/EndlessClient/HUD/Panels/StatsPanel.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using EndlessClient.Controllers; +using EndlessClient.Controllers; using EndlessClient.Dialogs; using EndlessClient.Dialogs.Factories; using EndlessClient.Rendering; @@ -9,6 +7,8 @@ using EOLib.Domain.Extensions; using EOLib.Graphics; using Microsoft.Xna.Framework; +using System; +using System.Linq; using XNAControls; namespace EndlessClient.HUD.Panels @@ -73,11 +73,11 @@ public StatsPanel(INativeGraphicsManager nativeGraphicsManager, ForeColor = ColorConstants.LightGrayText, AutoSize = false, Text = "", - DrawArea = new Rectangle(50, 8 + i*18, 73, 13) + DrawArea = new Rectangle(50, 8 + i * 18, 73, 13) }; _arrowButtons[i] = new XNAButton(buttonTexture, - new Vector2(106, 7 + i*18), + new Vector2(106, 7 + i * 18), outTextureArea, overTextureArea) { @@ -100,8 +100,8 @@ public StatsPanel(INativeGraphicsManager nativeGraphicsManager, for (int i = 0; i < _otherInfo.Length; ++i) { var drawArea = i < 4 - ? new Rectangle(280, 44 + i%4*18, 60, 13) - : new Rectangle(379, 44 + i%4*18, 94, 13); + ? new Rectangle(280, 44 + i % 4 * 18, 60, 13) + : new Rectangle(379, 44 + i % 4 * 18, 94, 13); _otherInfo[i] = new XNALabel(Constants.FontSize08pt5) { @@ -223,7 +223,7 @@ private void HandleArrowButtonClick(object sender, EventArgs e) } else { - var index = _arrowButtons.Select((btn, ndx) => new {btn, ndx}) + var index = _arrowButtons.Select((btn, ndx) => new { btn, ndx }) .Single(x => x.btn == sender).ndx; var characterStat = CharacterStat.Strength + index; _trainingController.AddStatPoint(characterStat); diff --git a/EndlessClient/HUD/Party/PartyPanelMember.cs b/EndlessClient/HUD/Party/PartyPanelMember.cs index 372e29df4..f37254f22 100644 --- a/EndlessClient/HUD/Party/PartyPanelMember.cs +++ b/EndlessClient/HUD/Party/PartyPanelMember.cs @@ -94,7 +94,7 @@ public PartyPanelMember(INativeGraphicsManager nativeGraphicsManager, { DrawPosition = new Vector2(205, 0), AutoSize = true, - ForeColor= Color.Black, + ForeColor = Color.Black, Text = "HP" }; _hpLabel.SetParentControl(this); @@ -132,4 +132,4 @@ protected override void OnDrawControl(GameTime gameTime) base.OnDrawControl(gameTime); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Spells/SpellPanelItem.cs b/EndlessClient/HUD/Spells/SpellPanelItem.cs index b3fe8afa2..ad936f914 100644 --- a/EndlessClient/HUD/Spells/SpellPanelItem.cs +++ b/EndlessClient/HUD/Spells/SpellPanelItem.cs @@ -33,7 +33,7 @@ public int DisplaySlot set { _displaySlot = value; - DrawPosition = GetDisplayPosition(_displaySlot); + DrawPosition = GetDisplayPosition(_displaySlot); } } @@ -196,4 +196,4 @@ private static Vector2 GetDisplayPosition(int slot) return new Vector2(101 + col * 45, 9 + row * 52); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Spells/SpellSelectActions.cs b/EndlessClient/HUD/Spells/SpellSelectActions.cs index 0c01ea633..58a3035bf 100644 --- a/EndlessClient/HUD/Spells/SpellSelectActions.cs +++ b/EndlessClient/HUD/Spells/SpellSelectActions.cs @@ -58,4 +58,4 @@ public interface ISpellSelectActions { void SelectSpellBySlot(int slot); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs b/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs index a477c05c8..e6bae1c2e 100644 --- a/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs +++ b/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs @@ -63,4 +63,4 @@ public SpellSlotDataRepository() SpellSlots = new Option[ActiveSpellsPanel.SpellRows * ActiveSpellsPanel.SpellRowLength]; } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/HPStatusBar.cs b/EndlessClient/HUD/StatusBars/HPStatusBar.cs index cea877923..03150e25c 100644 --- a/EndlessClient/HUD/StatusBars/HPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/HPStatusBar.cs @@ -36,4 +36,4 @@ protected override void DrawStatusBar() _spriteBatch.End(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/SPStatusBar.cs b/EndlessClient/HUD/StatusBars/SPStatusBar.cs index e02d50091..cf2e2916a 100644 --- a/EndlessClient/HUD/StatusBars/SPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/SPStatusBar.cs @@ -37,4 +37,4 @@ protected override void DrawStatusBar() _spriteBatch.End(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/StatusBarBase.cs b/EndlessClient/HUD/StatusBars/StatusBarBase.cs index 1260140a4..aec449222 100644 --- a/EndlessClient/HUD/StatusBars/StatusBarBase.cs +++ b/EndlessClient/HUD/StatusBars/StatusBarBase.cs @@ -121,4 +121,4 @@ protected void ChangeStatusBarPosition() /// private static Rectangle DropDownSourceRectangle => new Rectangle(220, 30, 110, 21); } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/TNLStatusBar.cs b/EndlessClient/HUD/StatusBars/TNLStatusBar.cs index 5915d3e5e..9919e57a8 100644 --- a/EndlessClient/HUD/StatusBars/TNLStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/TNLStatusBar.cs @@ -1,10 +1,10 @@ -using System; -using System.Collections.Generic; -using EndlessClient.Input; +using EndlessClient.Input; using EndlessClient.Rendering; using EOLib.Domain.Character; using EOLib.Graphics; using Microsoft.Xna.Framework; +using System; +using System.Collections.Generic; namespace EndlessClient.HUD.StatusBars { @@ -23,7 +23,7 @@ public TNLStatusBar(INativeGraphicsManager nativeGraphicsManager, _experienceTableProvider = experienceTableProvider; DrawArea = new Rectangle(430, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); - _sourceRectangleArea = new Rectangle(_sourceRectangleArea.Width*3 - 1, + _sourceRectangleArea = new Rectangle(_sourceRectangleArea.Width * 3 - 1, 0, _sourceRectangleArea.Width + 1, _sourceRectangleArea.Height); @@ -51,4 +51,4 @@ protected override void DrawStatusBar() private IReadOnlyList ExpTable => _experienceTableProvider.ExperienceByLevel; } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/TPStatusBar.cs b/EndlessClient/HUD/StatusBars/TPStatusBar.cs index 3e88aac8a..0d9c2705b 100644 --- a/EndlessClient/HUD/StatusBars/TPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/TPStatusBar.cs @@ -1,9 +1,9 @@ -using System; -using EndlessClient.Input; +using EndlessClient.Input; using EndlessClient.Rendering; using EOLib.Domain.Character; using EOLib.Graphics; using Microsoft.Xna.Framework; +using System; namespace EndlessClient.HUD.StatusBars { @@ -38,4 +38,4 @@ protected override void DrawStatusBar() _spriteBatch.End(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/HUD/StatusLabelSetter.cs b/EndlessClient/HUD/StatusLabelSetter.cs index 46501d04f..547124824 100644 --- a/EndlessClient/HUD/StatusLabelSetter.cs +++ b/EndlessClient/HUD/StatusLabelSetter.cs @@ -1,7 +1,7 @@ -using System; using AutomaticTypeMapper; using EOLib.Domain.Chat; using EOLib.Localization; +using System; namespace EndlessClient.HUD { diff --git a/EndlessClient/HUD/UserInterfaceActions.cs b/EndlessClient/HUD/UserInterfaceActions.cs index 9fe7de27d..46a0c2a3d 100644 --- a/EndlessClient/HUD/UserInterfaceActions.cs +++ b/EndlessClient/HUD/UserInterfaceActions.cs @@ -102,4 +102,4 @@ public void NotifyCharacterInventory(string name, int usage, int gold, IReadOnly _inGameDialogActions.ShowKeyValueMessageDialog(title, messages); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Initialization/ConfigInitializer.cs b/EndlessClient/Initialization/ConfigInitializer.cs index 83defdf85..3610a8654 100644 --- a/EndlessClient/Initialization/ConfigInitializer.cs +++ b/EndlessClient/Initialization/ConfigInitializer.cs @@ -18,4 +18,4 @@ public void Initialize() _configFileLoadActions.LoadConfigFile(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Initialization/EndlessClientInitializer.cs b/EndlessClient/Initialization/EndlessClientInitializer.cs index 4bd7b6e21..f4d90833d 100644 --- a/EndlessClient/Initialization/EndlessClientInitializer.cs +++ b/EndlessClient/Initialization/EndlessClientInitializer.cs @@ -96,4 +96,4 @@ public void Initialize() _paperdollDialogFactory.InjectInventoryController(_inventoryController); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Initialization/GraphicsInitializer.cs b/EndlessClient/Initialization/GraphicsInitializer.cs index 06bf931fe..d39032ce5 100644 --- a/EndlessClient/Initialization/GraphicsInitializer.cs +++ b/EndlessClient/Initialization/GraphicsInitializer.cs @@ -40,4 +40,4 @@ private static void TryInitializePEFiles(GFXTypes file, IPEFile peFile) throw new LibraryLoadException(number, file); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Initialization/IGameInitializer.cs b/EndlessClient/Initialization/IGameInitializer.cs index 3ac14a51d..7bddf1ae9 100644 --- a/EndlessClient/Initialization/IGameInitializer.cs +++ b/EndlessClient/Initialization/IGameInitializer.cs @@ -4,4 +4,4 @@ public interface IGameInitializer { void Initialize(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Initialization/LocalizationInitializer.cs b/EndlessClient/Initialization/LocalizationInitializer.cs index b08492391..72f96ae48 100644 --- a/EndlessClient/Initialization/LocalizationInitializer.cs +++ b/EndlessClient/Initialization/LocalizationInitializer.cs @@ -18,4 +18,4 @@ public void Initialize() _dataFileLoadActions.LoadDataFiles(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/ArrowKeyHandler.cs b/EndlessClient/Input/ArrowKeyHandler.cs index c425ef8e8..c4aac0903 100644 --- a/EndlessClient/Input/ArrowKeyHandler.cs +++ b/EndlessClient/Input/ArrowKeyHandler.cs @@ -37,4 +37,4 @@ protected override Option HandleInput() return Option.None(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/ControlKeyHandler.cs b/EndlessClient/Input/ControlKeyHandler.cs index 270ecea55..d0e51f4f1 100644 --- a/EndlessClient/Input/ControlKeyHandler.cs +++ b/EndlessClient/Input/ControlKeyHandler.cs @@ -30,4 +30,4 @@ protected override Option HandleInput() return Option.None(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/CurrentUserInputTracker.cs b/EndlessClient/Input/CurrentUserInputTracker.cs index 5f7e929ad..f09bb9f5e 100644 --- a/EndlessClient/Input/CurrentUserInputTracker.cs +++ b/EndlessClient/Input/CurrentUserInputTracker.cs @@ -26,4 +26,4 @@ public override void Update(GameTime gameTime) base.Update(gameTime); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/FunctionKeyHandler.cs b/EndlessClient/Input/FunctionKeyHandler.cs index 18d692bee..e0a1de145 100644 --- a/EndlessClient/Input/FunctionKeyHandler.cs +++ b/EndlessClient/Input/FunctionKeyHandler.cs @@ -41,4 +41,4 @@ protected override Option HandleInput() return Option.None(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/IUserInputRepository.cs b/EndlessClient/Input/IUserInputRepository.cs index 127b912f3..8382d233a 100644 --- a/EndlessClient/Input/IUserInputRepository.cs +++ b/EndlessClient/Input/IUserInputRepository.cs @@ -37,4 +37,4 @@ public class KeyStateRepository : IUserInputRepository, IUserInputProvider public MouseState CurrentMouseState { get; set; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/IUserInputTimeRepository.cs b/EndlessClient/Input/IUserInputTimeRepository.cs index 5f8c6c4da..e4d074b4b 100644 --- a/EndlessClient/Input/IUserInputTimeRepository.cs +++ b/EndlessClient/Input/IUserInputTimeRepository.cs @@ -1,5 +1,5 @@ -using System; -using AutomaticTypeMapper; +using AutomaticTypeMapper; +using System; namespace EndlessClient.Input { @@ -23,4 +23,4 @@ public UserInputTimeRepository() LastInputTime = DateTime.Now; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/KeyboardStateExtensions.cs b/EndlessClient/Input/KeyboardStateExtensions.cs index 55d97415d..977060c9b 100644 --- a/EndlessClient/Input/KeyboardStateExtensions.cs +++ b/EndlessClient/Input/KeyboardStateExtensions.cs @@ -28,4 +28,4 @@ public static bool IsKeyPressedOnce(this KeyboardState keyState, KeyboardState p return previousKeyState.IsKeyDown(key) && keyState.IsKeyUp(key); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/NumPadHandler.cs b/EndlessClient/Input/NumPadHandler.cs index 8a9bae140..44c490bd6 100644 --- a/EndlessClient/Input/NumPadHandler.cs +++ b/EndlessClient/Input/NumPadHandler.cs @@ -44,4 +44,4 @@ protected override Option HandleInput() return Option.None(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/PanelShortcutHandler.cs b/EndlessClient/Input/PanelShortcutHandler.cs index 390fa0e70..6287056b9 100644 --- a/EndlessClient/Input/PanelShortcutHandler.cs +++ b/EndlessClient/Input/PanelShortcutHandler.cs @@ -45,7 +45,7 @@ protected override Option HandleInput() case Keys.D7: _hudButtonController.ClickOnlineList(); break; case Keys.D8: _hudButtonController.ClickParty(); break; - // macro: intentionally not implemented + // macro: intentionally not implemented case Keys.D9: _hudButtonController.ClickSettings(); break; case Keys.D0: _hudButtonController.ClickHelp(); break; } @@ -57,4 +57,4 @@ protected override Option HandleInput() return Option.None(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/PreviousUserInputTracker.cs b/EndlessClient/Input/PreviousUserInputTracker.cs index fe128f5a6..d157bc31c 100644 --- a/EndlessClient/Input/PreviousUserInputTracker.cs +++ b/EndlessClient/Input/PreviousUserInputTracker.cs @@ -24,4 +24,4 @@ public override void Update(GameTime gameTime) base.Update(gameTime); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/UnwalkableTileActions.cs b/EndlessClient/Input/UnwalkableTileActions.cs index 6aced669e..5eeed3648 100644 --- a/EndlessClient/Input/UnwalkableTileActions.cs +++ b/EndlessClient/Input/UnwalkableTileActions.cs @@ -177,4 +177,4 @@ public interface IUnwalkableTileActions IReadOnlyList GetUnwalkableTileActions(IMapCellState mapCellState); } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/UnwalkableTileActionsHandler.cs b/EndlessClient/Input/UnwalkableTileActionsHandler.cs index 0f261fe57..c09c702eb 100644 --- a/EndlessClient/Input/UnwalkableTileActionsHandler.cs +++ b/EndlessClient/Input/UnwalkableTileActionsHandler.cs @@ -59,4 +59,4 @@ public interface IUnwalkableTileActionsHandler { void HandleUnwalkableTileActions(IReadOnlyList unwalkableActions, IMapCellState cellState); } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/UserInputHandler.cs b/EndlessClient/Input/UserInputHandler.cs index c69c03cc7..376889d2f 100644 --- a/EndlessClient/Input/UserInputHandler.cs +++ b/EndlessClient/Input/UserInputHandler.cs @@ -78,4 +78,4 @@ protected override void OnUpdateControl(GameTime gameTime) public interface IUserInputHandler : IGameComponent { } -} +} \ No newline at end of file diff --git a/EndlessClient/Input/UserInputHandlerFactory.cs b/EndlessClient/Input/UserInputHandlerFactory.cs index 3cbc3b809..0b7a37162 100644 --- a/EndlessClient/Input/UserInputHandlerFactory.cs +++ b/EndlessClient/Input/UserInputHandlerFactory.cs @@ -68,4 +68,4 @@ public interface IUserInputHandlerFactory { IUserInputHandler CreateUserInputHandler(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Network/PacketHandlerGameComponent.cs b/EndlessClient/Network/PacketHandlerGameComponent.cs index 57051d0db..cce3832a4 100644 --- a/EndlessClient/Network/PacketHandlerGameComponent.cs +++ b/EndlessClient/Network/PacketHandlerGameComponent.cs @@ -21,7 +21,7 @@ public PacketHandlerGameComponent(IEndlessGame game, INetworkClientProvider networkClientProvider, IBackgroundReceiveTaskRepository backgroundReceiveTaskRepository, IMainButtonController mainButtonController) - : base((Game) game) + : base((Game)game) { _packetHandler = packetHandler; _networkClientProvider = networkClientProvider; @@ -49,4 +49,4 @@ public override void Update(GameTime gameTime) base.Update(gameTime); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Network/UnknownEntitiesRequester.cs b/EndlessClient/Network/UnknownEntitiesRequester.cs index 21ddb08ba..53446e24f 100644 --- a/EndlessClient/Network/UnknownEntitiesRequester.cs +++ b/EndlessClient/Network/UnknownEntitiesRequester.cs @@ -37,7 +37,7 @@ public UnknownEntitiesRequester(IEndlessGameProvider gameProvider, INPCRendererProvider npcRendererProvider, ICharacterRendererProvider characterRendererProvider, IUnknownEntitiesRequestActions unknownEntitiesRequestActions) - : base((Game) gameProvider.Game) + : base((Game)gameProvider.Game) { _clientWindowSizeProvider = clientWindowSizeProvider; _characterProvider = characterProvider; @@ -112,4 +112,4 @@ private void ClearOutOfRangeActors() } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Program.cs b/EndlessClient/Program.cs index c0575733f..3b86ced2b 100644 --- a/EndlessClient/Program.cs +++ b/EndlessClient/Program.cs @@ -1,6 +1,6 @@ using AutomaticTypeMapper; -using System; using EndlessClient.GameExecution; +using System; using System.Reflection; namespace EndlessClient @@ -12,7 +12,7 @@ public static class Program [STAThread] public static void Main(string[] args) { - var assemblyNames = new [] + var assemblyNames = new[] { Assembly.GetExecutingAssembly().FullName, "EOLib", @@ -35,4 +35,4 @@ public static void Main(string[] args) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Properties/AssemblyInfo.cs b/EndlessClient/Properties/AssemblyInfo.cs index d9d051560..df4346355 100644 --- a/EndlessClient/Properties/AssemblyInfo.cs +++ b/EndlessClient/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.4.0.456")] -[assembly: AssemblyFileVersion("3.4.0.456")] +[assembly: AssemblyFileVersion("3.4.0.456")] \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterAnimationActions.cs b/EndlessClient/Rendering/Character/CharacterAnimationActions.cs index aae3d2823..ae352a600 100644 --- a/EndlessClient/Rendering/Character/CharacterAnimationActions.cs +++ b/EndlessClient/Rendering/Character/CharacterAnimationActions.cs @@ -130,7 +130,7 @@ public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate dest return; Animator.StartOtherCharacterWalkAnimation(characterID, destination, direction); - + ShowWaterSplashiesIfNeeded(CharacterActionState.Walking, characterID); if (IsSteppingStone(character.RenderProperties)) @@ -198,7 +198,7 @@ public void NotifySelfSpellCast(int playerId, int spellId, int spellHp, int perc var spellGraphic = _pubFileProvider.ESFFile[spellId].Graphic; if (playerId == _characterRepository.MainCharacter.ID) - { + { _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => { cr.ShoutSpellCast(); @@ -439,4 +439,4 @@ public interface ICharacterAnimationActions void Emote(Emote whichEmote); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterAnimator.cs b/EndlessClient/Rendering/Character/CharacterAnimator.cs index 951dc62d7..496a02f01 100644 --- a/EndlessClient/Rendering/Character/CharacterAnimator.cs +++ b/EndlessClient/Rendering/Character/CharacterAnimator.cs @@ -60,7 +60,7 @@ public CharacterAnimator(IEndlessGameProvider gameProvider, IPathFinder pathFinder, IFixedTimeStepRepository fixedTimeStepRepository, IMetadataProvider weaponMetadataProvider) - : base((Game) gameProvider.Game) + : base((Game)gameProvider.Game) { _characterRepository = characterRepository; _currentMapStateRepository = currentMapStateRepository; @@ -131,7 +131,7 @@ public void StartMainCharacterWalkAnimation(Option targetCoordina rp = FaceTarget(characterCoord, _walkPath.Peek(), rp); _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(rp); } - + doTheWalk(); }, none: doTheWalk); @@ -609,4 +609,4 @@ public interface ICharacterAnimator : IGameComponent void StopAllCharacterAnimations(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterRenderer.cs b/EndlessClient/Rendering/Character/CharacterRenderer.cs index 6dba6e6c3..be14bc636 100644 --- a/EndlessClient/Rendering/Character/CharacterRenderer.cs +++ b/EndlessClient/Rendering/Character/CharacterRenderer.cs @@ -242,7 +242,7 @@ public void SetToCenterScreenPosition() : 310; var yCoord = _clientWindowSizeRepository.Resizable ? (_clientWindowSizeRepository.Height - skinRect.Height) / 2 - 11 - : (298 - skinRect.Height) / 2 - skinRect.Height/4 - 3; + : (298 - skinRect.Height) / 2 - skinRect.Height / 4 - 3; SetAbsoluteScreenPosition(xCoord, yCoord); } @@ -386,7 +386,7 @@ private void UpdateNameLabel() private Vector2 GetNameLabelPosition() { - NameLabelY = DrawArea.Y - 12 - (int)(_nameLabel?.ActualHeight ?? 0) + ((int)Character.RenderProperties.SitState)*10; + NameLabelY = DrawArea.Y - 12 - (int)(_nameLabel?.ActualHeight ?? 0) + ((int)Character.RenderProperties.SitState) * 10; return new Vector2(HorizontalCenter - (_nameLabel.ActualWidth / 2f), NameLabelY); } @@ -405,7 +405,7 @@ private int GetSteppingStoneOffset(CharacterRenderProperties renderProps) if (isSteppingStone && renderProps.IsActing(CharacterActionState.Walking)) { - switch(renderProps.ActualWalkFrame) + switch (renderProps.ActualWalkFrame) { case 1: return -8; case 2: return -16; @@ -545,11 +545,11 @@ protected override void Dispose(bool disposing) _clientWindowSizeRepository.GameWindowSizeChanged -= RecreateRenderTargetEvent; - lock(_rt_locker_) + lock (_rt_locker_) _charRenderTarget?.Dispose(); } base.Dispose(disposing); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterTextures.cs b/EndlessClient/Rendering/Character/CharacterTextures.cs index 961c6c61c..9cfa89f4c 100644 --- a/EndlessClient/Rendering/Character/CharacterTextures.cs +++ b/EndlessClient/Rendering/Character/CharacterTextures.cs @@ -15,7 +15,7 @@ public class CharacterTextures : ICharacterTextures public ISpriteSheet Shield { get; private set; } public ISpriteSheet Weapon { get; private set; } public ISpriteSheet WeaponExtra { get; private set; } - public ISpriteSheet WeaponSlash{ get; private set; } + public ISpriteSheet WeaponSlash { get; private set; } public ISpriteSheet Hair { get; private set; } public ISpriteSheet Skin { get; private set; } @@ -47,4 +47,4 @@ public void Refresh(CharacterRenderProperties characterRenderProperties) Face = _characterSpriteCalculator.GetFaceTexture(characterRenderProperties); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ICharacterRenderer.cs b/EndlessClient/Rendering/Character/ICharacterRenderer.cs index 9c9a8ca73..02a7d51a4 100644 --- a/EndlessClient/Rendering/Character/ICharacterRenderer.cs +++ b/EndlessClient/Rendering/Character/ICharacterRenderer.cs @@ -22,4 +22,4 @@ public interface ICharacterRenderer : IDrawable, IUpdateable, IGameComponent, ID void HideName(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs b/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs index d1f8c118e..3249f039e 100644 --- a/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs +++ b/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs @@ -1,7 +1,7 @@ -using System; -using System.Collections.Generic; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using Optional; +using System; +using System.Collections.Generic; namespace EndlessClient.Rendering.Character { diff --git a/EndlessClient/Rendering/Character/ICharacterTextures.cs b/EndlessClient/Rendering/Character/ICharacterTextures.cs index 9869d503a..ae4e0d2f5 100644 --- a/EndlessClient/Rendering/Character/ICharacterTextures.cs +++ b/EndlessClient/Rendering/Character/ICharacterTextures.cs @@ -22,4 +22,4 @@ public interface ICharacterTextures void Refresh(CharacterRenderProperties characterRenderProperties); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs b/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs index 280cc11e6..fda41ba48 100644 --- a/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs +++ b/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs @@ -246,4 +246,4 @@ public interface IPeriodicEmoteHandler : IGameComponent, IUpdateable void CancelArenaBlockTimer(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs index 423cf75be..768f8320c 100644 --- a/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs @@ -1,11 +1,11 @@ -using System; -using EndlessClient.Rendering.Metadata.Models; +using EndlessClient.Rendering.Metadata.Models; using EndlessClient.Rendering.Sprites; using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; namespace EndlessClient.Rendering.CharacterProperties { @@ -74,4 +74,4 @@ private Vector2 GetOffsets(Vector2 parentCharacterSize, bool ranged) return new Vector2(resX, resY); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs b/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs index 18978c99d..2eae9521b 100644 --- a/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs @@ -33,4 +33,4 @@ protected virtual void Render(SpriteBatch spriteBatch, ISpriteSheet sheet, Vecto LayerDepth); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs b/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs index 3b0af0f47..f2ca4ee5e 100644 --- a/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs @@ -47,7 +47,7 @@ private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) { var isDownOrLeft = _renderProperties.IsFacing(EODirection.Down, EODirection.Left); var factor = isDownOrLeft ? -1 : 1; - var extra = !isDownOrLeft ? 2*_renderProperties.Gender : 0; + var extra = !isDownOrLeft ? 2 * _renderProperties.Gender : 0; resX += 2 * factor; resY += 1 * factor - extra; @@ -87,4 +87,4 @@ private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) return new Vector2(resX, resY); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs b/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs index d269f11bc..016df3bc5 100644 --- a/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs +++ b/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs @@ -74,9 +74,9 @@ private bool IsShieldBehindCharacter(CharacterRenderProperties renderProperties) private bool IsWeaponBehindCharacter(CharacterRenderProperties renderProperties) { - var weaponInfo = EIFFile.FirstOrDefault( - x => x.Type == ItemType.Weapon && - x.DollGraphic == renderProperties.WeaponGraphic); + var weaponInfo = EIFFile.FirstOrDefault( + x => x.Type == ItemType.Weapon && + x.DollGraphic == renderProperties.WeaponGraphic); var pass1 = renderProperties.RenderAttackFrame < 2; var pass2 = renderProperties.IsFacing(EODirection.Up, EODirection.Left); @@ -99,4 +99,4 @@ private bool IsShieldOnBack(int shieldGraphic) private IPubFile EIFFile => _eifFileProvider.EIFFile ?? new EIFFile(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs b/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs index 5031b7749..10978e828 100644 --- a/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs @@ -36,4 +36,4 @@ public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDr Render(spriteBatch, _emoteSheet, emotePos, 128); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs b/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs index 83e37046b..80f57e6b0 100644 --- a/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs @@ -46,4 +46,4 @@ public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDr Render(spriteBatch, _faceSheet, facePos); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs b/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs index 239b90e48..53e904a0d 100644 --- a/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs +++ b/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs @@ -1,8 +1,8 @@ -using System; -using EOLib; +using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; +using System; namespace EndlessClient.Rendering.CharacterProperties { @@ -65,4 +65,4 @@ public Vector2 CalculateDrawLocationOfCharacterHair(Rectangle hairRectangle, Rec return parentCharacterDrawArea.Location.ToVector2() + new Vector2(resX + flippedOffset, resY); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs b/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs index 6f7dd9066..e499b7f4c 100644 --- a/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs @@ -27,4 +27,4 @@ public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDr Render(spriteBatch, _hairSheet, drawLoc); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs b/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs index 30e78b456..798c50454 100644 --- a/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs @@ -45,4 +45,4 @@ private Vector2 GetOffsets() return new Vector2(xOff + flippedOffset, yOff); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs index 9d5bb6c96..fc8199f84 100644 --- a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs @@ -12,4 +12,4 @@ public interface ICharacterPropertyRenderer void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs index 2b03ff394..be977a4be 100644 --- a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs +++ b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; using EndlessClient.Rendering.Character; using EOLib.Domain.Character; +using System.Collections.Generic; namespace EndlessClient.Rendering.CharacterProperties { diff --git a/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs index 0fb203e7a..c8c7f54dd 100644 --- a/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs @@ -113,4 +113,4 @@ private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) return new Vector2(resX, resY); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs b/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs index 5689254d0..c346df073 100644 --- a/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs +++ b/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs @@ -1,8 +1,8 @@ -using System; using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; +using System; namespace EndlessClient.Rendering.CharacterProperties { @@ -80,4 +80,4 @@ public Vector2 CalculateDrawLocationOfCharacterSkin(Rectangle skinRectangle, Rec return new Vector2(resX, resY); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs b/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs index 3ee22f3b6..99c2c8107 100644 --- a/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs @@ -28,4 +28,4 @@ public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDr Render(spriteBatch, _skinSheet, drawLoc); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs b/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs index 30d521aef..7709d977d 100644 --- a/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs @@ -58,4 +58,4 @@ private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) return new Vector2(resX, resY); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs b/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs index 328aa6613..3ac4ca2a7 100644 --- a/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs @@ -43,4 +43,4 @@ private Vector2 GetOffsets(Rectangle parentCharacterDrawArea) }; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubble.cs b/EndlessClient/Rendering/Chat/ChatBubble.cs index 3af07edc7..58add07d0 100644 --- a/EndlessClient/Rendering/Chat/ChatBubble.cs +++ b/EndlessClient/Rendering/Chat/ChatBubble.cs @@ -96,7 +96,7 @@ public override void Update(GameTime gameTime) _startTime.MatchSome(st => { - if (st.ElapsedMilliseconds > (24 + _textLabel.Text.Length / 3)*120) + if (st.ElapsedMilliseconds > (24 + _textLabel.Text.Length / 3) * 120) { _textLabel.Visible = false; Visible = false; @@ -122,7 +122,7 @@ public override void Draw(GameTime gameTime) var xCov = TL.Width; var yCov = TL.Height; - + var color = _isGroupChat ? Color.FromNonPremultiplied(247, 234, 164, 232) : Color.FromNonPremultiplied(255, 255, 255, 232); _spriteBatch.Begin(); @@ -159,7 +159,7 @@ public override void Draw(GameTime gameTime) _spriteBatch.Draw(BR, _drawLocation + new Vector2(x2, y), color); y += BM.Height; - _spriteBatch.Draw(NUB, _drawLocation + new Vector2((x2 + BR.Width - NUB.Width)/2f, y - 1), color); + _spriteBatch.Draw(NUB, _drawLocation + new Vector2((x2 + BR.Width - NUB.Width) / 2f, y - 1), color); _spriteBatch.End(); } @@ -196,4 +196,4 @@ public interface IChatBubble : IDisposable void Show(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs b/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs index 6d474b266..630c98a05 100644 --- a/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs +++ b/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs @@ -35,4 +35,4 @@ public interface IChatBubbleFactory { IChatBubble CreateChatBubble(IMapActor owner); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs b/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs index 325fab3af..ee6c96602 100644 --- a/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs +++ b/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs @@ -13,4 +13,4 @@ public enum ChatBubbleTexture BottomRight, Nubbin } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs b/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs index 903921620..e9a3cdbf9 100644 --- a/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs +++ b/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EndlessClient.Content; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; +using System.Collections.Generic; namespace EndlessClient.Rendering.Chat { @@ -42,4 +42,4 @@ public interface IChatBubbleTextureProvider void LoadContent(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatColorExtensions.cs b/EndlessClient/Rendering/Chat/ChatColorExtensions.cs index 2ddaec0c2..cf46f5dff 100644 --- a/EndlessClient/Rendering/Chat/ChatColorExtensions.cs +++ b/EndlessClient/Rendering/Chat/ChatColorExtensions.cs @@ -1,7 +1,7 @@ -using System; -using EOLib.Domain.Chat; +using EOLib.Domain.Chat; using EOLib.Graphics; using Microsoft.Xna.Framework; +using System; namespace EndlessClient.Rendering.Chat { @@ -21,4 +21,4 @@ public static Color ToColor(this ChatColor chatColor) } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatRenderable.cs b/EndlessClient/Rendering/Chat/ChatRenderable.cs index 3ad4c6f64..9d9728d3b 100644 --- a/EndlessClient/Rendering/Chat/ChatRenderable.cs +++ b/EndlessClient/Rendering/Chat/ChatRenderable.cs @@ -39,7 +39,7 @@ public ChatRenderable(INativeGraphicsManager nativeGraphicsManager, public override bool Equals(object obj) { if (!(obj is ChatRenderable)) return false; - var other = (ChatRenderable) obj; + var other = (ChatRenderable)obj; return other.Data.Equals(Data) && other._partialMessage.Equals(_partialMessage); @@ -48,8 +48,8 @@ public override bool Equals(object obj) public override int GetHashCode() { var hash = 397 ^ Data.GetHashCode(); - hash = (hash*397) ^ DisplayIndex.GetHashCode(); - hash = (hash*397) ^ _partialMessage.GetHashCode(); + hash = (hash * 397) ^ DisplayIndex.GetHashCode(); + hash = (hash * 397) ^ _partialMessage.GetHashCode(); return hash; } @@ -57,7 +57,7 @@ public void Render(IHudPanel parentPanel, SpriteBatch spriteBatch, BitmapFont ch { spriteBatch.Begin(); - var pos = parentPanel.DrawPosition + new Vector2(0, DisplayIndex*13); + var pos = parentPanel.DrawPosition + new Vector2(0, DisplayIndex * 13); spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true), new Vector2(pos.X + ICON_GRAPHIC_X_OFF, pos.Y + HeaderYOffset), GetChatIconRectangle(Data.Icon), diff --git a/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs b/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs index ae2d2c31d..6e0ac4955 100644 --- a/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs +++ b/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs @@ -1,12 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using EndlessClient.Services; +using EndlessClient.Services; using EOLib; using EOLib.Domain.Chat; using EOLib.Graphics; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.BitmapFonts; +using System; +using System.Collections.Generic; +using System.Linq; using XNAControls; namespace EndlessClient.Rendering.Chat @@ -40,7 +40,7 @@ public IReadOnlyList GenerateNewsRenderables(IReadOnlyList GenerateChatRenderables(IEnumerable x.Equals(data.Who, StringComparison.InvariantCultureIgnoreCase))) continue; - var splitStrings = SplitTextIntoLines(data.Who, new[] {data.Message}); + var splitStrings = SplitTextIntoLines(data.Who, new[] { data.Message }); var renderables = splitStrings.Select( (pair, i) => CreateChatRenderableFromChatPair(pair, i, data)) .ToList(); @@ -91,7 +91,7 @@ private IReadOnlyList SplitTextIntoLines(string who, IReadOnlyList GenerateChatRenderables(IEnumerable chatData); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/ClientWindowSizeRepository.cs b/EndlessClient/Rendering/ClientWindowSizeRepository.cs index ab82aa7ff..17cbd99fe 100644 --- a/EndlessClient/Rendering/ClientWindowSizeRepository.cs +++ b/EndlessClient/Rendering/ClientWindowSizeRepository.cs @@ -107,4 +107,4 @@ public void ResetState() Height = DEFAULT_BACKBUFFER_HEIGHT; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/ContextMenuRenderer.cs b/EndlessClient/Rendering/ContextMenuRenderer.cs index cafc92f9a..c58f8d02e 100644 --- a/EndlessClient/Rendering/ContextMenuRenderer.cs +++ b/EndlessClient/Rendering/ContextMenuRenderer.cs @@ -78,7 +78,7 @@ public ContextMenuRenderer(INativeGraphicsManager nativeGraphicsManager, IContextMenuRepository contextMenuRepository, IPartyDataProvider partyDataProvider, ICharacterRenderer characterRenderer, - ICurrentMapStateProvider currentMapStateProvider, + ICurrentMapStateProvider currentMapStateProvider, IEOMessageBoxFactory messageBoxFactory, IClientWindowSizeProvider clientWindowSizeProvider, ISfxPlayer sfxPlayer) @@ -355,4 +355,4 @@ protected override void Dispose(bool disposing) public interface IContextMenuRenderer : IXNAControl { } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/ContextMenuRepository.cs b/EndlessClient/Rendering/ContextMenuRepository.cs index 771124e41..f0650e66a 100644 --- a/EndlessClient/Rendering/ContextMenuRepository.cs +++ b/EndlessClient/Rendering/ContextMenuRepository.cs @@ -10,7 +10,7 @@ public interface IContextMenuProvider public interface IContextMenuRepository { - Option ContextMenu { get; set; } + Option ContextMenu { get; set; } } [AutoMappedType(IsSingleton = true)] @@ -23,4 +23,4 @@ public ContextMenuRepository() ContextMenu = Option.None(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/DispatcherGameComponent.cs b/EndlessClient/Rendering/DispatcherGameComponent.cs index 8660c764e..66eeded55 100644 --- a/EndlessClient/Rendering/DispatcherGameComponent.cs +++ b/EndlessClient/Rendering/DispatcherGameComponent.cs @@ -33,7 +33,7 @@ public static async Task Invoke(Action action) public override void Update(GameTime gameTime) { - lock(_queuelocker_) + lock (_queuelocker_) { if (_actions.Any()) { @@ -45,4 +45,4 @@ public override void Update(GameTime gameTime) base.Update(gameTime); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectAnimationType.cs b/EndlessClient/Rendering/Effects/EffectAnimationType.cs index 7990b4245..3792c38b3 100644 --- a/EndlessClient/Rendering/Effects/EffectAnimationType.cs +++ b/EndlessClient/Rendering/Effects/EffectAnimationType.cs @@ -9,4 +9,4 @@ public enum EffectAnimationType Position = 2, Flickering = 3 } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectLayer.cs b/EndlessClient/Rendering/Effects/EffectLayer.cs index a53e79380..c5a37cd24 100644 --- a/EndlessClient/Rendering/Effects/EffectLayer.cs +++ b/EndlessClient/Rendering/Effects/EffectLayer.cs @@ -6,4 +6,4 @@ public enum EffectLayer Transparent, InFront } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectRenderer.cs b/EndlessClient/Rendering/Effects/EffectRenderer.cs index a3594b738..d23ae9644 100644 --- a/EndlessClient/Rendering/Effects/EffectRenderer.cs +++ b/EndlessClient/Rendering/Effects/EffectRenderer.cs @@ -217,4 +217,4 @@ public interface IEffectRenderer void DrawInFrontOfTarget(SpriteBatch sb, bool beginHasBeenCalled = true); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectRendererFactory.cs b/EndlessClient/Rendering/Effects/EffectRendererFactory.cs index b35740693..04354f61a 100644 --- a/EndlessClient/Rendering/Effects/EffectRendererFactory.cs +++ b/EndlessClient/Rendering/Effects/EffectRendererFactory.cs @@ -36,4 +36,4 @@ public interface IEffectRendererFactory { IEffectRenderer Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs b/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs index 267d00d95..5e19c8081 100644 --- a/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs +++ b/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs @@ -97,13 +97,13 @@ private Vector2 GetDrawLocation(Rectangle textureSourceRectangle, Vector2 gridCo private int GetDisplayFrame() { return _metadata.AnimationType switch - { - EffectAnimationType.Flickering => - _random.Next( - _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0, - 1 + (_metadata.RandomFlickeringMetadata?.LastFrame ?? _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0)), - _ => _displayFrame + 1 - }; + { + EffectAnimationType.Flickering => + _random.Next( + _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0, + 1 + (_metadata.RandomFlickeringMetadata?.LastFrame ?? _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0)), + _ => _displayFrame + 1 + }; } private void ResetFrame() @@ -114,4 +114,4 @@ private void ResetFrame() _displayFrame = 0; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectSpriteManager.cs b/EndlessClient/Rendering/Effects/EffectSpriteManager.cs index f333e0d73..e04c60a53 100644 --- a/EndlessClient/Rendering/Effects/EffectSpriteManager.cs +++ b/EndlessClient/Rendering/Effects/EffectSpriteManager.cs @@ -31,7 +31,7 @@ public IList GetEffectInfo(int graphic) } public IList GetEffectInfo(int graphic, EffectMetadata metadata) - { + { var baseGraphic = 101 + (graphic - 1) * 3; var retList = new List(); @@ -59,4 +59,4 @@ public interface IEffectSpriteManager IList GetEffectInfo(int graphic, EffectMetadata metadata); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/HardCodedEffect.cs b/EndlessClient/Rendering/Effects/HardCodedEffect.cs index 461057084..8736778b2 100644 --- a/EndlessClient/Rendering/Effects/HardCodedEffect.cs +++ b/EndlessClient/Rendering/Effects/HardCodedEffect.cs @@ -13,4 +13,4 @@ public enum HardCodedEffect WaterSplashies = 9, AdminHide = 25, } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs b/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs index c1179347b..4b5d38a64 100644 --- a/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs +++ b/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs @@ -13,4 +13,4 @@ public interface IEffectSpriteInfo void Restart(); void DrawToSpriteBatch(SpriteBatch sb, Vector2 gridCoordinatePosition); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs b/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs index 7cb406730..d2d1b81a5 100644 --- a/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs +++ b/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs @@ -13,4 +13,4 @@ public sealed partial class PositionOffsetEffectMetadata [JsonProperty("yOffsetPerFrame")] public IReadOnlyList OffsetYByFrame { get; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs b/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs index 939b607b5..4d20baae3 100644 --- a/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs +++ b/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs @@ -12,4 +12,4 @@ public sealed partial class RandomFlickeringEffectMetadata [JsonProperty("lastFrame")] public int LastFrame { get; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs b/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs index 75461c907..317e2eee8 100644 --- a/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs +++ b/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs @@ -9,4 +9,4 @@ public sealed partial class VerticalSlidingEffectMetadata [JsonProperty("yOffsetPerFrame")] public int FrameOffsetY { get; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs b/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs index c7ee761b9..60c176080 100644 --- a/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs @@ -69,7 +69,7 @@ public CharacterRendererFactory(IEndlessGameProvider gameProvider, public ICharacterRenderer CreateCharacterRenderer(EOLib.Domain.Character.Character character, bool isUiControl) { return new CharacterRenderer( - (Game) _gameProvider.Game, + (Game)_gameProvider.Game, _renderTargetFactory, _healthBarRendererFactory, _chatBubbleFactory, diff --git a/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs b/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs index 3c4623374..d65096ee6 100644 --- a/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs @@ -45,7 +45,7 @@ public ContextMenuRendererFactory(INativeGraphicsManager nativeGraphicsManager, IHudControlProvider hudControlProvider, IContextMenuRepository contextMenuRepository, IPartyDataProvider partyDataProvider, - ICurrentMapStateProvider currentMapStateProvider, + ICurrentMapStateProvider currentMapStateProvider, IEOMessageBoxFactory messageBoxFactory, IClientWindowSizeProvider clientWindowSizeProvider, ISfxPlayer sfxPlayer) @@ -80,7 +80,7 @@ public IContextMenuRenderer CreateContextMenuRenderer(ICharacterRenderer charact _hudControlProvider, _contextMenuRepository, _partyDataProvider, - characterRenderer, + characterRenderer, _currentMapStateProvider, _messageBoxFactory, _clientWindowSizeProvider, @@ -92,4 +92,4 @@ public interface IContextMenuRendererFactory { IContextMenuRenderer CreateContextMenuRenderer(ICharacterRenderer characterRenderer); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs b/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs index 662c60bf8..273c8002e 100644 --- a/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs @@ -23,4 +23,4 @@ public interface IHealthBarRendererFactory { IHealthBarRenderer CreateHealthBarRenderer(IMapActor entity); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs b/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs index 4ceaec244..76e9ee0b5 100644 --- a/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs @@ -6,4 +6,4 @@ public interface ICharacterRendererFactory { ICharacterRenderer CreateCharacterRenderer(EOLib.Domain.Character.Character character, bool isUiControl); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/IMapRendererFactory.cs b/EndlessClient/Rendering/Factories/IMapRendererFactory.cs index 1dffc0924..f70bd5d30 100644 --- a/EndlessClient/Rendering/Factories/IMapRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/IMapRendererFactory.cs @@ -6,4 +6,4 @@ public interface IMapRendererFactory { IMapRenderer CreateMapRenderer(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs b/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs index ae952d201..5619cb444 100644 --- a/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs +++ b/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs @@ -7,4 +7,4 @@ public interface IRenderTargetFactory RenderTarget2D CreateRenderTarget(); RenderTarget2D CreateRenderTarget(int width, int height); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/MapRendererFactory.cs b/EndlessClient/Rendering/Factories/MapRendererFactory.cs index 75d5b94a8..29815b5d8 100644 --- a/EndlessClient/Rendering/Factories/MapRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/MapRendererFactory.cs @@ -92,4 +92,4 @@ public IMapRenderer CreateMapRenderer() _fixedTimeStepRepository); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs b/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs index 4305ddd3e..3ebc0e979 100644 --- a/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs @@ -65,4 +65,4 @@ public interface IMouseCursorRendererFactory { IMouseCursorRenderer Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/RenderTargetFactory.cs b/EndlessClient/Rendering/Factories/RenderTargetFactory.cs index 3b6d4d91c..1234a95d7 100644 --- a/EndlessClient/Rendering/Factories/RenderTargetFactory.cs +++ b/EndlessClient/Rendering/Factories/RenderTargetFactory.cs @@ -33,4 +33,4 @@ public RenderTarget2D CreateRenderTarget(int width, int height) DepthFormat.None); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs b/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs index 3966f5f78..373262174 100644 --- a/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs +++ b/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs @@ -141,7 +141,7 @@ public MapCoordinate CalculateGridCoordinatesFromDrawLocation(Vector2 drawLocati var offsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); var offsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); - var gridX = (int)Math.Round((msX + 2 * msY - (ViewportWidthFactor*2) + offsetX + 2 * offsetY) / 64.0); + var gridX = (int)Math.Round((msX + 2 * msY - (ViewportWidthFactor * 2) + offsetX + 2 * offsetY) / 64.0); var gridY = (int)Math.Round((msY - gridX * 16 - ViewportHeightFactor + offsetY) / 16.0); return new MapCoordinate(gridX, gridY); @@ -184,4 +184,4 @@ public interface IGridDrawCoordinateCalculator MapCoordinate CalculateGridCoordinatesFromDrawLocation(Vector2 drawLocation); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/HealthBarRenderer.cs b/EndlessClient/Rendering/HealthBarRenderer.cs index 8625be55e..11cb8b9be 100644 --- a/EndlessClient/Rendering/HealthBarRenderer.cs +++ b/EndlessClient/Rendering/HealthBarRenderer.cs @@ -96,14 +96,14 @@ public void Update(GameTime gameTime) if (_isMiss) { var xPos = _parentReference.HorizontalCenter - (_numberSourceRectangles[0].Width / 2f); - var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height*2f; + var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height * 2f; _damageCounterPosition = new Vector2(xPos, yPos); } else { var digitCount = _numberSourceRectangles.Count; var xPos = _parentReference.HorizontalCenter - (digitCount * DigitWidth / 2f); - var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height*2f; + var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height * 2f; _damageCounterPosition = new Vector2(xPos, yPos); } } @@ -115,7 +115,7 @@ public void DrawToSpriteBatch(SpriteBatch spriteBatch) var numberNdx = 0; foreach (var numberSource in _numberSourceRectangles) { - spriteBatch.Draw(_sourceTexture, _damageCounterPosition + new Vector2(numberNdx*DigitWidth, 0), numberSource, Color.White); + spriteBatch.Draw(_sourceTexture, _damageCounterPosition + new Vector2(numberNdx * DigitWidth, 0), numberSource, Color.White); numberNdx++; } @@ -131,7 +131,7 @@ private static IEnumerable GetNumberSourceRectangles(int value, bool for (int i = 0; i < digits.Length; ++i) { int next = int.Parse($"{digits[i]}"); - yield return new Rectangle(next*DigitWidth, yCoord, 8, 11); + yield return new Rectangle(next * DigitWidth, yCoord, 8, 11); } } @@ -162,4 +162,4 @@ public interface IHealthBarRenderer void DrawToSpriteBatch(SpriteBatch spriteBatch); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/IMapActor.cs b/EndlessClient/Rendering/IMapActor.cs index 69be30187..058a69ea5 100644 --- a/EndlessClient/Rendering/IMapActor.cs +++ b/EndlessClient/Rendering/IMapActor.cs @@ -23,4 +23,4 @@ public interface IMapActor void PlayEffect(int effectId); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/ClickDispatcher.cs b/EndlessClient/Rendering/Map/ClickDispatcher.cs index 546dbfe2e..9d7025423 100644 --- a/EndlessClient/Rendering/Map/ClickDispatcher.cs +++ b/EndlessClient/Rendering/Map/ClickDispatcher.cs @@ -261,4 +261,4 @@ public interface IClickDispatcher : IGameComponent { int DrawOrder { get; set; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs b/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs index ea2478c42..1fd6e2c43 100644 --- a/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs +++ b/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs @@ -82,4 +82,4 @@ public interface IClickDispatcherFactory { IClickDispatcher Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs b/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs index 3c93819a2..52fc59fd5 100644 --- a/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs +++ b/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs @@ -151,4 +151,4 @@ public interface IDynamicMapObjectUpdater { void UpdateMapObjects(GameTime gameTime); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs b/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs index 6d2958cc8..0182979a0 100644 --- a/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs +++ b/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs @@ -6,4 +6,4 @@ public interface IMapItemGraphicProvider { Texture2D GetItemGraphic(int id, int amount); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs b/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs index 6d976aafa..7e29d6466 100644 --- a/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs +++ b/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs @@ -6,4 +6,4 @@ public interface IMapRenderDistanceCalculator { MapRenderBounds CalculateRenderBounds(EOLib.Domain.Character.Character character, IMapFile currentMap); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/IMapRenderer.cs b/EndlessClient/Rendering/Map/IMapRenderer.cs index e18b1de9b..00db8ffe2 100644 --- a/EndlessClient/Rendering/Map/IMapRenderer.cs +++ b/EndlessClient/Rendering/Map/IMapRenderer.cs @@ -21,4 +21,4 @@ public interface IMapRenderer : IGameComponent, IDrawable void ClearTransientRenderables(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapChangedActions.cs b/EndlessClient/Rendering/Map/MapChangedActions.cs index 9d4d40d5a..984c225f8 100644 --- a/EndlessClient/Rendering/Map/MapChangedActions.cs +++ b/EndlessClient/Rendering/Map/MapChangedActions.cs @@ -145,7 +145,7 @@ private void ClearNPCRenderersAndCache() { var currentMapNpcGraphics = _currentMapStateRepository.NPCs.Select(x => _enfFileProvider.ENFFile[x.ID].Graphic).ToList(); var priorMapNpcGraphics = _npcRendererRepository.NPCRenderers.Select(x => _enfFileProvider.ENFFile[x.Value.NPC.ID].Graphic); - + foreach (var evict in priorMapNpcGraphics.Except(currentMapNpcGraphics)) _npcSpriteDataCache.MarkForEviction(evict); @@ -252,4 +252,4 @@ public interface IMapChangedActions { void ActiveCharacterEnterMapForLogin(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs b/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs index 8f53bdd11..a5049694a 100644 --- a/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs +++ b/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using AutomaticTypeMapper; using EndlessClient.Rendering.Character; using EndlessClient.Rendering.MapEntityRenderers; @@ -7,6 +6,7 @@ using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.Graphics; +using System.Collections.Generic; namespace EndlessClient.Rendering.Map { diff --git a/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs b/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs index 62a0ec038..ef4fab820 100644 --- a/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs +++ b/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs @@ -28,10 +28,10 @@ public Texture2D GetItemGraphic(int id, int amount) amount >= 10000 ? 3 : ( amount >= 100 ? 2 : ( amount >= 2 ? 1 : 0))); - return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 269 + 2*gfx, true); + return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 269 + 2 * gfx, true); } - return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 2*item.Graphic - 1, true); + return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 2 * item.Graphic - 1, true); } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs b/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs index c1b6813fe..1a6625b4a 100644 --- a/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs +++ b/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs @@ -14,7 +14,7 @@ public class MapObjectBoundsCalculator : IMapObjectBoundsCalculator private readonly ICharacterProvider _characterProvider; private readonly IRenderOffsetCalculator _renderOffsetCalculator; private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - + public MapObjectBoundsCalculator(INativeGraphicsManager nativeGraphicsManager, ICharacterProvider characterProvider, IRenderOffsetCalculator renderOffsetCalculator, diff --git a/EndlessClient/Rendering/Map/MapRenderBounds.cs b/EndlessClient/Rendering/Map/MapRenderBounds.cs index 5a342a2da..cfc199502 100644 --- a/EndlessClient/Rendering/Map/MapRenderBounds.cs +++ b/EndlessClient/Rendering/Map/MapRenderBounds.cs @@ -16,4 +16,4 @@ public MapRenderBounds(int firstRow, int lastRow, int firstCol, int lastCol) LastCol = lastCol; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapRenderer.cs b/EndlessClient/Rendering/Map/MapRenderer.cs index 4ce993b61..60c66eaaa 100644 --- a/EndlessClient/Rendering/Map/MapRenderer.cs +++ b/EndlessClient/Rendering/Map/MapRenderer.cs @@ -297,8 +297,8 @@ private void DrawGroundLayerToRenderTarget() } } - if (transitionComplete) - _mapTransitionState = new MapTransitionState(Option.None(), 0); + if (transitionComplete) + _mapTransitionState = new MapTransitionState(Option.None(), 0); _sb.End(); GraphicsDevice.SetRenderTarget(null); @@ -573,7 +573,7 @@ internal MapQuakeState NextOffset() internal MapQuakeState NextState() { var flip = -OffsetTarget / Math.Abs(OffsetTarget); - var offset = OffsetTarget + 1*flip; + var offset = OffsetTarget + 1 * flip; var nextOffsetTarget = NewOffsetTarget(Magnitude) * flip; return new MapQuakeState(Magnitude, offset, nextOffsetTarget, Flips + 1); diff --git a/EndlessClient/Rendering/Map/MiniMapRenderer.cs b/EndlessClient/Rendering/Map/MiniMapRenderer.cs index c6821ae5d..56cdbc24b 100644 --- a/EndlessClient/Rendering/Map/MiniMapRenderer.cs +++ b/EndlessClient/Rendering/Map/MiniMapRenderer.cs @@ -146,7 +146,7 @@ protected override void OnDrawControl(GameTime gameTime) case TileSpec.ChairUpLeft: case TileSpec.Chest: case TileSpec.JammedDoor: - // Unknown TileSpecs 10-15 have been confirmed in the vanilla client to show a Blue ! on the minimap + // Unknown TileSpecs 10-15 have been confirmed in the vanilla client to show a Blue ! on the minimap case (TileSpec)10: case (TileSpec)11: case (TileSpec)12: @@ -273,11 +273,11 @@ private Rectangle GetSourceRect(MiniMapGfx gfx) private Vector2 GetCharacterOffset() { - var tileWidthFactor = TileWidth/2; - var tileHeightFactor = TileHeight/2; + var tileWidthFactor = TileWidth / 2; + var tileHeightFactor = TileHeight / 2; var (cx, cy) = (_characterProvider.MainCharacter.X, _characterProvider.MainCharacter.Y); return new Vector2(cx * tileWidthFactor - cy * tileWidthFactor, cx * tileHeightFactor + cy * tileHeightFactor); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs b/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs index 0fb5e591e..2bccedcba 100644 --- a/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs +++ b/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs @@ -55,4 +55,4 @@ public interface IMiniMapRendererFactory { MiniMapRenderer Create(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs index 9ff23015a..f431effcb 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs @@ -1,9 +1,9 @@ -using System; -using System.Collections.Generic; -using EndlessClient.Rendering.Map; +using EndlessClient.Rendering.Map; using EOLib.Domain.Character; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; +using System.Collections.Generic; namespace EndlessClient.Rendering.MapEntityRenderers { @@ -83,4 +83,4 @@ protected virtual Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) return _gridDrawCoordinateCalculator.CalculateDrawCoordinatesFromGridUnits(gridX, gridY) + _layerOffsets[RenderLayer].ToVector2(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs index 4bb3963fa..17182a148 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs @@ -103,4 +103,4 @@ protected override Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(gridX, gridY); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs index c7d3ecdcf..9315a11a5 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs @@ -1,7 +1,7 @@ -using System; -using EndlessClient.Rendering.Map; +using EndlessClient.Rendering.Map; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; namespace EndlessClient.Rendering.MapEntityRenderers { @@ -15,4 +15,4 @@ public interface IMapEntityRenderer void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalPixelOffset = default); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs index 40925ea68..90c1e5422 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs @@ -11,4 +11,4 @@ public interface IMapEntityRendererProvider IReadOnlyList MapEntityRenderers { get; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs index f88df7d2a..f45bc97d2 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs @@ -50,4 +50,4 @@ public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, }); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs index 8c295783e..8b7819708 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs @@ -43,10 +43,10 @@ public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, var itemTexture = _mapItemGraphicProvider.GetItemGraphic(item.ItemID, item.Amount); spriteBatch.Draw(itemTexture, - new Vector2(itemPos.X - (int) Math.Round(itemTexture.Width/2.0), - itemPos.Y - (int) Math.Round(itemTexture.Height/2.0)) + additionalOffset, + new Vector2(itemPos.X - (int)Math.Round(itemTexture.Width / 2.0), + itemPos.Y - (int)Math.Round(itemTexture.Height / 2.0)) + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs index 64c400238..3677dffa8 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs @@ -1,7 +1,4 @@ -using System; -using System.DirectoryServices.ActiveDirectory; -using System.Linq; -using EndlessClient.Rendering.Map; +using EndlessClient.Rendering.Map; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using EOLib.Domain.Map; @@ -9,7 +6,9 @@ using EOLib.IO.Map; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; - +using System; +using System.DirectoryServices.ActiveDirectory; +using System.Linq; using DomainCharacter = EOLib.Domain.Character.Character; namespace EndlessClient.Rendering.MapEntityRenderers @@ -90,4 +89,4 @@ private static bool CharacterAt(DomainCharacter c, MapCoordinate tile) : tile == c.RenderProperties.DestinationCoordinates(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs index 2ad75f5d3..ac63c5438 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs @@ -53,4 +53,4 @@ public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, } } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs index 3b19f9339..32a32620f 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs @@ -44,4 +44,4 @@ public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs index d9057e07e..e23dc5240 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs @@ -46,4 +46,4 @@ public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs index 9d9f617df..b6ff7111e 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs @@ -46,4 +46,4 @@ public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs index 12c7f3398..b42cff2e9 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs @@ -44,4 +44,4 @@ public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs index 7bd14fa36..d6ca67d0f 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs @@ -55,4 +55,4 @@ public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs index 73eb1ce90..eb8687289 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs @@ -1,11 +1,11 @@ -using System.Linq; -using EndlessClient.Rendering.Map; +using EndlessClient.Rendering.Map; using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.Graphics; using EOLib.IO.Map; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System.Linq; namespace EndlessClient.Rendering.MapEntityRenderers { @@ -39,7 +39,7 @@ protected void DrawWall(SpriteBatch spriteBatch, int row, int col, int alpha, in var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapWalls, gfxNum, true); - var gfxWidthDelta = gfx.Width/4; + var gfxWidthDelta = gfx.Width / 4; var src = gfx.Width > WALL_FRAME_WIDTH ? new Rectangle?(new Rectangle(gfxWidthDelta * _frameIndex, 0, gfxWidthDelta, gfx.Height)) : null; @@ -108,4 +108,4 @@ public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, DrawWall(spriteBatch, row, col, alpha, gfxNum, additionalOffset); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs b/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs index 577bc805c..c6dfe7e0d 100644 --- a/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs @@ -64,4 +64,4 @@ public EffectMetadata GetValueOrDefault(int graphic) .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : EffectMetadata.Default); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs b/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs index a89107ada..0456b8f54 100644 --- a/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs +++ b/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs @@ -67,4 +67,4 @@ public interface IGFXMetadataLoader Option GetMetadata(int graphic) where TMetadata : class, IGFXMetadata; } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs b/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs index e560f322e..d1c783103 100644 --- a/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs @@ -66,4 +66,4 @@ public HatMetadata GetValueOrDefault(int graphic) .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : HatMetadata.Default); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/IMetadataProvider.cs b/EndlessClient/Rendering/Metadata/IMetadataProvider.cs index df1392564..f7075edab 100644 --- a/EndlessClient/Rendering/Metadata/IMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/IMetadataProvider.cs @@ -10,4 +10,4 @@ public interface IMetadataProvider TMetadata GetValueOrDefault(int graphic); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs b/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs index 40a1d66e1..1d529de90 100644 --- a/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs @@ -46,4 +46,4 @@ public sealed partial class EffectMetadata : IGFXMetadata [JsonProperty("flickeringData")] public RandomFlickeringEffectMetadata RandomFlickeringMetadata { get; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/HatMetadata.cs b/EndlessClient/Rendering/Metadata/Models/HatMetadata.cs index 46f283d17..7290a5325 100644 --- a/EndlessClient/Rendering/Metadata/Models/HatMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/HatMetadata.cs @@ -10,4 +10,4 @@ public enum HatMaskType public record HatMetadata(HatMaskType ClipMode) : IGFXMetadata { public static HatMetadata Default { get; } = new HatMetadata(HatMaskType.Standard); -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs b/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs index 08ecf689c..afff2bc1d 100644 --- a/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs @@ -3,4 +3,4 @@ public interface IGFXMetadata { } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs b/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs index ee0e800cf..4cbe72b7d 100644 --- a/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs @@ -26,4 +26,4 @@ public sealed partial class NPCMetadata : IGFXMetadata [JsonProperty("nameHeight")] public int NameLabelOffset { get; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/ShieldMetadata.cs b/EndlessClient/Rendering/Metadata/Models/ShieldMetadata.cs index 1755292c9..399e6818c 100644 --- a/EndlessClient/Rendering/Metadata/Models/ShieldMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/ShieldMetadata.cs @@ -3,4 +3,4 @@ public sealed record ShieldMetadata(bool IsShieldOnBack) : IGFXMetadata { public static ShieldMetadata Default { get; } = new ShieldMetadata(false); -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/WeaponMetadata.cs b/EndlessClient/Rendering/Metadata/Models/WeaponMetadata.cs index 7e55ed2ed..b11153cad 100644 --- a/EndlessClient/Rendering/Metadata/Models/WeaponMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/WeaponMetadata.cs @@ -5,4 +5,4 @@ namespace EndlessClient.Rendering.Metadata.Models; public record WeaponMetadata(int? Slash, SoundEffectID[] SFX, bool Ranged) : IGFXMetadata { public static WeaponMetadata Default { get; } = new WeaponMetadata(Slash: null, SFX: new[] { SoundEffectID.PunchAttack }, Ranged: false); -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs b/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs index 7a5aa6d37..b6009357f 100644 --- a/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs @@ -198,4 +198,4 @@ public NPCMetadata GetValueOrDefault(int graphic) .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : NPCMetadata.Default); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs b/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs index 856f20287..b5fbab4ac 100644 --- a/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs @@ -33,4 +33,4 @@ public ShieldMetadata GetValueOrDefault(int graphic) .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : ShieldMetadata.Default); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs b/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs index 95f2830a9..5aa1bf734 100644 --- a/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs @@ -102,4 +102,4 @@ public WeaponMetadata GetValueOrDefault(int graphic) .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : WeaponMetadata.Default); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/MouseCursorRenderer.cs b/EndlessClient/Rendering/MouseCursorRenderer.cs index 97a1bf04f..f311a3a5b 100644 --- a/EndlessClient/Rendering/MouseCursorRenderer.cs +++ b/EndlessClient/Rendering/MouseCursorRenderer.cs @@ -80,7 +80,7 @@ public MouseCursorRenderer(INativeGraphicsManager nativeGraphicsManager, _contextMenuProvider = contextMenuProvider; SingleCursorFrameArea = new Rectangle(0, 0, - _mouseCursorTexture.Width/(int) CursorIndex.NumberOfFramesInSheet, + _mouseCursorTexture.Width / (int)CursorIndex.NumberOfFramesInSheet, _mouseCursorTexture.Height); DrawArea = SingleCursorFrameArea; @@ -258,7 +258,7 @@ public void Draw(SpriteBatch spriteBatch, Vector2 additionalOffset) { spriteBatch.Draw(_mouseCursorTexture, DrawPosition + additionalOffset, - new Rectangle(SingleCursorFrameArea.Width*(int) _cursorIndex, + new Rectangle(SingleCursorFrameArea.Width * (int)_cursorIndex, 0, SingleCursorFrameArea.Width, SingleCursorFrameArea.Height), @@ -315,4 +315,4 @@ public interface IMouseCursorRenderer : IXNAControl, IDisposable void ClearTransientRenderables(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCActions.cs b/EndlessClient/Rendering/NPC/NPCActions.cs index 02fe143b4..1a150be36 100644 --- a/EndlessClient/Rendering/NPC/NPCActions.cs +++ b/EndlessClient/Rendering/NPC/NPCActions.cs @@ -165,4 +165,4 @@ private void ShoutSpellCast(int playerId) private INPCAnimator Animator => _hudControlProvider.GetComponent(HudControlIdentifier.NPCAnimator); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCAnimator.cs b/EndlessClient/Rendering/NPC/NPCAnimator.cs index e1115a58f..77124741a 100644 --- a/EndlessClient/Rendering/NPC/NPCAnimator.cs +++ b/EndlessClient/Rendering/NPC/NPCAnimator.cs @@ -34,7 +34,7 @@ public override void Update(GameTime gameTime) { AnimateNPCWalking(); AnimateNPCAttacking(); - + base.Update(gameTime); } @@ -143,4 +143,4 @@ public interface INPCAnimator : IGameComponent void StopAllAnimations(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCCache.cs b/EndlessClient/Rendering/NPC/NPCCache.cs index 94c1e3fe4..65c527286 100644 --- a/EndlessClient/Rendering/NPC/NPCCache.cs +++ b/EndlessClient/Rendering/NPC/NPCCache.cs @@ -52,4 +52,4 @@ public interface INPCStateCache void Reset(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRenderer.cs b/EndlessClient/Rendering/NPC/NPCRenderer.cs index 0ffc99ec0..56befc44e 100644 --- a/EndlessClient/Rendering/NPC/NPCRenderer.cs +++ b/EndlessClient/Rendering/NPC/NPCRenderer.cs @@ -344,4 +344,4 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRendererFactory.cs b/EndlessClient/Rendering/NPC/NPCRendererFactory.cs index 9f69cbc9a..882dab75b 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererFactory.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererFactory.cs @@ -70,4 +70,4 @@ public interface INPCRendererFactory { INPCRenderer CreateRendererFor(EOLib.Domain.NPC.NPC npc); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRendererRepository.cs b/EndlessClient/Rendering/NPC/NPCRendererRepository.cs index c3a48042f..d6f93a73c 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererRepository.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererRepository.cs @@ -45,4 +45,4 @@ public void Dispose() DyingNPCs.Clear(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs b/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs index 931ac1f07..be61aa056 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs @@ -130,4 +130,4 @@ public interface INPCRendererUpdater : IDisposable { void UpdateNPCs(GameTime gameTime); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/PlayerStatusIconRenderer.cs b/EndlessClient/Rendering/PlayerStatusIconRenderer.cs index b7150de34..7b984422f 100644 --- a/EndlessClient/Rendering/PlayerStatusIconRenderer.cs +++ b/EndlessClient/Rendering/PlayerStatusIconRenderer.cs @@ -55,7 +55,7 @@ public PlayerStatusIconRenderer(INativeGraphicsManager nativeGraphicsManager, protected override void OnUpdateControl(GameTime gameTime) { var c = _characterProvider.MainCharacter; - + _icons = 0; if (_currentMapProvider.CurrentMap.Properties.PKAvailable) _icons |= StatusIconType.PK; @@ -94,10 +94,10 @@ private Rectangle GetSourceRectangle(StatusIconType type) var heightDelta = _statusIcons.Height / 2; //convert from power of two 'flag' value to base 10 index - var index = (int)Math.Log((int) type, 2); + var index = (int)Math.Log((int)type, 2); - var xOffset = widthDelta*index; + var xOffset = widthDelta * index; return new Rectangle(xOffset, 0, widthDelta, heightDelta); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/PointComparer.cs b/EndlessClient/Rendering/PointComparer.cs index c191bcb5d..eadbb3f36 100644 --- a/EndlessClient/Rendering/PointComparer.cs +++ b/EndlessClient/Rendering/PointComparer.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; +using System.Collections.Generic; namespace EndlessClient.Rendering { @@ -14,4 +14,4 @@ public int Compare(Point a, Point b) return 0; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/RenderOffsetCalculator.cs b/EndlessClient/Rendering/RenderOffsetCalculator.cs index b012673df..6bbc5432a 100644 --- a/EndlessClient/Rendering/RenderOffsetCalculator.cs +++ b/EndlessClient/Rendering/RenderOffsetCalculator.cs @@ -12,12 +12,12 @@ public class RenderOffsetCalculator : IRenderOffsetCalculator { private const int WidthFactor = 32; private const int HeightFactor = 16; - private const int WalkWidthFactor = WidthFactor/4; - private const int WalkHeightFactor = HeightFactor/4; + private const int WalkWidthFactor = WidthFactor / 4; + private const int WalkHeightFactor = HeightFactor / 4; public int CalculateOffsetX(CharacterRenderProperties properties) { - return properties.MapX*WidthFactor - properties.MapY*WidthFactor + CalculateWalkAdjustX(properties); + return properties.MapX * WidthFactor - properties.MapY * WidthFactor + CalculateWalkAdjustX(properties); } public int CalculateWalkAdjustX(CharacterRenderProperties properties) @@ -29,7 +29,7 @@ public int CalculateWalkAdjustX(CharacterRenderProperties properties) public int CalculateOffsetY(CharacterRenderProperties properties) { - return properties.MapX*HeightFactor + properties.MapY*HeightFactor + CalculateWalkAdjustY(properties); + return properties.MapX * HeightFactor + properties.MapY * HeightFactor + CalculateWalkAdjustY(properties); } public int CalculateWalkAdjustY(CharacterRenderProperties properties) @@ -41,7 +41,7 @@ public int CalculateWalkAdjustY(CharacterRenderProperties properties) public int CalculateOffsetX(EOLib.Domain.NPC.NPC npc) { - return npc.X*WidthFactor - npc.Y*WidthFactor + CalculateWalkAdjustX(npc); + return npc.X * WidthFactor - npc.Y * WidthFactor + CalculateWalkAdjustX(npc); } public int CalculateWalkAdjustX(EOLib.Domain.NPC.NPC npc) @@ -54,7 +54,7 @@ public int CalculateWalkAdjustX(EOLib.Domain.NPC.NPC npc) public int CalculateOffsetY(EOLib.Domain.NPC.NPC npc) { - return npc.X*HeightFactor + npc.Y*HeightFactor + CalculateWalkAdjustY(npc); + return npc.X * HeightFactor + npc.Y * HeightFactor + CalculateWalkAdjustY(npc); } public int CalculateWalkAdjustY(EOLib.Domain.NPC.NPC npc) diff --git a/EndlessClient/Rendering/RendererRepositoryResetter.cs b/EndlessClient/Rendering/RendererRepositoryResetter.cs index 8d3b2bfd6..1a00ae3ab 100644 --- a/EndlessClient/Rendering/RendererRepositoryResetter.cs +++ b/EndlessClient/Rendering/RendererRepositoryResetter.cs @@ -38,4 +38,4 @@ public interface IRendererRepositoryResetter { void ResetRenderers(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs b/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs index 6783e7ead..90c79b724 100644 --- a/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs +++ b/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs @@ -2,7 +2,7 @@ namespace EndlessClient.Rendering.Sprites { public enum ArmorShieldSpriteType { - //dir1/dir2 + //dir1/dir2 Standing = 1, //1/2 ShieldItemOnBack_AttackingWithBow = 3, WalkFrame1 = 3, //3/7 @@ -12,7 +12,7 @@ public enum ArmorShieldSpriteType SpellCast = 11, //11/12 PunchFrame1 = 13, //13/15 PunchFrame2 = 14, //14/16 - + //not valid for shields: SitChair = 17, //17/18 SitGround = 19, //19/20 diff --git a/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs b/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs index e1fcfbb79..e4f920f79 100644 --- a/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs +++ b/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs @@ -187,7 +187,7 @@ public ISpriteSheet GetShieldTexture(CharacterRenderProperties characterRenderPr { type = ArmorShieldSpriteType.SpellCast; } - else if(characterRenderProperties.SitState != SitState.Standing) + else if (characterRenderProperties.SitState != SitState.Standing) { return new EmptySpriteSheet(); } @@ -340,8 +340,8 @@ public ISpriteSheet GetSkinTexture(CharacterRenderProperties characterRenderProp var rotated = characterRenderProperties.Direction == EODirection.Left || characterRenderProperties.Direction == EODirection.Up; - var heightDelta = texture.Height / SheetRows; - var widthDelta = texture.Width / sheetColumns; + var heightDelta = texture.Height / SheetRows; + var widthDelta = texture.Width / sheetColumns; var sectionDelta = texture.Width / 4; var walkExtra = characterRenderProperties.RenderWalkFrame > 0 ? widthDelta * (characterRenderProperties.RenderWalkFrame - 1) : 0; @@ -429,16 +429,16 @@ public ISpriteSheet GetEmoteTexture(CharacterRenderProperties characterRenderPro const int NUM_EMOTES = 15; const int NUM_FRAMES = 4; - var emoteValue = Enum.GetName(typeof (Emote), characterRenderProperties.Emote) ?? ""; - var convertedValuesDictionary = Enum.GetNames(typeof (EmoteSpriteType)) - .ToDictionary(x => x, x => (EmoteSpriteType) Enum.Parse(typeof (EmoteSpriteType), x)); + var emoteValue = Enum.GetName(typeof(Emote), characterRenderProperties.Emote) ?? ""; + var convertedValuesDictionary = Enum.GetNames(typeof(EmoteSpriteType)) + .ToDictionary(x => x, x => (EmoteSpriteType)Enum.Parse(typeof(EmoteSpriteType), x)); var convertedEmote = (int)convertedValuesDictionary[emoteValue]; var emoteTexture = _gfxManager.TextureFromResource(GFXTypes.PostLoginUI, 38, true); var eachSet = emoteTexture.Width / NUM_EMOTES; var eachFrame = emoteTexture.Width / (NUM_EMOTES * NUM_FRAMES); - var startX = convertedEmote*eachSet + characterRenderProperties.EmoteFrame*eachFrame; + var startX = convertedEmote * eachSet + characterRenderProperties.EmoteFrame * eachFrame; var emoteRect = new Rectangle(startX, 0, eachFrame, emoteTexture.Height); @@ -531,4 +531,4 @@ private bool BowIsEquipped(CharacterRenderProperties characterRenderProperties) return _weaponMetadataProvider.GetValueOrDefault(characterRenderProperties.WeaponGraphic).Ranged; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs b/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs index aad9b755c..12edf2cba 100644 --- a/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs +++ b/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs @@ -18,4 +18,4 @@ public enum EmoteSpriteType Playful = 13, MusicNotes = 14, } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs b/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs index 9fed00789..5d8308eaf 100644 --- a/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs @@ -1,6 +1,6 @@ -using System.Linq; -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System.Linq; namespace EndlessClient.Rendering.Sprites { @@ -28,4 +28,4 @@ public Texture2D GetSourceTexture() return SheetTexture; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs b/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs index 1fe5818ba..f50db921c 100644 --- a/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs +++ b/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs @@ -16,4 +16,4 @@ public interface ICharacterSpriteCalculator ISpriteSheet GetFaceTexture(CharacterRenderProperties characterRenderProperties); ISpriteSheet GetEmoteTexture(CharacterRenderProperties characterRenderProperties); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/ISpriteSheet.cs b/EndlessClient/Rendering/Sprites/ISpriteSheet.cs index 7b1edde8e..10e7863a6 100644 --- a/EndlessClient/Rendering/Sprites/ISpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/ISpriteSheet.cs @@ -15,4 +15,4 @@ public interface ISpriteSheet Texture2D GetSourceTexture(); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs b/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs index a009ea936..5909e4f48 100644 --- a/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs +++ b/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs @@ -115,4 +115,4 @@ public interface INPCSpriteDataCache bool IsBlankSprite(int graphic); } -} +} \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/SpriteSheet.cs b/EndlessClient/Rendering/Sprites/SpriteSheet.cs index bbef04b71..4e44ea418 100644 --- a/EndlessClient/Rendering/Sprites/SpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/SpriteSheet.cs @@ -48,4 +48,4 @@ public Texture2D GetSourceTexture() return retText; } } -} +} \ No newline at end of file diff --git a/EndlessClient/Services/FriendIgnoreListService.cs b/EndlessClient/Services/FriendIgnoreListService.cs index b813ff9ca..6aa0ced90 100644 --- a/EndlessClient/Services/FriendIgnoreListService.cs +++ b/EndlessClient/Services/FriendIgnoreListService.cs @@ -87,4 +87,4 @@ public interface IFriendIgnoreListService void SaveNewIgnore(string path, string name); } -} +} \ No newline at end of file diff --git a/EndlessClient/Subscribers/ArenaEventSubscriber.cs b/EndlessClient/Subscribers/ArenaEventSubscriber.cs index b25bb9d9d..d8cd83401 100644 --- a/EndlessClient/Subscribers/ArenaEventSubscriber.cs +++ b/EndlessClient/Subscribers/ArenaEventSubscriber.cs @@ -104,4 +104,4 @@ private static bool AdjacentToArenaTile(MapCoordinate coord, IReadOnlyMatrix 500) { - var rend = _renderersForDifferentStates[(int) DisplayState.WalkingAnimation]; + var rend = _renderersForDifferentStates[(int)DisplayState.WalkingAnimation]; rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextWalkFrame(false)); _lastWalk = now; } @@ -264,7 +264,7 @@ private void RefreshDisplayedCharacters() foreach (var displayState in _allDisplayStates) { var props = GetRenderPropertiesForState(displayState); - _renderersForDifferentStates[(int) displayState].Character = Character.Default.WithRenderProperties(props); + _renderersForDifferentStates[(int)displayState].Character = Character.Default.WithRenderProperties(props); } } @@ -303,4 +303,4 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } -} +} \ No newline at end of file diff --git a/EndlessClient/Test/TestModeLauncher.cs b/EndlessClient/Test/TestModeLauncher.cs index 0e0f5cbd3..b6d5e8f96 100644 --- a/EndlessClient/Test/TestModeLauncher.cs +++ b/EndlessClient/Test/TestModeLauncher.cs @@ -49,4 +49,4 @@ public interface ITestModeLauncher { void LaunchTestMode(); } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/BlinkingLabel.cs b/EndlessClient/UIControls/BlinkingLabel.cs index 0c4663d6d..1b845f448 100644 --- a/EndlessClient/UIControls/BlinkingLabel.cs +++ b/EndlessClient/UIControls/BlinkingLabel.cs @@ -1,5 +1,5 @@ -using System; -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; +using System; using XNAControls; namespace EndlessClient.UIControls @@ -51,4 +51,4 @@ public override void Update(GameTime gameTime) base.Update(gameTime); } } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/CharacterControl.cs b/EndlessClient/UIControls/CharacterControl.cs index 11d7c7a0f..fd68673cc 100644 --- a/EndlessClient/UIControls/CharacterControl.cs +++ b/EndlessClient/UIControls/CharacterControl.cs @@ -59,4 +59,4 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/CharacterInfoPanel.cs b/EndlessClient/UIControls/CharacterInfoPanel.cs index 0ba977bd4..df74d5481 100644 --- a/EndlessClient/UIControls/CharacterInfoPanel.cs +++ b/EndlessClient/UIControls/CharacterInfoPanel.cs @@ -44,7 +44,7 @@ protected CharacterInfoPanel(int characterIndex, { _characterIndex = characterIndex; _gfxManager = gfxManager; - DrawPosition = new Vector2(334, 36 + characterIndex*124); + DrawPosition = new Vector2(334, 36 + characterIndex * 124); _loginButton = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(161, 57), @@ -204,7 +204,7 @@ private static string CapitalizeName(string name) private ISpriteSheet CreateAdminGraphic(AdminLevel adminLevel) { var adminGraphic = _gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 22); - + switch (adminLevel) { case AdminLevel.Player: @@ -250,4 +250,4 @@ protected override void AsyncButtonClick(Func clickHandler) { } } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/CharacterInfoPanelFactory.cs b/EndlessClient/UIControls/CharacterInfoPanelFactory.cs index aa069e6e3..5cd92c24b 100644 --- a/EndlessClient/UIControls/CharacterInfoPanelFactory.cs +++ b/EndlessClient/UIControls/CharacterInfoPanelFactory.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EndlessClient.Controllers; using EndlessClient.Dialogs.Services; using EndlessClient.Input; @@ -8,6 +6,8 @@ using EndlessClient.Rendering.Factories; using EOLib.Domain.Character; using EOLib.Graphics; +using System; +using System.Collections.Generic; namespace EndlessClient.UIControls { @@ -50,7 +50,7 @@ public void InjectCharacterManagementController(ICharacterManagementController c public IEnumerable CreatePanels(IEnumerable characters) { - if(_loginController == null || _characterManagementController == null) + if (_loginController == null || _characterManagementController == null) throw new InvalidOperationException("Missing controllers - the Unity container was initialized incorrectly"); int i = 0; diff --git a/EndlessClient/UIControls/ChatModePictureBox.cs b/EndlessClient/UIControls/ChatModePictureBox.cs index 9fe2e1e6f..4a88e318c 100644 --- a/EndlessClient/UIControls/ChatModePictureBox.cs +++ b/EndlessClient/UIControls/ChatModePictureBox.cs @@ -100,4 +100,4 @@ private void UpdateSourceRectangleForMode(ChatMode mode) private ChatTextBox ChatTextBox => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/ChatTextBox.cs b/EndlessClient/UIControls/ChatTextBox.cs index 0a086cb52..5bb41dc62 100644 --- a/EndlessClient/UIControls/ChatTextBox.cs +++ b/EndlessClient/UIControls/ChatTextBox.cs @@ -135,4 +135,4 @@ private bool IsSpecialInput(Keys k, KeyboardModifiers modifiers) modifiers == KeyboardModifiers.Alt; } } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/ClickableArea.cs b/EndlessClient/UIControls/ClickableArea.cs index 0df1cc688..12103f835 100644 --- a/EndlessClient/UIControls/ClickableArea.cs +++ b/EndlessClient/UIControls/ClickableArea.cs @@ -38,4 +38,4 @@ protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArg return true; } } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/CreateCharacterControl.cs b/EndlessClient/UIControls/CreateCharacterControl.cs index 7dfae3d85..a945d61a0 100644 --- a/EndlessClient/UIControls/CreateCharacterControl.cs +++ b/EndlessClient/UIControls/CreateCharacterControl.cs @@ -1,17 +1,17 @@ -using System; +using EndlessClient.Rendering.Factories; +using EOLib; +using EOLib.Domain.Character; using Microsoft.Xna.Framework; using MonoGame.Extended.Input.InputListeners; +using System; using XNAControls; -using EndlessClient.Rendering.Factories; -using EOLib; -using EOLib.Domain.Character; namespace EndlessClient.UIControls { public class CreateCharacterControl : CharacterControl { private Vector2 _lastPosition; - + public event EventHandler Clicked; @@ -79,4 +79,4 @@ private static CharacterRenderProperties GetDefaultProperties() return new CharacterRenderProperties.Builder { HairStyle = 1 }.ToImmutable(); } } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs b/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs index f3f1591a0..a96eebfae 100644 --- a/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs +++ b/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; -using EndlessClient.Controllers; +using EndlessClient.Controllers; using EOLib.Domain.Character; +using System.Collections.Generic; namespace EndlessClient.UIControls { @@ -10,4 +10,4 @@ public interface ICharacterInfoPanelFactory void InjectLoginController(ILoginController loginController); void InjectCharacterManagementController(ICharacterManagementController characterManagementController); } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/ScrollBar.cs b/EndlessClient/UIControls/ScrollBar.cs index 18a4af655..82bc11581 100644 --- a/EndlessClient/UIControls/ScrollBar.cs +++ b/EndlessClient/UIControls/ScrollBar.cs @@ -232,4 +232,4 @@ protected override bool HandleMouseWheelMoved(IXNAControl control, MouseEventArg return true; } } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/StatusBarLabel.cs b/EndlessClient/UIControls/StatusBarLabel.cs index 95500fe3b..4a4ef72ea 100644 --- a/EndlessClient/UIControls/StatusBarLabel.cs +++ b/EndlessClient/UIControls/StatusBarLabel.cs @@ -1,10 +1,10 @@ -using System; -using EndlessClient.HUD; +using EndlessClient.HUD; using EndlessClient.Rendering; using EOLib; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; using XNAControls; namespace EndlessClient.UIControls @@ -79,4 +79,4 @@ protected override void OnDrawControl(GameTime gameTime) base.OnDrawControl(gameTime); } } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/TimeLabel.cs b/EndlessClient/UIControls/TimeLabel.cs index 3436133a1..38c0b9e3a 100644 --- a/EndlessClient/UIControls/TimeLabel.cs +++ b/EndlessClient/UIControls/TimeLabel.cs @@ -1,7 +1,7 @@ -using System; -using EndlessClient.Rendering; +using EndlessClient.Rendering; using EOLib; using Microsoft.Xna.Framework; +using System; using XNAControls; namespace EndlessClient.UIControls @@ -39,4 +39,4 @@ private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider return new Rectangle(xLoc, yLoc, 1, 1); } } -} +} \ No newline at end of file diff --git a/EndlessClient/UIControls/XnaControlSoundMapper.cs b/EndlessClient/UIControls/XnaControlSoundMapper.cs index 9b81490d1..880c32796 100644 --- a/EndlessClient/UIControls/XnaControlSoundMapper.cs +++ b/EndlessClient/UIControls/XnaControlSoundMapper.cs @@ -43,4 +43,4 @@ public interface IXnaControlSoundMapper { void BindSoundToControl(IGameComponent component, Option soundEffectOverride = default); } -} +} \ No newline at end of file From 7a6718c3499f21c21ab29c5056b1dd41019b3b9d Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Sun, 28 Jul 2024 23:05:00 +0100 Subject: [PATCH 02/11] format --- .editorconfig | 3 +- BatchMap/Program.cs | 473 +++++---- BatchPub/Program.cs | 25 +- BatchPub/frmMain.cs | 725 +++++++------ EOBot/ArgumentsParser.cs | 331 +++--- EOBot/BotBase.cs | 119 ++- EOBot/BotException.cs | 9 +- EOBot/BotFramework.cs | 211 ++-- EOBot/BotHelper.cs | 171 ++- EOBot/ConsoleHelper.cs | 127 ++- EOBot/DependencyMaster.cs | 9 +- EOBot/IBot.cs | 33 +- EOBot/IBotFactory.cs | 9 +- EOBot/Interpreter/BotInterpreter.cs | 127 ++- EOBot/Interpreter/BotScriptErrorException.cs | 15 +- EOBot/Interpreter/BotToken.cs | 31 +- EOBot/Interpreter/BotTokenParser.cs | 369 ++++--- EOBot/Interpreter/BotTokenType.cs | 63 +- .../BuiltInIdentifierConfigurator.cs | 521 +++++---- .../Extensions/ProgramStateExtensions.cs | 35 +- .../Extensions/SymbolTableExtensions.cs | 67 +- EOBot/Interpreter/IdentifierBotToken.cs | 21 +- .../Interpreter/States/AssignmentEvaluator.cs | 141 ++- EOBot/Interpreter/States/BaseEvaluator.cs | 151 ++- EOBot/Interpreter/States/BlockEvaluator.cs | 157 ++- EOBot/Interpreter/States/EvalResult.cs | 31 +- .../Interpreter/States/ExpressionEvaluator.cs | 343 +++--- .../States/ExpressionTailEvaluator.cs | 31 +- EOBot/Interpreter/States/FunctionEvaluator.cs | 281 +++-- EOBot/Interpreter/States/GotoEvaluator.cs | 33 +- EOBot/Interpreter/States/IScriptEvaluator.cs | 9 +- EOBot/Interpreter/States/IfEvaluator.cs | 111 +- EOBot/Interpreter/States/KeywordEvaluator.cs | 29 +- EOBot/Interpreter/States/LabelEvaluator.cs | 17 +- EOBot/Interpreter/States/OperandEvaluator.cs | 29 +- EOBot/Interpreter/States/ProgramState.cs | 163 ++- EOBot/Interpreter/States/ScriptEvaluator.cs | 27 +- .../Interpreter/States/StatementEvaluator.cs | 41 +- .../States/StatementListEvaluator.cs | 25 +- EOBot/Interpreter/States/VariableEvaluator.cs | 89 +- EOBot/Interpreter/States/WhileEvaluator.cs | 57 +- EOBot/Interpreter/VariableBotToken.cs | 17 +- EOBot/Interpreter/Variables/ArrayVariable.cs | 33 +- EOBot/Interpreter/Variables/AsyncFunction.cs | 177 ++-- .../Variables/AsyncVoidFunction.cs | 177 ++-- EOBot/Interpreter/Variables/BoolVariable.cs | 23 +- EOBot/Interpreter/Variables/Function.cs | 177 ++-- EOBot/Interpreter/Variables/ICallable.cs | 37 +- EOBot/Interpreter/Variables/IIdentifiable.cs | 9 +- EOBot/Interpreter/Variables/IVariable.cs | 17 +- EOBot/Interpreter/Variables/IntVariable.cs | 23 +- EOBot/Interpreter/Variables/ObjectVariable.cs | 47 +- .../Variables/PredefinedIdentifiers.cs | 87 +- EOBot/Interpreter/Variables/StringVariable.cs | 23 +- .../Variables/UndefinedVariable.cs | 17 +- EOBot/Interpreter/Variables/VoidFunction.cs | 177 ++-- EOBot/NamesList.cs | 89 +- EOBot/Program.cs | 527 +++++----- EOBot/ScriptedBot.cs | 73 +- EOBot/ScriptedBotFactory.cs | 23 +- EOBot/TrainerBot.cs | 601 ++++++----- EOBot/TrainerBotFactory.cs | 23 +- .../ConfigFileLoadActionsTest.cs | 189 ++-- EOLib.Config.Test/IniReaderTest.cs | 477 +++++---- .../GraphicsDeviceTestHelper.cs | 53 +- .../NativeGraphicsLoaderTest.cs | 99 +- .../NativeGraphicsManagerTest.cs | 353 ++++--- EOLib.Graphics.Test/PEFileCollectionTest.cs | 105 +- EOLib.Graphics.Test/RectangleExtensionTest.cs | 57 +- EOLib.Graphics/ColorConstants.cs | 21 +- EOLib.Graphics/GFXTypes.cs | 207 ++-- EOLib.Graphics/IGraphicsDeviceRepository.cs | 35 +- EOLib.Graphics/INativeGraphicsLoader.cs | 9 +- EOLib.Graphics/INativeGraphicsManager.cs | 29 +- EOLib.Graphics/LibraryLoadException.cs | 23 +- EOLib.Graphics/NativeGraphicsLoader.cs | 47 +- EOLib.Graphics/NativeGraphicsManager.cs | 183 ++-- EOLib.Graphics/PEFileCollection.cs | 45 +- EOLib.Graphics/RectangleExtension.cs | 45 +- EOLib.IO.Test/EIFRecordExtensionsTest.cs | 75 +- EOLib.IO.Test/Map/MapFilePropertiesTest.cs | 221 ++-- EOLib.IO.Test/Map/MapFileTest.cs | 259 +++-- .../Map/MapStringEncoderServiceTest.cs | 127 ++- EOLib.IO.Test/Pub/BasePubFileTest.cs | 323 +++--- EOLib.IO.Test/Pub/ECFFileTest.cs | 15 +- EOLib.IO.Test/Pub/ECFRecordTest.cs | 39 +- EOLib.IO.Test/Pub/EIFFileTest.cs | 15 +- EOLib.IO.Test/Pub/EIFRecordTest.cs | 39 +- EOLib.IO.Test/Pub/ENFFileTest.cs | 15 +- EOLib.IO.Test/Pub/ENFRecordTest.cs | 39 +- EOLib.IO.Test/Pub/ESFFileTest.cs | 15 +- EOLib.IO.Test/Pub/ESFRecordTest.cs | 39 +- .../Serializers/PubFileSerializerTest.cs | 231 ++-- .../Serializers/PubRecordSerializerTest.cs | 81 +- .../DataFileLoadActionsTest.cs | 117 +-- .../EDFLoaderServiceTest.cs | 303 +++--- .../LocalizedStringServiceTest.cs | 245 +++-- .../FileTransfer/FileRequestServiceTest.cs | 429 ++++---- .../TestHelpers/PacketSendServiceHelpers.cs | 31 +- EndlessClient/Audio/AudioActions.cs | 107 +- EndlessClient/Audio/MfxPlayer.cs | 197 ++-- EndlessClient/Audio/SfxPlayer.cs | 155 ++- EndlessClient/Audio/SoundEffectID.cs | 203 ++-- EndlessClient/Audio/WAVFileValidator.cs | 41 +- EndlessClient/Content/ContentProvider.cs | 249 +++-- .../ControlSets/BackButtonControlSet.cs | 89 +- EndlessClient/ControlSets/BaseControlSet.cs | 175 ++-- .../ControlSets/ControlSetFactory.cs | 171 ++- .../ControlSets/CreateAccountControlSet.cs | 331 +++--- EndlessClient/ControlSets/EmptyControlSet.cs | 43 +- .../ControlSets/GameControlIdentifier.cs | 65 +- EndlessClient/ControlSets/IControlSet.cs | 65 +- .../ControlSets/IControlSetFactory.cs | 17 +- .../ControlSets/IControlSetRepository.cs | 35 +- .../ControlSets/IHudControlProvider.cs | 93 +- EndlessClient/ControlSets/InGameControlSet.cs | 93 +- .../ControlSets/InitialControlSet.cs | 263 +++-- .../ControlSets/IntermediateControlSet.cs | 113 +- .../ControlSets/LoggedInControlSet.cs | 149 ++- .../ControlSets/LoginPromptControlSet.cs | 241 +++-- .../ControlSets/ViewCreditsControlSet.cs | 57 +- .../Controllers/AccountController.cs | 183 ++-- .../Controllers/ArrowKeyController.cs | 217 ++-- EndlessClient/Controllers/BardController.cs | 57 +- .../CharacterManagementController.cs | 227 ++-- EndlessClient/Controllers/ChatController.cs | 159 ++- .../Controllers/ControlKeyController.cs | 143 ++- .../Controllers/FunctionKeyController.cs | 175 ++-- .../Controllers/InventoryController.cs | 651 ++++++------ EndlessClient/Controllers/LoginController.cs | 481 +++++---- .../Controllers/MainButtonController.cs | 259 +++-- .../Controllers/MapInteractionController.cs | 487 +++++---- .../Controllers/NPCInteractionController.cs | 125 ++- EndlessClient/Controllers/NumPadController.cs | 51 +- .../Controllers/TrainingController.cs | 79 +- .../Actions/AccountDialogDisplayActions.cs | 135 ++- .../Dialogs/Actions/CharacterDialogActions.cs | 117 +-- .../Actions/ErrorDialogDisplayAction.cs | 263 +++-- .../Dialogs/Actions/FirstTimePlayerActions.cs | 43 +- EndlessClient/Dialogs/Actions/HelpActions.cs | 155 ++- .../Actions/IAccountDialogDisplayActions.cs | 19 +- .../Actions/ICharacterDialogActions.cs | 17 +- .../Actions/IErrorDialogDisplayAction.cs | 19 +- .../Dialogs/Actions/InGameDialogActions.cs | 791 +++++++------- .../Dialogs/Actions/NpcInteractionActions.cs | 347 +++--- .../Dialogs/Actions/PartyDialogActions.cs | 121 ++- .../Dialogs/Actions/TradeDialogActions.cs | 127 ++- .../Dialogs/ActiveDialogRepository.cs | 269 +++-- EndlessClient/Dialogs/BankAccountDialog.cs | 389 ++++--- EndlessClient/Dialogs/BarberDialog.cs | 309 +++--- EndlessClient/Dialogs/BardDialog.cs | 149 ++- EndlessClient/Dialogs/BaseEODialog.cs | 61 +- EndlessClient/Dialogs/BoardDialog.cs | 477 +++++---- EndlessClient/Dialogs/BookDialog.cs | 171 ++- EndlessClient/Dialogs/ChangePasswordDialog.cs | 211 ++-- EndlessClient/Dialogs/ChestDialog.cs | 167 ++- .../Dialogs/CreateCharacterDialog.cs | 301 +++--- EndlessClient/Dialogs/EODialogButton.cs | 13 +- EndlessClient/Dialogs/EOMessageBox.cs | 201 ++-- .../Extensions/EquipLocationExtensions.cs | 43 +- .../Factories/BankAccountDialogFactory.cs | 119 ++- .../Dialogs/Factories/BarberDialogFactory.cs | 111 +- .../Dialogs/Factories/BardDialogFactory.cs | 47 +- .../Dialogs/Factories/BoardDialogFactory.cs | 103 +- .../Dialogs/Factories/BookDialogFactory.cs | 59 +- .../Factories/ChangePasswordDialogFactory.cs | 73 +- .../Dialogs/Factories/ChestDialogFactory.cs | 111 +- .../CreateAccountProgressDialogFactory.cs | 69 +- .../CreateAccountWarningDialogFactory.cs | 67 +- .../Factories/CreateCharacterDialogFactory.cs | 79 +- .../Dialogs/Factories/EOMessageBoxFactory.cs | 161 ++- .../FriendIgnoreListDialogFactory.cs | 207 ++-- .../Factories/GameLoadingDialogFactory.cs | 55 +- .../Dialogs/Factories/HelpDialogFactory.cs | 115 +- .../Factories/IChangePasswordDialogFactory.cs | 9 +- .../Dialogs/Factories/IEOMessageBoxFactory.cs | 45 +- .../Factories/InnkeeperDialogFactory.cs | 103 +- .../Factories/ItemTransferDialogFactory.cs | 91 +- .../Dialogs/Factories/JukeboxDialogFactory.cs | 103 +- .../Dialogs/Factories/LawDialogFactory.cs | 95 +- .../Dialogs/Factories/LockerDialogFactory.cs | 111 +- .../Factories/PaperdollDialogFactory.cs | 115 +- .../Dialogs/Factories/QuestDialogFactory.cs | 71 +- .../Factories/QuestStatusDialogFactory.cs | 63 +- .../Factories/ScrollingListDialogFactory.cs | 37 +- .../Factories/SessionExpDialogFactory.cs | 71 +- .../Dialogs/Factories/ShopDialogFactory.cs | 119 ++- .../Factories/SkillmasterDialogFactory.cs | 127 ++- .../Factories/TextInputDialogFactory.cs | 69 +- .../Factories/TextInputMultiDialogFactory.cs | 79 +- .../Dialogs/Factories/TradeDialogFactory.cs | 119 ++- .../Dialogs/FriendIgnoreListDialog.cs | 43 +- EndlessClient/Dialogs/GameLoadingDialog.cs | 209 ++-- EndlessClient/Dialogs/InnkeeperDialog.cs | 401 ++++--- EndlessClient/Dialogs/ItemTransferDialog.cs | 326 +++--- EndlessClient/Dialogs/JukeboxDialog.cs | 269 +++-- EndlessClient/Dialogs/LawDialog.cs | 323 +++--- EndlessClient/Dialogs/ListDialogItem.cs | 431 ++++---- EndlessClient/Dialogs/LockerDialog.cs | 173 ++- EndlessClient/Dialogs/PaperdollDialog.cs | 229 ++-- EndlessClient/Dialogs/PaperdollDialogItem.cs | 167 ++- EndlessClient/Dialogs/PlayerInfoDialog.cs | 249 +++-- EndlessClient/Dialogs/ProgressDialog.cs | 193 ++-- EndlessClient/Dialogs/QuestDialog.cs | 285 +++-- EndlessClient/Dialogs/QuestStatusDialog.cs | 201 ++-- .../Dialogs/QuestStatusListDialogItem.cs | 197 ++-- EndlessClient/Dialogs/ScrollingListDialog.cs | 945 +++++++++-------- .../Dialogs/ScrollingMessageDialog.cs | 155 ++- .../Dialogs/Services/EODialogButtonService.cs | 83 +- .../Dialogs/Services/EODialogIconService.cs | 87 +- EndlessClient/Dialogs/SessionExpDialog.cs | 189 ++-- EndlessClient/Dialogs/ShopDialog.cs | 641 ++++++------ EndlessClient/Dialogs/SkillmasterDialog.cs | 657 ++++++------ EndlessClient/Dialogs/TextInputDialog.cs | 107 +- EndlessClient/Dialogs/TextMultiInputDialog.cs | 243 +++-- EndlessClient/Dialogs/TradeDialog.cs | 637 ++++++----- .../GameExecution/DebugGameRunner.cs | 17 +- EndlessClient/GameExecution/EndlessGame.cs | 425 ++++---- EndlessClient/GameExecution/GameRunnerBase.cs | 201 ++-- .../GameExecution/GameStateActions.cs | 243 +++-- EndlessClient/GameExecution/GameStates.cs | 75 +- EndlessClient/GameExecution/IEndlessGame.cs | 21 +- .../GameExecution/IEndlessGameProvider.cs | 29 +- EndlessClient/GameExecution/IGameRunner.cs | 11 +- .../GameExecution/IGameStateActions.cs | 13 +- .../GameExecution/IGameStateRepository.cs | 29 +- .../GameExecution/ReleaseGameRunner.cs | 171 ++- EndlessClient/HUD/AStarPathFinder.cs | 153 ++- EndlessClient/HUD/Chat/ChatBubbleActions.cs | 65 +- EndlessClient/HUD/Chat/ChatModeCalculator.cs | 55 +- .../HUD/Chat/ChatNotificationActions.cs | 155 ++- EndlessClient/HUD/Chat/ChatPanelTab.cs | 351 ++++--- EndlessClient/HUD/Chat/ChatTextBoxActions.cs | 43 +- EndlessClient/HUD/Chat/IChatModeCalculator.cs | 9 +- EndlessClient/HUD/Chat/IChatTextBoxActions.cs | 11 +- .../HUD/Chat/PrivateMessageActions.cs | 109 +- .../HUD/Chat/ServerMessageHandler.cs | 63 +- .../HUD/Controls/DragCompletedEventArgs.cs | 25 +- .../HUD/Controls/DraggablePanelItem.cs | 193 ++-- .../HUD/Controls/HudBackgroundFrame.cs | 97 +- .../HUD/Controls/HudControlIdentifier.cs | 109 +- .../HUD/Controls/HudControlsFactory.cs | 987 +++++++++--------- .../HUD/Controls/IDraggableItemContainer.cs | 9 +- .../HUD/Controls/IHudControlsFactory.cs | 11 +- .../Controls/PeriodicStatUpdaterComponent.cs | 101 +- EndlessClient/HUD/HudButtonController.cs | 227 ++-- EndlessClient/HUD/HudStateActions.cs | 117 +-- EndlessClient/HUD/IHudButtonController.cs | 37 +- EndlessClient/HUD/IHudStateActions.cs | 11 +- EndlessClient/HUD/IStatusLabelSetter.cs | 15 +- .../HUD/IStatusLabelTextRepository.cs | 43 +- EndlessClient/HUD/InGameStates.cs | 31 +- .../HUD/Inventory/InventoryPanelItem.cs | 347 +++--- .../HUD/Inventory/InventoryService.cs | 149 ++- .../HUD/Inventory/InventorySlotRepository.cs | 53 +- .../HUD/Inventory/InventorySpaceValidator.cs | 121 ++- EndlessClient/HUD/ItemNameColorService.cs | 43 +- EndlessClient/HUD/Panels/ActiveSpellsPanel.cs | 933 +++++++++-------- EndlessClient/HUD/Panels/ChatPanel.cs | 201 ++-- EndlessClient/HUD/Panels/DraggableHudPanel.cs | 89 +- EndlessClient/HUD/Panels/HelpPanel.cs | 23 +- EndlessClient/HUD/Panels/HudPanelFactory.cs | 425 ++++---- EndlessClient/HUD/Panels/IHudPanel.cs | 21 +- EndlessClient/HUD/Panels/IHudPanelFactory.cs | 27 +- EndlessClient/HUD/Panels/InventoryPanel.cs | 827 ++++++++------- EndlessClient/HUD/Panels/NewsPanel.cs | 187 ++-- EndlessClient/HUD/Panels/OnlineListPanel.cs | 363 ++++--- EndlessClient/HUD/Panels/PartyPanel.cs | 237 +++-- .../HUD/Panels/PassiveSpellsPanel.cs | 23 +- EndlessClient/HUD/Panels/SettingsPanel.cs | 407 ++++---- EndlessClient/HUD/Panels/StatsPanel.cs | 381 ++++--- EndlessClient/HUD/Party/PartyPanelMember.cs | 201 ++-- EndlessClient/HUD/Spells/SpellPanelItem.cs | 271 +++-- .../HUD/Spells/SpellSelectActions.cs | 87 +- .../HUD/Spells/SpellSlotDataRepository.cs | 87 +- EndlessClient/HUD/StatusBars/HPStatusBar.cs | 51 +- EndlessClient/HUD/StatusBars/SPStatusBar.cs | 53 +- EndlessClient/HUD/StatusBars/StatusBarBase.cs | 169 ++- EndlessClient/HUD/StatusBars/TNLStatusBar.cs | 83 +- EndlessClient/HUD/StatusBars/TPStatusBar.cs | 53 +- EndlessClient/HUD/StatusLabelSetter.cs | 129 ++- EndlessClient/HUD/UserInterfaceActions.cs | 155 ++- .../Initialization/ConfigInitializer.cs | 25 +- .../EndlessClientInitializer.cs | 145 ++- .../Initialization/GraphicsInitializer.cs | 55 +- .../Initialization/IGameInitializer.cs | 9 +- .../Initialization/LocalizationInitializer.cs | 25 +- EndlessClient/Input/ArrowKeyHandler.cs | 53 +- EndlessClient/Input/ControlKeyHandler.cs | 41 +- .../Input/CurrentUserInputTracker.cs | 35 +- EndlessClient/Input/FunctionKeyHandler.cs | 53 +- EndlessClient/Input/IUserInputRepository.cs | 47 +- .../Input/IUserInputTimeRepository.cs | 33 +- EndlessClient/Input/InputHandlerBase.cs | 145 ++- .../Input/KeyboardStateExtensions.cs | 47 +- EndlessClient/Input/NumPadHandler.cs | 57 +- EndlessClient/Input/PanelShortcutHandler.cs | 81 +- .../Input/PreviousUserInputTracker.cs | 35 +- EndlessClient/Input/UnwalkableTileActions.cs | 285 +++-- .../Input/UnwalkableTileActionsHandler.cs | 91 +- EndlessClient/Input/UserInputHandler.cs | 113 +- .../Input/UserInputHandlerFactory.cs | 111 +- .../Network/PacketHandlerGameComponent.cs | 65 +- .../Network/UnknownEntitiesRequester.cs | 161 ++- EndlessClient/Program.cs | 45 +- .../Character/CharacterAnimationActions.cs | 633 ++++++----- .../Rendering/Character/CharacterAnimator.cs | 915 ++++++++-------- .../Rendering/Character/CharacterRenderer.cs | 811 +++++++------- .../Character/CharacterRendererUpdater.cs | 283 +++-- .../Character/CharacterStateCache.cs | 133 ++- .../Rendering/Character/CharacterTextures.cs | 81 +- .../Rendering/Character/ICharacterRenderer.cs | 23 +- .../Character/ICharacterRendererRepository.cs | 65 +- .../Character/ICharacterStateCache.cs | 29 +- .../Rendering/Character/ICharacterTextures.cs | 31 +- .../Rendering/Character/ISpellCaster.cs | 13 +- .../Character/PeriodicEmoteHandler.cs | 389 ++++--- .../CharacterProperties/ArmorRenderer.cs | 97 +- .../BaseCharacterPropertyRenderer.cs | 37 +- .../CharacterProperties/BootsRenderer.cs | 123 ++- .../CharacterPropertyRendererBuilder.cs | 137 ++- .../CharacterProperties/EmoteRenderer.cs | 49 +- .../CharacterProperties/FaceRenderer.cs | 73 +- .../HairRenderLocationCalculator.cs | 87 +- .../CharacterProperties/HairRenderer.cs | 35 +- .../CharacterProperties/HatRenderer.cs | 57 +- .../ICharacterPropertyRenderer.cs | 13 +- .../ICharacterPropertyRendererBuilder.cs | 11 +- .../CharacterProperties/ShieldRenderer.cs | 155 ++- .../SkinRenderLocationCalculator.cs | 109 +- .../CharacterProperties/SkinRenderer.cs | 35 +- .../CharacterProperties/WeaponRenderer.cs | 95 +- .../WeaponSlashRenderer.cs | 57 +- EndlessClient/Rendering/Chat/ChatBubble.cs | 307 +++--- .../Rendering/Chat/ChatBubbleFactory.cs | 51 +- .../Rendering/Chat/ChatBubbleTexture.cs | 27 +- .../Chat/ChatBubbleTextureProvider.cs | 61 +- .../Rendering/Chat/ChatColorExtensions.cs | 25 +- .../Rendering/Chat/ChatRenderable.cs | 157 ++- .../Rendering/Chat/ChatRenderableGenerator.cs | 195 ++-- .../Rendering/Chat/IChatRenderable.cs | 13 +- .../Chat/IChatRenderableGenerator.cs | 11 +- .../Rendering/ClientWindowSizeRepository.cs | 157 ++- .../Rendering/ContextMenuRenderer.cs | 525 +++++----- .../Rendering/ContextMenuRepository.cs | 33 +- .../Rendering/DispatcherGameComponent.cs | 51 +- .../Rendering/Effects/EffectAnimationType.cs | 15 +- .../Rendering/Effects/EffectLayer.cs | 13 +- .../Rendering/Effects/EffectRenderer.cs | 307 +++--- .../Effects/EffectRendererFactory.cs | 55 +- .../Rendering/Effects/EffectSpriteInfo.cs | 167 ++- .../Rendering/Effects/EffectSpriteManager.cs | 91 +- .../Rendering/Effects/HardCodedEffect.cs | 27 +- .../Rendering/Effects/IEffectSpriteInfo.cs | 17 +- .../Effects/PositionOffsetEffectMetadata.cs | 17 +- .../Effects/RandomFlickeringEffectMetadata.cs | 17 +- .../Effects/VerticalSlidingEffectMetadata.cs | 13 +- .../Factories/CharacterRendererFactory.cs | 143 ++- .../Factories/ContextMenuRendererFactory.cs | 145 ++- .../Factories/HealthBarRendererFactory.cs | 31 +- .../Factories/ICharacterRendererFactory.cs | 9 +- .../Factories/IMapRendererFactory.cs | 9 +- .../Factories/IRenderTargetFactory.cs | 11 +- .../Rendering/Factories/MapRendererFactory.cs | 153 ++- .../Factories/MouseCursorRendererFactory.cs | 101 +- .../Factories/RenderTargetFactory.cs | 51 +- .../Rendering/GridDrawCoordinateCalculator.cs | 281 +++-- EndlessClient/Rendering/HealthBarRenderer.cs | 245 +++-- .../Rendering/IGameWindowRepository.cs | 27 +- EndlessClient/Rendering/IMapActor.cs | 25 +- .../Rendering/Map/ClickDispatcher.cs | 387 ++++--- .../Rendering/Map/ClickDispatcherFactory.cs | 135 ++- .../Rendering/Map/DynamicMapObjectUpdater.cs | 219 ++-- .../Rendering/Map/IMapItemGraphicProvider.cs | 9 +- .../Map/IMapRenderDistanceCalculator.cs | 9 +- EndlessClient/Rendering/Map/IMapRenderer.cs | 23 +- .../Rendering/Map/MapChangedActions.cs | 389 ++++--- .../Map/MapEntityRendererProvider.cs | 205 ++-- .../Rendering/Map/MapItemGraphicProvider.cs | 45 +- .../Map/MapObjectBoundsCalculator.cs | 59 +- .../Rendering/Map/MapRenderBounds.cs | 29 +- .../Map/MapRenderDistanceCalculator.cs | 39 +- EndlessClient/Rendering/Map/MapRenderLayer.cs | 35 +- EndlessClient/Rendering/Map/MapRenderer.cs | 841 ++++++++------- .../Rendering/Map/MiniMapRenderer.cs | 435 ++++---- .../Rendering/Map/MiniMapRendererFactory.cs | 87 +- .../BaseMapEntityRenderer.cs | 115 +- .../MapEntityRenderers/GroundLayerRenderer.cs | 151 ++- .../MapEntityRenderers/IMapEntityRenderer.cs | 15 +- .../IMapEntityRendererProvider.cs | 13 +- .../MainCharacterEntityRenderer.cs | 69 +- .../MapItemLayerRenderer.cs | 67 +- .../MapObjectLayerRenderer.cs | 113 +- .../MapEntityRenderers/NPCEntityRenderer.cs | 75 +- .../MapEntityRenderers/OnTopLayerRenderer.cs | 69 +- .../OtherCharacterEntityRenderer.cs | 61 +- .../Overlay2LayerRenderer.cs | 61 +- .../OverlayLayerRenderer.cs | 61 +- .../MapEntityRenderers/RoofLayerRenderer.cs | 69 +- .../MapEntityRenderers/ShadowLayerRenderer.cs | 89 +- .../MapEntityRenderers/WallLayerRenderer.cs | 177 ++-- .../Metadata/EffectMetadataProvider.cs | 107 +- .../Rendering/Metadata/GFXMetadataLoader.cs | 93 +- .../Rendering/Metadata/HatMetadataProvider.cs | 103 +- .../Rendering/Metadata/IMetadataProvider.cs | 13 +- .../Metadata/Models/EffectMetadata.cs | 59 +- .../Rendering/Metadata/Models/IGFXMetadata.cs | 7 +- .../Rendering/Metadata/Models/NPCMetadata.cs | 35 +- .../Rendering/Metadata/NPCMetadataProvider.cs | 379 ++++--- .../Metadata/ShieldMetadataProvider.cs | 49 +- .../Metadata/WeaponMetadataProvider.cs | 185 ++-- .../Rendering/MouseCursorRenderer.cs | 503 +++++---- EndlessClient/Rendering/NPC/INPCRenderer.cs | 17 +- EndlessClient/Rendering/NPC/NPCActions.cs | 253 +++-- EndlessClient/Rendering/NPC/NPCAnimator.cs | 201 ++-- EndlessClient/Rendering/NPC/NPCCache.cs | 83 +- EndlessClient/Rendering/NPC/NPCRenderer.cs | 513 +++++---- .../Rendering/NPC/NPCRendererFactory.cs | 113 +- .../Rendering/NPC/NPCRendererRepository.cs | 59 +- .../Rendering/NPC/NPCRendererUpdater.cs | 197 ++-- .../Rendering/PlayerStatusIconRenderer.cs | 145 ++- EndlessClient/Rendering/PointComparer.cs | 19 +- .../Rendering/RenderFrameActionTime.cs | 55 +- .../Rendering/RenderOffsetCalculator.cs | 155 ++- .../Rendering/RendererRepositoryResetter.cs | 57 +- .../Sprites/ArmorShieldSpriteType.cs | 35 +- .../Rendering/Sprites/BootsSpriteType.cs | 23 +- .../Sprites/CharacterSpriteCalculator.cs | 833 ++++++++------- .../Rendering/Sprites/EmoteSpriteType.cs | 37 +- .../Rendering/Sprites/EmptySpriteSheet.cs | 39 +- .../Sprites/ICharacterSpriteCalculator.cs | 27 +- .../Rendering/Sprites/ISpriteSheet.cs | 17 +- .../Rendering/Sprites/NPCSpriteDataCache.cs | 157 ++- .../Rendering/Sprites/NPCSpriteSheet.cs | 107 +- .../Rendering/Sprites/SpriteSheet.cs | 69 +- .../Rendering/Sprites/WeaponSpriteType.cs | 29 +- .../Services/FriendIgnoreListService.cs | 129 ++- .../Subscribers/ArenaEventSubscriber.cs | 143 ++- .../Subscribers/JukeboxEventSubscriber.cs | 27 +- .../Subscribers/LockerEventSubscriber.cs | 37 +- .../MainCharacterEventSubscriber.cs | 147 ++- .../OtherCharacterEventSubscriber.cs | 103 +- .../ServerRebootEventSubscriber.cs | 43 +- EndlessClient/Test/CharacterStateTest.cs | 455 ++++---- EndlessClient/Test/TestModeLauncher.cs | 73 +- EndlessClient/UIControls/BlinkingLabel.cs | 79 +- EndlessClient/UIControls/CharacterControl.cs | 81 +- .../UIControls/CharacterInfoPanel.cs | 399 ++++--- .../UIControls/CharacterInfoPanelFactory.cs | 107 +- .../UIControls/ChatModePictureBox.cs | 147 ++- EndlessClient/UIControls/ChatTextBox.cs | 197 ++-- EndlessClient/UIControls/ClickableArea.cs | 53 +- .../UIControls/CreateCharacterControl.cs | 107 +- .../UIControls/ICharacterInfoPanelFactory.cs | 13 +- EndlessClient/UIControls/ScrollBar.cs | 363 ++++--- EndlessClient/UIControls/StatusBarLabel.cs | 107 +- EndlessClient/UIControls/TimeLabel.cs | 49 +- .../UIControls/XnaControlSoundMapper.cs | 59 +- 458 files changed, 32717 insertions(+), 33174 deletions(-) diff --git a/.editorconfig b/.editorconfig index 696be7353..b9eae88d8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -266,4 +266,5 @@ dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent dotnet_style_qualification_for_field = false:silent dotnet_style_qualification_for_property = false:silent dotnet_style_qualification_for_method = false:silent -dotnet_style_qualification_for_event = false:silent \ No newline at end of file +dotnet_style_qualification_for_event = false:silent +insert_final_newline = false \ No newline at end of file diff --git a/BatchMap/Program.cs b/BatchMap/Program.cs index c88ed8e56..700ce1067 100644 --- a/BatchMap/Program.cs +++ b/BatchMap/Program.cs @@ -8,309 +8,308 @@ using System.IO; using System.Linq; -namespace BatchMap +namespace BatchMap; + +public static class Program { - public static class Program - { - private static ITypeRegistry _typeRegistry; - private static IPubFileProvider _pubProvider; - private static IMapFileProvider _mapFileProvider; + private static ITypeRegistry _typeRegistry; + private static IPubFileProvider _pubProvider; + private static IMapFileProvider _mapFileProvider; - private static void Main(string[] args) + private static void Main(string[] args) + { + if (args.Length != 3) { - if (args.Length != 3) - { - Console.WriteLine("Usage: BatchMap.exe "); - return; - } + Console.WriteLine("Usage: BatchMap.exe "); + return; + } - var srcFilePath = args[0]; - var dstFilePath = args[1]; - var pubFilePath = args[2]; - var singleFileProcess = false; + var srcFilePath = args[0]; + var dstFilePath = args[1]; + var pubFilePath = args[2]; + var singleFileProcess = false; - if (srcFilePath.ToLower().EndsWith(".emf") && !dstFilePath.ToLower().EndsWith(".emf")) - { - Console.WriteLine("Invalid: single map cannot be processed into output directory. Specify destination emf file."); - return; - } + if (srcFilePath.ToLower().EndsWith(".emf") && !dstFilePath.ToLower().EndsWith(".emf")) + { + Console.WriteLine("Invalid: single map cannot be processed into output directory. Specify destination emf file."); + return; + } + + if (dstFilePath.ToLower().EndsWith(".emf") && !srcFilePath.ToLower().EndsWith(".emf")) + { + Console.WriteLine("Invalid: map directory cannot be processed into single output map. Specify destination output directory."); + return; + } - if (dstFilePath.ToLower().EndsWith(".emf") && !srcFilePath.ToLower().EndsWith(".emf")) + if (srcFilePath.ToLower().EndsWith(".emf") && dstFilePath.ToLower().EndsWith(".emf")) + { + singleFileProcess = true; + if (!File.Exists(srcFilePath)) { - Console.WriteLine("Invalid: map directory cannot be processed into single output map. Specify destination output directory."); + Console.WriteLine("Invalid input: input file does not exist!"); return; } - if (srcFilePath.ToLower().EndsWith(".emf") && dstFilePath.ToLower().EndsWith(".emf")) + if (File.Exists(dstFilePath)) { - singleFileProcess = true; - if (!File.Exists(srcFilePath)) + char inp; + do { - Console.WriteLine("Invalid input: input file does not exist!"); - return; - } + Console.Write("Destination file exists. Overwrite? [y/n] "); + string input = Console.ReadLine() ?? ""; + inp = input.Length > 0 ? input[0] : ' '; + } while (inp != 'y' && inp != 'n' && inp != 'Y' && inp != 'N'); - if (File.Exists(dstFilePath)) + if (inp == 'n' || inp == 'N') { - char inp; - do - { - Console.Write("Destination file exists. Overwrite? [y/n] "); - string input = Console.ReadLine() ?? ""; - inp = input.Length > 0 ? input[0] : ' '; - } while (inp != 'y' && inp != 'n' && inp != 'Y' && inp != 'N'); - - if (inp == 'n' || inp == 'N') - { - Console.WriteLine("Will not overwrite existing file. Exiting."); - return; - } + Console.WriteLine("Will not overwrite existing file. Exiting."); + return; } } - else + } + else + { + if (!Directory.Exists(srcFilePath) || Directory.GetFiles(srcFilePath, "*.emf").Length == 0) { - if (!Directory.Exists(srcFilePath) || Directory.GetFiles(srcFilePath, "*.emf").Length == 0) - { - Console.WriteLine("Invalid input: source directory does not exist or is missing maps!"); - return; - } + Console.WriteLine("Invalid input: source directory does not exist or is missing maps!"); + return; + } - if (Directory.Exists(dstFilePath) && Directory.GetFiles(dstFilePath, "*.emf").Length > 0) + if (Directory.Exists(dstFilePath) && Directory.GetFiles(dstFilePath, "*.emf").Length > 0) + { + char inp; + do { - char inp; - do - { - Console.WriteLine("Destination directory contains emf files. Overwrite? [y/n] "); - string input = Console.ReadLine() ?? ""; - inp = input.Length > 0 ? input[0] : ' '; - } while (inp != 'y' && inp != 'n' && inp != 'Y' && inp != 'N'); + Console.WriteLine("Destination directory contains emf files. Overwrite? [y/n] "); + string input = Console.ReadLine() ?? ""; + inp = input.Length > 0 ? input[0] : ' '; + } while (inp != 'y' && inp != 'n' && inp != 'Y' && inp != 'N'); - if (inp == 'n' || inp == 'N') - { - Console.WriteLine("Will not overwrite existing files. Exiting."); - return; - } - } - else if (!Directory.Exists(dstFilePath)) + if (inp == 'n' || inp == 'N') { - Directory.CreateDirectory(dstFilePath); + Console.WriteLine("Will not overwrite existing files. Exiting."); + return; } } - - SetupDependencies(); - - try - { - var actions = _typeRegistry.Resolve(); - - actions.LoadItemFileByName(Path.Combine(pubFilePath, "dat001.eif")); - actions.LoadNPCFileByName(Path.Combine(pubFilePath, "dtn001.enf")); - } - catch + else if (!Directory.Exists(dstFilePath)) { - Console.WriteLine("Error loading pub files!"); - _typeRegistry.Dispose(); - return; + Directory.CreateDirectory(dstFilePath); } + } - try - { - ProcessFiles(srcFilePath, dstFilePath, singleFileProcess); - } - catch (Exception ex) - { - Console.WriteLine(); - - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("Exception was thrown: "); - Console.ForegroundColor = ConsoleColor.Gray; - Console.WriteLine(ex.Message); + SetupDependencies(); - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("\nCall stack: \n"); - Console.ForegroundColor = ConsoleColor.Gray; - Console.WriteLine(ex.StackTrace); - } + try + { + var actions = _typeRegistry.Resolve(); + actions.LoadItemFileByName(Path.Combine(pubFilePath, "dat001.eif")); + actions.LoadNPCFileByName(Path.Combine(pubFilePath, "dtn001.enf")); + } + catch + { + Console.WriteLine("Error loading pub files!"); _typeRegistry.Dispose(); + return; } - private static void SetupDependencies() + try { - _typeRegistry = new UnityRegistry("EOLib.IO"); - _typeRegistry.RegisterDiscoveredTypes(); + ProcessFiles(srcFilePath, dstFilePath, singleFileProcess); + } + catch (Exception ex) + { + Console.WriteLine(); + + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("Exception was thrown: "); + Console.ForegroundColor = ConsoleColor.Gray; + Console.WriteLine(ex.Message); - _pubProvider = _typeRegistry.Resolve(); - _mapFileProvider = _typeRegistry.Resolve(); + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("\nCall stack: \n"); + Console.ForegroundColor = ConsoleColor.Gray; + Console.WriteLine(ex.StackTrace); } - private static void ProcessFiles(string src, string dst, bool singleFile) - { - var mapFileLoadActions = _typeRegistry.Resolve(); - var mapFileSaveService = _typeRegistry.Resolve(); + _typeRegistry.Dispose(); + } - var inFiles = singleFile ? new[] { src } : Directory.GetFiles(src, "*.emf"); + private static void SetupDependencies() + { + _typeRegistry = new UnityRegistry("EOLib.IO"); + _typeRegistry.RegisterDiscoveredTypes(); + + _pubProvider = _typeRegistry.Resolve(); + _mapFileProvider = _typeRegistry.Resolve(); + } - for (int mapIndex = 0; mapIndex < inFiles.Length; ++mapIndex) + private static void ProcessFiles(string src, string dst, bool singleFile) + { + var mapFileLoadActions = _typeRegistry.Resolve(); + var mapFileSaveService = _typeRegistry.Resolve(); + + var inFiles = singleFile ? new[] { src } : Directory.GetFiles(src, "*.emf"); + + for (int mapIndex = 0; mapIndex < inFiles.Length; ++mapIndex) + { + var mapID = new MapPathToIDConverter().ConvertFromPathToID(inFiles[mapIndex]); + + mapFileLoadActions.LoadMapFileByName(inFiles[mapIndex]); + var mapFile = _mapFileProvider.MapFiles[mapID]; + + var changesMade = false; + + //todo: find way to store actual input data, since invalid tiles/warps will be auto-removed + //for (int i = mapFile.TileRows.Count - 1; i >= 0; --i) + //{ + // var tr = mapFile.TileRows[i]; + // for (int j = tr.EntityItems.Count - 1; j >= 0; --j) + // { + // var tt = tr.EntityItems[j]; + // if (tt.X > mapFile.Properties.Width || tr.Y > mapFile.Properties.Height) + // { + // Console.WriteLine("[MAP {0}] Tile {1}x{2} ({3}) is out of map bounds. Removing.", + // mapID, tt.X, tr.Y, Enum.GetName(typeof(TileSpec), tt.Value)); + // mapFile.RemoveTileAt(tr.Y, tt.X); + // changesMade = true; + // } + // } + //} + + //for (int i = mapFile.WarpRows.Count - 1; i >= 0; --i) + //{ + // var tr = mapFile.WarpRows[i]; + // for (int j = tr.EntityItems.Count - 1; j >= 0; --j) + // { + // var tt = tr.EntityItems[j]; + // if (tt.X > mapFile.Properties.Width || tr.Y > mapFile.Properties.Height) + // { + // Console.WriteLine("[MAP {0}] Warp {1}x{2} is out of map bounds. Removing.", mapID, tt.X, tr.Y); + // mapFile.RemoveWarpAt(tr.Y, tt.X); + // changesMade = true; + // } + // } + //} + + for (int ndx = mapFile.NPCSpawns.Count - 1; ndx >= 0; --ndx) { - var mapID = new MapPathToIDConverter().ConvertFromPathToID(inFiles[mapIndex]); - - mapFileLoadActions.LoadMapFileByName(inFiles[mapIndex]); - var mapFile = _mapFileProvider.MapFiles[mapID]; - - var changesMade = false; - - //todo: find way to store actual input data, since invalid tiles/warps will be auto-removed - //for (int i = mapFile.TileRows.Count - 1; i >= 0; --i) - //{ - // var tr = mapFile.TileRows[i]; - // for (int j = tr.EntityItems.Count - 1; j >= 0; --j) - // { - // var tt = tr.EntityItems[j]; - // if (tt.X > mapFile.Properties.Width || tr.Y > mapFile.Properties.Height) - // { - // Console.WriteLine("[MAP {0}] Tile {1}x{2} ({3}) is out of map bounds. Removing.", - // mapID, tt.X, tr.Y, Enum.GetName(typeof(TileSpec), tt.Value)); - // mapFile.RemoveTileAt(tr.Y, tt.X); - // changesMade = true; - // } - // } - //} - - //for (int i = mapFile.WarpRows.Count - 1; i >= 0; --i) - //{ - // var tr = mapFile.WarpRows[i]; - // for (int j = tr.EntityItems.Count - 1; j >= 0; --j) - // { - // var tt = tr.EntityItems[j]; - // if (tt.X > mapFile.Properties.Width || tr.Y > mapFile.Properties.Height) - // { - // Console.WriteLine("[MAP {0}] Warp {1}x{2} is out of map bounds. Removing.", mapID, tt.X, tr.Y); - // mapFile.RemoveWarpAt(tr.Y, tt.X); - // changesMade = true; - // } - // } - //} - - for (int ndx = mapFile.NPCSpawns.Count - 1; ndx >= 0; --ndx) + var npcSpawn = mapFile.NPCSpawns[ndx]; + var npcRec = _pubProvider.ENFFile[npcSpawn.ID]; + if (npcSpawn.ID > _pubProvider.ENFFile.Length || npcRec == null) { - var npcSpawn = mapFile.NPCSpawns[ndx]; - var npcRec = _pubProvider.ENFFile[npcSpawn.ID]; - if (npcSpawn.ID > _pubProvider.ENFFile.Length || npcRec == null) - { - Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} uses non-existent NPC #{3}. Removing.", mapID, npcSpawn.X, npcSpawn.Y, npcSpawn.ID); - mapFile = mapFile.RemoveNPCSpawn(npcSpawn); - changesMade = true; - continue; - } + Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} uses non-existent NPC #{3}. Removing.", mapID, npcSpawn.X, npcSpawn.Y, npcSpawn.ID); + mapFile = mapFile.RemoveNPCSpawn(npcSpawn); + changesMade = true; + continue; + } - if (npcSpawn.X > mapFile.Properties.Width || npcSpawn.Y > mapFile.Properties.Height) - { - Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} ({3}) is out of map bounds. Removing.", mapID, npcSpawn.X, npcSpawn.Y, npcRec.Name); - mapFile = mapFile.RemoveNPCSpawn(npcSpawn); - changesMade = true; - continue; - } + if (npcSpawn.X > mapFile.Properties.Width || npcSpawn.Y > mapFile.Properties.Height) + { + Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} ({3}) is out of map bounds. Removing.", mapID, npcSpawn.X, npcSpawn.Y, npcRec.Name); + mapFile = mapFile.RemoveNPCSpawn(npcSpawn); + changesMade = true; + continue; + } - if (!TileIsValidNPCSpawnPoint(mapFile, npcSpawn.X, npcSpawn.Y)) + if (!TileIsValidNPCSpawnPoint(mapFile, npcSpawn.X, npcSpawn.Y)) + { + Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} ({3}) is invalid...", mapID, npcSpawn.X, npcSpawn.Y, npcRec.Name); + var found = false; + for (int row = npcSpawn.Y - 2; row < npcSpawn.Y + 2; ++row) { - Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} ({3}) is invalid...", mapID, npcSpawn.X, npcSpawn.Y, npcRec.Name); - var found = false; - for (int row = npcSpawn.Y - 2; row < npcSpawn.Y + 2; ++row) + if (found) break; + for (int col = npcSpawn.X - 2; col < npcSpawn.X + 2; ++col) { if (found) break; - for (int col = npcSpawn.X - 2; col < npcSpawn.X + 2; ++col) + if (TileIsValidNPCSpawnPoint(mapFile, col, row)) { - if (found) break; - if (TileIsValidNPCSpawnPoint(mapFile, col, row)) - { - Console.WriteLine("[MAP {0}] Found valid spawn point. Continuing.", mapID); - found = true; - } + Console.WriteLine("[MAP {0}] Found valid spawn point. Continuing.", mapID); + found = true; } } - - if (!found) - { - Console.WriteLine("[MAP {0}] NPC couldn't spawn anywhere valid! Removing.", mapID); - mapFile = mapFile.RemoveNPCSpawn(npcSpawn); - changesMade = true; - } } - } - for (int ndx = mapFile.Chests.Count - 1; ndx >= 0; --ndx) - { - var chestSpawn = mapFile.Chests[ndx]; - var rec = _pubProvider.EIFFile[chestSpawn.ItemID]; - if (chestSpawn.ItemID > _pubProvider.EIFFile.Length || rec == null) + if (!found) { - Console.WriteLine("[MAP {0}] Chest Spawn {1}x{2} uses non-existent Item #{3}. Removing.", mapID, chestSpawn.X, chestSpawn.Y, chestSpawn.ItemID); - mapFile = mapFile.RemoveChestSpawn(chestSpawn); - changesMade = true; - continue; - } - - if (chestSpawn.X > mapFile.Properties.Width || - chestSpawn.Y > mapFile.Properties.Height || - mapFile.Tiles[chestSpawn.Y, chestSpawn.X] != TileSpec.Chest) - { - Console.WriteLine("[MAP {0}] Chest Spawn {1}x{2} points to a non-chest. Removing.", mapID, chestSpawn.X, chestSpawn.Y); - mapFile = mapFile.RemoveChestSpawn(chestSpawn); + Console.WriteLine("[MAP {0}] NPC couldn't spawn anywhere valid! Removing.", mapID); + mapFile = mapFile.RemoveNPCSpawn(npcSpawn); changesMade = true; } } + } - if (!changesMade) + for (int ndx = mapFile.Chests.Count - 1; ndx >= 0; --ndx) + { + var chestSpawn = mapFile.Chests[ndx]; + var rec = _pubProvider.EIFFile[chestSpawn.ItemID]; + if (chestSpawn.ItemID > _pubProvider.EIFFile.Length || rec == null) { - Console.WriteLine("Map {0} processed without any errors. No changes made.", mapID); + Console.WriteLine("[MAP {0}] Chest Spawn {1}x{2} uses non-existent Item #{3}. Removing.", mapID, chestSpawn.X, chestSpawn.Y, chestSpawn.ItemID); + mapFile = mapFile.RemoveChestSpawn(chestSpawn); + changesMade = true; continue; } - if (mapIndex == 0 && singleFile && inFiles.Length == 1) + if (chestSpawn.X > mapFile.Properties.Width || + chestSpawn.Y > mapFile.Properties.Height || + mapFile.Tiles[chestSpawn.Y, chestSpawn.X] != TileSpec.Chest) { - mapFileSaveService.SaveFile(dst, mapFile); - break; + Console.WriteLine("[MAP {0}] Chest Spawn {1}x{2} points to a non-chest. Removing.", mapID, chestSpawn.X, chestSpawn.Y); + mapFile = mapFile.RemoveChestSpawn(chestSpawn); + changesMade = true; } - - mapFileSaveService.SaveFile( - Path.Combine(dst, $"{mapID,5:D5}.emf"), - mapFile); } - } - private static bool TileIsValidNPCSpawnPoint(IMapFile EMF, int x, int y) - { - if (EMF.Warps[y, x] != null) - return false; + if (!changesMade) + { + Console.WriteLine("Map {0} processed without any errors. No changes made.", mapID); + continue; + } - switch (EMF.Tiles[y, x]) + if (mapIndex == 0 && singleFile && inFiles.Length == 1) { - case TileSpec.Wall: - case TileSpec.ChairDown: - case TileSpec.ChairLeft: - case TileSpec.ChairRight: - case TileSpec.ChairUp: - case TileSpec.ChairDownRight: - case TileSpec.ChairUpLeft: - case TileSpec.ChairAll: - case TileSpec.Chest: - case TileSpec.BankVault: - case TileSpec.NPCBoundary: - case TileSpec.MapEdge: - case TileSpec.Board1: - case TileSpec.Board2: - case TileSpec.Board3: - case TileSpec.Board4: - case TileSpec.Board5: - case TileSpec.Board6: - case TileSpec.Board7: - case TileSpec.Board8: - case TileSpec.Jukebox: - return false; + mapFileSaveService.SaveFile(dst, mapFile); + break; } - return true; + mapFileSaveService.SaveFile( + Path.Combine(dst, $"{mapID,5:D5}.emf"), + mapFile); + } + } + + private static bool TileIsValidNPCSpawnPoint(IMapFile EMF, int x, int y) + { + if (EMF.Warps[y, x] != null) + return false; + + switch (EMF.Tiles[y, x]) + { + case TileSpec.Wall: + case TileSpec.ChairDown: + case TileSpec.ChairLeft: + case TileSpec.ChairRight: + case TileSpec.ChairUp: + case TileSpec.ChairDownRight: + case TileSpec.ChairUpLeft: + case TileSpec.ChairAll: + case TileSpec.Chest: + case TileSpec.BankVault: + case TileSpec.NPCBoundary: + case TileSpec.MapEdge: + case TileSpec.Board1: + case TileSpec.Board2: + case TileSpec.Board3: + case TileSpec.Board4: + case TileSpec.Board5: + case TileSpec.Board6: + case TileSpec.Board7: + case TileSpec.Board8: + case TileSpec.Jukebox: + return false; } + + return true; } } \ No newline at end of file diff --git a/BatchPub/Program.cs b/BatchPub/Program.cs index 78957a790..13ad94191 100644 --- a/BatchPub/Program.cs +++ b/BatchPub/Program.cs @@ -1,20 +1,19 @@ using System; using System.Windows.Forms; -namespace BatchPub +namespace BatchPub; + +static class Program { - static class Program + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - Application.EnableVisualStyles(); - Application.SetHighDpiMode(HighDpiMode.SystemAware); - Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new frmMain()); - } + Application.EnableVisualStyles(); + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new frmMain()); } } \ No newline at end of file diff --git a/BatchPub/frmMain.cs b/BatchPub/frmMain.cs index da545cc36..4f47ddec2 100644 --- a/BatchPub/frmMain.cs +++ b/BatchPub/frmMain.cs @@ -9,447 +9,446 @@ using System.Text.RegularExpressions; using System.Windows.Forms; -namespace BatchPub +namespace BatchPub; + +public partial class frmMain : Form { - public partial class frmMain : Form + private IPubFile eif; + private string _fname; + private bool changes; + + private enum CompareOperator { - private IPubFile eif; - private string _fname; - private bool changes; + EQ, + GT, + LT, + GTE, + LTE, + NE, + REGEX + } - private enum CompareOperator - { - EQ, - GT, - LT, - GTE, - LTE, - NE, - REGEX - } + public frmMain() + { + InitializeComponent(); + InitializeMore(); + } - public frmMain() - { - InitializeComponent(); - InitializeMore(); - } + private void btnReset_Click(object sender, EventArgs e) + { + SuspendLayout(); + Controls.Clear(); + ResumeLayout(); + InitializeComponent(); + InitializeMore(); + eif = null; + } - private void btnReset_Click(object sender, EventArgs e) + private void InitializeMore() + { + cmbStepTwoField.Items.Clear(); + cmbStepThreeField.Items.Clear(); + + var eifType = typeof(EIFRecord); + foreach (System.Reflection.PropertyInfo prop in eifType.GetProperties()) { - SuspendLayout(); - Controls.Clear(); - ResumeLayout(); - InitializeComponent(); - InitializeMore(); - eif = null; + cmbStepTwoField.Items.Add(new PropInfo(prop)); + cmbStepThreeField.Items.Add(new PropInfo(prop)); } + } - private void InitializeMore() + private void btnProcess_Click(object sender, EventArgs e) + { + //process everything + System.Reflection.PropertyInfo pi = (cmbStepTwoField.SelectedItem as PropInfo).PropertyInfo; + object newValue; + switch ((cmbStepTwoField.SelectedItem as PropInfo).PropertyInfo.Name) { - cmbStepTwoField.Items.Clear(); - cmbStepThreeField.Items.Clear(); + case "Type": + case "SubType": + case "Special": + case "Size": + newValue = cmbStepTwoValue.SelectedIndex; + break; + case "Name": + newValue = txtStepTwoValue.Text; + break; + default: + int dummy; + newValue = txtStepTwoValue.Text.ToString(); + if (!int.TryParse(newValue.ToString(), out dummy)) + { + MessageBox.Show("Only integer values are supported for the value field in step two."); + return; + } + newValue = dummy; + break; + } - var eifType = typeof(EIFRecord); - foreach (System.Reflection.PropertyInfo prop in eifType.GetProperties()) + if (!chkFilterOn.Checked) + { //process the change for EVERY item record. save changes immediately. + if (MessageBox.Show( + "This change will be processed for every item immediately. The change is irreversible. Are you sure you want to continue? You may specify a filter by checking the filter option.", "No filter selected", + MessageBoxButtons.YesNo, + MessageBoxIcon.Exclamation) == DialogResult.No + ) { - cmbStepTwoField.Items.Add(new PropInfo(prop)); - cmbStepThreeField.Items.Add(new PropInfo(prop)); + return; } - } - private void btnProcess_Click(object sender, EventArgs e) - { - //process everything - System.Reflection.PropertyInfo pi = (cmbStepTwoField.SelectedItem as PropInfo).PropertyInfo; - object newValue; - switch ((cmbStepTwoField.SelectedItem as PropInfo).PropertyInfo.Name) + rtfOutput.Text += "Processing change: set " + pi.Name + "(" + pi.PropertyType.ToString() + ")=" + newValue.ToString() + " for all items..."; + foreach (var rec in eif) { - case "Type": - case "SubType": - case "Special": - case "Size": - newValue = cmbStepTwoValue.SelectedIndex; - break; - case "Name": - newValue = txtStepTwoValue.Text; - break; - default: - int dummy; - newValue = txtStepTwoValue.Text.ToString(); - if (!int.TryParse(newValue.ToString(), out dummy)) - { - MessageBox.Show("Only integer values are supported for the value field in step two."); - return; - } - newValue = dummy; - break; + System.Reflection.PropertyInfo prop = rec.GetType().GetProperty(pi.Name); + prop.SetValue(rec, Convert.ChangeType(newValue, pi.PropertyType)); } - if (!chkFilterOn.Checked) - { //process the change for EVERY item record. save changes immediately. - if (MessageBox.Show( - "This change will be processed for every item immediately. The change is irreversible. Are you sure you want to continue? You may specify a filter by checking the filter option.", "No filter selected", - MessageBoxButtons.YesNo, - MessageBoxIcon.Exclamation) == DialogResult.No - ) + rtfOutput.Text += "done.\n\n"; + } + else + { + object compareValue; + CompareOperator op; + try + { + op = (CompareOperator)cmbCompareType.SelectedIndex; + if (op == CompareOperator.REGEX && cmbCompareValue.Enabled) { + MessageBox.Show("You can't use a regex to parse enumerated types"); return; } - - rtfOutput.Text += "Processing change: set " + pi.Name + "(" + pi.PropertyType.ToString() + ")=" + newValue.ToString() + " for all items..."; - foreach (var rec in eif) - { - System.Reflection.PropertyInfo prop = rec.GetType().GetProperty(pi.Name); - prop.SetValue(rec, Convert.ChangeType(newValue, pi.PropertyType)); - } - - rtfOutput.Text += "done.\n\n"; } - else + catch + { + MessageBox.Show("Invalid comparison operator specified."); + return; + } + + Regex comparer = null; + if (op == CompareOperator.REGEX) { - object compareValue; - CompareOperator op; try { - op = (CompareOperator)cmbCompareType.SelectedIndex; - if (op == CompareOperator.REGEX && cmbCompareValue.Enabled) - { - MessageBox.Show("You can't use a regex to parse enumerated types"); - return; - } + compareValue = txtCompareValue.Text; + comparer = new Regex(compareValue.ToString()); } - catch + catch (Exception ex) { - MessageBox.Show("Invalid comparison operator specified."); + MessageBox.Show("Unable to parse regular expression:\n " + ex.Message, "Error!"); return; } - - Regex comparer = null; - if (op == CompareOperator.REGEX) + } + else + { + switch ((cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo.Name) { - try - { + case "Type": + compareValue = (ItemType)cmbCompareValue.SelectedIndex; + break; + case "SubType": + compareValue = (ItemSubType)cmbCompareValue.SelectedIndex; + break; + case "Special": + compareValue = (ItemSpecial)cmbCompareValue.SelectedIndex; + break; + case "Size": + compareValue = (ItemSize)cmbCompareValue.SelectedIndex; + break; + case "Name": compareValue = txtCompareValue.Text; - comparer = new Regex(compareValue.ToString()); - } - catch (Exception ex) - { - MessageBox.Show("Unable to parse regular expression:\n " + ex.Message, "Error!"); - return; - } + break; + default: + compareValue = txtCompareValue.Text; + int dummy; + if (!int.TryParse(compareValue.ToString(), out dummy)) + { + MessageBox.Show("Only integer values are allowed for this comparison type.", "Error parsing"); + return; + } + compareValue = dummy; + break; } - else + } + + List filtered = eif.Where(record => { - switch ((cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo.Name) + EIFRecord rec = (EIFRecord)record; + if (rec == null || rec.ID == 0) return false; + + System.Reflection.PropertyInfo comparePropertyInfo = (cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo; + System.Reflection.PropertyInfo currentInfo = rec.GetType().GetProperty(comparePropertyInfo.Name); + switch (op) { - case "Type": - compareValue = (ItemType)cmbCompareValue.SelectedIndex; - break; - case "SubType": - compareValue = (ItemSubType)cmbCompareValue.SelectedIndex; - break; - case "Special": - compareValue = (ItemSpecial)cmbCompareValue.SelectedIndex; - break; - case "Size": - compareValue = (ItemSize)cmbCompareValue.SelectedIndex; - break; - case "Name": - compareValue = txtCompareValue.Text; - break; + case CompareOperator.EQ: + return compareValue.ToString() == currentInfo.GetValue(rec).ToString(); + case CompareOperator.GT: + return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) > 0; + case CompareOperator.GTE: + return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) >= 0; + case CompareOperator.LT: + return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) < 0; + case CompareOperator.LTE: + return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) <= 0; + case CompareOperator.NE: + return compareValue.ToString() != currentInfo.GetValue(rec).ToString(); + case CompareOperator.REGEX: + object curValAsString = currentInfo.GetValue(rec); + if (curValAsString == null) + return false; + + return comparer.IsMatch(curValAsString.ToString()); default: - compareValue = txtCompareValue.Text; - int dummy; - if (!int.TryParse(compareValue.ToString(), out dummy)) - { - MessageBox.Show("Only integer values are allowed for this comparison type.", "Error parsing"); - return; - } - compareValue = dummy; - break; + return false; } - } + }).ToList(); - List filtered = eif.Where(record => - { - EIFRecord rec = (EIFRecord)record; - if (rec == null || rec.ID == 0) return false; + filtered.ForEach(rec => + { + if (!changes) + changes = true; + + int index = rec.ID - 1; + + rtfOutput.Text += "Found matching item " + rec.Name + " (" + rec.ID + ")\n"; + rtfOutput.Text += " replacing " + pi.Name + " (currently " + pi.GetValue(rec).ToString() + ") with new value " + newValue.ToString() + "\n"; + rtfOutput.SelectionStart = rtfOutput.TextLength; + rtfOutput.ScrollToCaret(); + + object setter; + //enums are special: convert them to object + if (pi.PropertyType == typeof(ItemType) || + pi.PropertyType == typeof(ItemSubType) || + pi.PropertyType == typeof(ItemSpecial) || + pi.PropertyType == typeof(ItemSize)) + setter = Convert.ChangeType(Enum.ToObject(pi.PropertyType, newValue), pi.PropertyType); + else + setter = Convert.ChangeType(newValue, pi.PropertyType); - System.Reflection.PropertyInfo comparePropertyInfo = (cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo; - System.Reflection.PropertyInfo currentInfo = rec.GetType().GetProperty(comparePropertyInfo.Name); - switch (op) - { - case CompareOperator.EQ: - return compareValue.ToString() == currentInfo.GetValue(rec).ToString(); - case CompareOperator.GT: - return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) > 0; - case CompareOperator.GTE: - return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) >= 0; - case CompareOperator.LT: - return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) < 0; - case CompareOperator.LTE: - return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) <= 0; - case CompareOperator.NE: - return compareValue.ToString() != currentInfo.GetValue(rec).ToString(); - case CompareOperator.REGEX: - object curValAsString = currentInfo.GetValue(rec); - if (curValAsString == null) - return false; - - return comparer.IsMatch(curValAsString.ToString()); - default: - return false; - } - }).ToList(); + pi.SetValue(rec, setter); - filtered.ForEach(rec => - { - if (!changes) - changes = true; - - int index = rec.ID - 1; - - rtfOutput.Text += "Found matching item " + rec.Name + " (" + rec.ID + ")\n"; - rtfOutput.Text += " replacing " + pi.Name + " (currently " + pi.GetValue(rec).ToString() + ") with new value " + newValue.ToString() + "\n"; - rtfOutput.SelectionStart = rtfOutput.TextLength; - rtfOutput.ScrollToCaret(); - - object setter; - //enums are special: convert them to object - if (pi.PropertyType == typeof(ItemType) || - pi.PropertyType == typeof(ItemSubType) || - pi.PropertyType == typeof(ItemSpecial) || - pi.PropertyType == typeof(ItemSize)) - setter = Convert.ChangeType(Enum.ToObject(pi.PropertyType, newValue), pi.PropertyType); - else - setter = Convert.ChangeType(newValue, pi.PropertyType); - - pi.SetValue(rec, setter); - - //eif.ReplaceRecordAt(index, rec); //todo: way to modify pub files - }); - } + //eif.ReplaceRecordAt(index, rec); //todo: way to modify pub files + }); } + } - private void btnExit_Click(object sender, EventArgs e) - { - this.Close(); - } + private void btnExit_Click(object sender, EventArgs e) + { + this.Close(); + } - private void btnBrowse_Click(object sender, EventArgs e) + private void btnBrowse_Click(object sender, EventArgs e) + { + using (OpenFileDialog ofd = new OpenFileDialog()) { - using (OpenFileDialog ofd = new OpenFileDialog()) - { - ofd.CheckFileExists = true; - ofd.CheckPathExists = true; - ofd.AddExtension = true; - ofd.Filter = "Endless Online Item Data File|*.eif"; - ofd.Multiselect = false; - ofd.InitialDirectory = Application.ExecutablePath; - - if (ofd.ShowDialog() == DialogResult.Cancel) - return; + ofd.CheckFileExists = true; + ofd.CheckPathExists = true; + ofd.AddExtension = true; + ofd.Filter = "Endless Online Item Data File|*.eif"; + ofd.Multiselect = false; + ofd.InitialDirectory = Application.ExecutablePath; + + if (ofd.ShowDialog() == DialogResult.Cancel) + return; - txtFileName.Text = ofd.FileName; - } + txtFileName.Text = ofd.FileName; } + } - private void btnLoad_Click(object sender, EventArgs e) + private void btnLoad_Click(object sender, EventArgs e) + { + var deserializer = new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); + _fname = ""; + try { - var deserializer = new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); - _fname = ""; - try - { - var fileBytes = File.ReadAllBytes(_fname = string.IsNullOrEmpty(txtFileName.Text) ? string.Format(PubFileNameConstants.EIFFormat, 1) : txtFileName.Text); - eif = deserializer.DeserializeFromByteArray(1, fileBytes, () => new EIFFile()); - lblFileName.Text = "Loaded file: " + _fname; - grpStepTwo.Enabled = true; - btnReset.Enabled = true; - } - catch (Exception ex) - { - eif = null; - MessageBox.Show("Error loading " + _fname + ":\n" + ex.Message, "Error!"); - } + var fileBytes = File.ReadAllBytes(_fname = string.IsNullOrEmpty(txtFileName.Text) ? string.Format(PubFileNameConstants.EIFFormat, 1) : txtFileName.Text); + eif = deserializer.DeserializeFromByteArray(1, fileBytes, () => new EIFFile()); + lblFileName.Text = "Loaded file: " + _fname; + grpStepTwo.Enabled = true; + btnReset.Enabled = true; } - - private void cmbStepTwoField_SelectedIndexChanged(object sender, EventArgs e) + catch (Exception ex) { - cmbStepTwoValue.Items.Clear(); - txtStepTwoValue.Enabled = false; - cmbStepTwoValue.Enabled = true; - switch ((cmbStepTwoField.SelectedItem as PropInfo).DisplayName) - { - case "Type": - foreach (string val in Enum.GetNames(typeof(ItemType))) - cmbStepTwoValue.Items.Add(val); - break; - case "SubType": - foreach (string val in Enum.GetNames(typeof(ItemSubType))) - cmbStepTwoValue.Items.Add(val); - break; - case "Special": - foreach (string val in Enum.GetNames(typeof(ItemSpecial))) - cmbStepTwoValue.Items.Add(val); - break; - case "Size": - foreach (string val in Enum.GetNames(typeof(ItemSize))) - cmbStepTwoValue.Items.Add(val); - break; - default: - txtStepTwoValue.Enabled = true; - cmbStepTwoValue.Enabled = false; - break; - } + eif = null; + MessageBox.Show("Error loading " + _fname + ":\n" + ex.Message, "Error!"); } + } - private void LeaveStepTwo(object sender, EventArgs e) + private void cmbStepTwoField_SelectedIndexChanged(object sender, EventArgs e) + { + cmbStepTwoValue.Items.Clear(); + txtStepTwoValue.Enabled = false; + cmbStepTwoValue.Enabled = true; + switch ((cmbStepTwoField.SelectedItem as PropInfo).DisplayName) { - if (cmbStepTwoField.SelectedIndex >= 0 && - ((txtStepTwoValue.Enabled && txtStepTwoValue.TextLength > 0) || (cmbStepTwoValue.Enabled && cmbStepTwoValue.SelectedIndex >= 0)) - ) - { - grpStepThree.Enabled = true; - btnProcess.Enabled = true; - } - else - { - grpStepThree.Enabled = false; - btnProcess.Enabled = false; - } + case "Type": + foreach (string val in Enum.GetNames(typeof(ItemType))) + cmbStepTwoValue.Items.Add(val); + break; + case "SubType": + foreach (string val in Enum.GetNames(typeof(ItemSubType))) + cmbStepTwoValue.Items.Add(val); + break; + case "Special": + foreach (string val in Enum.GetNames(typeof(ItemSpecial))) + cmbStepTwoValue.Items.Add(val); + break; + case "Size": + foreach (string val in Enum.GetNames(typeof(ItemSize))) + cmbStepTwoValue.Items.Add(val); + break; + default: + txtStepTwoValue.Enabled = true; + cmbStepTwoValue.Enabled = false; + break; } + } - private void chkFilterOn_CheckedChanged(object sender, EventArgs e) + private void LeaveStepTwo(object sender, EventArgs e) + { + if (cmbStepTwoField.SelectedIndex >= 0 && + ((txtStepTwoValue.Enabled && txtStepTwoValue.TextLength > 0) || (cmbStepTwoValue.Enabled && cmbStepTwoValue.SelectedIndex >= 0)) + ) { - if (chkFilterOn.Checked) - { - cmbStepThreeField.Enabled = true; - txtCompareValue.Enabled = true; - cmbCompareType.Enabled = true; - cmbCompareType.SelectedIndex = 0; - cmbStepThreeField.SelectedIndex = 0; - } - else - { - cmbStepThreeField.Enabled = false; - txtCompareValue.Enabled = false; - cmbCompareType.Enabled = false; - cmbCompareType.SelectedIndex = -1; - cmbStepThreeField.SelectedIndex = -1; - } + grpStepThree.Enabled = true; + btnProcess.Enabled = true; } - - private void frmMain_Load(object sender, EventArgs e) + else { - MessageBox.Show("It is highly recommended that you back up your pub files before using this utility. Changes are irreversable.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning); + grpStepThree.Enabled = false; + btnProcess.Enabled = false; } + } - private void cmbStepThreeField_SelectedIndexChanged(object sender, EventArgs e) + private void chkFilterOn_CheckedChanged(object sender, EventArgs e) + { + if (chkFilterOn.Checked) + { + cmbStepThreeField.Enabled = true; + txtCompareValue.Enabled = true; + cmbCompareType.Enabled = true; + cmbCompareType.SelectedIndex = 0; + cmbStepThreeField.SelectedIndex = 0; + } + else { - SuspendLayout(); - cmbCompareValue.Items.Clear(); - cmbCompareValue.Enabled = true; - cmbCompareValue.Visible = true; + cmbStepThreeField.Enabled = false; txtCompareValue.Enabled = false; - txtCompareValue.Visible = false; + cmbCompareType.Enabled = false; + cmbCompareType.SelectedIndex = -1; + cmbStepThreeField.SelectedIndex = -1; + } + } - if (cmbStepThreeField.SelectedItem == null) - { - ResumeLayout(); - return; - } + private void frmMain_Load(object sender, EventArgs e) + { + MessageBox.Show("It is highly recommended that you back up your pub files before using this utility. Changes are irreversable.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } - switch ((cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo.Name) - { - case "Type": - foreach (string val in Enum.GetNames(typeof(ItemType))) - cmbCompareValue.Items.Add(val); - break; - case "SubType": - foreach (string val in Enum.GetNames(typeof(ItemSubType))) - cmbCompareValue.Items.Add(val); - break; - case "Special": - foreach (string val in Enum.GetNames(typeof(ItemSpecial))) - cmbCompareValue.Items.Add(val); - break; - case "Size": - foreach (string val in Enum.GetNames(typeof(ItemSize))) - cmbCompareValue.Items.Add(val); - break; - default: - cmbCompareValue.Enabled = false; - cmbCompareValue.Visible = false; - txtCompareValue.Enabled = true; - txtCompareValue.Visible = true; - break; - } + private void cmbStepThreeField_SelectedIndexChanged(object sender, EventArgs e) + { + SuspendLayout(); + cmbCompareValue.Items.Clear(); + cmbCompareValue.Enabled = true; + cmbCompareValue.Visible = true; + txtCompareValue.Enabled = false; + txtCompareValue.Visible = false; + + if (cmbStepThreeField.SelectedItem == null) + { ResumeLayout(); + return; } - private void rtfOutput_TextChanged(object sender, EventArgs e) + switch ((cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo.Name) { - if (rtfOutput.TextLength > 0) - btnClear.Enabled = true; - else - btnClear.Enabled = false; + case "Type": + foreach (string val in Enum.GetNames(typeof(ItemType))) + cmbCompareValue.Items.Add(val); + break; + case "SubType": + foreach (string val in Enum.GetNames(typeof(ItemSubType))) + cmbCompareValue.Items.Add(val); + break; + case "Special": + foreach (string val in Enum.GetNames(typeof(ItemSpecial))) + cmbCompareValue.Items.Add(val); + break; + case "Size": + foreach (string val in Enum.GetNames(typeof(ItemSize))) + cmbCompareValue.Items.Add(val); + break; + default: + cmbCompareValue.Enabled = false; + cmbCompareValue.Visible = false; + txtCompareValue.Enabled = true; + txtCompareValue.Visible = true; + break; } + ResumeLayout(); + } - private void btnClear_Click(object sender, EventArgs e) - { - rtfOutput.Text = ""; - } + private void rtfOutput_TextChanged(object sender, EventArgs e) + { + if (rtfOutput.TextLength > 0) + btnClear.Enabled = true; + else + btnClear.Enabled = false; + } - private void btnSave_Click(object sender, EventArgs e) - { - if (changes) - { - DialogResult dr = MessageBox.Show("WARNING: This will update the pub file you currently have open with any batch changes that have been made. Confirm that this behavior is desired.", "Confirm changes?", MessageBoxButtons.YesNo); - if (dr == DialogResult.No) - return; + private void btnClear_Click(object sender, EventArgs e) + { + rtfOutput.Text = ""; + } - //var version = eif.Version; - //if (eif.Version == 0) - //{ - // version = 1; - // MessageBox.Show("Saving using this tool will update the version of the EIF file."); - //} + private void btnSave_Click(object sender, EventArgs e) + { + if (changes) + { + DialogResult dr = MessageBox.Show("WARNING: This will update the pub file you currently have open with any batch changes that have been made. Confirm that this behavior is desired.", "Confirm changes?", MessageBoxButtons.YesNo); + if (dr == DialogResult.No) + return; - try - { - var serializer = new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); - var bytes = serializer.SerializeToByteArray(eif); - } - catch (Exception ex) - { - MessageBox.Show("Error saving changes to the file:\n" + ex.Message); - return; - } + //var version = eif.Version; + //if (eif.Version == 0) + //{ + // version = 1; + // MessageBox.Show("Saving using this tool will update the version of the EIF file."); + //} - MessageBox.Show("Changes saved."); + try + { + var serializer = new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); + var bytes = serializer.SerializeToByteArray(eif); } - else + catch (Exception ex) { - MessageBox.Show("Changes to the pub file were not detected. No changes have been processed."); + MessageBox.Show("Error saving changes to the file:\n" + ex.Message); + return; } + + MessageBox.Show("Changes saved."); + } + else + { + MessageBox.Show("Changes to the pub file were not detected. No changes have been processed."); } } +} - public class PropInfo - { - public System.Reflection.PropertyInfo PropertyInfo { get; set; } - public string DisplayName => PropertyInfo.Name; +public class PropInfo +{ + public System.Reflection.PropertyInfo PropertyInfo { get; set; } + public string DisplayName => PropertyInfo.Name; - public PropInfo(System.Reflection.PropertyInfo info) - { - if (info == null) - throw new ArgumentNullException("Info parameter may not be null."); - PropertyInfo = info; - } + public PropInfo(System.Reflection.PropertyInfo info) + { + if (info == null) + throw new ArgumentNullException("Info parameter may not be null."); + PropertyInfo = info; + } - public override string ToString() - { - return DisplayName; - } + public override string ToString() + { + return DisplayName; } } \ No newline at end of file diff --git a/EOBot/ArgumentsParser.cs b/EOBot/ArgumentsParser.cs index a0a0c7a6a..aebb17faf 100644 --- a/EOBot/ArgumentsParser.cs +++ b/EOBot/ArgumentsParser.cs @@ -3,214 +3,213 @@ using System.IO; using System.Linq; -namespace EOBot +namespace EOBot; + +public enum ArgsError { - public enum ArgsError - { - NoError, - BadFormat, - WrongNumberOfArgs, - InvalidPort, - InvalidNumberOfBots, - TooManyBots, - NotEnoughBots, - InvalidSimultaneousNumberOfBots, - InvalidWaitFlag, - InvalidInitDelay, - InvalidPath, - InvalidScriptArgs, - AutoConnectRequired - } + NoError, + BadFormat, + WrongNumberOfArgs, + InvalidPort, + InvalidNumberOfBots, + TooManyBots, + NotEnoughBots, + InvalidSimultaneousNumberOfBots, + InvalidWaitFlag, + InvalidInitDelay, + InvalidPath, + InvalidScriptArgs, + AutoConnectRequired +} + +public class ArgumentsParser +{ + public ArgsError Error { get; private set; } - public class ArgumentsParser - { - public ArgsError Error { get; private set; } + public string ScriptFile { get; private set; } - public string ScriptFile { get; private set; } + public string Host { get; private set; } + public ushort Port { get; private set; } - public string Host { get; private set; } - public ushort Port { get; private set; } + public int NumBots { get; private set; } + public int SimultaneousBots { get; private set; } - public int NumBots { get; private set; } - public int SimultaneousBots { get; private set; } + public int InitDelay { get; private set; } - public int InitDelay { get; private set; } + public string Account { get; private set; } + public string Password { get; private set; } + public string Character { get; private set; } - public string Account { get; private set; } - public string Password { get; private set; } - public string Character { get; private set; } + public bool AutoConnect { get; private set; } = true; - public bool AutoConnect { get; private set; } = true; + public List UserArgs { get; internal set; } - public List UserArgs { get; internal set; } + public bool ExtendedHelp { get; private set; } - public bool ExtendedHelp { get; private set; } + public ArgumentsParser(string[] args) + { + InitDelay = 1100; - public ArgumentsParser(string[] args) + Error = ArgsError.NoError; + + if ((!args.Contains("--") && args.Select(x => x.ToLower()).Contains("help")) || + (args.Contains("--") && args.TakeWhile(x => x != "--").Select(x => x.ToLower()).Contains("help"))) + { + ExtendedHelp = true; + } + else { - InitDelay = 1100; + for (int i = 0; i < args.Length; i++) + { + var arg = args[i]; + + if (arg == "--") + { + UserArgs = new List(); + for (i = i + 1; i < args.Length; i++) + { + UserArgs.Add(args[i]); + } + break; + } - Error = ArgsError.NoError; + var pair = arg.Split('='); - if ((!args.Contains("--") && args.Select(x => x.ToLower()).Contains("help")) || - (args.Contains("--") && args.TakeWhile(x => x != "--").Select(x => x.ToLower()).Contains("help"))) - { - ExtendedHelp = true; - } - else - { - for (int i = 0; i < args.Length; i++) + if (pair.Length != 2) { - var arg = args[i]; + Error = ArgsError.BadFormat; + return; + } - if (arg == "--") - { - UserArgs = new List(); - for (i = i + 1; i < args.Length; i++) + switch (pair[0].ToLower()) + { + case "script": + if (!File.Exists(pair[1])) { - UserArgs.Add(args[i]); + Error = ArgsError.InvalidPath; + return; } + ScriptFile = pair[1]; break; - } - - var pair = arg.Split('='); - - if (pair.Length != 2) - { + case "autoconnect": + AutoConnect = bool.Parse(pair[1]); + break; + case "host": + ParseHost(pair[1]); + break; + case "port": + if (!ParsePort(pair[1])) + return; + break; + case "bots": + if (!ParseNumBots(pair)) + return; + break; + case "initdelay": + if (!ParseInitDelay(pair[1])) + return; + break; + case "account": + Account = pair[1]; + break; + case "password": + Password = pair[1]; + break; + case "character": + Character = pair[1]; + break; + default: Error = ArgsError.BadFormat; return; - } - - switch (pair[0].ToLower()) - { - case "script": - if (!File.Exists(pair[1])) - { - Error = ArgsError.InvalidPath; - return; - } - ScriptFile = pair[1]; - break; - case "autoconnect": - AutoConnect = bool.Parse(pair[1]); - break; - case "host": - ParseHost(pair[1]); - break; - case "port": - if (!ParsePort(pair[1])) - return; - break; - case "bots": - if (!ParseNumBots(pair)) - return; - break; - case "initdelay": - if (!ParseInitDelay(pair[1])) - return; - break; - case "account": - Account = pair[1]; - break; - case "password": - Password = pair[1]; - break; - case "character": - Character = pair[1]; - break; - default: - Error = ArgsError.BadFormat; - return; - } } + } - if (ScriptFile == null) + if (ScriptFile == null) + { + if (Host == null || Port == 0 || NumBots == 0 || Account == null || Password == null || Character == null) { - if (Host == null || Port == 0 || NumBots == 0 || Account == null || Password == null || Character == null) - { - Error = ArgsError.WrongNumberOfArgs; - } - else if (UserArgs != null || !AutoConnect) - { - Error = ArgsError.InvalidScriptArgs; - } + Error = ArgsError.WrongNumberOfArgs; } - else if (NumBots > 1 && ScriptFile != null && !AutoConnect) + else if (UserArgs != null || !AutoConnect) { - Error = ArgsError.AutoConnectRequired; + Error = ArgsError.InvalidScriptArgs; } } - } - - private void ParseHost(string hostStr) - { - Host = hostStr; - } - - private bool ParsePort(string portStr) - { - ushort port; - if (!ushort.TryParse(portStr, out port)) + else if (NumBots > 1 && ScriptFile != null && !AutoConnect) { - Error = ArgsError.InvalidPort; - return false; + Error = ArgsError.AutoConnectRequired; } - Port = port; - return true; } + } - private bool ParseNumBots(string[] pair) + private void ParseHost(string hostStr) + { + Host = hostStr; + } + + private bool ParsePort(string portStr) + { + ushort port; + if (!ushort.TryParse(portStr, out port)) { - var both = pair[1].Split(','); + Error = ArgsError.InvalidPort; + return false; + } + Port = port; + return true; + } - if (both.Length < 1 || both.Length > 2) - { - Error = ArgsError.BadFormat; - return false; - } + private bool ParseNumBots(string[] pair) + { + var both = pair[1].Split(','); - bool needSimul = both.Length == 2; + if (both.Length < 1 || both.Length > 2) + { + Error = ArgsError.BadFormat; + return false; + } - int numBots, simul = -1; - if (!int.TryParse(both[0], out numBots)) - { - Error = ArgsError.InvalidNumberOfBots; - return false; - } - if (needSimul && !int.TryParse(both[1], out simul)) - { - Error = ArgsError.InvalidSimultaneousNumberOfBots; - return false; - } - if (numBots > BotFramework.NUM_BOTS_MAX || (needSimul && (simul > BotFramework.NUM_BOTS_MAX || simul > numBots))) - { - Error = ArgsError.TooManyBots; - return false; - } - if (numBots < 1 || (needSimul && simul < 1)) - { - Error = ArgsError.NotEnoughBots; - return false; - } + bool needSimul = both.Length == 2; - NumBots = numBots; - SimultaneousBots = needSimul ? simul : numBots; - return true; + int numBots, simul = -1; + if (!int.TryParse(both[0], out numBots)) + { + Error = ArgsError.InvalidNumberOfBots; + return false; } - - private bool ParseInitDelay(string initDelay) + if (needSimul && !int.TryParse(both[1], out simul)) { - int delay; - if (!int.TryParse(initDelay, out delay) || delay < 1100) - { - Error = ArgsError.InvalidInitDelay; - return false; - } + Error = ArgsError.InvalidSimultaneousNumberOfBots; + return false; + } + if (numBots > BotFramework.NUM_BOTS_MAX || (needSimul && (simul > BotFramework.NUM_BOTS_MAX || simul > numBots))) + { + Error = ArgsError.TooManyBots; + return false; + } + if (numBots < 1 || (needSimul && simul < 1)) + { + Error = ArgsError.NotEnoughBots; + return false; + } - InitDelay = delay; + NumBots = numBots; + SimultaneousBots = needSimul ? simul : numBots; + return true; + } - return true; + private bool ParseInitDelay(string initDelay) + { + int delay; + if (!int.TryParse(initDelay, out delay) || delay < 1100) + { + Error = ArgsError.InvalidInitDelay; + return false; } + + InitDelay = delay; + + return true; } } \ No newline at end of file diff --git a/EOBot/BotBase.cs b/EOBot/BotBase.cs index 731bcded0..1ee4790f6 100644 --- a/EOBot/BotBase.cs +++ b/EOBot/BotBase.cs @@ -10,83 +10,82 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot +namespace EOBot; + +public abstract class BotBase : IBot { - public abstract class BotBase : IBot - { - protected bool _initialized; + protected bool _initialized; - protected readonly int _index; + protected readonly int _index; - public event Action WorkCompleted; + public event Action WorkCompleted; - protected Random _random; + protected Random _random; - protected BotBase(int botIndex) - { - _index = botIndex; - _random = new Random(); - } + protected BotBase(int botIndex) + { + _index = botIndex; + _random = new Random(); + } - //all bots are going to want to do the init handshake with the server - public virtual async Task InitializeAsync(string host, int port) - { - var c = DependencyMaster.TypeRegistry[_index]; + //all bots are going to want to do the init handshake with the server + public virtual async Task InitializeAsync(string host, int port) + { + var c = DependencyMaster.TypeRegistry[_index]; - var networkClientRepository = c.Resolve(); - var networkClientFactory = c.Resolve(); - networkClientRepository.NetworkClient = networkClientFactory.CreateNetworkClient(); + var networkClientRepository = c.Resolve(); + var networkClientFactory = c.Resolve(); + networkClientRepository.NetworkClient = networkClientFactory.CreateNetworkClient(); - var configRepo = c.Resolve(); - configRepo.Host = host; - configRepo.Port = port; + var configRepo = c.Resolve(); + configRepo.Host = host; + configRepo.Port = port; - configRepo.VersionMajor = 0; - configRepo.VersionMinor = 0; - configRepo.VersionBuild = 29; + configRepo.VersionMajor = 0; + configRepo.VersionMinor = 0; + configRepo.VersionBuild = 29; - var connectionActions = c.Resolve(); - var connectResult = await connectionActions.ConnectToServer(); - if (connectResult != ConnectResult.Success) - throw new ArgumentException($"Bot {_index}: Unable to connect to server! Host={host} Port={port}"); + var connectionActions = c.Resolve(); + var connectResult = await connectionActions.ConnectToServer(); + if (connectResult != ConnectResult.Success) + throw new ArgumentException($"Bot {_index}: Unable to connect to server! Host={host} Port={port}"); - var backgroundReceiveActions = c.Resolve(); - backgroundReceiveActions.RunBackgroundReceiveLoop(); - WorkCompleted += () => - { - backgroundReceiveActions.CancelBackgroundReceiveLoop(); - connectionActions.DisconnectFromServer(); - }; + var backgroundReceiveActions = c.Resolve(); + backgroundReceiveActions.RunBackgroundReceiveLoop(); + WorkCompleted += () => + { + backgroundReceiveActions.CancelBackgroundReceiveLoop(); + connectionActions.DisconnectFromServer(); + }; - var handshakeResult = await connectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)); + var handshakeResult = await connectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)); - if (handshakeResult.ReplyCode != InitReply.Ok) - throw new InvalidOperationException(string.Format("Bot {0}: Invalid response from server or connection failed! Must receive an OK reply.", _index)); + if (handshakeResult.ReplyCode != InitReply.Ok) + throw new InvalidOperationException(string.Format("Bot {0}: Invalid response from server or connection failed! Must receive an OK reply.", _index)); - var handshakeData = (InitInitServerPacket.ReplyCodeDataOk)handshakeResult.ReplyCodeData; + var handshakeData = (InitInitServerPacket.ReplyCodeDataOk)handshakeResult.ReplyCodeData; - var packetProcessActions = c.Resolve(); - packetProcessActions.SetSequenceStart(InitSequenceStart.FromInitValues(handshakeData.Seq1, handshakeData.Seq2)); - packetProcessActions.SetEncodeMultiples(handshakeData.ServerEncryptionMultiple, handshakeData.ClientEncryptionMultiple); + var packetProcessActions = c.Resolve(); + packetProcessActions.SetSequenceStart(InitSequenceStart.FromInitValues(handshakeData.Seq1, handshakeData.Seq2)); + packetProcessActions.SetEncodeMultiples(handshakeData.ServerEncryptionMultiple, handshakeData.ClientEncryptionMultiple); - connectionActions.CompleteHandshake(handshakeResult); + connectionActions.CompleteHandshake(handshakeResult); - _initialized = true; - } + _initialized = true; + } - public async Task RunAsync(CancellationToken ct) - { - if (!_initialized) - throw new InvalidOperationException("Initialize must be called before calling RunAsync"); - - await DoWorkAsync(ct); - WorkCompleted?.Invoke(); - } - - /// - /// Abstract worker method. Override with custom work logic for the bot to execute - /// - /// A cancellation token that will be signalled when Terminate() is called - protected abstract Task DoWorkAsync(CancellationToken ct); + public async Task RunAsync(CancellationToken ct) + { + if (!_initialized) + throw new InvalidOperationException("Initialize must be called before calling RunAsync"); + + await DoWorkAsync(ct); + WorkCompleted?.Invoke(); } + + /// + /// Abstract worker method. Override with custom work logic for the bot to execute + /// + /// A cancellation token that will be signalled when Terminate() is called + protected abstract Task DoWorkAsync(CancellationToken ct); } \ No newline at end of file diff --git a/EOBot/BotException.cs b/EOBot/BotException.cs index 558420ab9..83f306d0f 100644 --- a/EOBot/BotException.cs +++ b/EOBot/BotException.cs @@ -1,9 +1,8 @@ using System; -namespace EOBot +namespace EOBot; + +public class BotException : Exception { - public class BotException : Exception - { - public BotException(string message) : base(message) { } - } + public BotException(string message) : base(message) { } } \ No newline at end of file diff --git a/EOBot/BotFramework.cs b/EOBot/BotFramework.cs index 732455115..e766626f3 100644 --- a/EOBot/BotFramework.cs +++ b/EOBot/BotFramework.cs @@ -5,148 +5,147 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot +namespace EOBot; + +sealed class BotFramework : IDisposable { - sealed class BotFramework : IDisposable - { - public const int NUM_BOTS_MAX = 25; + public const int NUM_BOTS_MAX = 25; - private readonly CancellationTokenSource _cancellationTokenSource; - private readonly List _botsList; - private readonly string _host; - private readonly ushort _port; + private readonly CancellationTokenSource _cancellationTokenSource; + private readonly List _botsList; + private readonly string _host; + private readonly ushort _port; - private Semaphore _doneSignal; - private bool _initialized; - private int _numBots; - private bool _terminating; + private Semaphore _doneSignal; + private bool _initialized; + private int _numBots; + private bool _terminating; - public BotFramework(ArgumentsParser parsedArgs) - { - if (parsedArgs == null) - throw new ArgumentNullException(nameof(parsedArgs)); + public BotFramework(ArgumentsParser parsedArgs) + { + if (parsedArgs == null) + throw new ArgumentNullException(nameof(parsedArgs)); - _cancellationTokenSource = new CancellationTokenSource(); + _cancellationTokenSource = new CancellationTokenSource(); - var numberOfBots = parsedArgs.NumBots; - var simultaneousBots = parsedArgs.SimultaneousBots; - var host = parsedArgs.Host; - var port = parsedArgs.Port; + var numberOfBots = parsedArgs.NumBots; + var simultaneousBots = parsedArgs.SimultaneousBots; + var host = parsedArgs.Host; + var port = parsedArgs.Port; - if (numberOfBots > NUM_BOTS_MAX || simultaneousBots > NUM_BOTS_MAX || simultaneousBots > numberOfBots) - throw new ArgumentException("Too many bots requested"); + if (numberOfBots > NUM_BOTS_MAX || simultaneousBots > NUM_BOTS_MAX || simultaneousBots > numberOfBots) + throw new ArgumentException("Too many bots requested"); - if (numberOfBots <= 0 || simultaneousBots <= 0) - throw new ArgumentException("Not enough bots requested"); + if (numberOfBots <= 0 || simultaneousBots <= 0) + throw new ArgumentException("Not enough bots requested"); - _numBots = numberOfBots; - _host = host; - _port = port; + _numBots = numberOfBots; + _host = host; + _port = port; - _botsList = new List(numberOfBots); + _botsList = new List(numberOfBots); - _doneSignal = new Semaphore(simultaneousBots, simultaneousBots); - } + _doneSignal = new Semaphore(simultaneousBots, simultaneousBots); + } - public async Task InitializeAsync(IBotFactory botFactory, int delayBetweenInitsMS = 1100) - { - if (_initialized) - throw new InvalidOperationException("Unable to initialize bot framework a second time."); + public async Task InitializeAsync(IBotFactory botFactory, int delayBetweenInitsMS = 1100) + { + if (_initialized) + throw new InvalidOperationException("Unable to initialize bot framework a second time."); - int numFailed = 0; - for (int i = 0; i < _numBots; ++i) - { - if (_terminating) - throw new BotException("Received termination signal; initialization has been cancelled"); - - try - { - var bot = botFactory.CreateBot(i); - bot.WorkCompleted += () => _doneSignal.Release(); - await bot.InitializeAsync(_host, _port); - _botsList.Add(bot); - } - catch (Exception ex) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, ex.Message, ConsoleColor.DarkRed); - numFailed++; - continue; - } - - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Bot {i} initialized."); - await Task.Delay(delayBetweenInitsMS); //minimum for this is 1sec server-side - } + int numFailed = 0; + for (int i = 0; i < _numBots; ++i) + { + if (_terminating) + throw new BotException("Received termination signal; initialization has been cancelled"); - if (numFailed > 0) + try { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, "Some bot instances failed to initialize. These bot instances will not be run.", ConsoleColor.DarkYellow); - _numBots -= numFailed; + var bot = botFactory.CreateBot(i); + bot.WorkCompleted += () => _doneSignal.Release(); + await bot.InitializeAsync(_host, _port); + _botsList.Add(bot); } - else if (numFailed == _numBots) + catch (Exception ex) { - throw new BotException("All bots failed to initialize. No bots will run."); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, ex.Message, ConsoleColor.DarkRed); + numFailed++; + continue; } - _initialized = true; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Bot {i} initialized."); + await Task.Delay(delayBetweenInitsMS); //minimum for this is 1sec server-side } - public async Task RunAsync() + if (numFailed > 0) { - if (!_initialized) - throw new InvalidOperationException("Must call Initialize() before running!"); - - var botTasks = new List(); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, "Some bot instances failed to initialize. These bot instances will not be run.", ConsoleColor.DarkYellow); + _numBots -= numFailed; + } + else if (numFailed == _numBots) + { + throw new BotException("All bots failed to initialize. No bots will run."); + } - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "Bot framework run has started.\n"); - for (int i = 0; i < _numBots; ++i) - { - _doneSignal.WaitOne(); - //acquire mutex for bot - //semaphore limits number of concurrently running bots based on cmd-line param - botTasks.Add(_botsList[i].RunAsync(_cancellationTokenSource.Token)); - } + _initialized = true; + } - // this is done to force handling of exceptions as an Aggregate exception so errors from multiple bots are shown properly - // otherwise, only the first exception from the first faulting task will be thrown - var continuation = Task.WhenAll(botTasks); - try - { - await continuation; - } - catch { } + public async Task RunAsync() + { + if (!_initialized) + throw new InvalidOperationException("Must call Initialize() before running!"); - if (continuation.Status != TaskStatus.RanToCompletion && continuation.Exception != null) - { - throw continuation.Exception; - } - } + var botTasks = new List(); - public void TerminateBots() + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "Bot framework run has started.\n"); + for (int i = 0; i < _numBots; ++i) { - _terminating = true; - if (!_initialized) return; - - _cancellationTokenSource.Cancel(); + _doneSignal.WaitOne(); + //acquire mutex for bot + //semaphore limits number of concurrently running bots based on cmd-line param + botTasks.Add(_botsList[i].RunAsync(_cancellationTokenSource.Token)); } - ~BotFramework() + // this is done to force handling of exceptions as an Aggregate exception so errors from multiple bots are shown properly + // otherwise, only the first exception from the first faulting task will be thrown + var continuation = Task.WhenAll(botTasks); + try { - Dispose(false); - GC.SuppressFinalize(this); + await continuation; } + catch { } - public void Dispose() + if (continuation.Status != TaskStatus.RanToCompletion && continuation.Exception != null) { - Dispose(true); + throw continuation.Exception; } + } + + public void TerminateBots() + { + _terminating = true; + if (!_initialized) return; + + _cancellationTokenSource.Cancel(); + } + + ~BotFramework() + { + Dispose(false); + GC.SuppressFinalize(this); + } + + public void Dispose() + { + Dispose(true); + } - private void Dispose(bool disposing) + private void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - _doneSignal?.Dispose(); - _cancellationTokenSource?.Dispose(); - } + _doneSignal?.Dispose(); + _cancellationTokenSource?.Dispose(); } } } \ No newline at end of file diff --git a/EOBot/BotHelper.cs b/EOBot/BotHelper.cs index 373f4addd..06c02151b 100644 --- a/EOBot/BotHelper.cs +++ b/EOBot/BotHelper.cs @@ -12,115 +12,114 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot +namespace EOBot; + +delegate void DisplayMessageFunc(string message = ""); + +public class BotHelper { - delegate void DisplayMessageFunc(string message = ""); + private readonly int _botIndex; - public class BotHelper + public BotHelper(int botIndex) { - private readonly int _botIndex; + _botIndex = botIndex; + } - public BotHelper(int botIndex) - { - _botIndex = botIndex; - } + public async Task CreateAccountAsync(string name, string password) + { + var accountActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var accParams = new CreateAccountParameters(name, password, password, name, name, name + "@eobot.net"); + var nameResult = await accountActions.CheckAccountNameWithServer(name); + return nameResult >= (AccountReply)10 + ? await accountActions.CreateAccount(accParams, (int)nameResult) + : nameResult; + } - public async Task CreateAccountAsync(string name, string password) - { - var accountActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var accParams = new CreateAccountParameters(name, password, password, name, name, name + "@eobot.net"); - var nameResult = await accountActions.CheckAccountNameWithServer(name); - return nameResult >= (AccountReply)10 - ? await accountActions.CreateAccount(accParams, (int)nameResult) - : nameResult; - } + public async Task LoginToAccountAsync(string name, string password) + { + var loginActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var loginParameters = new LoginParameters(name, password); + return await loginActions.LoginToServer(loginParameters); + } - public async Task LoginToAccountAsync(string name, string password) - { - var loginActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var loginParameters = new LoginParameters(name, password); - return await loginActions.LoginToServer(loginParameters); - } + public async Task CreateCharacterAsync(string name) + { + var characterActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var createId = await characterActions.RequestCharacterCreation(); + var charParams = new CharacterCreateParameters(name, 0, 1, 0, 0); + return await characterActions.CreateCharacter(charParams, createId); + } - public async Task CreateCharacterAsync(string name) + public async Task LoginToCharacterAsync(string name) + { + var loginActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var characters = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var mapStateProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + + if (characters.Characters == null || !characters.Characters.Any()) + await CreateCharacterAsync(name); + + var character = characters.Characters.Single(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)); + var sessionID = await loginActions.RequestCharacterLogin(character); + + var unableToLoadMap = false; + try { - var characterActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var createId = await characterActions.RequestCharacterCreation(); - var charParams = new CharacterCreateParameters(name, 0, 1, 0, 0); - return await characterActions.CreateCharacter(charParams, createId); + var mapLoadActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + mapLoadActions.LoadMapFileByID(mapStateProvider.CurrentMapID); } - - public async Task LoginToCharacterAsync(string name) + catch (IOException) { - var loginActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var characters = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var mapStateProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - - if (characters.Characters == null || !characters.Characters.Any()) - await CreateCharacterAsync(name); + unableToLoadMap = true; + } - var character = characters.Characters.Single(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)); - var sessionID = await loginActions.RequestCharacterLogin(character); + var fileRequestActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + if (unableToLoadMap || fileRequestActions.NeedsFileForLogin(FileType.Emf, mapStateProvider.CurrentMapID)) + await fileRequestActions.GetMapFromServer(mapStateProvider.CurrentMapID, sessionID); - var unableToLoadMap = false; - try - { - var mapLoadActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - mapLoadActions.LoadMapFileByID(mapStateProvider.CurrentMapID); - } - catch (IOException) - { - unableToLoadMap = true; - } + if (fileRequestActions.NeedsFileForLogin(FileType.Eif)) + await fileRequestActions.GetItemFileFromServer(sessionID); - var fileRequestActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - if (unableToLoadMap || fileRequestActions.NeedsFileForLogin(FileType.Emf, mapStateProvider.CurrentMapID)) - await fileRequestActions.GetMapFromServer(mapStateProvider.CurrentMapID, sessionID); + if (fileRequestActions.NeedsFileForLogin(FileType.Enf)) + await fileRequestActions.GetNPCFileFromServer(sessionID); - if (fileRequestActions.NeedsFileForLogin(FileType.Eif)) - await fileRequestActions.GetItemFileFromServer(sessionID); + if (fileRequestActions.NeedsFileForLogin(FileType.Esf)) + await fileRequestActions.GetSpellFileFromServer(sessionID); - if (fileRequestActions.NeedsFileForLogin(FileType.Enf)) - await fileRequestActions.GetNPCFileFromServer(sessionID); + if (fileRequestActions.NeedsFileForLogin(FileType.Ecf)) + await fileRequestActions.GetClassFileFromServer(sessionID); - if (fileRequestActions.NeedsFileForLogin(FileType.Esf)) - await fileRequestActions.GetSpellFileFromServer(sessionID); + await loginActions.CompleteCharacterLogin(sessionID); + } - if (fileRequestActions.NeedsFileForLogin(FileType.Ecf)) - await fileRequestActions.GetClassFileFromServer(sessionID); + public async Task ChangePasswordAsync(string name, string oldPass, string newPass) + { + var accountActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var accParams = new ChangePasswordParameters(name, oldPass, newPass); + return await accountActions.ChangePassword(accParams); + } - await loginActions.CompleteCharacterLogin(sessionID); - } + public async Task DeleteCharacterAsync(string name, bool force) + { + var characterSelectorRepository = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + characterSelectorRepository.CharacterForDelete = characterSelectorRepository.Characters.SingleOrNone(x => x.Name == name); - public async Task ChangePasswordAsync(string name, string oldPass, string newPass) + if (!characterSelectorRepository.CharacterForDelete.HasValue) { - var accountActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var accParams = new ChangePasswordParameters(name, oldPass, newPass); - return await accountActions.ChangePassword(accParams); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Character {name} could not be deleted / does not exist"); + return (CharacterReply)255; } - public async Task DeleteCharacterAsync(string name, bool force) + var characterActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var deleteId = await characterActions.RequestCharacterDelete(); + + if (!force) { - var characterSelectorRepository = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - characterSelectorRepository.CharacterForDelete = characterSelectorRepository.Characters.SingleOrNone(x => x.Name == name); - - if (!characterSelectorRepository.CharacterForDelete.HasValue) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Character {name} could not be deleted / does not exist"); - return (CharacterReply)255; - } - - var characterActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var deleteId = await characterActions.RequestCharacterDelete(); - - if (!force) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, "DELETING CHARACTER - ARE YOU SURE [Y/N]?", ConsoleColor.Yellow); - if (Console.ReadLine().ToLower() != "y") - return CharacterReply.NotApproved; - } - - return await characterActions.DeleteCharacter(deleteId); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, "DELETING CHARACTER - ARE YOU SURE [Y/N]?", ConsoleColor.Yellow); + if (Console.ReadLine().ToLower() != "y") + return CharacterReply.NotApproved; } + + return await characterActions.DeleteCharacter(deleteId); } } \ No newline at end of file diff --git a/EOBot/ConsoleHelper.cs b/EOBot/ConsoleHelper.cs index 16053186f..6d1386fce 100644 --- a/EOBot/ConsoleHelper.cs +++ b/EOBot/ConsoleHelper.cs @@ -2,79 +2,78 @@ using System.Linq; using System.Reflection; -namespace EOBot +namespace EOBot; + +internal sealed class StringValue : Attribute { - internal sealed class StringValue : Attribute - { - public string Value { get; set; } + public string Value { get; set; } - public StringValue(string value) => Value = value; - } + public StringValue(string value) => Value = value; +} - internal static class EnumExtensions +internal static class EnumExtensions +{ + public static string String(this Enum item) { - public static string String(this Enum item) - { - var enumType = item.GetType(); - var memberInfos = enumType.GetMember(item.ToString()); - var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == enumType); - var valueAttributes = enumValueMemberInfo.GetCustomAttributes(false); - return valueAttributes.Single().Value; - } + var enumType = item.GetType(); + var memberInfos = enumType.GetMember(item.ToString()); + var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == enumType); + var valueAttributes = enumValueMemberInfo.GetCustomAttributes(false); + return valueAttributes.Single().Value; } +} - public static class ConsoleHelper +public static class ConsoleHelper +{ + public enum Type { - public enum Type - { - [StringValue(" ")] - None, - [StringValue("WRN ")] - Warning, - [StringValue("ERR ")] - Error, - [StringValue("ATK ")] - Attack, - [StringValue("MOVE")] - Move, - [StringValue("WALK")] - Walk, - [StringValue("FACE")] - Face, - [StringValue("TAKE")] - TakeItem, - [StringValue("JUNK")] - JunkItem, - [StringValue("USE ")] - UseItem, - [StringValue("CAST")] - Cast, - [StringValue("SIT ")] - Sit, - [StringValue("HIT ")] - Hit, - [StringValue("EXP ")] - Experience, - [StringValue("HEAL")] - Heal, - [StringValue("DMG ")] - Damage, - [StringValue("DEAD")] - Dead, - [StringValue("ITEM")] - Item, - [StringValue("CHAT")] - Chat - } + [StringValue(" ")] + None, + [StringValue("WRN ")] + Warning, + [StringValue("ERR ")] + Error, + [StringValue("ATK ")] + Attack, + [StringValue("MOVE")] + Move, + [StringValue("WALK")] + Walk, + [StringValue("FACE")] + Face, + [StringValue("TAKE")] + TakeItem, + [StringValue("JUNK")] + JunkItem, + [StringValue("USE ")] + UseItem, + [StringValue("CAST")] + Cast, + [StringValue("SIT ")] + Sit, + [StringValue("HIT ")] + Hit, + [StringValue("EXP ")] + Experience, + [StringValue("HEAL")] + Heal, + [StringValue("DMG ")] + Damage, + [StringValue("DEAD")] + Dead, + [StringValue("ITEM")] + Item, + [StringValue("CHAT")] + Chat + } - public static void WriteMessage(Type messageType, string message, ConsoleColor color = ConsoleColor.Gray) - { - var oldColor = Console.ForegroundColor; - Console.ForegroundColor = color; + public static void WriteMessage(Type messageType, string message, ConsoleColor color = ConsoleColor.Gray) + { + var oldColor = Console.ForegroundColor; + Console.ForegroundColor = color; - Console.WriteLine($"[{messageType.String()}] {message}"); + Console.WriteLine($"[{messageType.String()}] {message}"); - Console.ForegroundColor = oldColor; - } + Console.ForegroundColor = oldColor; } } \ No newline at end of file diff --git a/EOBot/DependencyMaster.cs b/EOBot/DependencyMaster.cs index 72ffebcb6..41647d49d 100644 --- a/EOBot/DependencyMaster.cs +++ b/EOBot/DependencyMaster.cs @@ -1,9 +1,8 @@ using AutomaticTypeMapper; -namespace EOBot +namespace EOBot; + +public static class DependencyMaster { - public static class DependencyMaster - { - public static ITypeRegistry[] TypeRegistry { get; set; } - } + public static ITypeRegistry[] TypeRegistry { get; set; } } \ No newline at end of file diff --git a/EOBot/IBot.cs b/EOBot/IBot.cs index 48eca1739..fb76b7865 100644 --- a/EOBot/IBot.cs +++ b/EOBot/IBot.cs @@ -2,24 +2,23 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot +namespace EOBot; + +public interface IBot { - public interface IBot - { - /// - /// Event that is called when work for the Bot has been completed - /// - event Action WorkCompleted; + /// + /// Event that is called when work for the Bot has been completed + /// + event Action WorkCompleted; - /// - /// Initialization logic for the bot instance. Called automatically by the framework. - /// - Task InitializeAsync(string host, int port); + /// + /// Initialization logic for the bot instance. Called automatically by the framework. + /// + Task InitializeAsync(string host, int port); - /// - /// Run logic for the bot instance. Called automatically by the framework. - /// - /// True to wait until a call to Terminate() is made, false otherwise - Task RunAsync(CancellationToken cancellationToken); - } + /// + /// Run logic for the bot instance. Called automatically by the framework. + /// + /// True to wait until a call to Terminate() is made, false otherwise + Task RunAsync(CancellationToken cancellationToken); } \ No newline at end of file diff --git a/EOBot/IBotFactory.cs b/EOBot/IBotFactory.cs index ee573ea0c..1d4bbfcae 100644 --- a/EOBot/IBotFactory.cs +++ b/EOBot/IBotFactory.cs @@ -1,7 +1,6 @@ -namespace EOBot +namespace EOBot; + +interface IBotFactory { - interface IBotFactory - { - IBot CreateBot(int index); - } + IBot CreateBot(int index); } \ No newline at end of file diff --git a/EOBot/Interpreter/BotInterpreter.cs b/EOBot/Interpreter/BotInterpreter.cs index 4be01ea55..e85f0a27f 100644 --- a/EOBot/Interpreter/BotInterpreter.cs +++ b/EOBot/Interpreter/BotInterpreter.cs @@ -4,88 +4,87 @@ using System.IO; using System.Threading.Tasks; -namespace EOBot.Interpreter +namespace EOBot.Interpreter; + +public class BotInterpreter { - public class BotInterpreter - { - private readonly BotTokenParser _parser; + private readonly BotTokenParser _parser; - public BotInterpreter(string filePath) - : this(File.OpenText(filePath)) - { - } + public BotInterpreter(string filePath) + : this(File.OpenText(filePath)) + { + } - public BotInterpreter(StreamReader inputStream) - { - _parser = new BotTokenParser(inputStream); - } + public BotInterpreter(StreamReader inputStream) + { + _parser = new BotTokenParser(inputStream); + } - public IReadOnlyList Parse() - { - _parser.Reset(); + public IReadOnlyList Parse() + { + _parser.Reset(); - var retList = new List(); + var retList = new List(); - BotToken nextToken; - do + BotToken nextToken; + do + { + nextToken = _parser.GetNextToken(); + if (nextToken.TokenType == BotTokenType.Error) { - nextToken = _parser.GetNextToken(); - if (nextToken.TokenType == BotTokenType.Error) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error at line {_parser.LineNumber} column {_parser.Column}: token value {nextToken.TokenValue}", ConsoleColor.Red); - throw new InvalidOperationException("Unable to parse input"); - } + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error at line {_parser.LineNumber} column {_parser.Column}: token value {nextToken.TokenValue}", ConsoleColor.Red); + throw new InvalidOperationException("Unable to parse input"); + } - retList.Add(nextToken); - } while (nextToken.TokenType != BotTokenType.EOF); + retList.Add(nextToken); + } while (nextToken.TokenType != BotTokenType.EOF); - return retList; - } + return retList; + } - internal ProgramState Prepare(int botIndex, ArgumentsParser parsedArgs, IReadOnlyList tokens) - { - ProgramState input = new ProgramState(tokens); + internal ProgramState Prepare(int botIndex, ArgumentsParser parsedArgs, IReadOnlyList tokens) + { + ProgramState input = new ProgramState(tokens); - var setup = new BuiltInIdentifierConfigurator(input, botIndex, parsedArgs); - setup.SetupBuiltInFunctions(); - setup.SetupBuiltInVariables(); + var setup = new BuiltInIdentifierConfigurator(input, botIndex, parsedArgs); + setup.SetupBuiltInFunctions(); + setup.SetupBuiltInVariables(); - return input; - } + return input; + } - public async Task Run(ProgramState programState) - { - var evaluators = new List(); - evaluators.Add(new StatementListEvaluator(evaluators)); - evaluators.Add(new StatementEvaluator(evaluators)); - evaluators.Add(new AssignmentEvaluator(evaluators)); - evaluators.Add(new KeywordEvaluator(evaluators)); - evaluators.Add(new LabelEvaluator()); - evaluators.Add(new FunctionEvaluator(evaluators)); - evaluators.Add(new VariableEvaluator(evaluators)); - evaluators.Add(new ExpressionEvaluator(evaluators)); - evaluators.Add(new ExpressionTailEvaluator(evaluators)); - evaluators.Add(new OperandEvaluator(evaluators)); - evaluators.Add(new IfEvaluator(evaluators)); - evaluators.Add(new WhileEvaluator(evaluators)); - evaluators.Add(new GotoEvaluator()); + public async Task Run(ProgramState programState) + { + var evaluators = new List(); + evaluators.Add(new StatementListEvaluator(evaluators)); + evaluators.Add(new StatementEvaluator(evaluators)); + evaluators.Add(new AssignmentEvaluator(evaluators)); + evaluators.Add(new KeywordEvaluator(evaluators)); + evaluators.Add(new LabelEvaluator()); + evaluators.Add(new FunctionEvaluator(evaluators)); + evaluators.Add(new VariableEvaluator(evaluators)); + evaluators.Add(new ExpressionEvaluator(evaluators)); + evaluators.Add(new ExpressionTailEvaluator(evaluators)); + evaluators.Add(new OperandEvaluator(evaluators)); + evaluators.Add(new IfEvaluator(evaluators)); + evaluators.Add(new WhileEvaluator(evaluators)); + evaluators.Add(new GotoEvaluator()); - IScriptEvaluator scriptEvaluator = new ScriptEvaluator(evaluators); + IScriptEvaluator scriptEvaluator = new ScriptEvaluator(evaluators); - var result = await scriptEvaluator.EvaluateAsync(programState); - if (result.Result == EvalResult.Failed) + var result = await scriptEvaluator.EvaluateAsync(programState); + if (result.Result == EvalResult.Failed) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error during execution at line {result.Token.LineNumber} column {result.Token.Column}", ConsoleColor.DarkRed); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, result.Reason, ConsoleColor.DarkRed); + } + else if (result.Result == EvalResult.NotMatch) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error at line {result.Token.LineNumber} column {result.Token.Column}: {result.Token.TokenType} {result.Token.TokenValue} was unexpected", ConsoleColor.DarkRed); + if (!string.IsNullOrWhiteSpace(result.Reason)) { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error during execution at line {result.Token.LineNumber} column {result.Token.Column}", ConsoleColor.DarkRed); ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, result.Reason, ConsoleColor.DarkRed); } - else if (result.Result == EvalResult.NotMatch) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error at line {result.Token.LineNumber} column {result.Token.Column}: {result.Token.TokenType} {result.Token.TokenValue} was unexpected", ConsoleColor.DarkRed); - if (!string.IsNullOrWhiteSpace(result.Reason)) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, result.Reason, ConsoleColor.DarkRed); - } - } } } } \ No newline at end of file diff --git a/EOBot/Interpreter/BotScriptErrorException.cs b/EOBot/Interpreter/BotScriptErrorException.cs index 121d3cb0d..0f7e8f740 100644 --- a/EOBot/Interpreter/BotScriptErrorException.cs +++ b/EOBot/Interpreter/BotScriptErrorException.cs @@ -1,13 +1,12 @@ using System; -namespace EOBot.Interpreter +namespace EOBot.Interpreter; + +public class BotScriptErrorException : Exception { - public class BotScriptErrorException : Exception - { - public BotScriptErrorException(string message) - : base(message) { } + public BotScriptErrorException(string message) + : base(message) { } - public BotScriptErrorException(string message, BotToken token) - : base($"Error at line {token.LineNumber} column {token.Column}: {message}") { } - } + public BotScriptErrorException(string message, BotToken token) + : base($"Error at line {token.LineNumber} column {token.Column}: {message}") { } } \ No newline at end of file diff --git a/EOBot/Interpreter/BotToken.cs b/EOBot/Interpreter/BotToken.cs index 460ddba07..ba4beb9a6 100644 --- a/EOBot/Interpreter/BotToken.cs +++ b/EOBot/Interpreter/BotToken.cs @@ -1,23 +1,22 @@ -namespace EOBot.Interpreter -{ - public class BotToken - { - public BotTokenType TokenType { get; } +namespace EOBot.Interpreter; - public string TokenValue { get; } +public class BotToken +{ + public BotTokenType TokenType { get; } - public int LineNumber { get; } + public string TokenValue { get; } - public int Column { get; } + public int LineNumber { get; } - public BotToken(BotTokenType tokenType, string tokenValue, int line, int col) - { - TokenType = tokenType; - TokenValue = tokenValue; - LineNumber = line; - Column = col; - } + public int Column { get; } - public override string ToString() => $"{TokenType}: {TokenValue}"; + public BotToken(BotTokenType tokenType, string tokenValue, int line, int col) + { + TokenType = tokenType; + TokenValue = tokenValue; + LineNumber = line; + Column = col; } + + public override string ToString() => $"{TokenType}: {TokenValue}"; } \ No newline at end of file diff --git a/EOBot/Interpreter/BotTokenParser.cs b/EOBot/Interpreter/BotTokenParser.cs index 69a89ff16..a385cac43 100644 --- a/EOBot/Interpreter/BotTokenParser.cs +++ b/EOBot/Interpreter/BotTokenParser.cs @@ -2,233 +2,232 @@ using System.Collections.Generic; using System.IO; -namespace EOBot.Interpreter +namespace EOBot.Interpreter; + +public sealed class BotTokenParser : IDisposable { - public sealed class BotTokenParser : IDisposable + private static readonly HashSet Keywords = new HashSet { - private static readonly HashSet Keywords = new HashSet - { - "if", - "while", - "goto", - "else", - }; + "if", + "while", + "goto", + "else", + }; - private static readonly HashSet Literals = new HashSet - { - "true", - "false" - }; + private static readonly HashSet Literals = new HashSet + { + "true", + "false" + }; - private readonly StreamReader _inputStream; - private readonly bool _streamNeedsDispose; + private readonly StreamReader _inputStream; + private readonly bool _streamNeedsDispose; - public int LineNumber { get; private set; } + public int LineNumber { get; private set; } - public int Column { get; private set; } + public int Column { get; private set; } - public BotTokenParser(string filePath) - : this(File.OpenText(filePath)) - { - _streamNeedsDispose = true; - } + public BotTokenParser(string filePath) + : this(File.OpenText(filePath)) + { + _streamNeedsDispose = true; + } - public BotTokenParser(StreamReader inputStream) - { - _inputStream = inputStream; - LineNumber = 1; - Column = 1; - } + public BotTokenParser(StreamReader inputStream) + { + _inputStream = inputStream; + LineNumber = 1; + Column = 1; + } - public void Reset() - { - _inputStream.BaseStream.Seek(0, SeekOrigin.Begin); - LineNumber = 1; - Column = 1; - } + public void Reset() + { + _inputStream.BaseStream.Seek(0, SeekOrigin.Begin); + LineNumber = 1; + Column = 1; + } + + public BotToken GetNextToken() + { + if (_inputStream.EndOfStream) + return Token(BotTokenType.EOF, string.Empty); - public BotToken GetNextToken() + char inputChar; + do { - if (_inputStream.EndOfStream) - return Token(BotTokenType.EOF, string.Empty); + inputChar = Read(); - char inputChar; - do + if (inputChar == '\n') { - inputChar = Read(); + LineNumber++; + Column = 1; + return Token(BotTokenType.NewLine, inputChar.ToString()); + } - if (inputChar == '\n') + if (inputChar == '/' && !_inputStream.EndOfStream && Peek() == '*') + { + // skip the comment: block format + do { - LineNumber++; - Column = 1; - return Token(BotTokenType.NewLine, inputChar.ToString()); - } + inputChar = Read(); + } while (!(inputChar == '*' && !_inputStream.EndOfStream && Peek() == '/')); - if (inputChar == '/' && !_inputStream.EndOfStream && Peek() == '*') + // skip the slash ending the comment and set input char to the character after the comment + Read(); + inputChar = Read(); + } + else if (inputChar == '/' && !_inputStream.EndOfStream && Peek() == '/') + { + // skip the comment: line format + do { - // skip the comment: block format - do - { - inputChar = Read(); - } while (!(inputChar == '*' && !_inputStream.EndOfStream && Peek() == '/')); - - // skip the slash ending the comment and set input char to the character after the comment - Read(); inputChar = Read(); - } - else if (inputChar == '/' && !_inputStream.EndOfStream && Peek() == '/') - { - // skip the comment: line format - do - { - inputChar = Read(); - } while (inputChar != '\n' && !_inputStream.EndOfStream); + } while (inputChar != '\n' && !_inputStream.EndOfStream); - LineNumber++; - Column = 1; - return Token(BotTokenType.NewLine, inputChar.ToString()); - } - } while (!_inputStream.EndOfStream && char.IsWhiteSpace(inputChar)); + LineNumber++; + Column = 1; + return Token(BotTokenType.NewLine, inputChar.ToString()); + } + } while (!_inputStream.EndOfStream && char.IsWhiteSpace(inputChar)); - if (char.IsLetter(inputChar)) - { - var identifier = inputChar.ToString(); - while ((char.IsLetterOrDigit(Peek()) || Peek() == '_') && !_inputStream.EndOfStream) - identifier += Read(); + if (char.IsLetter(inputChar)) + { + var identifier = inputChar.ToString(); + while ((char.IsLetterOrDigit(Peek()) || Peek() == '_') && !_inputStream.EndOfStream) + identifier += Read(); - var type = Keywords.Contains(identifier) - ? BotTokenType.Keyword - : Literals.Contains(identifier) - ? BotTokenType.Literal - : BotTokenType.Identifier; + var type = Keywords.Contains(identifier) + ? BotTokenType.Keyword + : Literals.Contains(identifier) + ? BotTokenType.Literal + : BotTokenType.Identifier; - return Token(type, identifier); - } - else if (char.IsDigit(inputChar)) - { - var number = inputChar.ToString(); - while (char.IsDigit(Peek()) && !_inputStream.EndOfStream) - number += Read(); - return Token(BotTokenType.Literal, number); - } - else + return Token(type, identifier); + } + else if (char.IsDigit(inputChar)) + { + var number = inputChar.ToString(); + while (char.IsDigit(Peek()) && !_inputStream.EndOfStream) + number += Read(); + return Token(BotTokenType.Literal, number); + } + else + { + switch (inputChar) { - switch (inputChar) - { - case '(': return Token(BotTokenType.LParen, inputChar.ToString()); - case ')': return Token(BotTokenType.RParen, inputChar.ToString()); - case '{': return Token(BotTokenType.LBrace, inputChar.ToString()); - case '}': return Token(BotTokenType.RBrace, inputChar.ToString()); - case '[': return Token(BotTokenType.LBracket, inputChar.ToString()); - case ']': return Token(BotTokenType.RBracket, inputChar.ToString()); - case ':': return Token(BotTokenType.Colon, inputChar.ToString()); - case ',': return Token(BotTokenType.Comma, inputChar.ToString()); - case '"': - { - var stringLiteral = string.Empty; - while (Peek() != '"' && !_inputStream.EndOfStream) - stringLiteral += Read(); + case '(': return Token(BotTokenType.LParen, inputChar.ToString()); + case ')': return Token(BotTokenType.RParen, inputChar.ToString()); + case '{': return Token(BotTokenType.LBrace, inputChar.ToString()); + case '}': return Token(BotTokenType.RBrace, inputChar.ToString()); + case '[': return Token(BotTokenType.LBracket, inputChar.ToString()); + case ']': return Token(BotTokenType.RBracket, inputChar.ToString()); + case ':': return Token(BotTokenType.Colon, inputChar.ToString()); + case ',': return Token(BotTokenType.Comma, inputChar.ToString()); + case '"': + { + var stringLiteral = string.Empty; + while (Peek() != '"' && !_inputStream.EndOfStream) + stringLiteral += Read(); - if (_inputStream.EndOfStream) - return Token(BotTokenType.Error, string.Empty); + if (_inputStream.EndOfStream) + return Token(BotTokenType.Error, string.Empty); - Read(); - return Token(BotTokenType.Literal, stringLiteral); - } - case '=': + Read(); + return Token(BotTokenType.Literal, stringLiteral); + } + case '=': + { + switch (Peek()) { - switch (Peek()) - { - case '=': - var nextChar = Read(); - return Token(BotTokenType.EqualOperator, inputChar.ToString() + nextChar); - default: - return Token(BotTokenType.AssignOperator, inputChar.ToString()); - } + case '=': + var nextChar = Read(); + return Token(BotTokenType.EqualOperator, inputChar.ToString() + nextChar); + default: + return Token(BotTokenType.AssignOperator, inputChar.ToString()); } - case '!': + } + case '!': + { + switch (Peek()) { - switch (Peek()) - { - case '=': - var nextChar = Read(); - return Token(BotTokenType.NotEqualOperator, inputChar.ToString() + nextChar); - default: - return Token(BotTokenType.NotOperator, inputChar.ToString()); - } + case '=': + var nextChar = Read(); + return Token(BotTokenType.NotEqualOperator, inputChar.ToString() + nextChar); + default: + return Token(BotTokenType.NotOperator, inputChar.ToString()); } - case '>': + } + case '>': + { + switch (Peek()) { - switch (Peek()) - { - case '=': - var nextChar = Read(); - return Token(BotTokenType.GreaterThanEqOperator, inputChar.ToString() + nextChar); - default: - return Token(BotTokenType.GreaterThanOperator, inputChar.ToString()); - } + case '=': + var nextChar = Read(); + return Token(BotTokenType.GreaterThanEqOperator, inputChar.ToString() + nextChar); + default: + return Token(BotTokenType.GreaterThanOperator, inputChar.ToString()); } - case '<': + } + case '<': + { + switch (Peek()) { - switch (Peek()) - { - case '=': - var nextChar = Read(); - return Token(BotTokenType.LessThanEqOperator, inputChar.ToString() + nextChar); - default: - return Token(BotTokenType.LessThanOperator, inputChar.ToString()); - } + case '=': + var nextChar = Read(); + return Token(BotTokenType.LessThanEqOperator, inputChar.ToString() + nextChar); + default: + return Token(BotTokenType.LessThanOperator, inputChar.ToString()); } - case '$': - { - if (_inputStream.EndOfStream) - return Token(BotTokenType.Error, inputChar.ToString()); - - // ensure variable starts with letter or underscore before getting variable name - inputChar = Peek(); - if (!char.IsLetter(inputChar) && inputChar != '_') - return Token(BotTokenType.Error, inputChar.ToString()); + } + case '$': + { + if (_inputStream.EndOfStream) + return Token(BotTokenType.Error, inputChar.ToString()); - var variable = string.Empty; - for (inputChar = Peek(); !_inputStream.EndOfStream && (char.IsLetterOrDigit(inputChar) || inputChar == '_'); inputChar = Peek()) - { - variable += Read(); - } + // ensure variable starts with letter or underscore before getting variable name + inputChar = Peek(); + if (!char.IsLetter(inputChar) && inputChar != '_') + return Token(BotTokenType.Error, inputChar.ToString()); - return Token(BotTokenType.Variable, variable); + var variable = string.Empty; + for (inputChar = Peek(); !_inputStream.EndOfStream && (char.IsLetterOrDigit(inputChar) || inputChar == '_'); inputChar = Peek()) + { + variable += Read(); } - case '+': return Token(BotTokenType.PlusOperator, inputChar.ToString()); - case '-': return Token(BotTokenType.MinusOperator, inputChar.ToString()); - case '*': return Token(BotTokenType.MultiplyOperator, inputChar.ToString()); - case '/': return Token(BotTokenType.DivideOperator, inputChar.ToString()); - case '.': return Token(BotTokenType.Dot, inputChar.ToString()); - default: return Token(BotTokenType.Error, inputChar.ToString()); - } + + return Token(BotTokenType.Variable, variable); + } + case '+': return Token(BotTokenType.PlusOperator, inputChar.ToString()); + case '-': return Token(BotTokenType.MinusOperator, inputChar.ToString()); + case '*': return Token(BotTokenType.MultiplyOperator, inputChar.ToString()); + case '/': return Token(BotTokenType.DivideOperator, inputChar.ToString()); + case '.': return Token(BotTokenType.Dot, inputChar.ToString()); + default: return Token(BotTokenType.Error, inputChar.ToString()); } } + } - private BotToken Token(BotTokenType tokenType, string tokenValue) - { - return new BotToken(tokenType, tokenValue, LineNumber, Column); - } + private BotToken Token(BotTokenType tokenType, string tokenValue) + { + return new BotToken(tokenType, tokenValue, LineNumber, Column); + } - public void Dispose() - { - if (_streamNeedsDispose) - _inputStream.Dispose(); + public void Dispose() + { + if (_streamNeedsDispose) + _inputStream.Dispose(); - GC.SuppressFinalize(this); - } + GC.SuppressFinalize(this); + } - private char Peek() - { - return (char)_inputStream.Peek(); - } + private char Peek() + { + return (char)_inputStream.Peek(); + } - private char Read() - { - Column++; - return (char)_inputStream.Read(); - } + private char Read() + { + Column++; + return (char)_inputStream.Read(); } } \ No newline at end of file diff --git a/EOBot/Interpreter/BotTokenType.cs b/EOBot/Interpreter/BotTokenType.cs index e93ed43cd..b2145907d 100644 --- a/EOBot/Interpreter/BotTokenType.cs +++ b/EOBot/Interpreter/BotTokenType.cs @@ -1,34 +1,33 @@ -namespace EOBot.Interpreter +namespace EOBot.Interpreter; + +public enum BotTokenType { - public enum BotTokenType - { - EOF, - LParen, - RParen, - LBrace, - RBrace, - LBracket, - RBracket, - Colon, - Comma, - Keyword, - Variable, - Identifier, - Literal, - AssignOperator, - EqualOperator, - LessThanOperator, - LessThanEqOperator, - GreaterThanOperator, - GreaterThanEqOperator, - NotEqualOperator, - PlusOperator, - MinusOperator, - MultiplyOperator, - DivideOperator, - NotOperator, - Dot, - NewLine, - Error, - } + EOF, + LParen, + RParen, + LBrace, + RBrace, + LBracket, + RBracket, + Colon, + Comma, + Keyword, + Variable, + Identifier, + Literal, + AssignOperator, + EqualOperator, + LessThanOperator, + LessThanEqOperator, + GreaterThanOperator, + GreaterThanEqOperator, + NotEqualOperator, + PlusOperator, + MinusOperator, + MultiplyOperator, + DivideOperator, + NotOperator, + Dot, + NewLine, + Error, } \ No newline at end of file diff --git a/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs b/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs index 7069b8c51..7e5522044 100644 --- a/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs +++ b/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs @@ -21,307 +21,306 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot.Interpreter +namespace EOBot.Interpreter; + +public class BuiltInIdentifierConfigurator { - public class BuiltInIdentifierConfigurator + private readonly ProgramState _state; + private readonly int _botIndex; + private readonly ArgumentsParser _parsedArgs; + private readonly BotHelper _botHelper; + private readonly Random _random; + + public BuiltInIdentifierConfigurator(ProgramState state, int botIndex, ArgumentsParser parsedArgs) { - private readonly ProgramState _state; - private readonly int _botIndex; - private readonly ArgumentsParser _parsedArgs; - private readonly BotHelper _botHelper; - private readonly Random _random; + _state = state; + _botIndex = botIndex; + _parsedArgs = parsedArgs; + _botHelper = new BotHelper(_botIndex); + _random = new Random(); + } - public BuiltInIdentifierConfigurator(ProgramState state, int botIndex, ArgumentsParser parsedArgs) - { - _state = state; - _botIndex = botIndex; - _parsedArgs = parsedArgs; - _botHelper = new BotHelper(_botIndex); - _random = new Random(); - } + public void SetupBuiltInFunctions() + { + _state.SymbolTable[PredefinedIdentifiers.PRINT_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.PRINT_FUNC, param1 => ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, param1.ToString()))); + _state.SymbolTable[PredefinedIdentifiers.LEN_FUNC] = Readonly(new Function(PredefinedIdentifiers.LEN_FUNC, param1 => param1.Value.Count)); + _state.SymbolTable[PredefinedIdentifiers.ARRAY_FUNC] = Readonly(new Function>(PredefinedIdentifiers.ARRAY_FUNC, param1 => Enumerable.Repeat(UndefinedVariable.Instance, param1).Cast().ToList())); + _state.SymbolTable[PredefinedIdentifiers.SLEEP_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.SLEEP_FUNC, param1 => Thread.Sleep(param1))); + _state.SymbolTable[PredefinedIdentifiers.TIME_FUNC] = Readonly(new Function(PredefinedIdentifiers.TIME_FUNC, () => DateTime.Now.ToLongTimeString())); + _state.SymbolTable[PredefinedIdentifiers.OBJECT_FUNC] = Readonly(new Function(PredefinedIdentifiers.OBJECT_FUNC, () => new ObjectVariable())); + _state.SymbolTable[PredefinedIdentifiers.SETENV_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.SETENV_FUNC, (varName, varValue) => Environment.SetEnvironmentVariable(varName, varValue, EnvironmentVariableTarget.User))); + _state.SymbolTable[PredefinedIdentifiers.GETENV_FUNC] = Readonly(new Function(PredefinedIdentifiers.GETENV_FUNC, varName => Environment.GetEnvironmentVariable(varName, EnvironmentVariableTarget.User))); + _state.SymbolTable[PredefinedIdentifiers.ERROR_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.ERROR_FUNC, message => throw new BotScriptErrorException(message))); + _state.SymbolTable[PredefinedIdentifiers.LOWER_FUNC] = Readonly(new Function(PredefinedIdentifiers.LOWER_FUNC, s => s.ToLower())); + _state.SymbolTable[PredefinedIdentifiers.UPPER_FUNC] = Readonly(new Function(PredefinedIdentifiers.UPPER_FUNC, s => s.ToUpper())); + + BotDependencySetup(); + // pre-game flow + _state.SymbolTable[PredefinedIdentifiers.CONNECT_FUNC] = Readonly(new AsyncVoidFunction(PredefinedIdentifiers.CONNECT_FUNC, ConnectAsync)); + _state.SymbolTable[PredefinedIdentifiers.DISCONNECT_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.DISCONNECT_FUNC, Disconnect)); + _state.SymbolTable[PredefinedIdentifiers.CREATE_ACCOUNT_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_ACCOUNT_FUNC, CreateAccountAsync)); + _state.SymbolTable[PredefinedIdentifiers.LOGIN_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.LOGIN_FUNC, LoginAsync)); + _state.SymbolTable[PredefinedIdentifiers.CREATE_AND_LOGIN_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_AND_LOGIN_FUNC, CreateAndLoginAsync)); + _state.SymbolTable[PredefinedIdentifiers.CHANGE_PASS_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CHANGE_PASS_FUNC, ChangePasswordAsync)); + _state.SymbolTable[PredefinedIdentifiers.CREATE_CHARACTER_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_CHARACTER_FUNC, CreateCharacterAsync)); + _state.SymbolTable[PredefinedIdentifiers.DELETE_CHARACTER_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.DELETE_CHARACTER_FUNC, DeleteCharacterAsync)); + _state.SymbolTable[PredefinedIdentifiers.LOGIN_CHARACTER_FUNC] = Readonly(new AsyncVoidFunction(PredefinedIdentifiers.LOGIN_CHARACTER_FUNC, LoginToCharacterAsync)); + + // in-game stuff + _state.SymbolTable[PredefinedIdentifiers.JOIN_PARTY] = Readonly(new VoidFunction(PredefinedIdentifiers.JOIN_PARTY, JoinParty)); + _state.SymbolTable[PredefinedIdentifiers.CHAT] = Readonly(new VoidFunction(PredefinedIdentifiers.CHAT, Chat)); + } - public void SetupBuiltInFunctions() - { - _state.SymbolTable[PredefinedIdentifiers.PRINT_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.PRINT_FUNC, param1 => ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, param1.ToString()))); - _state.SymbolTable[PredefinedIdentifiers.LEN_FUNC] = Readonly(new Function(PredefinedIdentifiers.LEN_FUNC, param1 => param1.Value.Count)); - _state.SymbolTable[PredefinedIdentifiers.ARRAY_FUNC] = Readonly(new Function>(PredefinedIdentifiers.ARRAY_FUNC, param1 => Enumerable.Repeat(UndefinedVariable.Instance, param1).Cast().ToList())); - _state.SymbolTable[PredefinedIdentifiers.SLEEP_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.SLEEP_FUNC, param1 => Thread.Sleep(param1))); - _state.SymbolTable[PredefinedIdentifiers.TIME_FUNC] = Readonly(new Function(PredefinedIdentifiers.TIME_FUNC, () => DateTime.Now.ToLongTimeString())); - _state.SymbolTable[PredefinedIdentifiers.OBJECT_FUNC] = Readonly(new Function(PredefinedIdentifiers.OBJECT_FUNC, () => new ObjectVariable())); - _state.SymbolTable[PredefinedIdentifiers.SETENV_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.SETENV_FUNC, (varName, varValue) => Environment.SetEnvironmentVariable(varName, varValue, EnvironmentVariableTarget.User))); - _state.SymbolTable[PredefinedIdentifiers.GETENV_FUNC] = Readonly(new Function(PredefinedIdentifiers.GETENV_FUNC, varName => Environment.GetEnvironmentVariable(varName, EnvironmentVariableTarget.User))); - _state.SymbolTable[PredefinedIdentifiers.ERROR_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.ERROR_FUNC, message => throw new BotScriptErrorException(message))); - _state.SymbolTable[PredefinedIdentifiers.LOWER_FUNC] = Readonly(new Function(PredefinedIdentifiers.LOWER_FUNC, s => s.ToLower())); - _state.SymbolTable[PredefinedIdentifiers.UPPER_FUNC] = Readonly(new Function(PredefinedIdentifiers.UPPER_FUNC, s => s.ToUpper())); - - BotDependencySetup(); - // pre-game flow - _state.SymbolTable[PredefinedIdentifiers.CONNECT_FUNC] = Readonly(new AsyncVoidFunction(PredefinedIdentifiers.CONNECT_FUNC, ConnectAsync)); - _state.SymbolTable[PredefinedIdentifiers.DISCONNECT_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.DISCONNECT_FUNC, Disconnect)); - _state.SymbolTable[PredefinedIdentifiers.CREATE_ACCOUNT_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_ACCOUNT_FUNC, CreateAccountAsync)); - _state.SymbolTable[PredefinedIdentifiers.LOGIN_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.LOGIN_FUNC, LoginAsync)); - _state.SymbolTable[PredefinedIdentifiers.CREATE_AND_LOGIN_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_AND_LOGIN_FUNC, CreateAndLoginAsync)); - _state.SymbolTable[PredefinedIdentifiers.CHANGE_PASS_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CHANGE_PASS_FUNC, ChangePasswordAsync)); - _state.SymbolTable[PredefinedIdentifiers.CREATE_CHARACTER_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_CHARACTER_FUNC, CreateCharacterAsync)); - _state.SymbolTable[PredefinedIdentifiers.DELETE_CHARACTER_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.DELETE_CHARACTER_FUNC, DeleteCharacterAsync)); - _state.SymbolTable[PredefinedIdentifiers.LOGIN_CHARACTER_FUNC] = Readonly(new AsyncVoidFunction(PredefinedIdentifiers.LOGIN_CHARACTER_FUNC, LoginToCharacterAsync)); - - // in-game stuff - _state.SymbolTable[PredefinedIdentifiers.JOIN_PARTY] = Readonly(new VoidFunction(PredefinedIdentifiers.JOIN_PARTY, JoinParty)); - _state.SymbolTable[PredefinedIdentifiers.CHAT] = Readonly(new VoidFunction(PredefinedIdentifiers.CHAT, Chat)); - } + public void SetupBuiltInVariables() + { + _state.SymbolTable[PredefinedIdentifiers.HOST] = Readonly(new StringVariable(_parsedArgs.Host)); + _state.SymbolTable[PredefinedIdentifiers.PORT] = Readonly(new IntVariable(_parsedArgs.Port)); + _state.SymbolTable[PredefinedIdentifiers.USER] = Readonly(new StringVariable(_parsedArgs.Account)); + _state.SymbolTable[PredefinedIdentifiers.PASS] = Readonly(new StringVariable(_parsedArgs.Password)); + _state.SymbolTable[PredefinedIdentifiers.BOTINDEX] = Readonly(new IntVariable(_botIndex)); + _state.SymbolTable[PredefinedIdentifiers.ARGS] = Readonly(new ArrayVariable( + (_parsedArgs.UserArgs ?? new List()).Select(x => new StringVariable(x)).Cast().ToList())); + + // default to version 0.0.28 + _state.SymbolTable[PredefinedIdentifiers.VERSION] = (false, new IntVariable(28)); + + _state.SymbolTable[PredefinedIdentifiers.RESULT] = (false, UndefinedVariable.Instance); + _state.SymbolTable[PredefinedIdentifiers.ACCOUNT] = SetupAccountObject(); + _state.SymbolTable[PredefinedIdentifiers.CHARACTER] = SetupCharacterObject(); + _state.SymbolTable[PredefinedIdentifiers.MAPSTATE] = SetupMapStateObject(); + } - public void SetupBuiltInVariables() - { - _state.SymbolTable[PredefinedIdentifiers.HOST] = Readonly(new StringVariable(_parsedArgs.Host)); - _state.SymbolTable[PredefinedIdentifiers.PORT] = Readonly(new IntVariable(_parsedArgs.Port)); - _state.SymbolTable[PredefinedIdentifiers.USER] = Readonly(new StringVariable(_parsedArgs.Account)); - _state.SymbolTable[PredefinedIdentifiers.PASS] = Readonly(new StringVariable(_parsedArgs.Password)); - _state.SymbolTable[PredefinedIdentifiers.BOTINDEX] = Readonly(new IntVariable(_botIndex)); - _state.SymbolTable[PredefinedIdentifiers.ARGS] = Readonly(new ArrayVariable( - (_parsedArgs.UserArgs ?? new List()).Select(x => new StringVariable(x)).Cast().ToList())); - - // default to version 0.0.28 - _state.SymbolTable[PredefinedIdentifiers.VERSION] = (false, new IntVariable(28)); - - _state.SymbolTable[PredefinedIdentifiers.RESULT] = (false, UndefinedVariable.Instance); - _state.SymbolTable[PredefinedIdentifiers.ACCOUNT] = SetupAccountObject(); - _state.SymbolTable[PredefinedIdentifiers.CHARACTER] = SetupCharacterObject(); - _state.SymbolTable[PredefinedIdentifiers.MAPSTATE] = SetupMapStateObject(); - } + private static (bool, IIdentifiable) Readonly(IIdentifiable identifiable) + { + return (true, identifiable); + } - private static (bool, IIdentifiable) Readonly(IIdentifiable identifiable) - { - return (true, identifiable); - } + private void BotDependencySetup() + { + var c = DependencyMaster.TypeRegistry[_botIndex]; + var networkClientRepository = c.Resolve(); + var networkClientFactory = c.Resolve(); - private void BotDependencySetup() - { - var c = DependencyMaster.TypeRegistry[_botIndex]; - var networkClientRepository = c.Resolve(); - var networkClientFactory = c.Resolve(); + const int LongReceiveTimeout = 15000; + networkClientRepository.NetworkClient = networkClientFactory.CreateNetworkClient(LongReceiveTimeout); + } - const int LongReceiveTimeout = 15000; - networkClientRepository.NetworkClient = networkClientFactory.CreateNetworkClient(LongReceiveTimeout); - } + private async Task ConnectAsync(string host, int port) + { + var c = DependencyMaster.TypeRegistry[_botIndex]; - private async Task ConnectAsync(string host, int port) - { - var c = DependencyMaster.TypeRegistry[_botIndex]; + var configRepo = c.Resolve(); + configRepo.Host = host; + configRepo.Port = port; - var configRepo = c.Resolve(); - configRepo.Host = host; - configRepo.Port = port; + configRepo.VersionBuild = ((IntVariable)_state.SymbolTable[PredefinedIdentifiers.VERSION].Identifiable).Value; - configRepo.VersionBuild = ((IntVariable)_state.SymbolTable[PredefinedIdentifiers.VERSION].Identifiable).Value; + var connectionActions = c.Resolve(); + var connectResult = await connectionActions.ConnectToServer(); + if (connectResult != ConnectResult.Success) + throw new ArgumentException($"Bot {_botIndex}: Unable to connect to server! Host={host} Port={port}"); - var connectionActions = c.Resolve(); - var connectResult = await connectionActions.ConnectToServer(); - if (connectResult != ConnectResult.Success) - throw new ArgumentException($"Bot {_botIndex}: Unable to connect to server! Host={host} Port={port}"); + var backgroundReceiveActions = c.Resolve(); + backgroundReceiveActions.RunBackgroundReceiveLoop(); - var backgroundReceiveActions = c.Resolve(); - backgroundReceiveActions.RunBackgroundReceiveLoop(); + var handshakeResult = await connectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)); - var handshakeResult = await connectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)); + if (handshakeResult.ReplyCode != InitReply.Ok) + throw new InvalidOperationException($"Bot {_botIndex}: Invalid response from server or connection failed! Must receive an OK reply."); - if (handshakeResult.ReplyCode != InitReply.Ok) - throw new InvalidOperationException($"Bot {_botIndex}: Invalid response from server or connection failed! Must receive an OK reply."); + var handshakeData = (InitInitServerPacket.ReplyCodeDataOk)handshakeResult.ReplyCodeData; - var handshakeData = (InitInitServerPacket.ReplyCodeDataOk)handshakeResult.ReplyCodeData; + var packetProcessActions = c.Resolve(); + packetProcessActions.SetSequenceStart(InitSequenceStart.FromInitValues(handshakeData.Seq1, handshakeData.Seq2)); + packetProcessActions.SetEncodeMultiples(handshakeData.ServerEncryptionMultiple, handshakeData.ClientEncryptionMultiple); - var packetProcessActions = c.Resolve(); - packetProcessActions.SetSequenceStart(InitSequenceStart.FromInitValues(handshakeData.Seq1, handshakeData.Seq2)); - packetProcessActions.SetEncodeMultiples(handshakeData.ServerEncryptionMultiple, handshakeData.ClientEncryptionMultiple); + connectionActions.CompleteHandshake(handshakeResult); + } - connectionActions.CompleteHandshake(handshakeResult); - } + private void Disconnect() + { + var c = DependencyMaster.TypeRegistry[_botIndex]; + var backgroundReceiveActions = c.Resolve(); + var connectionActions = c.Resolve(); - private void Disconnect() - { - var c = DependencyMaster.TypeRegistry[_botIndex]; - var backgroundReceiveActions = c.Resolve(); - var connectionActions = c.Resolve(); + backgroundReceiveActions.CancelBackgroundReceiveLoop(); + connectionActions.DisconnectFromServer(); + } - backgroundReceiveActions.CancelBackgroundReceiveLoop(); - connectionActions.DisconnectFromServer(); - } + private async Task CreateAccountAsync(string user, string pass) + { + return (int)await _botHelper.CreateAccountAsync(user, pass); + } - private async Task CreateAccountAsync(string user, string pass) - { - return (int)await _botHelper.CreateAccountAsync(user, pass); - } + private async Task LoginAsync(string user, string pass) + { + return (int)await _botHelper.LoginToAccountAsync(user, pass); + } - private async Task LoginAsync(string user, string pass) + private async Task CreateAndLoginAsync(string user, string pass) + { + var accountReply = (AccountReply)await CreateAccountAsync(user, pass); + if (accountReply == AccountReply.Created || accountReply == AccountReply.Exists) { - return (int)await _botHelper.LoginToAccountAsync(user, pass); + return await LoginAsync(user, pass); } - private async Task CreateAndLoginAsync(string user, string pass) - { - var accountReply = (AccountReply)await CreateAccountAsync(user, pass); - if (accountReply == AccountReply.Created || accountReply == AccountReply.Exists) - { - return await LoginAsync(user, pass); - } + return (int)LoginReply.WrongUser; + } - return (int)LoginReply.WrongUser; - } + private async Task ChangePasswordAsync(string user, string oldPass, string newPass) + { + return (int)await _botHelper.ChangePasswordAsync(user, oldPass, newPass); + } - private async Task ChangePasswordAsync(string user, string oldPass, string newPass) - { - return (int)await _botHelper.ChangePasswordAsync(user, oldPass, newPass); - } + private async Task CreateCharacterAsync(string charName) + { + return (int)await _botHelper.CreateCharacterAsync(charName); + } - private async Task CreateCharacterAsync(string charName) - { - return (int)await _botHelper.CreateCharacterAsync(charName); - } + private async Task DeleteCharacterAsync(string charName, bool force) + { + return (int)await _botHelper.DeleteCharacterAsync(charName, force); + } - private async Task DeleteCharacterAsync(string charName, bool force) - { - return (int)await _botHelper.DeleteCharacterAsync(charName, force); - } + private Task LoginToCharacterAsync(string charName) + { + return _botHelper.LoginToCharacterAsync(charName); + } - private Task LoginToCharacterAsync(string charName) - { - return _botHelper.LoginToCharacterAsync(charName); - } + private void JoinParty(int characterId) + { + var c = DependencyMaster.TypeRegistry[_botIndex]; + c.Resolve().RequestParty(PartyRequestType.Join, characterId); + } - private void JoinParty(int characterId) - { - var c = DependencyMaster.TypeRegistry[_botIndex]; - c.Resolve().RequestParty(PartyRequestType.Join, characterId); - } + private void Chat(string chatText) + { + var c = DependencyMaster.TypeRegistry[_botIndex]; + c.Resolve().SendChatToServer(chatText, string.Empty, ChatType.Local); + } - private void Chat(string chatText) - { - var c = DependencyMaster.TypeRegistry[_botIndex]; - c.Resolve().SendChatToServer(chatText, string.Empty, ChatType.Local); - } + private (bool, IIdentifiable) SetupAccountObject() + { + var playerInfoProv = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var charSelectProv = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + + var accountObj = new RuntimeEvaluatedMemberObjectVariable(); + accountObj.SymbolTable[PredefinedIdentifiers.NAME] = (true, () => new StringVariable(playerInfoProv.LoggedInAccountName)); + accountObj.SymbolTable[PredefinedIdentifiers.CHARACTERS] = (true, + () => new ArrayVariable( + charSelectProv.Characters.Select(x => + { + var retObj = new ObjectVariable(); + retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(x.Name)); + return (IVariable)retObj; + }).ToList())); - private (bool, IIdentifiable) SetupAccountObject() - { - var playerInfoProv = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var charSelectProv = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - - var accountObj = new RuntimeEvaluatedMemberObjectVariable(); - accountObj.SymbolTable[PredefinedIdentifiers.NAME] = (true, () => new StringVariable(playerInfoProv.LoggedInAccountName)); - accountObj.SymbolTable[PredefinedIdentifiers.CHARACTERS] = (true, - () => new ArrayVariable( - charSelectProv.Characters.Select(x => - { - var retObj = new ObjectVariable(); - retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(x.Name)); - return (IVariable)retObj; - }).ToList())); - - return Readonly(accountObj); - } + return Readonly(accountObj); + } - private (bool, IIdentifiable) SetupCharacterObject() - { - var cp = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var inventoryProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var pubProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - - var charObj = new RuntimeEvaluatedMemberObjectVariable(); - charObj.SymbolTable["id"] = (true, () => new IntVariable(cp.MainCharacter.ID)); - charObj.SymbolTable[PredefinedIdentifiers.NAME] = (true, () => new StringVariable(cp.MainCharacter.Name)); - charObj.SymbolTable["map"] = (true, () => new IntVariable(cp.MainCharacter.MapID)); - charObj.SymbolTable["x"] = (true, () => new IntVariable(cp.MainCharacter.RenderProperties.MapX)); - charObj.SymbolTable["y"] = (true, () => new IntVariable(cp.MainCharacter.RenderProperties.MapY)); - charObj.SymbolTable["direction"] = (true, () => new IntVariable((int)cp.MainCharacter.RenderProperties.Direction)); - charObj.SymbolTable["admin"] = (true, () => new IntVariable((int)cp.MainCharacter.AdminLevel)); - charObj.SymbolTable["inventory"] = (true, - () => new ArrayVariable( - inventoryProvider.ItemInventory.Select(x => - { - var itemName = pubProvider.EIFFile.Single(d => d.ID == x.ItemID).Name; - - var retObj = new ObjectVariable(); - retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(itemName)); - retObj.SymbolTable["id"] = Readonly(new IntVariable(x.ItemID)); - retObj.SymbolTable["amount"] = Readonly(new IntVariable(x.Amount)); - return (IVariable)retObj; - }).ToList())); - charObj.SymbolTable["spells"] = (true, - () => new ArrayVariable( - inventoryProvider.SpellInventory.Select(x => - { - var spellName = pubProvider.ESFFile.Single(d => d.ID == x.ID).Name; - - var retObj = new ObjectVariable(); - retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(spellName)); - retObj.SymbolTable["id"] = Readonly(new IntVariable(x.ID)); - retObj.SymbolTable["amount"] = Readonly(new IntVariable(x.Level)); - return (IVariable)retObj; - }).ToList())); - charObj.SymbolTable["stats"] = (true, - () => + private (bool, IIdentifiable) SetupCharacterObject() + { + var cp = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var inventoryProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var pubProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + + var charObj = new RuntimeEvaluatedMemberObjectVariable(); + charObj.SymbolTable["id"] = (true, () => new IntVariable(cp.MainCharacter.ID)); + charObj.SymbolTable[PredefinedIdentifiers.NAME] = (true, () => new StringVariable(cp.MainCharacter.Name)); + charObj.SymbolTable["map"] = (true, () => new IntVariable(cp.MainCharacter.MapID)); + charObj.SymbolTable["x"] = (true, () => new IntVariable(cp.MainCharacter.RenderProperties.MapX)); + charObj.SymbolTable["y"] = (true, () => new IntVariable(cp.MainCharacter.RenderProperties.MapY)); + charObj.SymbolTable["direction"] = (true, () => new IntVariable((int)cp.MainCharacter.RenderProperties.Direction)); + charObj.SymbolTable["admin"] = (true, () => new IntVariable((int)cp.MainCharacter.AdminLevel)); + charObj.SymbolTable["inventory"] = (true, + () => new ArrayVariable( + inventoryProvider.ItemInventory.Select(x => { - var statsObj = new ObjectVariable(); - statsObj.SymbolTable["hp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.HP])); - statsObj.SymbolTable["maxhp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxHP])); - statsObj.SymbolTable["weight"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.Weight])); - statsObj.SymbolTable["maxweight"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxWeight])); - statsObj.SymbolTable["tp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.TP])); - statsObj.SymbolTable["maxtp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxTP])); - return statsObj; - } - ); - - return Readonly(charObj); - } + var itemName = pubProvider.EIFFile.Single(d => d.ID == x.ItemID).Name; + + var retObj = new ObjectVariable(); + retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(itemName)); + retObj.SymbolTable["id"] = Readonly(new IntVariable(x.ItemID)); + retObj.SymbolTable["amount"] = Readonly(new IntVariable(x.Amount)); + return (IVariable)retObj; + }).ToList())); + charObj.SymbolTable["spells"] = (true, + () => new ArrayVariable( + inventoryProvider.SpellInventory.Select(x => + { + var spellName = pubProvider.ESFFile.Single(d => d.ID == x.ID).Name; + + var retObj = new ObjectVariable(); + retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(spellName)); + retObj.SymbolTable["id"] = Readonly(new IntVariable(x.ID)); + retObj.SymbolTable["amount"] = Readonly(new IntVariable(x.Level)); + return (IVariable)retObj; + }).ToList())); + charObj.SymbolTable["stats"] = (true, + () => + { + var statsObj = new ObjectVariable(); + statsObj.SymbolTable["hp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.HP])); + statsObj.SymbolTable["maxhp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxHP])); + statsObj.SymbolTable["weight"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.Weight])); + statsObj.SymbolTable["maxweight"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxWeight])); + statsObj.SymbolTable["tp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.TP])); + statsObj.SymbolTable["maxtp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxTP])); + return statsObj; + } + ); - private (bool, IIdentifiable) SetupMapStateObject() - { - var ms = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + return Readonly(charObj); + } - var mapStateObj = new RuntimeEvaluatedMemberObjectVariable(); - mapStateObj.SymbolTable["characters"] = (true, () => new ArrayVariable(ms.Characters.Select(GetMapStateCharacter).ToList())); - mapStateObj.SymbolTable["npcs"] = (true, () => new ArrayVariable(ms.NPCs.Select(GetMapStateNPC).ToList())); - mapStateObj.SymbolTable["items"] = (true, () => new ArrayVariable(ms.MapItems.Select(GetMapStateItem).ToList())); + private (bool, IIdentifiable) SetupMapStateObject() + { + var ms = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - return Readonly(mapStateObj); - } + var mapStateObj = new RuntimeEvaluatedMemberObjectVariable(); + mapStateObj.SymbolTable["characters"] = (true, () => new ArrayVariable(ms.Characters.Select(GetMapStateCharacter).ToList())); + mapStateObj.SymbolTable["npcs"] = (true, () => new ArrayVariable(ms.NPCs.Select(GetMapStateNPC).ToList())); + mapStateObj.SymbolTable["items"] = (true, () => new ArrayVariable(ms.MapItems.Select(GetMapStateItem).ToList())); - private IVariable GetMapStateCharacter(Character c) - { - var charObj = new ObjectVariable(); - charObj.SymbolTable["id"] = Readonly(new IntVariable(c.ID)); - charObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(c.Name)); - charObj.SymbolTable["map"] = Readonly(new IntVariable(c.MapID)); - charObj.SymbolTable["x"] = Readonly(new IntVariable(c.RenderProperties.MapX)); - charObj.SymbolTable["y"] = Readonly(new IntVariable(c.RenderProperties.MapY)); - charObj.SymbolTable["direction"] = Readonly(new IntVariable((int)c.RenderProperties.Direction)); - return charObj; - } + return Readonly(mapStateObj); + } - private IVariable GetMapStateNPC(NPC npc) - { - var npcFile = DependencyMaster.TypeRegistry[_botIndex].Resolve().ENFFile; - - var npcObj = new ObjectVariable(); - npcObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(npcFile.Single(x => x.ID == npc.ID).Name)); - npcObj.SymbolTable["x"] = Readonly(new IntVariable(npc.X)); - npcObj.SymbolTable["y"] = Readonly(new IntVariable(npc.Y)); - npcObj.SymbolTable["id"] = Readonly(new IntVariable(npc.ID)); - npcObj.SymbolTable["direction"] = Readonly(new IntVariable((int)npc.Direction)); - return npcObj; - } + private IVariable GetMapStateCharacter(Character c) + { + var charObj = new ObjectVariable(); + charObj.SymbolTable["id"] = Readonly(new IntVariable(c.ID)); + charObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(c.Name)); + charObj.SymbolTable["map"] = Readonly(new IntVariable(c.MapID)); + charObj.SymbolTable["x"] = Readonly(new IntVariable(c.RenderProperties.MapX)); + charObj.SymbolTable["y"] = Readonly(new IntVariable(c.RenderProperties.MapY)); + charObj.SymbolTable["direction"] = Readonly(new IntVariable((int)c.RenderProperties.Direction)); + return charObj; + } - private IVariable GetMapStateItem(MapItem item) - { - var itemFile = DependencyMaster.TypeRegistry[_botIndex].Resolve().EIFFile; - - var itemObj = new ObjectVariable(); - itemObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(itemFile.Single(x => x.ID == item.ItemID).Name)); - itemObj.SymbolTable["x"] = Readonly(new IntVariable(item.X)); - itemObj.SymbolTable["y"] = Readonly(new IntVariable(item.Y)); - itemObj.SymbolTable["id"] = Readonly(new IntVariable(item.ItemID)); - itemObj.SymbolTable["amount"] = Readonly(new IntVariable(item.Amount)); - return itemObj; - } + private IVariable GetMapStateNPC(NPC npc) + { + var npcFile = DependencyMaster.TypeRegistry[_botIndex].Resolve().ENFFile; + + var npcObj = new ObjectVariable(); + npcObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(npcFile.Single(x => x.ID == npc.ID).Name)); + npcObj.SymbolTable["x"] = Readonly(new IntVariable(npc.X)); + npcObj.SymbolTable["y"] = Readonly(new IntVariable(npc.Y)); + npcObj.SymbolTable["id"] = Readonly(new IntVariable(npc.ID)); + npcObj.SymbolTable["direction"] = Readonly(new IntVariable((int)npc.Direction)); + return npcObj; + } + + private IVariable GetMapStateItem(MapItem item) + { + var itemFile = DependencyMaster.TypeRegistry[_botIndex].Resolve().EIFFile; + + var itemObj = new ObjectVariable(); + itemObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(itemFile.Single(x => x.ID == item.ItemID).Name)); + itemObj.SymbolTable["x"] = Readonly(new IntVariable(item.X)); + itemObj.SymbolTable["y"] = Readonly(new IntVariable(item.Y)); + itemObj.SymbolTable["id"] = Readonly(new IntVariable(item.ItemID)); + itemObj.SymbolTable["amount"] = Readonly(new IntVariable(item.Amount)); + return itemObj; } } \ No newline at end of file diff --git a/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs b/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs index 4a7ec0625..19f1d6f72 100644 --- a/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs +++ b/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs @@ -1,28 +1,27 @@ using EOBot.Interpreter.States; -namespace EOBot.Interpreter.Extensions +namespace EOBot.Interpreter.Extensions; + +public static class ProgramStateExtensions { - public static class ProgramStateExtensions + public static bool MatchOneOf(this ProgramState input, params BotTokenType[] tokenTypes) { - public static bool MatchOneOf(this ProgramState input, params BotTokenType[] tokenTypes) + // todo: there's probably LINQ for this but I'm tired and my brain isn't quite working + // needs to stop trying to match after first match, can't use FirstOrDefault unless default(BotTokenType) can be used as an "empty" value + foreach (var type in tokenTypes) { - // todo: there's probably LINQ for this but I'm tired and my brain isn't quite working - // needs to stop trying to match after first match, can't use FirstOrDefault unless default(BotTokenType) can be used as an "empty" value - foreach (var type in tokenTypes) - { - if (input.Match(type)) - return true; - } - - return false; + if (input.Match(type)) + return true; } - public static BotToken Current(this ProgramState input) - { - if (input.ExecutionIndex >= input.Program.Count) - return input.Program[input.Program.Count - 1]; + return false; + } - return input.Program[input.ExecutionIndex]; - } + public static BotToken Current(this ProgramState input) + { + if (input.ExecutionIndex >= input.Program.Count) + return input.Program[input.Program.Count - 1]; + + return input.Program[input.ExecutionIndex]; } } \ No newline at end of file diff --git a/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs b/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs index 974525d41..aefdbdf21 100644 --- a/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs +++ b/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs @@ -2,55 +2,54 @@ using EOBot.Interpreter.Variables; using System.Collections.Generic; -namespace EOBot.Interpreter.Extensions +namespace EOBot.Interpreter.Extensions; + +public static class SymbolTableExtensions { - public static class SymbolTableExtensions + + public static (EvalResult Result, string Reason, IVariable Variable) GetVariable(this Dictionary symbols, string identifier, int? arrayIndex = null) { + if (!symbols.ContainsKey(identifier)) + symbols[identifier] = (false, UndefinedVariable.Instance); - public static (EvalResult Result, string Reason, IVariable Variable) GetVariable(this Dictionary symbols, string identifier, int? arrayIndex = null) + var variableValue = symbols[identifier].Identifiable as IVariable; + if (variableValue == null) { - if (!symbols.ContainsKey(identifier)) - symbols[identifier] = (false, UndefinedVariable.Instance); + return (EvalResult.Failed, $"Identifier {identifier} is not a variable", null); + } - var variableValue = symbols[identifier].Identifiable as IVariable; - if (variableValue == null) + if (arrayIndex != null) + { + var arrayVariable = variableValue as ArrayVariable; + + if (arrayVariable == null) { - return (EvalResult.Failed, $"Identifier {identifier} is not a variable", null); + return (EvalResult.Failed, $"Identifier {identifier} is not an array", null); } - if (arrayIndex != null) + if (arrayVariable.Value.Count <= arrayIndex.Value) { - var arrayVariable = variableValue as ArrayVariable; - - if (arrayVariable == null) - { - return (EvalResult.Failed, $"Identifier {identifier} is not an array", null); - } - - if (arrayVariable.Value.Count <= arrayIndex.Value) - { - return (EvalResult.Failed, $"Index {arrayIndex.Value} is out of range of the array {identifier} (size {arrayVariable.Value.Count})", null); - } - - variableValue = arrayVariable.Value[arrayIndex.Value]; + return (EvalResult.Failed, $"Index {arrayIndex.Value} is out of range of the array {identifier} (size {arrayVariable.Value.Count})", null); } - return (EvalResult.Ok, string.Empty, variableValue); + variableValue = arrayVariable.Value[arrayIndex.Value]; } - public static (EvalResult Result, string Reason, T Variable) GetVariable(this Dictionary symbols, string identifier, int? arrayIndex = null) - where T : class, IVariable - { - var getResult = GetVariable(symbols, identifier, arrayIndex); + return (EvalResult.Ok, string.Empty, variableValue); + } - if (getResult.Result != EvalResult.Ok) - return (getResult.Result, getResult.Reason, null); + public static (EvalResult Result, string Reason, T Variable) GetVariable(this Dictionary symbols, string identifier, int? arrayIndex = null) + where T : class, IVariable + { + var getResult = GetVariable(symbols, identifier, arrayIndex); - var variable = getResult.Variable as T; - if (variable == null) - return (EvalResult.Failed, $"Identifier {identifier} is not a {typeof(T).Name}", null); + if (getResult.Result != EvalResult.Ok) + return (getResult.Result, getResult.Reason, null); - return (EvalResult.Ok, string.Empty, variable); - } + var variable = getResult.Variable as T; + if (variable == null) + return (EvalResult.Failed, $"Identifier {identifier} is not a {typeof(T).Name}", null); + + return (EvalResult.Ok, string.Empty, variable); } } \ No newline at end of file diff --git a/EOBot/Interpreter/IdentifierBotToken.cs b/EOBot/Interpreter/IdentifierBotToken.cs index 5b59a915e..50ec2250d 100644 --- a/EOBot/Interpreter/IdentifierBotToken.cs +++ b/EOBot/Interpreter/IdentifierBotToken.cs @@ -1,16 +1,15 @@ -namespace EOBot.Interpreter +namespace EOBot.Interpreter; + +public class IdentifierBotToken : BotToken { - public class IdentifierBotToken : BotToken - { - public int? ArrayIndex { get; } + public int? ArrayIndex { get; } - public IdentifierBotToken Member { get; } + public IdentifierBotToken Member { get; } - public IdentifierBotToken(BotToken identifier, int? arrayIndex = null, IdentifierBotToken member = null) - : base(identifier.TokenType, identifier.TokenValue, identifier.LineNumber, identifier.Column) - { - ArrayIndex = arrayIndex; - Member = member; - } + public IdentifierBotToken(BotToken identifier, int? arrayIndex = null, IdentifierBotToken member = null) + : base(identifier.TokenType, identifier.TokenValue, identifier.LineNumber, identifier.Column) + { + ArrayIndex = arrayIndex; + Member = member; } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/AssignmentEvaluator.cs b/EOBot/Interpreter/States/AssignmentEvaluator.cs index 4cd58275e..ad0d3c600 100644 --- a/EOBot/Interpreter/States/AssignmentEvaluator.cs +++ b/EOBot/Interpreter/States/AssignmentEvaluator.cs @@ -4,96 +4,95 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class AssignmentEvaluator : BaseEvaluator { - public class AssignmentEvaluator : BaseEvaluator - { - public AssignmentEvaluator(IEnumerable evaluators) - : base(evaluators) { } + public AssignmentEvaluator(IEnumerable evaluators) + : base(evaluators) { } - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) - { - var eval = await Evaluator().EvaluateAsync(input); - if (eval.Result != EvalResult.Ok) - return eval; + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + var eval = await Evaluator().EvaluateAsync(input); + if (eval.Result != EvalResult.Ok) + return eval; - if (!input.Match(BotTokenType.AssignOperator)) - return Error(input.Current(), BotTokenType.AssignOperator); + if (!input.Match(BotTokenType.AssignOperator)) + return Error(input.Current(), BotTokenType.AssignOperator); - eval = await Evaluator().EvaluateAsync(input); - if (eval.Result != EvalResult.Ok) - return eval; + eval = await Evaluator().EvaluateAsync(input); + if (eval.Result != EvalResult.Ok) + return eval; - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var expressionResult = (VariableBotToken)input.OperationStack.Pop(); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var expressionResult = (VariableBotToken)input.OperationStack.Pop(); - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var assignOp = input.OperationStack.Pop(); - if (assignOp.TokenType != BotTokenType.AssignOperator) - return StackTokenError(BotTokenType.AssignOperator, assignOp); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var assignOp = input.OperationStack.Pop(); + if (assignOp.TokenType != BotTokenType.AssignOperator) + return StackTokenError(BotTokenType.AssignOperator, assignOp); - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var assignmentTarget = (IdentifierBotToken)input.OperationStack.Pop(); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var assignmentTarget = (IdentifierBotToken)input.OperationStack.Pop(); - return Assign(input.SymbolTable, assignmentTarget, expressionResult); - } + return Assign(input.SymbolTable, assignmentTarget, expressionResult); + } - private (EvalResult, string, BotToken) Assign(Dictionary symbols, IdentifierBotToken assignmentTarget, VariableBotToken expressionResult) + private (EvalResult, string, BotToken) Assign(Dictionary symbols, IdentifierBotToken assignmentTarget, VariableBotToken expressionResult) + { + if (assignmentTarget.Member != null) { - if (assignmentTarget.Member != null) + if (!symbols.ContainsKey(assignmentTarget.TokenValue)) + return IdentifierNotFoundError(assignmentTarget); + + var getVariableRes = symbols.GetVariable(assignmentTarget.TokenValue, assignmentTarget.ArrayIndex); + if (getVariableRes.Result != EvalResult.Ok) { - if (!symbols.ContainsKey(assignmentTarget.TokenValue)) - return IdentifierNotFoundError(assignmentTarget); - - var getVariableRes = symbols.GetVariable(assignmentTarget.TokenValue, assignmentTarget.ArrayIndex); - if (getVariableRes.Result != EvalResult.Ok) - { - var getRuntimeEvaluatedVariableRes = symbols.GetVariable(assignmentTarget.TokenValue, assignmentTarget.ArrayIndex); - if (getRuntimeEvaluatedVariableRes.Result != EvalResult.Ok) - return (EvalResult.Failed, $"Identifier '{assignmentTarget.TokenValue}' is not an object", assignmentTarget); - - getVariableRes.Result = getRuntimeEvaluatedVariableRes.Result; - getVariableRes.Reason = getRuntimeEvaluatedVariableRes.Reason; - getVariableRes.Variable = new ObjectVariable( - getRuntimeEvaluatedVariableRes.Variable.SymbolTable - .Select(x => (x.Key, (x.Value.ReadOnly, x.Value.Variable()))) - .ToDictionary(x => x.Key, x => x.Item2)); - } - - var targetObject = getVariableRes.Variable; - return Assign(targetObject.SymbolTable, assignmentTarget.Member, expressionResult); + var getRuntimeEvaluatedVariableRes = symbols.GetVariable(assignmentTarget.TokenValue, assignmentTarget.ArrayIndex); + if (getRuntimeEvaluatedVariableRes.Result != EvalResult.Ok) + return (EvalResult.Failed, $"Identifier '{assignmentTarget.TokenValue}' is not an object", assignmentTarget); + + getVariableRes.Result = getRuntimeEvaluatedVariableRes.Result; + getVariableRes.Reason = getRuntimeEvaluatedVariableRes.Reason; + getVariableRes.Variable = new ObjectVariable( + getRuntimeEvaluatedVariableRes.Variable.SymbolTable + .Select(x => (x.Key, (x.Value.ReadOnly, x.Value.Variable()))) + .ToDictionary(x => x.Key, x => x.Item2)); } - if (assignmentTarget.ArrayIndex != null) - { - if (!symbols.ContainsKey(assignmentTarget.TokenValue)) - return IdentifierNotFoundError(assignmentTarget); + var targetObject = getVariableRes.Variable; + return Assign(targetObject.SymbolTable, assignmentTarget.Member, expressionResult); + } - var getVariableResult = symbols.GetVariable(assignmentTarget.TokenValue); - if (getVariableResult.Result != EvalResult.Ok) - return (getVariableResult.Result, getVariableResult.Reason, assignmentTarget); + if (assignmentTarget.ArrayIndex != null) + { + if (!symbols.ContainsKey(assignmentTarget.TokenValue)) + return IdentifierNotFoundError(assignmentTarget); - var targetArray = getVariableResult.Variable; - targetArray.Value[assignmentTarget.ArrayIndex.Value] = expressionResult.VariableValue; - } - else - { - if (symbols.ContainsKey(assignmentTarget.TokenValue) && symbols[assignmentTarget.TokenValue].ReadOnly) - return ReadOnlyVariableError(assignmentTarget); + var getVariableResult = symbols.GetVariable(assignmentTarget.TokenValue); + if (getVariableResult.Result != EvalResult.Ok) + return (getVariableResult.Result, getVariableResult.Reason, assignmentTarget); - if (symbols.ContainsKey(assignmentTarget.TokenValue) && symbols[assignmentTarget.TokenValue].Identifiable.GetType() != expressionResult.VariableValue.GetType()) - { - // todo: surface warnings to caller and let caller decide what to do with it instead of making the interpreter write to console directly - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Changing type of variable {assignmentTarget.TokenValue} from {symbols[assignmentTarget.TokenValue].Identifiable.GetType()} to {expressionResult.VariableValue.GetType()}", System.ConsoleColor.DarkYellow); - } + var targetArray = getVariableResult.Variable; + targetArray.Value[assignmentTarget.ArrayIndex.Value] = expressionResult.VariableValue; + } + else + { + if (symbols.ContainsKey(assignmentTarget.TokenValue) && symbols[assignmentTarget.TokenValue].ReadOnly) + return ReadOnlyVariableError(assignmentTarget); - symbols[assignmentTarget.TokenValue] = (false, expressionResult.VariableValue); + if (symbols.ContainsKey(assignmentTarget.TokenValue) && symbols[assignmentTarget.TokenValue].Identifiable.GetType() != expressionResult.VariableValue.GetType()) + { + // todo: surface warnings to caller and let caller decide what to do with it instead of making the interpreter write to console directly + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Changing type of variable {assignmentTarget.TokenValue} from {symbols[assignmentTarget.TokenValue].Identifiable.GetType()} to {expressionResult.VariableValue.GetType()}", System.ConsoleColor.DarkYellow); } - return Success(); + symbols[assignmentTarget.TokenValue] = (false, expressionResult.VariableValue); } + + return Success(); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/BaseEvaluator.cs b/EOBot/Interpreter/States/BaseEvaluator.cs index 39449f0f4..08df15cbe 100644 --- a/EOBot/Interpreter/States/BaseEvaluator.cs +++ b/EOBot/Interpreter/States/BaseEvaluator.cs @@ -2,83 +2,82 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public abstract class BaseEvaluator : IScriptEvaluator { - public abstract class BaseEvaluator : IScriptEvaluator + private readonly IEnumerable _evaluators; + + protected BaseEvaluator() { } + + protected BaseEvaluator(IEnumerable evaluators) + { + _evaluators = evaluators; + } + + public abstract Task<(EvalResult Result, string Reason, BotToken Token)> EvaluateAsync(ProgramState input); + + protected IScriptEvaluator Evaluator() where T : IScriptEvaluator + { + return _evaluators.OfType().Single(); + } + + protected (EvalResult, string, BotToken) Success(BotToken token = null) + { + return (EvalResult.Ok, string.Empty, token); + } + + protected (EvalResult, string, BotToken) Error(BotToken current, params BotTokenType[] expectedTypes) + { + var extra = string.IsNullOrWhiteSpace(current.TokenValue) + ? string.Empty + : $" ({current.TokenValue})"; + + if (expectedTypes.Length == 0) + return (EvalResult.Failed, string.Empty, current); + else if (expectedTypes.Length == 1) + return (EvalResult.Failed, $"Expected {expectedTypes[0]}, got {current.TokenType}{extra}", current); + else + return (EvalResult.Failed, $"Expected one of [{string.Join(", ", expectedTypes)}], got {current.TokenType}{extra}", current); + } + + protected (EvalResult, string, BotToken) UnexpectedTokenError(BotToken current, params BotTokenType[] unexpectedTypes) + { + if (unexpectedTypes.Length == 0) + return (EvalResult.Failed, string.Empty, current); + else if (unexpectedTypes.Length == 1) + return (EvalResult.Failed, $"{unexpectedTypes[0]} was unexpected", current); + else + return (EvalResult.Failed, $"One of {string.Join(",", unexpectedTypes)} was unexpected", current); + } + + protected (EvalResult, string, BotToken) StackEmptyError(BotToken current) + { + return (EvalResult.Failed, $"Expected operation stack to have operands, but it was empty", current); + } + + protected (EvalResult, string, BotToken) UnsupportedOperatorError(BotToken actualToken) + { + return (EvalResult.Failed, $"Unsupported operator evaluating expression: {actualToken.TokenType}", actualToken); + } + + protected (EvalResult, string, BotToken) StackTokenError(BotTokenType expectedTokenType, BotToken actualToken) + { + return (EvalResult.Failed, $"Expected operation stack to have {expectedTokenType} token, got {actualToken.TokenType}", actualToken); + } + + protected (EvalResult, string, BotToken) ReadOnlyVariableError(IdentifierBotToken token) + { + return (EvalResult.Failed, $"Attempted to assign value to read-only variable {token.TokenValue}", token); + } + + protected (EvalResult, string, BotToken) IdentifierNotFoundError(IdentifierBotToken token) + { + return (EvalResult.Failed, $"Identifier {token.TokenValue} is not defined", token); + } + + protected (EvalResult, string, BotToken) GotoError(BotToken token) { - private readonly IEnumerable _evaluators; - - protected BaseEvaluator() { } - - protected BaseEvaluator(IEnumerable evaluators) - { - _evaluators = evaluators; - } - - public abstract Task<(EvalResult Result, string Reason, BotToken Token)> EvaluateAsync(ProgramState input); - - protected IScriptEvaluator Evaluator() where T : IScriptEvaluator - { - return _evaluators.OfType().Single(); - } - - protected (EvalResult, string, BotToken) Success(BotToken token = null) - { - return (EvalResult.Ok, string.Empty, token); - } - - protected (EvalResult, string, BotToken) Error(BotToken current, params BotTokenType[] expectedTypes) - { - var extra = string.IsNullOrWhiteSpace(current.TokenValue) - ? string.Empty - : $" ({current.TokenValue})"; - - if (expectedTypes.Length == 0) - return (EvalResult.Failed, string.Empty, current); - else if (expectedTypes.Length == 1) - return (EvalResult.Failed, $"Expected {expectedTypes[0]}, got {current.TokenType}{extra}", current); - else - return (EvalResult.Failed, $"Expected one of [{string.Join(", ", expectedTypes)}], got {current.TokenType}{extra}", current); - } - - protected (EvalResult, string, BotToken) UnexpectedTokenError(BotToken current, params BotTokenType[] unexpectedTypes) - { - if (unexpectedTypes.Length == 0) - return (EvalResult.Failed, string.Empty, current); - else if (unexpectedTypes.Length == 1) - return (EvalResult.Failed, $"{unexpectedTypes[0]} was unexpected", current); - else - return (EvalResult.Failed, $"One of {string.Join(",", unexpectedTypes)} was unexpected", current); - } - - protected (EvalResult, string, BotToken) StackEmptyError(BotToken current) - { - return (EvalResult.Failed, $"Expected operation stack to have operands, but it was empty", current); - } - - protected (EvalResult, string, BotToken) UnsupportedOperatorError(BotToken actualToken) - { - return (EvalResult.Failed, $"Unsupported operator evaluating expression: {actualToken.TokenType}", actualToken); - } - - protected (EvalResult, string, BotToken) StackTokenError(BotTokenType expectedTokenType, BotToken actualToken) - { - return (EvalResult.Failed, $"Expected operation stack to have {expectedTokenType} token, got {actualToken.TokenType}", actualToken); - } - - protected (EvalResult, string, BotToken) ReadOnlyVariableError(IdentifierBotToken token) - { - return (EvalResult.Failed, $"Attempted to assign value to read-only variable {token.TokenValue}", token); - } - - protected (EvalResult, string, BotToken) IdentifierNotFoundError(IdentifierBotToken token) - { - return (EvalResult.Failed, $"Identifier {token.TokenValue} is not defined", token); - } - - protected (EvalResult, string, BotToken) GotoError(BotToken token) - { - return (EvalResult.Failed, $"Failed to goto label {token.TokenValue}", token); - } + return (EvalResult.Failed, $"Failed to goto label {token.TokenValue}", token); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/BlockEvaluator.cs b/EOBot/Interpreter/States/BlockEvaluator.cs index eca9cec26..21e83deb2 100644 --- a/EOBot/Interpreter/States/BlockEvaluator.cs +++ b/EOBot/Interpreter/States/BlockEvaluator.cs @@ -2,107 +2,106 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public abstract class BlockEvaluator : BaseEvaluator { - public abstract class BlockEvaluator : BaseEvaluator + protected BlockEvaluator(IEnumerable evaluators) + : base(evaluators) { } + + protected async Task<(EvalResult, string, BotToken)> EvaluateConditionAsync(int blockStartIndex, ProgramState input) { - protected BlockEvaluator(IEnumerable evaluators) - : base(evaluators) { } + input.Goto(blockStartIndex); - protected async Task<(EvalResult, string, BotToken)> EvaluateConditionAsync(int blockStartIndex, ProgramState input) - { - input.Goto(blockStartIndex); + if (!input.ExpectPair(BotTokenType.Keyword, BotTokenType.LParen)) + return (EvalResult.Failed, "Missing keyword and lparen to start condition evaluation", input.Current()); - if (!input.ExpectPair(BotTokenType.Keyword, BotTokenType.LParen)) - return (EvalResult.Failed, "Missing keyword and lparen to start condition evaluation", input.Current()); + var evalResult = await Evaluator().EvaluateAsync(input); + if (evalResult.Result != EvalResult.Ok) + return evalResult; - var evalResult = await Evaluator().EvaluateAsync(input); - if (evalResult.Result != EvalResult.Ok) - return evalResult; + if (!input.Expect(BotTokenType.RParen)) + return Error(input.Current(), BotTokenType.RParen); - if (!input.Expect(BotTokenType.RParen)) - return Error(input.Current(), BotTokenType.RParen); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); + return Success(input.OperationStack.Pop()); + } - return Success(input.OperationStack.Pop()); - } + protected async Task<(EvalResult, string, BotToken)> EvaluateBlockAsync(ProgramState input) + { + input.Expect(BotTokenType.NewLine); - protected async Task<(EvalResult, string, BotToken)> EvaluateBlockAsync(ProgramState input) - { - input.Expect(BotTokenType.NewLine); + (EvalResult Result, string, BotToken) evalResult; - (EvalResult Result, string, BotToken) evalResult; + // either: multi-line statement / evaluate statement list (consumes RBrace as end condition) + // or: single statement + // evaluated in separate blocks because we want to check statement list OR statement, not both + if (input.Expect(BotTokenType.LBrace)) + { + evalResult = await Evaluator().EvaluateAsync(input); + if (evalResult.Result != EvalResult.Ok) + return evalResult; + } + else + { + evalResult = await Evaluator().EvaluateAsync(input); + if (evalResult.Result != EvalResult.Ok) + return evalResult; + } - // either: multi-line statement / evaluate statement list (consumes RBrace as end condition) - // or: single statement - // evaluated in separate blocks because we want to check statement list OR statement, not both - if (input.Expect(BotTokenType.LBrace)) - { - evalResult = await Evaluator().EvaluateAsync(input); - if (evalResult.Result != EvalResult.Ok) - return evalResult; - } - else - { - evalResult = await Evaluator().EvaluateAsync(input); - if (evalResult.Result != EvalResult.Ok) - return evalResult; - } + RestoreLastNewline(input); + return evalResult; + } - RestoreLastNewline(input); - return evalResult; + protected void SkipBlock(ProgramState input) + { + // ensure that for 'else if' the if condition is skipped as well + var current = input.Current(); + if (current.TokenType == BotTokenType.Keyword && current.TokenValue == "if") + { + input.Expect(BotTokenType.Keyword); + input.Expect(BotTokenType.LParen); + while (!input.Expect(BotTokenType.RParen)) + input.SkipToken(); } - protected void SkipBlock(ProgramState input) + // potential newline character - skip so we can advance execution beyond the block + input.Expect(BotTokenType.NewLine); + + // skip the rest of the block + if (input.Expect(BotTokenType.LBrace)) { - // ensure that for 'else if' the if condition is skipped as well - var current = input.Current(); - if (current.TokenType == BotTokenType.Keyword && current.TokenValue == "if") + int rBraceCount = 1; + while (rBraceCount > 0 && input.Current().TokenType != BotTokenType.EOF) { - input.Expect(BotTokenType.Keyword); - input.Expect(BotTokenType.LParen); - while (!input.Expect(BotTokenType.RParen)) - input.SkipToken(); - } + if (input.Current().TokenType == BotTokenType.LBrace) + rBraceCount++; + else if (input.Current().TokenType == BotTokenType.RBrace) + rBraceCount--; - // potential newline character - skip so we can advance execution beyond the block - input.Expect(BotTokenType.NewLine); - - // skip the rest of the block - if (input.Expect(BotTokenType.LBrace)) - { - int rBraceCount = 1; - while (rBraceCount > 0 && input.Current().TokenType != BotTokenType.EOF) - { - if (input.Current().TokenType == BotTokenType.LBrace) - rBraceCount++; - else if (input.Current().TokenType == BotTokenType.RBrace) - rBraceCount--; - - input.SkipToken(); - } + input.SkipToken(); } - else - { - // optional newline before statement - input.Expect(BotTokenType.NewLine); + } + else + { + // optional newline before statement + input.Expect(BotTokenType.NewLine); - while (input.Current().TokenType != BotTokenType.NewLine && input.Current().TokenType != BotTokenType.EOF) - input.SkipToken(); + while (input.Current().TokenType != BotTokenType.NewLine && input.Current().TokenType != BotTokenType.EOF) + input.SkipToken(); - // optional newline after statement - input.Expect(BotTokenType.NewLine); - } + // optional newline after statement + input.Expect(BotTokenType.NewLine); } + } - protected static void RestoreLastNewline(ProgramState input) - { - // hack: put the \n token back since StatementList/Statement will have consumed it - if (input.Program[input.ExecutionIndex - 1].TokenType == BotTokenType.NewLine) - input.Goto(input.ExecutionIndex - 1); - } + protected static void RestoreLastNewline(ProgramState input) + { + // hack: put the \n token back since StatementList/Statement will have consumed it + if (input.Program[input.ExecutionIndex - 1].TokenType == BotTokenType.NewLine) + input.Goto(input.ExecutionIndex - 1); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/EvalResult.cs b/EOBot/Interpreter/States/EvalResult.cs index 714f138db..dae1cbc98 100644 --- a/EOBot/Interpreter/States/EvalResult.cs +++ b/EOBot/Interpreter/States/EvalResult.cs @@ -1,18 +1,17 @@ -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public enum EvalResult { - public enum EvalResult - { - /// - /// The result of the evaluation succeeded - /// - Ok, - /// - /// The result of the evaluation failed - /// - Failed, - /// - /// The evaluator was not a match for the program's current execution point - /// - NotMatch - } + /// + /// The result of the evaluation succeeded + /// + Ok, + /// + /// The result of the evaluation failed + /// + Failed, + /// + /// The evaluator was not a match for the program's current execution point + /// + NotMatch } \ No newline at end of file diff --git a/EOBot/Interpreter/States/ExpressionEvaluator.cs b/EOBot/Interpreter/States/ExpressionEvaluator.cs index 1df7948e7..0bde0fb61 100644 --- a/EOBot/Interpreter/States/ExpressionEvaluator.cs +++ b/EOBot/Interpreter/States/ExpressionEvaluator.cs @@ -4,226 +4,225 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class ExpressionEvaluator : BaseEvaluator { - public class ExpressionEvaluator : BaseEvaluator + public ExpressionEvaluator(IEnumerable evaluators) + : base(evaluators) { } + + // todo: this code is a mess and could use cleaning up (lots of copy/paste...) + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - public ExpressionEvaluator(IEnumerable evaluators) - : base(evaluators) { } + input.Match(BotTokenType.NotOperator); - // todo: this code is a mess and could use cleaning up (lots of copy/paste...) - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + if (input.Expect(BotTokenType.LParen)) { - input.Match(BotTokenType.NotOperator); - - if (input.Expect(BotTokenType.LParen)) + var evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result != EvalResult.Ok) + return evalRes; + + // if we get an RParen, the nested expression has been evaluated + if (input.Expect(BotTokenType.RParen)) + return NegateIfNeeded(input); + + // expression_tail is optional + evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result == EvalResult.NotMatch) + return EvaluateSingleOperand(input); + else if (evalRes.Result == EvalResult.Failed) + return evalRes; + + if (!input.Expect(BotTokenType.RParen)) + return Error(input.Current(), BotTokenType.RParen); + } + else + { + // an expression can be a function call + var evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result == EvalResult.Ok) { - var evalRes = await Evaluator().EvaluateAsync(input); + // there may or may not be an expression tail after a function call + // if there is an expression tail, evaluate the operands below, otherwise return early + evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result == EvalResult.NotMatch) + { + // function call as single operand expression - negate the result if needed + return NegateIfNeeded(input); + } + else if (evalRes.Result == EvalResult.Failed) + return evalRes; + } + else if (evalRes.Result == EvalResult.NotMatch) + { + // if not a function, evaluate operand and expression tail (basic expression) + evalRes = await Evaluator().EvaluateAsync(input); if (evalRes.Result != EvalResult.Ok) return evalRes; - // if we get an RParen, the nested expression has been evaluated - if (input.Expect(BotTokenType.RParen)) - return NegateIfNeeded(input); - - // expression_tail is optional + // expression_tail is optional, if not set no need to evaluate operation stack below / return early evalRes = await Evaluator().EvaluateAsync(input); if (evalRes.Result == EvalResult.NotMatch) return EvaluateSingleOperand(input); else if (evalRes.Result == EvalResult.Failed) return evalRes; - - if (!input.Expect(BotTokenType.RParen)) - return Error(input.Current(), BotTokenType.RParen); } else { - // an expression can be a function call - var evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result == EvalResult.Ok) - { - // there may or may not be an expression tail after a function call - // if there is an expression tail, evaluate the operands below, otherwise return early - evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result == EvalResult.NotMatch) - { - // function call as single operand expression - negate the result if needed - return NegateIfNeeded(input); - } - else if (evalRes.Result == EvalResult.Failed) - return evalRes; - } - else if (evalRes.Result == EvalResult.NotMatch) - { - // if not a function, evaluate operand and expression tail (basic expression) - evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result != EvalResult.Ok) - return evalRes; - - // expression_tail is optional, if not set no need to evaluate operation stack below / return early - evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result == EvalResult.NotMatch) - return EvaluateSingleOperand(input); - else if (evalRes.Result == EvalResult.Failed) - return evalRes; - } - else - { - return evalRes; - } + return evalRes; } + } - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); - var (result, reason, op2) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); - if (result == EvalResult.Failed) - return (result, reason, op2); - var operand2 = op2 as VariableBotToken; + var (result, reason, op2) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); + if (result == EvalResult.Failed) + return (result, reason, op2); + var operand2 = op2 as VariableBotToken; - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var @operator = input.OperationStack.Pop(); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var @operator = input.OperationStack.Pop(); - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); - BotToken op1; - (result, reason, op1) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); - if (result == EvalResult.Failed) - return (result, reason, op1); - var operand1 = op1 as VariableBotToken; + BotToken op1; + (result, reason, op1) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); + if (result == EvalResult.Failed) + return (result, reason, op1); + var operand1 = op1 as VariableBotToken; - (IVariable Result, string Reason) res; - res.Reason = string.Empty; - switch (@operator.TokenType) - { - case BotTokenType.EqualOperator: res.Result = new BoolVariable(operand1.VariableValue.Equals(operand2.VariableValue)); break; - case BotTokenType.NotEqualOperator: res.Result = new BoolVariable(!operand1.VariableValue.Equals(operand2.VariableValue)); break; - case BotTokenType.LessThanOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) < 0); break; - case BotTokenType.GreaterThanOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) > 0); break; - case BotTokenType.LessThanEqOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) <= 0); break; - case BotTokenType.GreaterThanEqOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) >= 0); break; - case BotTokenType.PlusOperator: res = Add((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; - case BotTokenType.MinusOperator: res = Subtract((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; - case BotTokenType.MultiplyOperator: res = Multiply((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; - case BotTokenType.DivideOperator: res = Divide((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; - default: return UnsupportedOperatorError(@operator); - } + (IVariable Result, string Reason) res; + res.Reason = string.Empty; + switch (@operator.TokenType) + { + case BotTokenType.EqualOperator: res.Result = new BoolVariable(operand1.VariableValue.Equals(operand2.VariableValue)); break; + case BotTokenType.NotEqualOperator: res.Result = new BoolVariable(!operand1.VariableValue.Equals(operand2.VariableValue)); break; + case BotTokenType.LessThanOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) < 0); break; + case BotTokenType.GreaterThanOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) > 0); break; + case BotTokenType.LessThanEqOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) <= 0); break; + case BotTokenType.GreaterThanEqOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) >= 0); break; + case BotTokenType.PlusOperator: res = Add((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; + case BotTokenType.MinusOperator: res = Subtract((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; + case BotTokenType.MultiplyOperator: res = Multiply((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; + case BotTokenType.DivideOperator: res = Divide((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; + default: return UnsupportedOperatorError(@operator); + } - if (res.Result == null) - return (EvalResult.Failed, $"Error evaluating expression: {res.Reason}", input.Current()); + if (res.Result == null) + return (EvalResult.Failed, $"Error evaluating expression: {res.Reason}", input.Current()); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, res.Result.StringValue, res.Result)); - return NegateIfNeeded(input); - } + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, res.Result.StringValue, res.Result)); + return NegateIfNeeded(input); + } - private (EvalResult, string, BotToken) EvaluateSingleOperand(ProgramState input) - { - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); + private (EvalResult, string, BotToken) EvaluateSingleOperand(ProgramState input) + { + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); - // convert to variable token (resolve identifier) so consumer of expression result can use it - var (localResult, localReason, singleOperand) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); - if (localResult != EvalResult.Ok) - return (localResult, localReason, singleOperand); + // convert to variable token (resolve identifier) so consumer of expression result can use it + var (localResult, localReason, singleOperand) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); + if (localResult != EvalResult.Ok) + return (localResult, localReason, singleOperand); - input.OperationStack.Push(singleOperand); - return NegateIfNeeded(input); + input.OperationStack.Push(singleOperand); + return NegateIfNeeded(input); + } + + // todo: a lot of this code is the same as what's in AssignmentEvaluator::Assign, see if it can be split out/shared + private (EvalResult, string, BotToken) GetOperand(Dictionary symbols, BotToken nextToken) + { + if (nextToken.TokenType == BotTokenType.Literal) + { + if (int.TryParse(nextToken.TokenValue, out var intValue)) + return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new IntVariable(intValue))); + else if (bool.TryParse(nextToken.TokenValue, out var boolValue)) + return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new BoolVariable(boolValue))); + else + return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new StringVariable(nextToken.TokenValue))); } - // todo: a lot of this code is the same as what's in AssignmentEvaluator::Assign, see if it can be split out/shared - private (EvalResult, string, BotToken) GetOperand(Dictionary symbols, BotToken nextToken) + var operand = nextToken as VariableBotToken; + if (operand == null) { - if (nextToken.TokenType == BotTokenType.Literal) - { - if (int.TryParse(nextToken.TokenValue, out var intValue)) - return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new IntVariable(intValue))); - else if (bool.TryParse(nextToken.TokenValue, out var boolValue)) - return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new BoolVariable(boolValue))); - else - return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new StringVariable(nextToken.TokenValue))); - } + var identifier = nextToken as IdentifierBotToken; + if (identifier == null) + return (EvalResult.Failed, $"Expected operand of type Variable or Identifier but got {nextToken.TokenType}", nextToken); - var operand = nextToken as VariableBotToken; - if (operand == null) + if (identifier.Member == null) { - var identifier = nextToken as IdentifierBotToken; - if (identifier == null) - return (EvalResult.Failed, $"Expected operand of type Variable or Identifier but got {nextToken.TokenType}", nextToken); + var getVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); + if (getVariableRes.Result != EvalResult.Ok) + return (getVariableRes.Result, getVariableRes.Reason, identifier); - if (identifier.Member == null) - { - var getVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); - if (getVariableRes.Result != EvalResult.Ok) - return (getVariableRes.Result, getVariableRes.Reason, identifier); - - operand = new VariableBotToken(BotTokenType.Literal, getVariableRes.Variable.ToString(), getVariableRes.Variable); - } - else + operand = new VariableBotToken(BotTokenType.Literal, getVariableRes.Variable.ToString(), getVariableRes.Variable); + } + else + { + var getVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); + if (getVariableRes.Result != EvalResult.Ok) { - var getVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); - if (getVariableRes.Result != EvalResult.Ok) - { - var getRuntimeEvaluatedVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); - if (getRuntimeEvaluatedVariableRes.Result != EvalResult.Ok) - return (EvalResult.Failed, $"Identifier '{identifier.TokenValue}' is not an object", identifier); - - getVariableRes.Result = getRuntimeEvaluatedVariableRes.Result; - getVariableRes.Reason = getRuntimeEvaluatedVariableRes.Reason; - getVariableRes.Variable = new ObjectVariable( - getRuntimeEvaluatedVariableRes.Variable.SymbolTable - .Select(x => (x.Key, (x.Value.ReadOnly, x.Value.Variable()))) - .ToDictionary(x => x.Key, x => x.Item2)); - } - - return GetOperand(getVariableRes.Variable.SymbolTable, identifier.Member); + var getRuntimeEvaluatedVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); + if (getRuntimeEvaluatedVariableRes.Result != EvalResult.Ok) + return (EvalResult.Failed, $"Identifier '{identifier.TokenValue}' is not an object", identifier); + + getVariableRes.Result = getRuntimeEvaluatedVariableRes.Result; + getVariableRes.Reason = getRuntimeEvaluatedVariableRes.Reason; + getVariableRes.Variable = new ObjectVariable( + getRuntimeEvaluatedVariableRes.Variable.SymbolTable + .Select(x => (x.Key, (x.Value.ReadOnly, x.Value.Variable()))) + .ToDictionary(x => x.Key, x => x.Item2)); } - } - return Success(operand); + return GetOperand(getVariableRes.Variable.SymbolTable, identifier.Member); + } } - // negate the VariableBotToken on top of the stack if there as a 'not' operator immediately below it - private (EvalResult, string, BotToken) NegateIfNeeded(ProgramState input) - { - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); + return Success(operand); + } - var operand = input.OperationStack.Pop(); + // negate the VariableBotToken on top of the stack if there as a 'not' operator immediately below it + private (EvalResult, string, BotToken) NegateIfNeeded(ProgramState input) + { + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); - var varToken = operand as VariableBotToken; - if (varToken == null) - return StackTokenError(BotTokenType.Literal, operand); + var operand = input.OperationStack.Pop(); - while (input.OperationStack.Count > 0 && input.OperationStack.Peek().TokenType == BotTokenType.NotOperator) - { - var notOperator = input.OperationStack.Pop(); + var varToken = operand as VariableBotToken; + if (varToken == null) + return StackTokenError(BotTokenType.Literal, operand); - var boolOperand = varToken.VariableValue as BoolVariable; - if (boolOperand == null) - return UnsupportedOperatorError(notOperator); + while (input.OperationStack.Count > 0 && input.OperationStack.Peek().TokenType == BotTokenType.NotOperator) + { + var notOperator = input.OperationStack.Pop(); - varToken = new VariableBotToken(varToken.TokenType, (!boolOperand.Value).ToString(), new BoolVariable(!boolOperand.Value)); - } + var boolOperand = varToken.VariableValue as BoolVariable; + if (boolOperand == null) + return UnsupportedOperatorError(notOperator); - input.OperationStack.Push(varToken); - return Success(); + varToken = new VariableBotToken(varToken.TokenType, (!boolOperand.Value).ToString(), new BoolVariable(!boolOperand.Value)); } - private (IVariable, string) Add(IntVariable a, IntVariable b) => (new IntVariable(a.Value + b.Value), string.Empty); - private (IVariable, string) Add(IntVariable a, StringVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); - private (IVariable, string) Add(StringVariable a, IntVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); - private (IVariable, string) Add(StringVariable a, StringVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); - private (IVariable, string) Add(object a, object b) => (null, $"Objects {a} and {b} could not be added (currently the operands must be int or string)"); + input.OperationStack.Push(varToken); + return Success(); + } - private (IVariable, string) Subtract(IntVariable a, IntVariable b) => (new IntVariable(a.Value - b.Value), string.Empty); - private (IVariable, string) Subtract(object a, object b) => (null, $"Objects {a} and {b} could not be subtracted (currently the operands must be int)"); + private (IVariable, string) Add(IntVariable a, IntVariable b) => (new IntVariable(a.Value + b.Value), string.Empty); + private (IVariable, string) Add(IntVariable a, StringVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); + private (IVariable, string) Add(StringVariable a, IntVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); + private (IVariable, string) Add(StringVariable a, StringVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); + private (IVariable, string) Add(object a, object b) => (null, $"Objects {a} and {b} could not be added (currently the operands must be int or string)"); - private (IVariable, string) Multiply(IntVariable a, IntVariable b) => (new IntVariable(a.Value * b.Value), string.Empty); - private (IVariable, string) Multiply(object a, object b) => (null, $"Objects {a} and {b} could not be multiplied (currently the operands must be int)"); + private (IVariable, string) Subtract(IntVariable a, IntVariable b) => (new IntVariable(a.Value - b.Value), string.Empty); + private (IVariable, string) Subtract(object a, object b) => (null, $"Objects {a} and {b} could not be subtracted (currently the operands must be int)"); - private (IVariable, string) Divide(IntVariable a, IntVariable b) => (new IntVariable(a.Value / b.Value), string.Empty); - private (IVariable, string) Divide(object a, object b) => (null, $"Objects {a} and {b} could not be divided (currently the operands must be int)"); - } + private (IVariable, string) Multiply(IntVariable a, IntVariable b) => (new IntVariable(a.Value * b.Value), string.Empty); + private (IVariable, string) Multiply(object a, object b) => (null, $"Objects {a} and {b} could not be multiplied (currently the operands must be int)"); + + private (IVariable, string) Divide(IntVariable a, IntVariable b) => (new IntVariable(a.Value / b.Value), string.Empty); + private (IVariable, string) Divide(object a, object b) => (null, $"Objects {a} and {b} could not be divided (currently the operands must be int)"); } \ No newline at end of file diff --git a/EOBot/Interpreter/States/ExpressionTailEvaluator.cs b/EOBot/Interpreter/States/ExpressionTailEvaluator.cs index c24d311dd..2e2f7b354 100644 --- a/EOBot/Interpreter/States/ExpressionTailEvaluator.cs +++ b/EOBot/Interpreter/States/ExpressionTailEvaluator.cs @@ -2,26 +2,25 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class ExpressionTailEvaluator : BaseEvaluator { - public class ExpressionTailEvaluator : BaseEvaluator - { - public ExpressionTailEvaluator(IEnumerable evaluators) - : base(evaluators) { } + public ExpressionTailEvaluator(IEnumerable evaluators) + : base(evaluators) { } - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + var expectedTokens = new[] { - var expectedTokens = new[] - { - BotTokenType.EqualOperator, BotTokenType.NotEqualOperator, BotTokenType.GreaterThanOperator, - BotTokenType.LessThanOperator, BotTokenType.GreaterThanEqOperator, BotTokenType.LessThanEqOperator, - BotTokenType.PlusOperator, BotTokenType.MinusOperator, BotTokenType.MultiplyOperator, BotTokenType.DivideOperator - }; + BotTokenType.EqualOperator, BotTokenType.NotEqualOperator, BotTokenType.GreaterThanOperator, + BotTokenType.LessThanOperator, BotTokenType.GreaterThanEqOperator, BotTokenType.LessThanEqOperator, + BotTokenType.PlusOperator, BotTokenType.MinusOperator, BotTokenType.MultiplyOperator, BotTokenType.DivideOperator + }; - if (!input.MatchOneOf(expectedTokens)) - return (EvalResult.NotMatch, string.Empty, input.Current()); + if (!input.MatchOneOf(expectedTokens)) + return (EvalResult.NotMatch, string.Empty, input.Current()); - return await Evaluator().EvaluateAsync(input); - } + return await Evaluator().EvaluateAsync(input); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/FunctionEvaluator.cs b/EOBot/Interpreter/States/FunctionEvaluator.cs index 8888e0837..b7698bbac 100644 --- a/EOBot/Interpreter/States/FunctionEvaluator.cs +++ b/EOBot/Interpreter/States/FunctionEvaluator.cs @@ -5,169 +5,168 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class FunctionEvaluator : BaseEvaluator { - public class FunctionEvaluator : BaseEvaluator + public FunctionEvaluator(IEnumerable evaluators) + : base(evaluators) { } + + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - public FunctionEvaluator(IEnumerable evaluators) - : base(evaluators) { } + if (!input.MatchPair(BotTokenType.Identifier, BotTokenType.LParen)) + return (EvalResult.NotMatch, string.Empty, input.Current()); - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + var firstParam = true; + while (!input.Match(BotTokenType.RParen)) { - if (!input.MatchPair(BotTokenType.Identifier, BotTokenType.LParen)) - return (EvalResult.NotMatch, string.Empty, input.Current()); - - var firstParam = true; - while (!input.Match(BotTokenType.RParen)) - { - if (input.Expect(BotTokenType.NewLine) || input.Expect(BotTokenType.EOF)) - return UnexpectedTokenError(input.Current(), BotTokenType.NewLine, BotTokenType.EOF); - - if (!firstParam && !input.Expect(BotTokenType.Comma)) - return Error(input.Current(), BotTokenType.Comma); - - var parameterExpression = await Evaluator().EvaluateAsync(input); - if (parameterExpression.Result != EvalResult.Ok) - return parameterExpression; - - firstParam = false; - } - - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var rParen = input.OperationStack.Pop(); - if (rParen.TokenType != BotTokenType.RParen) - return StackTokenError(BotTokenType.RParen, rParen); - - var parameters = new List(); - while (input.OperationStack.Count > 0 && input.OperationStack.Peek().TokenType != BotTokenType.LParen) - { - var parameter = (VariableBotToken)input.OperationStack.Pop(); - parameters.Insert(0, parameter); - } - - var lParen = input.OperationStack.Pop(); - if (lParen.TokenType != BotTokenType.LParen) - return StackTokenError(BotTokenType.LParen, lParen); - - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var functionToken = input.OperationStack.Pop(); - - if (!input.SymbolTable.ContainsKey(functionToken.TokenValue)) - return IdentifierNotFoundError(new IdentifierBotToken(functionToken)); - - var function = input.SymbolTable[functionToken.TokenValue].Identifiable; - - try - { - if (function is IAsyncFunction) - await CallAsync(input, (dynamic)function, parameters.Select(x => x.VariableValue).ToArray()); - else if (function is IFunction) - Call(input, (dynamic)function, parameters.Select(x => x.VariableValue).ToArray()); - else - return (EvalResult.Failed, $"Expected identifier {functionToken.TokenValue} to be a function, but it was {function.GetType().Name}", functionToken); - } - catch (BotScriptErrorException bse) - { - // stack information isn't really important since this is only used to signal to the framework that a bot failed - // recreate the exception so it prints line number/column info with the error - throw new BotScriptErrorException(bse.Message, functionToken); - } - catch (ArgumentException ae) - { - return (EvalResult.Failed, ae.Message, functionToken); - } - - return Success(); - } + if (input.Expect(BotTokenType.NewLine) || input.Expect(BotTokenType.EOF)) + return UnexpectedTokenError(input.Current(), BotTokenType.NewLine, BotTokenType.EOF); - private void Call(ProgramState input, ICallable function, params IVariable[] variables) - { - function.Call(variables); - } + if (!firstParam && !input.Expect(BotTokenType.Comma)) + return Error(input.Current(), BotTokenType.Comma); - private void Call(ProgramState input, ICallable function, params IVariable[] variables) - { - var result = function.Call(variables); - var varResult = new IntVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + var parameterExpression = await Evaluator().EvaluateAsync(input); + if (parameterExpression.Result != EvalResult.Ok) + return parameterExpression; - private void Call(ProgramState input, ICallable function, params IVariable[] variables) - { - var result = function.Call(variables); - var varResult = new StringVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + firstParam = false; } - private void Call(ProgramState input, ICallable> function, params IVariable[] variables) - { - var result = function.Call(variables); - var varResult = new ArrayVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var rParen = input.OperationStack.Pop(); + if (rParen.TokenType != BotTokenType.RParen) + return StackTokenError(BotTokenType.RParen, rParen); - private void Call(ProgramState input, ICallable function, params IVariable[] variables) + var parameters = new List(); + while (input.OperationStack.Count > 0 && input.OperationStack.Peek().TokenType != BotTokenType.LParen) { - var result = function.Call(variables); - var varResult = new BoolVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + var parameter = (VariableBotToken)input.OperationStack.Pop(); + parameters.Insert(0, parameter); } - private void Call(ProgramState input, ICallable function, params IVariable[] variables) - { - var varResult = function.Call(variables); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + var lParen = input.OperationStack.Pop(); + if (lParen.TokenType != BotTokenType.LParen) + return StackTokenError(BotTokenType.LParen, lParen); - private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) - { - await function.CallAsync(variables); - } + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var functionToken = input.OperationStack.Pop(); - private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) - { - var result = await function.CallAsync(variables); - var varResult = new IntVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + if (!input.SymbolTable.ContainsKey(functionToken.TokenValue)) + return IdentifierNotFoundError(new IdentifierBotToken(functionToken)); - private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) - { - var result = await function.CallAsync(variables); - var varResult = new StringVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + var function = input.SymbolTable[functionToken.TokenValue].Identifiable; - private async Task CallAsync(ProgramState input, IAsyncCallable> function, params IVariable[] variables) + try { - var result = await function.CallAsync(variables); - var varResult = new ArrayVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + if (function is IAsyncFunction) + await CallAsync(input, (dynamic)function, parameters.Select(x => x.VariableValue).ToArray()); + else if (function is IFunction) + Call(input, (dynamic)function, parameters.Select(x => x.VariableValue).ToArray()); + else + return (EvalResult.Failed, $"Expected identifier {functionToken.TokenValue} to be a function, but it was {function.GetType().Name}", functionToken); } - - private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + catch (BotScriptErrorException bse) { - var result = await function.CallAsync(variables); - var varResult = new BoolVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + // stack information isn't really important since this is only used to signal to the framework that a bot failed + // recreate the exception so it prints line number/column info with the error + throw new BotScriptErrorException(bse.Message, functionToken); } - - private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + catch (ArgumentException ae) { - var varResult = await function.CallAsync(variables); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + return (EvalResult.Failed, ae.Message, functionToken); } + + return Success(); + } + + private void Call(ProgramState input, ICallable function, params IVariable[] variables) + { + function.Call(variables); + } + + private void Call(ProgramState input, ICallable function, params IVariable[] variables) + { + var result = function.Call(variables); + var varResult = new IntVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } + + private void Call(ProgramState input, ICallable function, params IVariable[] variables) + { + var result = function.Call(variables); + var varResult = new StringVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } + + private void Call(ProgramState input, ICallable> function, params IVariable[] variables) + { + var result = function.Call(variables); + var varResult = new ArrayVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } + + private void Call(ProgramState input, ICallable function, params IVariable[] variables) + { + var result = function.Call(variables); + var varResult = new BoolVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } + + private void Call(ProgramState input, ICallable function, params IVariable[] variables) + { + var varResult = function.Call(variables); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } + + private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + { + await function.CallAsync(variables); + } + + private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + { + var result = await function.CallAsync(variables); + var varResult = new IntVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } + + private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + { + var result = await function.CallAsync(variables); + var varResult = new StringVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } + + private async Task CallAsync(ProgramState input, IAsyncCallable> function, params IVariable[] variables) + { + var result = await function.CallAsync(variables); + var varResult = new ArrayVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } + + private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + { + var result = await function.CallAsync(variables); + var varResult = new BoolVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } + + private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + { + var varResult = await function.CallAsync(variables); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/GotoEvaluator.cs b/EOBot/Interpreter/States/GotoEvaluator.cs index 71c2d5292..20337d6dd 100644 --- a/EOBot/Interpreter/States/GotoEvaluator.cs +++ b/EOBot/Interpreter/States/GotoEvaluator.cs @@ -1,28 +1,27 @@ using EOBot.Interpreter.Extensions; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class GotoEvaluator : BaseEvaluator { - public class GotoEvaluator : BaseEvaluator + public override Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - public override Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) - { - // ensure we have the right keyword before advancing the program - var current = input.Current(); - if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "goto") - return Task.FromResult((EvalResult.NotMatch, string.Empty, input.Current())); + // ensure we have the right keyword before advancing the program + var current = input.Current(); + if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "goto") + return Task.FromResult((EvalResult.NotMatch, string.Empty, input.Current())); - input.Expect(BotTokenType.Keyword); + input.Expect(BotTokenType.Keyword); - if (!input.Match(BotTokenType.Identifier)) - return Task.FromResult(Error(input.Current(), BotTokenType.Identifier)); + if (!input.Match(BotTokenType.Identifier)) + return Task.FromResult(Error(input.Current(), BotTokenType.Identifier)); - var label = input.OperationStack.Pop(); - if (!input.Labels.ContainsKey(label.TokenValue)) - return Task.FromResult(IdentifierNotFoundError(new IdentifierBotToken(label))); + var label = input.OperationStack.Pop(); + if (!input.Labels.ContainsKey(label.TokenValue)) + return Task.FromResult(IdentifierNotFoundError(new IdentifierBotToken(label))); - var result = input.Goto(input.Labels[label.TokenValue]); - return Task.FromResult(result ? Success() : GotoError(label)); - } + var result = input.Goto(input.Labels[label.TokenValue]); + return Task.FromResult(result ? Success() : GotoError(label)); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/IScriptEvaluator.cs b/EOBot/Interpreter/States/IScriptEvaluator.cs index db12d2a4a..0266ba280 100644 --- a/EOBot/Interpreter/States/IScriptEvaluator.cs +++ b/EOBot/Interpreter/States/IScriptEvaluator.cs @@ -1,9 +1,8 @@ using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public interface IScriptEvaluator { - public interface IScriptEvaluator - { - Task<(EvalResult Result, string Reason, BotToken Token)> EvaluateAsync(ProgramState input); - } + Task<(EvalResult Result, string Reason, BotToken Token)> EvaluateAsync(ProgramState input); } \ No newline at end of file diff --git a/EOBot/Interpreter/States/IfEvaluator.cs b/EOBot/Interpreter/States/IfEvaluator.cs index 1285e7df0..c53a1642c 100644 --- a/EOBot/Interpreter/States/IfEvaluator.cs +++ b/EOBot/Interpreter/States/IfEvaluator.cs @@ -2,79 +2,78 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class IfEvaluator : BlockEvaluator { - public class IfEvaluator : BlockEvaluator - { - public IfEvaluator(IEnumerable evaluators) - : base(evaluators) { } + public IfEvaluator(IEnumerable evaluators) + : base(evaluators) { } - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) - { - // ensure we have the right keyword before advancing the program - var current = input.Current(); - if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "if") - return (EvalResult.NotMatch, string.Empty, input.Current()); + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + // ensure we have the right keyword before advancing the program + var current = input.Current(); + if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "if") + return (EvalResult.NotMatch, string.Empty, input.Current()); - var ifStartIndex = input.ExecutionIndex; + var ifStartIndex = input.ExecutionIndex; - var (result, reason, token) = await EvaluateConditionAsync(ifStartIndex, input); - if (result == EvalResult.Ok) + var (result, reason, token) = await EvaluateConditionAsync(ifStartIndex, input); + if (result == EvalResult.Ok) + { + if (bool.TryParse(token.TokenValue, out var conditionValue) && conditionValue) { - if (bool.TryParse(token.TokenValue, out var conditionValue) && conditionValue) - { - var ifRes = await EvaluateBlockAsync(input); - if (ifRes.Item1 == EvalResult.Ok) - SkipElseBlocks(input); + var ifRes = await EvaluateBlockAsync(input); + if (ifRes.Item1 == EvalResult.Ok) + SkipElseBlocks(input); - return ifRes; - } + return ifRes; + } - SkipBlock(input); + SkipBlock(input); - while (input.Expect(BotTokenType.NewLine)) ; + while (input.Expect(BotTokenType.NewLine)) ; - if (IsElse(input)) + if (IsElse(input)) + { + input.Expect(BotTokenType.Keyword); + + var elseIfRes = await Evaluator().EvaluateAsync(input); + if (elseIfRes.Result == EvalResult.Failed) + return elseIfRes; + else if (elseIfRes.Result == EvalResult.Ok) { - input.Expect(BotTokenType.Keyword); - - var elseIfRes = await Evaluator().EvaluateAsync(input); - if (elseIfRes.Result == EvalResult.Failed) - return elseIfRes; - else if (elseIfRes.Result == EvalResult.Ok) - { - SkipElseBlocks(input); - return elseIfRes; - } - - // if not a match for else if, it is an else block - return await EvaluateBlockAsync(input); + SkipElseBlocks(input); + return elseIfRes; } - } - RestoreLastNewline(input); - return (result, reason, token); + // if not a match for else if, it is an else block + return await EvaluateBlockAsync(input); + } } - private bool IsElse(ProgramState input) - { - var current = input.Current(); - return current.TokenType == BotTokenType.Keyword && current.TokenValue == "else"; - } + RestoreLastNewline(input); + return (result, reason, token); + } - private void SkipElseBlocks(ProgramState input) - { - while (input.Expect(BotTokenType.NewLine)) ; + private bool IsElse(ProgramState input) + { + var current = input.Current(); + return current.TokenType == BotTokenType.Keyword && current.TokenValue == "else"; + } - // skip the rest of the following blocks if evaluated - while (IsElse(input)) - { - input.Expect(BotTokenType.Keyword); - SkipBlock(input); - while (input.Expect(BotTokenType.NewLine)) ; - } + private void SkipElseBlocks(ProgramState input) + { + while (input.Expect(BotTokenType.NewLine)) ; - RestoreLastNewline(input); + // skip the rest of the following blocks if evaluated + while (IsElse(input)) + { + input.Expect(BotTokenType.Keyword); + SkipBlock(input); + while (input.Expect(BotTokenType.NewLine)) ; } + + RestoreLastNewline(input); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/KeywordEvaluator.cs b/EOBot/Interpreter/States/KeywordEvaluator.cs index e55c4278c..73a32dc9c 100644 --- a/EOBot/Interpreter/States/KeywordEvaluator.cs +++ b/EOBot/Interpreter/States/KeywordEvaluator.cs @@ -1,27 +1,26 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class KeywordEvaluator : BaseEvaluator { - public class KeywordEvaluator : BaseEvaluator - { - public KeywordEvaluator(IEnumerable evaluators) - : base(evaluators) { } + public KeywordEvaluator(IEnumerable evaluators) + : base(evaluators) { } - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + var res = await Evaluator().EvaluateAsync(input); + if (res.Result == EvalResult.NotMatch) { - var res = await Evaluator().EvaluateAsync(input); + res = await Evaluator().EvaluateAsync(input); + if (res.Result == EvalResult.NotMatch) { - res = await Evaluator().EvaluateAsync(input); - - if (res.Result == EvalResult.NotMatch) - { - res = await Evaluator().EvaluateAsync(input); - } + res = await Evaluator().EvaluateAsync(input); } - - return res; } + + return res; } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/LabelEvaluator.cs b/EOBot/Interpreter/States/LabelEvaluator.cs index def562c1c..d41d00006 100644 --- a/EOBot/Interpreter/States/LabelEvaluator.cs +++ b/EOBot/Interpreter/States/LabelEvaluator.cs @@ -1,16 +1,15 @@ using EOBot.Interpreter.Extensions; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class LabelEvaluator : BaseEvaluator { - public class LabelEvaluator : BaseEvaluator + public override Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - public override Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) - { - var result = input.ExpectPair(BotTokenType.Identifier, BotTokenType.Colon) - ? EvalResult.Ok - : EvalResult.NotMatch; - return Task.FromResult((result, string.Empty, input.Current())); - } + var result = input.ExpectPair(BotTokenType.Identifier, BotTokenType.Colon) + ? EvalResult.Ok + : EvalResult.NotMatch; + return Task.FromResult((result, string.Empty, input.Current())); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/OperandEvaluator.cs b/EOBot/Interpreter/States/OperandEvaluator.cs index 058dbb9a3..89594f517 100644 --- a/EOBot/Interpreter/States/OperandEvaluator.cs +++ b/EOBot/Interpreter/States/OperandEvaluator.cs @@ -2,26 +2,25 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class OperandEvaluator : BaseEvaluator { - public class OperandEvaluator : BaseEvaluator - { - public OperandEvaluator(IEnumerable evaluators) - : base(evaluators) { } + public OperandEvaluator(IEnumerable evaluators) + : base(evaluators) { } - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + if (input.Match(BotTokenType.NotOperator)) { - if (input.Match(BotTokenType.NotOperator)) - { - } + } - var evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result == EvalResult.Ok) - return evalRes; + var evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result == EvalResult.Ok) + return evalRes; - var matchRes = input.Match(BotTokenType.Literal); - return matchRes ? Success() : (EvalResult.NotMatch, string.Empty, input.Current()); - } + var matchRes = input.Match(BotTokenType.Literal); + return matchRes ? Success() : (EvalResult.NotMatch, string.Empty, input.Current()); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/ProgramState.cs b/EOBot/Interpreter/States/ProgramState.cs index 5ce7906d7..1b2290fbb 100644 --- a/EOBot/Interpreter/States/ProgramState.cs +++ b/EOBot/Interpreter/States/ProgramState.cs @@ -3,115 +3,114 @@ using System.Collections.Generic; using System.Linq; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class ProgramState { - public class ProgramState - { - public Stack OperationStack { get; } + public Stack OperationStack { get; } - public IReadOnlyList Program { get; } + public IReadOnlyList Program { get; } - public Dictionary SymbolTable { get; } + public Dictionary SymbolTable { get; } - public Dictionary Labels { get; } + public Dictionary Labels { get; } - public int ExecutionIndex { get; private set; } + public int ExecutionIndex { get; private set; } - public ProgramState(IReadOnlyList program) - { - OperationStack = new Stack(); - Program = program; - SymbolTable = new Dictionary(); - Labels = Program - .Select((token, ndx) => (token, ndx)) - .Where(x => x.token.TokenType == BotTokenType.Identifier && Program[x.ndx + 1].TokenType == BotTokenType.Colon) - .ToDictionary(x => x.token.TokenValue, y => y.ndx + 2); - ExecutionIndex = 0; - } + public ProgramState(IReadOnlyList program) + { + OperationStack = new Stack(); + Program = program; + SymbolTable = new Dictionary(); + Labels = Program + .Select((token, ndx) => (token, ndx)) + .Where(x => x.token.TokenType == BotTokenType.Identifier && Program[x.ndx + 1].TokenType == BotTokenType.Colon) + .ToDictionary(x => x.token.TokenValue, y => y.ndx + 2); + ExecutionIndex = 0; + } - public void SkipToken() - { - ExecutionIndex++; - } + public void SkipToken() + { + ExecutionIndex++; + } - public bool Goto(int executionIndex) - { - if (executionIndex >= Program.Count) - return false; + public bool Goto(int executionIndex) + { + if (executionIndex >= Program.Count) + return false; - ExecutionIndex = executionIndex; - return true; - } + ExecutionIndex = executionIndex; + return true; + } + + /// + /// Check for a token at the program's execution index. If it is the expected type, increment execution index. + /// + public bool Expect(BotTokenType tokenType) + { + if (ExecutionIndex >= Program.Count) + return tokenType == BotTokenType.EOF; - /// - /// Check for a token at the program's execution index. If it is the expected type, increment execution index. - /// - public bool Expect(BotTokenType tokenType) + if (Program[ExecutionIndex].TokenType == tokenType) { - if (ExecutionIndex >= Program.Count) - return tokenType == BotTokenType.EOF; + ExecutionIndex++; + return true; + } - if (Program[ExecutionIndex].TokenType == tokenType) - { - ExecutionIndex++; - return true; - } + return false; + } + /// + /// Check for a token at the program's execution index. If it is the expected type, push it onto the operation stack and increment execution index. + /// + public bool Match(BotTokenType tokenType) + { + if (ExecutionIndex >= Program.Count) return false; - } - /// - /// Check for a token at the program's execution index. If it is the expected type, push it onto the operation stack and increment execution index. - /// - public bool Match(BotTokenType tokenType) + if (Program[ExecutionIndex].TokenType == tokenType) { - if (ExecutionIndex >= Program.Count) - return false; + OperationStack.Push(Program[ExecutionIndex]); + ExecutionIndex++; + return true; + } - if (Program[ExecutionIndex].TokenType == tokenType) - { - OperationStack.Push(Program[ExecutionIndex]); - ExecutionIndex++; - return true; - } + return false; + } + public bool ExpectPair(BotTokenType first, BotTokenType second) + { + if (ExecutionIndex >= Program.Count - 1) return false; - } - public bool ExpectPair(BotTokenType first, BotTokenType second) + if (Program[ExecutionIndex].TokenType == first && + Program[ExecutionIndex + 1].TokenType == second) { - if (ExecutionIndex >= Program.Count - 1) - return false; + ExecutionIndex += 2; + return true; + } - if (Program[ExecutionIndex].TokenType == first && - Program[ExecutionIndex + 1].TokenType == second) - { - ExecutionIndex += 2; - return true; - } + return false; + } + /// + /// Matches a pair of tokens in order at the program's execution index. + /// + public bool MatchPair(BotTokenType first, BotTokenType second) + { + if (ExecutionIndex >= Program.Count - 1) return false; - } - /// - /// Matches a pair of tokens in order at the program's execution index. - /// - public bool MatchPair(BotTokenType first, BotTokenType second) + if (Program[ExecutionIndex].TokenType == first && + Program[ExecutionIndex + 1].TokenType == second) { - if (ExecutionIndex >= Program.Count - 1) - return false; + OperationStack.Push(Program[ExecutionIndex]); + OperationStack.Push(Program[ExecutionIndex + 1]); + ExecutionIndex += 2; - if (Program[ExecutionIndex].TokenType == first && - Program[ExecutionIndex + 1].TokenType == second) - { - OperationStack.Push(Program[ExecutionIndex]); - OperationStack.Push(Program[ExecutionIndex + 1]); - ExecutionIndex += 2; - - return true; - } - - return false; + return true; } + + return false; } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/ScriptEvaluator.cs b/EOBot/Interpreter/States/ScriptEvaluator.cs index 93cf583c1..6854347b3 100644 --- a/EOBot/Interpreter/States/ScriptEvaluator.cs +++ b/EOBot/Interpreter/States/ScriptEvaluator.cs @@ -2,23 +2,22 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class ScriptEvaluator : BaseEvaluator { - public class ScriptEvaluator : BaseEvaluator - { - public ScriptEvaluator(IEnumerable evaluators) - : base(evaluators) { } + public ScriptEvaluator(IEnumerable evaluators) + : base(evaluators) { } - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) - { - var evalResult = await Evaluator().EvaluateAsync(input); - if (evalResult.Result != EvalResult.Ok) - return evalResult; + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + var evalResult = await Evaluator().EvaluateAsync(input); + if (evalResult.Result != EvalResult.Ok) + return evalResult; - if (!input.Expect(BotTokenType.EOF)) - return Error(input.Current(), BotTokenType.EOF); + if (!input.Expect(BotTokenType.EOF)) + return Error(input.Current(), BotTokenType.EOF); - return Success(); - } + return Success(); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/StatementEvaluator.cs b/EOBot/Interpreter/States/StatementEvaluator.cs index cda9f1fb4..3da758305 100644 --- a/EOBot/Interpreter/States/StatementEvaluator.cs +++ b/EOBot/Interpreter/States/StatementEvaluator.cs @@ -2,39 +2,38 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class StatementEvaluator : BaseEvaluator { - public class StatementEvaluator : BaseEvaluator + public StatementEvaluator(IEnumerable evaluators) + : base(evaluators) { } + + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - public StatementEvaluator(IEnumerable evaluators) - : base(evaluators) { } + while (input.Current().TokenType == BotTokenType.NewLine) + input.Expect(BotTokenType.NewLine); - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + var (result, reason, token) = await Evaluator().EvaluateAsync(input); + if (result == EvalResult.NotMatch) { - while (input.Current().TokenType == BotTokenType.NewLine) - input.Expect(BotTokenType.NewLine); - - var (result, reason, token) = await Evaluator().EvaluateAsync(input); + (result, reason, token) = await Evaluator().EvaluateAsync(input); if (result == EvalResult.NotMatch) { - (result, reason, token) = await Evaluator().EvaluateAsync(input); + (result, reason, token) = await Evaluator().EvaluateAsync(input); if (result == EvalResult.NotMatch) { - (result, reason, token) = await Evaluator().EvaluateAsync(input); - if (result == EvalResult.NotMatch) - { - (result, reason, token) = await Evaluator().EvaluateAsync(input); - } + (result, reason, token) = await Evaluator().EvaluateAsync(input); } } + } - if (result != EvalResult.Ok) - return (result, reason, token); + if (result != EvalResult.Ok) + return (result, reason, token); - if (!input.Expect(BotTokenType.NewLine) && !input.Expect(BotTokenType.EOF)) - return Error(input.Current(), BotTokenType.NewLine, BotTokenType.EOF); + if (!input.Expect(BotTokenType.NewLine) && !input.Expect(BotTokenType.EOF)) + return Error(input.Current(), BotTokenType.NewLine, BotTokenType.EOF); - return (result, reason, token); - } + return (result, reason, token); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/StatementListEvaluator.cs b/EOBot/Interpreter/States/StatementListEvaluator.cs index 31da34c1a..c65e11b8c 100644 --- a/EOBot/Interpreter/States/StatementListEvaluator.cs +++ b/EOBot/Interpreter/States/StatementListEvaluator.cs @@ -1,23 +1,22 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class StatementListEvaluator : BaseEvaluator { - public class StatementListEvaluator : BaseEvaluator + public StatementListEvaluator(IEnumerable evaluators) + : base(evaluators) { } + + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - public StatementListEvaluator(IEnumerable evaluators) - : base(evaluators) { } + (EvalResult Result, string, BotToken) result; - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + do { - (EvalResult Result, string, BotToken) result; - - do - { - result = await Evaluator().EvaluateAsync(input); - } while (result.Result == EvalResult.Ok && !input.Expect(BotTokenType.EOF) && !input.Expect(BotTokenType.RBrace)); + result = await Evaluator().EvaluateAsync(input); + } while (result.Result == EvalResult.Ok && !input.Expect(BotTokenType.EOF) && !input.Expect(BotTokenType.RBrace)); - return result; - } + return result; } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/VariableEvaluator.cs b/EOBot/Interpreter/States/VariableEvaluator.cs index 44f2ff5d7..c23d7e6b4 100644 --- a/EOBot/Interpreter/States/VariableEvaluator.cs +++ b/EOBot/Interpreter/States/VariableEvaluator.cs @@ -3,65 +3,64 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States +namespace EOBot.Interpreter.States; + +public class VariableEvaluator : BaseEvaluator { - public class VariableEvaluator : BaseEvaluator + public VariableEvaluator(IEnumerable evaluators) + : base(evaluators) { } + + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - public VariableEvaluator(IEnumerable evaluators) - : base(evaluators) { } + if (!input.Match(BotTokenType.Variable)) + return (EvalResult.NotMatch, string.Empty, input.Current()); - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + int? arrayIndex = null; + if (input.Expect(BotTokenType.LBracket)) { - if (!input.Match(BotTokenType.Variable)) - return (EvalResult.NotMatch, string.Empty, input.Current()); - - int? arrayIndex = null; - if (input.Expect(BotTokenType.LBracket)) - { - var expressionEval = await Evaluator().EvaluateAsync(input); - if (expressionEval.Result != EvalResult.Ok) - return expressionEval; - - if (!input.Expect(BotTokenType.RBracket)) - return Error(input.Current(), BotTokenType.RBracket); + var expressionEval = await Evaluator().EvaluateAsync(input); + if (expressionEval.Result != EvalResult.Ok) + return expressionEval; - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var expressionResult = (VariableBotToken)input.OperationStack.Pop(); + if (!input.Expect(BotTokenType.RBracket)) + return Error(input.Current(), BotTokenType.RBracket); - if (!(expressionResult.VariableValue is IntVariable)) - return (EvalResult.Failed, $"Expected index to be int, but it was {expressionResult.VariableValue.GetType().Name}", expressionResult); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var expressionResult = (VariableBotToken)input.OperationStack.Pop(); - arrayIndex = ((IntVariable)expressionResult.VariableValue).Value; - } + if (!(expressionResult.VariableValue is IntVariable)) + return (EvalResult.Failed, $"Expected index to be int, but it was {expressionResult.VariableValue.GetType().Name}", expressionResult); - IdentifierBotToken nestedIdentifier = null; - if (input.Match(BotTokenType.Dot)) - { - var evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result != EvalResult.Ok) - return evalRes; + arrayIndex = ((IntVariable)expressionResult.VariableValue).Value; + } - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - nestedIdentifier = (IdentifierBotToken)input.OperationStack.Pop(); - if (nestedIdentifier.TokenType != BotTokenType.Variable) - return StackTokenError(BotTokenType.Variable, nestedIdentifier); + IdentifierBotToken nestedIdentifier = null; + if (input.Match(BotTokenType.Dot)) + { + var evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result != EvalResult.Ok) + return evalRes; - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var expectedDot = input.OperationStack.Pop(); - if (expectedDot.TokenType != BotTokenType.Dot) - return StackTokenError(BotTokenType.Dot, expectedDot); - } + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + nestedIdentifier = (IdentifierBotToken)input.OperationStack.Pop(); + if (nestedIdentifier.TokenType != BotTokenType.Variable) + return StackTokenError(BotTokenType.Variable, nestedIdentifier); if (input.OperationStack.Count == 0) return StackEmptyError(input.Current()); - var identifier = input.OperationStack.Pop(); + var expectedDot = input.OperationStack.Pop(); + if (expectedDot.TokenType != BotTokenType.Dot) + return StackTokenError(BotTokenType.Dot, expectedDot); + } - input.OperationStack.Push(new IdentifierBotToken(identifier, arrayIndex, nestedIdentifier)); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var identifier = input.OperationStack.Pop(); - return Success(); - } + input.OperationStack.Push(new IdentifierBotToken(identifier, arrayIndex, nestedIdentifier)); + + return Success(); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/WhileEvaluator.cs b/EOBot/Interpreter/States/WhileEvaluator.cs index b8b576296..688ac7dc4 100644 --- a/EOBot/Interpreter/States/WhileEvaluator.cs +++ b/EOBot/Interpreter/States/WhileEvaluator.cs @@ -2,40 +2,39 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States -{ - public class WhileEvaluator : BlockEvaluator - { - public WhileEvaluator(IEnumerable evaluators) - : base(evaluators) { } +namespace EOBot.Interpreter.States; - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) - { - // ensure we have the right keyword before advancing the program - var current = input.Current(); - if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "while") - return (EvalResult.NotMatch, string.Empty, input.Current()); +public class WhileEvaluator : BlockEvaluator +{ + public WhileEvaluator(IEnumerable evaluators) + : base(evaluators) { } - var whileLoopStartIndex = input.ExecutionIndex; + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + // ensure we have the right keyword before advancing the program + var current = input.Current(); + if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "while") + return (EvalResult.NotMatch, string.Empty, input.Current()); - EvalResult result; - string reason; - BotToken token; - for ((result, reason, token) = await EvaluateConditionAsync(whileLoopStartIndex, input); - result == EvalResult.Ok && bool.TryParse(token.TokenValue, out var conditionValue) && conditionValue; - (result, reason, token) = await EvaluateConditionAsync(whileLoopStartIndex, input)) - { - var blockEval = await EvaluateBlockAsync(input); - if (blockEval.Item1 != EvalResult.Ok) - return blockEval; - } + var whileLoopStartIndex = input.ExecutionIndex; - if (result == EvalResult.Ok) - { - SkipBlock(input); - } + EvalResult result; + string reason; + BotToken token; + for ((result, reason, token) = await EvaluateConditionAsync(whileLoopStartIndex, input); + result == EvalResult.Ok && bool.TryParse(token.TokenValue, out var conditionValue) && conditionValue; + (result, reason, token) = await EvaluateConditionAsync(whileLoopStartIndex, input)) + { + var blockEval = await EvaluateBlockAsync(input); + if (blockEval.Item1 != EvalResult.Ok) + return blockEval; + } - return (result, reason, token); + if (result == EvalResult.Ok) + { + SkipBlock(input); } + + return (result, reason, token); } } \ No newline at end of file diff --git a/EOBot/Interpreter/VariableBotToken.cs b/EOBot/Interpreter/VariableBotToken.cs index 953de3f5b..31f9dfb2f 100644 --- a/EOBot/Interpreter/VariableBotToken.cs +++ b/EOBot/Interpreter/VariableBotToken.cs @@ -1,15 +1,14 @@ using EOBot.Interpreter.Variables; -namespace EOBot.Interpreter +namespace EOBot.Interpreter; + +public class VariableBotToken : BotToken { - public class VariableBotToken : BotToken - { - public IVariable VariableValue { get; } + public IVariable VariableValue { get; } - public VariableBotToken(BotTokenType tokenType, string tokenValue, IVariable variableValue) - : base(tokenType, tokenValue, 0, 0) - { - VariableValue = variableValue; - } + public VariableBotToken(BotTokenType tokenType, string tokenValue, IVariable variableValue) + : base(tokenType, tokenValue, 0, 0) + { + VariableValue = variableValue; } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/ArrayVariable.cs b/EOBot/Interpreter/Variables/ArrayVariable.cs index 25e01a1a4..8c3807bd4 100644 --- a/EOBot/Interpreter/Variables/ArrayVariable.cs +++ b/EOBot/Interpreter/Variables/ArrayVariable.cs @@ -2,27 +2,26 @@ using System.Collections.Generic; using System.Linq; -namespace EOBot.Interpreter.Variables -{ - public class ArrayVariable : IVariable> - { - public List Value { get; } +namespace EOBot.Interpreter.Variables; - public string StringValue => "[" + string.Join(", ", Value.Select(x => x.StringValue)) + "]"; +public class ArrayVariable : IVariable> +{ + public List Value { get; } - public ArrayVariable(List value) - { - Value = value; - } + public string StringValue => "[" + string.Join(", ", Value.Select(x => x.StringValue)) + "]"; - // todo: should arrays be comparable? - public int CompareTo(object obj) => -1; + public ArrayVariable(List value) + { + Value = value; + } - public IVariable> WithNewValue(List value) - { - return new ArrayVariable(value); - } + // todo: should arrays be comparable? + public int CompareTo(object obj) => -1; - public override string ToString() => StringValue; + public IVariable> WithNewValue(List value) + { + return new ArrayVariable(value); } + + public override string ToString() => StringValue; } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/AsyncFunction.cs b/EOBot/Interpreter/Variables/AsyncFunction.cs index 85a2136c4..9e9fe701d 100644 --- a/EOBot/Interpreter/Variables/AsyncFunction.cs +++ b/EOBot/Interpreter/Variables/AsyncFunction.cs @@ -1,132 +1,131 @@ using System; using System.Threading.Tasks; -namespace EOBot.Interpreter.Variables -{ - public class AsyncFunction : IAsyncCallable - { - private readonly Func> _referenceFunc; - - public string StringValue { get; } +namespace EOBot.Interpreter.Variables; - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class AsyncFunction : IAsyncCallable +{ + private readonly Func> _referenceFunc; - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 0) - throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); + public string StringValue { get; } - return _referenceFunc(); - } + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class AsyncFunction : IAsyncCallable + public Task CallAsync(params IIdentifiable[] parameters) { - private readonly Func> _referenceFunc; + if (parameters.Length != 0) + throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); - public string StringValue { get; } + return _referenceFunc(); + } +} - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class AsyncFunction : IAsyncCallable +{ + private readonly Func> _referenceFunc; - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 1) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface - return _referenceFunc((TParam1)(dynamic)parameters[0]); - } + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class AsyncFunction : IAsyncCallable + public Task CallAsync(params IIdentifiable[] parameters) { - private readonly Func> _referenceFunc; + if (parameters.Length != 1) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface + return _referenceFunc((TParam1)(dynamic)parameters[0]); + } +} - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class AsyncFunction : IAsyncCallable +{ + private readonly Func> _referenceFunc; - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 2) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); - } + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class AsyncFunction : IAsyncCallable + public Task CallAsync(params IIdentifiable[] parameters) { - private readonly Func> _referenceFunc; + if (parameters.Length != 2) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); + } +} - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class AsyncFunction : IAsyncCallable +{ + private readonly Func> _referenceFunc; - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 3) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); - } + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class AsyncFunction : IAsyncCallable + public Task CallAsync(params IIdentifiable[] parameters) { - private readonly Func> _referenceFunc; + if (parameters.Length != 3) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); + } +} - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class AsyncFunction : IAsyncCallable +{ + private readonly Func> _referenceFunc; - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 4) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); - } + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class AsyncFunction : IAsyncCallable + public Task CallAsync(params IIdentifiable[] parameters) { - private readonly Func> _referenceFunc; + if (parameters.Length != 4) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); + } +} + +public class AsyncFunction : IAsyncCallable +{ + private readonly Func> _referenceFunc; - public string StringValue { get; } + public string StringValue { get; } - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 5) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 5) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); - } + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/AsyncVoidFunction.cs b/EOBot/Interpreter/Variables/AsyncVoidFunction.cs index f4beb6c09..66254844f 100644 --- a/EOBot/Interpreter/Variables/AsyncVoidFunction.cs +++ b/EOBot/Interpreter/Variables/AsyncVoidFunction.cs @@ -1,132 +1,131 @@ using System; using System.Threading.Tasks; -namespace EOBot.Interpreter.Variables -{ - public class AsyncVoidFunction : IAsyncCallable - { - private readonly Func _referenceFunc; - - public string StringValue { get; } +namespace EOBot.Interpreter.Variables; - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class AsyncVoidFunction : IAsyncCallable +{ + private readonly Func _referenceFunc; - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 0) - throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); + public string StringValue { get; } - return _referenceFunc(); - } + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class AsyncVoidFunction : IAsyncCallable + public Task CallAsync(params IIdentifiable[] parameters) { - private readonly Func _referenceFunc; + if (parameters.Length != 0) + throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); - public string StringValue { get; } + return _referenceFunc(); + } +} - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class AsyncVoidFunction : IAsyncCallable +{ + private readonly Func _referenceFunc; - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 1) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface - return _referenceFunc((TParam1)(dynamic)parameters[0]); - } + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class AsyncVoidFunction : IAsyncCallable + public Task CallAsync(params IIdentifiable[] parameters) { - private readonly Func _referenceFunc; + if (parameters.Length != 1) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface + return _referenceFunc((TParam1)(dynamic)parameters[0]); + } +} - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class AsyncVoidFunction : IAsyncCallable +{ + private readonly Func _referenceFunc; - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 2) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); - } + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class AsyncVoidFunction : IAsyncCallable + public Task CallAsync(params IIdentifiable[] parameters) { - private readonly Func _referenceFunc; + if (parameters.Length != 2) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); + } +} - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class AsyncVoidFunction : IAsyncCallable +{ + private readonly Func _referenceFunc; - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 3) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); - } + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class AsyncVoidFunction : IAsyncCallable + public Task CallAsync(params IIdentifiable[] parameters) { - private readonly Func _referenceFunc; + if (parameters.Length != 3) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); + } +} - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class AsyncVoidFunction : IAsyncCallable +{ + private readonly Func _referenceFunc; - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 4) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); - } + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class AsyncVoidFunction : IAsyncCallable + public Task CallAsync(params IIdentifiable[] parameters) { - private readonly Func _referenceFunc; + if (parameters.Length != 4) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); + } +} + +public class AsyncVoidFunction : IAsyncCallable +{ + private readonly Func _referenceFunc; - public string StringValue { get; } + public string StringValue { get; } - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public Task CallAsync(params IIdentifiable[] parameters) - { - if (parameters.Length != 5) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 5) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); - } + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/BoolVariable.cs b/EOBot/Interpreter/Variables/BoolVariable.cs index 369537c19..533ee1371 100644 --- a/EOBot/Interpreter/Variables/BoolVariable.cs +++ b/EOBot/Interpreter/Variables/BoolVariable.cs @@ -1,21 +1,20 @@ -namespace EOBot.Interpreter.Variables +namespace EOBot.Interpreter.Variables; + +public class BoolVariable : IVariable { - public class BoolVariable : IVariable - { - public bool Value { get; } + public bool Value { get; } - public BoolVariable(bool value) => Value = value; + public BoolVariable(bool value) => Value = value; - public string StringValue => Value.ToString(); + public string StringValue => Value.ToString(); - public override bool Equals(object obj) => CompareTo(obj) == 0; + public override bool Equals(object obj) => CompareTo(obj) == 0; - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value.GetHashCode(); - public int CompareTo(object obj) => obj is BoolVariable ? Value.CompareTo(((BoolVariable)obj).Value) : -1; + public int CompareTo(object obj) => obj is BoolVariable ? Value.CompareTo(((BoolVariable)obj).Value) : -1; - public static explicit operator bool(BoolVariable input) => input.Value; + public static explicit operator bool(BoolVariable input) => input.Value; - public override string ToString() => StringValue; - } + public override string ToString() => StringValue; } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/Function.cs b/EOBot/Interpreter/Variables/Function.cs index 4615850b7..d41a8340c 100644 --- a/EOBot/Interpreter/Variables/Function.cs +++ b/EOBot/Interpreter/Variables/Function.cs @@ -1,131 +1,130 @@ using System; -namespace EOBot.Interpreter.Variables -{ - public class Function : ICallable - { - private readonly Func _referenceFunc; - - public string StringValue { get; } +namespace EOBot.Interpreter.Variables; - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class Function : ICallable +{ + private readonly Func _referenceFunc; - public T Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 0) - throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); + public string StringValue { get; } - return _referenceFunc(); - } + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class Function : ICallable + public T Call(params IIdentifiable[] parameters) { - private readonly Func _referenceFunc; + if (parameters.Length != 0) + throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); - public string StringValue { get; } + return _referenceFunc(); + } +} - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class Function : ICallable +{ + private readonly Func _referenceFunc; - public T Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 1) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface - return _referenceFunc((TParam1)(dynamic)parameters[0]); - } + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class Function : ICallable + public T Call(params IIdentifiable[] parameters) { - private readonly Func _referenceFunc; + if (parameters.Length != 1) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface + return _referenceFunc((TParam1)(dynamic)parameters[0]); + } +} - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class Function : ICallable +{ + private readonly Func _referenceFunc; - public T Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 2) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); - } + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class Function : ICallable + public T Call(params IIdentifiable[] parameters) { - private readonly Func _referenceFunc; + if (parameters.Length != 2) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); + } +} - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class Function : ICallable +{ + private readonly Func _referenceFunc; - public T Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 3) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); - } + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class Function : ICallable + public T Call(params IIdentifiable[] parameters) { - private readonly Func _referenceFunc; + if (parameters.Length != 3) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); + } +} - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class Function : ICallable +{ + private readonly Func _referenceFunc; - public T Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 4) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); - } + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class Function : ICallable + public T Call(params IIdentifiable[] parameters) { - private readonly Func _referenceFunc; + if (parameters.Length != 4) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); + } +} + +public class Function : ICallable +{ + private readonly Func _referenceFunc; - public string StringValue { get; } + public string StringValue { get; } - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public T Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 5) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public T Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 5) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); - } + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/ICallable.cs b/EOBot/Interpreter/Variables/ICallable.cs index b82f237fd..9ded8ff1a 100644 --- a/EOBot/Interpreter/Variables/ICallable.cs +++ b/EOBot/Interpreter/Variables/ICallable.cs @@ -1,27 +1,26 @@ using System.Threading.Tasks; -namespace EOBot.Interpreter.Variables +namespace EOBot.Interpreter.Variables; + +public interface IFunction : IIdentifiable { } +public interface ICallable : IFunction { - public interface IFunction : IIdentifiable { } - public interface ICallable : IFunction - { - void Call(params IIdentifiable[] parameters); - } + void Call(params IIdentifiable[] parameters); +} - public interface ICallable : IFunction - { - T Call(params IIdentifiable[] parameters); - } +public interface ICallable : IFunction +{ + T Call(params IIdentifiable[] parameters); +} - public interface IAsyncFunction : IIdentifiable { } +public interface IAsyncFunction : IIdentifiable { } - public interface IAsyncCallable : IAsyncFunction - { - Task CallAsync(params IIdentifiable[] parameters); - } +public interface IAsyncCallable : IAsyncFunction +{ + Task CallAsync(params IIdentifiable[] parameters); +} - public interface IAsyncCallable : IAsyncFunction - { - Task CallAsync(params IIdentifiable[] parameters); - } +public interface IAsyncCallable : IAsyncFunction +{ + Task CallAsync(params IIdentifiable[] parameters); } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/IIdentifiable.cs b/EOBot/Interpreter/Variables/IIdentifiable.cs index f1c87c708..6b5081f74 100644 --- a/EOBot/Interpreter/Variables/IIdentifiable.cs +++ b/EOBot/Interpreter/Variables/IIdentifiable.cs @@ -1,7 +1,6 @@ -namespace EOBot.Interpreter.Variables +namespace EOBot.Interpreter.Variables; + +public interface IIdentifiable { - public interface IIdentifiable - { - string StringValue { get; } - } + string StringValue { get; } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/IVariable.cs b/EOBot/Interpreter/Variables/IVariable.cs index 42badf86c..ee054be41 100644 --- a/EOBot/Interpreter/Variables/IVariable.cs +++ b/EOBot/Interpreter/Variables/IVariable.cs @@ -1,14 +1,13 @@ using System; -namespace EOBot.Interpreter.Variables +namespace EOBot.Interpreter.Variables; + +// marker interface so we don't have to implement CompareTo for a million different function/action interfaces +public interface IVariable : IIdentifiable, IComparable { - // marker interface so we don't have to implement CompareTo for a million different function/action interfaces - public interface IVariable : IIdentifiable, IComparable - { - } +} - public interface IVariable : IVariable - { - T Value { get; } - } +public interface IVariable : IVariable +{ + T Value { get; } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/IntVariable.cs b/EOBot/Interpreter/Variables/IntVariable.cs index 397d519aa..f584f43d9 100644 --- a/EOBot/Interpreter/Variables/IntVariable.cs +++ b/EOBot/Interpreter/Variables/IntVariable.cs @@ -1,21 +1,20 @@ -namespace EOBot.Interpreter.Variables +namespace EOBot.Interpreter.Variables; + +public class IntVariable : IVariable { - public class IntVariable : IVariable - { - public int Value { get; } + public int Value { get; } - public IntVariable(int value) => Value = value; + public IntVariable(int value) => Value = value; - public string StringValue => Value.ToString(); + public string StringValue => Value.ToString(); - public override bool Equals(object obj) => CompareTo(obj) == 0; + public override bool Equals(object obj) => CompareTo(obj) == 0; - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value.GetHashCode(); - public int CompareTo(object obj) => obj is IntVariable ? Value.CompareTo(((IntVariable)obj).Value) : -1; + public int CompareTo(object obj) => obj is IntVariable ? Value.CompareTo(((IntVariable)obj).Value) : -1; - public static explicit operator int(IntVariable input) => input.Value; + public static explicit operator int(IntVariable input) => input.Value; - public override string ToString() => StringValue; - } + public override string ToString() => StringValue; } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/ObjectVariable.cs b/EOBot/Interpreter/Variables/ObjectVariable.cs index 099c9a8ca..74c217819 100644 --- a/EOBot/Interpreter/Variables/ObjectVariable.cs +++ b/EOBot/Interpreter/Variables/ObjectVariable.cs @@ -2,45 +2,44 @@ using System.Collections.Generic; using System.Linq; -namespace EOBot.Interpreter.Variables +namespace EOBot.Interpreter.Variables; + +public class ObjectVariable : IVariable { - public class ObjectVariable : IVariable - { - public object Value => SymbolTable; + public object Value => SymbolTable; - public Dictionary SymbolTable { get; } + public Dictionary SymbolTable { get; } - public ObjectVariable() => SymbolTable = new Dictionary(); + public ObjectVariable() => SymbolTable = new Dictionary(); - public ObjectVariable(Dictionary symbolTable) => SymbolTable = symbolTable; + public ObjectVariable(Dictionary symbolTable) => SymbolTable = symbolTable; - public string StringValue => $"Object: [{string.Join(", ", SymbolTable.Select(x => $"({x.Key}, {x.Value.Variable})"))}]"; + public string StringValue => $"Object: [{string.Join(", ", SymbolTable.Select(x => $"({x.Key}, {x.Value.Variable})"))}]"; - public override bool Equals(object obj) => CompareTo(obj) == 0; + public override bool Equals(object obj) => CompareTo(obj) == 0; - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value.GetHashCode(); - public int CompareTo(object obj) => obj is ObjectVariable ? SymbolTable.Equals(((ObjectVariable)obj).SymbolTable) ? 0 : -1 : -1; + public int CompareTo(object obj) => obj is ObjectVariable ? SymbolTable.Equals(((ObjectVariable)obj).SymbolTable) ? 0 : -1 : -1; - public override string ToString() => StringValue; - } + public override string ToString() => StringValue; +} - public class RuntimeEvaluatedMemberObjectVariable : IVariable - { - public object Value => SymbolTable; +public class RuntimeEvaluatedMemberObjectVariable : IVariable +{ + public object Value => SymbolTable; - public Dictionary Variable)> SymbolTable { get; } + public Dictionary Variable)> SymbolTable { get; } - public RuntimeEvaluatedMemberObjectVariable() => SymbolTable = new Dictionary)>(); + public RuntimeEvaluatedMemberObjectVariable() => SymbolTable = new Dictionary)>(); - public string StringValue => $"Object: [{string.Join(", ", SymbolTable.Select(x => $"({x.Key}, {x.Value.Variable()})"))}]"; + public string StringValue => $"Object: [{string.Join(", ", SymbolTable.Select(x => $"({x.Key}, {x.Value.Variable()})"))}]"; - public override bool Equals(object obj) => CompareTo(obj) == 0; + public override bool Equals(object obj) => CompareTo(obj) == 0; - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value.GetHashCode(); - public int CompareTo(object obj) => obj is ObjectVariable ? SymbolTable.Equals(((ObjectVariable)obj).SymbolTable) ? 0 : -1 : -1; + public int CompareTo(object obj) => obj is ObjectVariable ? SymbolTable.Equals(((ObjectVariable)obj).SymbolTable) ? 0 : -1 : -1; - public override string ToString() => StringValue; - } + public override string ToString() => StringValue; } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs b/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs index 977d4dcd1..23cabf21e 100644 --- a/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs +++ b/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs @@ -1,51 +1,50 @@ -namespace EOBot.Interpreter.Variables +namespace EOBot.Interpreter.Variables; + +public static class PredefinedIdentifiers { - public static class PredefinedIdentifiers - { - // variables - public const string RESULT = "result"; - public const string HOST = "host"; - public const string PORT = "port"; - public const string USER = "user"; - public const string PASS = "pass"; - public const string VERSION = "version"; - public const string ARGS = "args"; - public const string BOTINDEX = "botindex"; - public const string RETCODE = "retcode"; + // variables + public const string RESULT = "result"; + public const string HOST = "host"; + public const string PORT = "port"; + public const string USER = "user"; + public const string PASS = "pass"; + public const string VERSION = "version"; + public const string ARGS = "args"; + public const string BOTINDEX = "botindex"; + public const string RETCODE = "retcode"; - // state variables - public const string ACCOUNT = "account"; - public const string CHARACTER = "character"; - public const string MAPSTATE = "mapstate"; + // state variables + public const string ACCOUNT = "account"; + public const string CHARACTER = "character"; + public const string MAPSTATE = "mapstate"; - public const string NAME = "name"; - public const string CHARACTERS = "characters"; + public const string NAME = "name"; + public const string CHARACTERS = "characters"; - // interpreter functions - public const string PRINT_FUNC = "print"; - public const string LEN_FUNC = "len"; - public const string ARRAY_FUNC = "array"; - public const string OBJECT_FUNC = "object"; - public const string SLEEP_FUNC = "sleep"; - public const string TIME_FUNC = "time"; - public const string SETENV_FUNC = "setenv"; - public const string GETENV_FUNC = "getenv"; - public const string ERROR_FUNC = "error"; - public const string LOWER_FUNC = "lower"; - public const string UPPER_FUNC = "upper"; + // interpreter functions + public const string PRINT_FUNC = "print"; + public const string LEN_FUNC = "len"; + public const string ARRAY_FUNC = "array"; + public const string OBJECT_FUNC = "object"; + public const string SLEEP_FUNC = "sleep"; + public const string TIME_FUNC = "time"; + public const string SETENV_FUNC = "setenv"; + public const string GETENV_FUNC = "getenv"; + public const string ERROR_FUNC = "error"; + public const string LOWER_FUNC = "lower"; + public const string UPPER_FUNC = "upper"; - // game functions - public const string CONNECT_FUNC = "Connect"; - public const string DISCONNECT_FUNC = "Disconnect"; - public const string CREATE_ACCOUNT_FUNC = "CreateAccount"; - public const string LOGIN_FUNC = "Login"; - public const string CREATE_AND_LOGIN_FUNC = "CreateAndLogin"; - public const string CHANGE_PASS_FUNC = "ChangePassword"; - public const string CREATE_CHARACTER_FUNC = "CreateCharacter"; - public const string LOGIN_CHARACTER_FUNC = "LoginCharacter"; - public const string DELETE_CHARACTER_FUNC = "DeleteCharacter"; + // game functions + public const string CONNECT_FUNC = "Connect"; + public const string DISCONNECT_FUNC = "Disconnect"; + public const string CREATE_ACCOUNT_FUNC = "CreateAccount"; + public const string LOGIN_FUNC = "Login"; + public const string CREATE_AND_LOGIN_FUNC = "CreateAndLogin"; + public const string CHANGE_PASS_FUNC = "ChangePassword"; + public const string CREATE_CHARACTER_FUNC = "CreateCharacter"; + public const string LOGIN_CHARACTER_FUNC = "LoginCharacter"; + public const string DELETE_CHARACTER_FUNC = "DeleteCharacter"; - public const string JOIN_PARTY = "JoinParty"; - public const string CHAT = "Chat"; - } + public const string JOIN_PARTY = "JoinParty"; + public const string CHAT = "Chat"; } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/StringVariable.cs b/EOBot/Interpreter/Variables/StringVariable.cs index 7884fd76b..82ca102ca 100644 --- a/EOBot/Interpreter/Variables/StringVariable.cs +++ b/EOBot/Interpreter/Variables/StringVariable.cs @@ -1,21 +1,20 @@ -namespace EOBot.Interpreter.Variables +namespace EOBot.Interpreter.Variables; + +public class StringVariable : IVariable { - public class StringVariable : IVariable - { - public string Value { get; } + public string Value { get; } - public StringVariable(string value) => Value = value; + public StringVariable(string value) => Value = value; - public string StringValue => Value; + public string StringValue => Value; - public override bool Equals(object obj) => CompareTo(obj) == 0; + public override bool Equals(object obj) => CompareTo(obj) == 0; - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value.GetHashCode(); - public int CompareTo(object obj) => obj is StringVariable ? Value.CompareTo(((StringVariable)obj).Value) : -1; + public int CompareTo(object obj) => obj is StringVariable ? Value.CompareTo(((StringVariable)obj).Value) : -1; - public static explicit operator string(StringVariable variable) => variable.Value; + public static explicit operator string(StringVariable variable) => variable.Value; - public override string ToString() => StringValue; - } + public override string ToString() => StringValue; } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/UndefinedVariable.cs b/EOBot/Interpreter/Variables/UndefinedVariable.cs index 95582b946..2ab86a224 100644 --- a/EOBot/Interpreter/Variables/UndefinedVariable.cs +++ b/EOBot/Interpreter/Variables/UndefinedVariable.cs @@ -1,15 +1,14 @@ -namespace EOBot.Interpreter.Variables +namespace EOBot.Interpreter.Variables; + +public class UndefinedVariable : IVariable { - public class UndefinedVariable : IVariable - { - public static UndefinedVariable Instance { get; } = new UndefinedVariable(); + public static UndefinedVariable Instance { get; } = new UndefinedVariable(); - public string StringValue => "Undefined"; + public string StringValue => "Undefined"; - private UndefinedVariable() { } + private UndefinedVariable() { } - public int CompareTo(object obj) => obj is UndefinedVariable ? 0 : -1; + public int CompareTo(object obj) => obj is UndefinedVariable ? 0 : -1; - public override string ToString() => StringValue; - } + public override string ToString() => StringValue; } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/VoidFunction.cs b/EOBot/Interpreter/Variables/VoidFunction.cs index 1429b34ef..9b61d82a0 100644 --- a/EOBot/Interpreter/Variables/VoidFunction.cs +++ b/EOBot/Interpreter/Variables/VoidFunction.cs @@ -1,131 +1,130 @@ using System; -namespace EOBot.Interpreter.Variables -{ - public class VoidFunction : ICallable - { - private readonly Action _referenceFunc; - - public string StringValue { get; } +namespace EOBot.Interpreter.Variables; - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class VoidFunction : ICallable +{ + private readonly Action _referenceFunc; - public void Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 0) - throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); + public string StringValue { get; } - _referenceFunc(); - } + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class VoidFunction : ICallable + public void Call(params IIdentifiable[] parameters) { - private readonly Action _referenceFunc; + if (parameters.Length != 0) + throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); - public string StringValue { get; } + _referenceFunc(); + } +} - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class VoidFunction : ICallable +{ + private readonly Action _referenceFunc; - public void Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 1) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface - _referenceFunc((TParam1)(dynamic)parameters[0]); - } + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class VoidFunction : ICallable + public void Call(params IIdentifiable[] parameters) { - private readonly Action _referenceFunc; + if (parameters.Length != 1) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface + _referenceFunc((TParam1)(dynamic)parameters[0]); + } +} - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class VoidFunction : ICallable +{ + private readonly Action _referenceFunc; - public void Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 2) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); - } + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class VoidFunction : ICallable + public void Call(params IIdentifiable[] parameters) { - private readonly Action _referenceFunc; + if (parameters.Length != 2) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); + } +} - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class VoidFunction : ICallable +{ + private readonly Action _referenceFunc; - public void Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 3) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); - } + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class VoidFunction : ICallable + public void Call(params IIdentifiable[] parameters) { - private readonly Action _referenceFunc; + if (parameters.Length != 3) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public string StringValue { get; } + _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); + } +} - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } +public class VoidFunction : ICallable +{ + private readonly Action _referenceFunc; - public void Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 4) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public string StringValue { get; } - _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); - } + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; } - public class VoidFunction : ICallable + public void Call(params IIdentifiable[] parameters) { - private readonly Action _referenceFunc; + if (parameters.Length != 4) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + + _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); + } +} + +public class VoidFunction : ICallable +{ + private readonly Action _referenceFunc; - public string StringValue { get; } + public string StringValue { get; } - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public void Call(params IIdentifiable[] parameters) - { - if (parameters.Length != 5) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + public void Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 5) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); - } + _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); } } \ No newline at end of file diff --git a/EOBot/NamesList.cs b/EOBot/NamesList.cs index 0c1a91aea..ae851ccf1 100644 --- a/EOBot/NamesList.cs +++ b/EOBot/NamesList.cs @@ -1,55 +1,54 @@ using System; -namespace EOBot +namespace EOBot; + +static class NamesList { - static class NamesList + private static readonly string[] namesArray = { - private static readonly string[] namesArray = - { - "AlphaAA", - "BravoBB", - "Charlie", - "DeltaDD", - "EchoEE", - "Foxtrot", - "GolfGG", - "HotelHH", - "IndiaII", - "Juliett", - "KiloKK", - "LimaLL", - "MikeMM", - "November", - "OscarOO", - "PapaPO", - "Quebec", - "RomeoRR", - "Sierra", - "TangoTT", - "Uniform", - "Victor", - "Whiskey", - "XrayXX", - "Yankee" - }; + "AlphaAA", + "BravoBB", + "Charlie", + "DeltaDD", + "EchoEE", + "Foxtrot", + "GolfGG", + "HotelHH", + "IndiaII", + "Juliett", + "KiloKK", + "LimaLL", + "MikeMM", + "November", + "OscarOO", + "PapaPO", + "Quebec", + "RomeoRR", + "Sierra", + "TangoTT", + "Uniform", + "Victor", + "Whiskey", + "XrayXX", + "Yankee" + }; - public static string Get(int index) - { - if (index < 0 || index >= namesArray.Length) - index = 0; - return namesArray[index]; - } + public static string Get(int index) + { + if (index < 0 || index >= namesArray.Length) + index = 0; + return namesArray[index]; + } - public static string Rand() + public static string Rand() + { + Random gen = new Random(); + int len = gen.Next(5, 11); + string ret = ""; + for (int i = 0; i < len; ++i) { - Random gen = new Random(); - int len = gen.Next(5, 11); - string ret = ""; - for (int i = 0; i < len; ++i) - { - ret += Convert.ToChar(Convert.ToInt32('a') + gen.Next(0, 25)); - } - return ret; + ret += Convert.ToChar(Convert.ToInt32('a') + gen.Next(0, 25)); } + return ret; } } \ No newline at end of file diff --git a/EOBot/Program.cs b/EOBot/Program.cs index 48acacfc4..491231f2e 100644 --- a/EOBot/Program.cs +++ b/EOBot/Program.cs @@ -14,322 +14,322 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot +namespace EOBot; + +static class Program { - static class Program + private static BotFramework f; + + [AutoMappedType] + class NpcWalkNotifier : INPCActionNotifier { - private static BotFramework f; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly ICharacterProvider _characterProvider; + private readonly IENFFileProvider _enfFileProvider; - [AutoMappedType] - class NpcWalkNotifier : INPCActionNotifier + public NpcWalkNotifier(ICurrentMapStateRepository currentMapStateRepository, + ICharacterProvider characterProvider, + IENFFileProvider enfFileProvider) { - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly ICharacterProvider _characterProvider; - private readonly IENFFileProvider _enfFileProvider; - - public NpcWalkNotifier(ICurrentMapStateRepository currentMapStateRepository, - ICharacterProvider characterProvider, - IENFFileProvider enfFileProvider) - { - _currentMapStateRepository = currentMapStateRepository; - _characterProvider = characterProvider; - _enfFileProvider = enfFileProvider; - } - - public void NPCTakeDamage(int npcIndex, int fromPlayerId, int damageToNpc, int npcPctHealth, Option spellId) - { - if (fromPlayerId != _characterProvider.MainCharacter.ID) - return; + _currentMapStateRepository = currentMapStateRepository; + _characterProvider = characterProvider; + _enfFileProvider = enfFileProvider; + } - var npc = _currentMapStateRepository.NPCs.SingleOrDefault(x => x.Index == npcIndex); - var npcName = _enfFileProvider.ENFFile.SingleOrDefault(x => npc != null && npc.ID == x.ID)?.Name; + public void NPCTakeDamage(int npcIndex, int fromPlayerId, int damageToNpc, int npcPctHealth, Option spellId) + { + if (fromPlayerId != _characterProvider.MainCharacter.ID) + return; - var color = npcPctHealth < 25 - ? ConsoleColor.Red - : npcPctHealth < 50 - ? ConsoleColor.Yellow - : ConsoleColor.Green; + var npc = _currentMapStateRepository.NPCs.SingleOrDefault(x => x.Index == npcIndex); + var npcName = _enfFileProvider.ENFFile.SingleOrDefault(x => npc != null && npc.ID == x.ID)?.Name; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Hit, $"{damageToNpc,7} - {npcPctHealth,3}% HP - {npcIndex,2} - {npcName ?? string.Empty}", color); - } + var color = npcPctHealth < 25 + ? ConsoleColor.Red + : npcPctHealth < 50 + ? ConsoleColor.Yellow + : ConsoleColor.Green; - public void RemoveNPCFromView(int npcIndex, int playerId, Option spellId, Option damage, bool showDeathAnimation) - { - } + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Hit, $"{damageToNpc,7} - {npcPctHealth,3}% HP - {npcIndex,2} - {npcName ?? string.Empty}", color); + } - public void ShowNPCSpeechBubble(int npcIndex, string message) - { - } + public void RemoveNPCFromView(int npcIndex, int playerId, Option spellId, Option damage, bool showDeathAnimation) + { + } - public void StartNPCAttackAnimation(int npcIndex) - { - } + public void ShowNPCSpeechBubble(int npcIndex, string message) + { + } - public void StartNPCWalkAnimation(int npcIndex) - { - // immediately walk the NPC to the destination index - var npc = _currentMapStateRepository.NPCs.SingleOrDefault(x => x.Index == npcIndex); - if (npc == null) return; + public void StartNPCAttackAnimation(int npcIndex) + { + } - var newNpc = npc.WithX(npc.GetDestinationX()).WithY(npc.GetDestinationY()).WithFrame(NPCFrame.Standing); - _currentMapStateRepository.NPCs.Remove(npc); - _currentMapStateRepository.NPCs.Add(newNpc); - } + public void StartNPCWalkAnimation(int npcIndex) + { + // immediately walk the NPC to the destination index + var npc = _currentMapStateRepository.NPCs.SingleOrDefault(x => x.Index == npcIndex); + if (npc == null) return; - public void NPCDropItem(MapItem item) - { - } + var newNpc = npc.WithX(npc.GetDestinationX()).WithY(npc.GetDestinationY()).WithFrame(NPCFrame.Standing); + _currentMapStateRepository.NPCs.Remove(npc); + _currentMapStateRepository.NPCs.Add(newNpc); } - [AutoMappedType] - class CharacterTakeDamageNotifier : IMainCharacterEventNotifier + public void NPCDropItem(MapItem item) { - private readonly ICharacterProvider _characterProvider; - private readonly IExperienceTableProvider _experienceTableProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; + } + } - public CharacterTakeDamageNotifier(ICharacterProvider characterProvider, - IExperienceTableProvider experienceTableProvider, - ICharacterInventoryProvider characterInventoryProvider) - { - _characterProvider = characterProvider; - _experienceTableProvider = experienceTableProvider; - _characterInventoryProvider = characterInventoryProvider; - } + [AutoMappedType] + class CharacterTakeDamageNotifier : IMainCharacterEventNotifier + { + private readonly ICharacterProvider _characterProvider; + private readonly IExperienceTableProvider _experienceTableProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; - public void NotifyGainedExp(int expDifference) - { - var nextLevelExp = _experienceTableProvider.ExperienceByLevel[_characterProvider.MainCharacter.Stats[CharacterStat.Level] + 1]; - var tnl = nextLevelExp - _characterProvider.MainCharacter.Stats[CharacterStat.Experience] - expDifference; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Experience, $"{expDifference,7} - {tnl} TNL", ConsoleColor.DarkCyan); - } + public CharacterTakeDamageNotifier(ICharacterProvider characterProvider, + IExperienceTableProvider experienceTableProvider, + ICharacterInventoryProvider characterInventoryProvider) + { + _characterProvider = characterProvider; + _experienceTableProvider = experienceTableProvider; + _characterInventoryProvider = characterInventoryProvider; + } - public void NotifyTakeDamage(int damageTaken, int playerPercentHealth, bool isHeal) - { - var type = isHeal ? ConsoleHelper.Type.Heal : ConsoleHelper.Type.Damage; - var color = isHeal ? ConsoleColor.DarkGreen - : playerPercentHealth < 25 - ? ConsoleColor.Red - : playerPercentHealth < 50 - ? ConsoleColor.Yellow - : ConsoleColor.Green; - - ConsoleHelper.WriteMessage(type, $"{damageTaken,7} - {playerPercentHealth,3}% HP", color); - - var hp = _characterProvider.MainCharacter.Stats[CharacterStat.HP]; - if (!isHeal && hp - damageTaken <= 0) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Dead, "**** YOU DIED ****", ConsoleColor.DarkRed); - } - } + public void NotifyGainedExp(int expDifference) + { + var nextLevelExp = _experienceTableProvider.ExperienceByLevel[_characterProvider.MainCharacter.Stats[CharacterStat.Level] + 1]; + var tnl = nextLevelExp - _characterProvider.MainCharacter.Stats[CharacterStat.Experience] - expDifference; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Experience, $"{expDifference,7} - {tnl} TNL", ConsoleColor.DarkCyan); + } - public void TakeItemFromMap(int id, int amountTaken) - { - var inventoryCount = _characterInventoryProvider.ItemInventory.SingleOrDefault(x => x.ItemID == id); - var weight = _characterProvider.MainCharacter.Stats[CharacterStat.Weight]; - var maxWeight = _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Item, $"{weight,3}/{maxWeight,3} - weight - {inventoryCount.Amount} in inventory"); - } + public void NotifyTakeDamage(int damageTaken, int playerPercentHealth, bool isHeal) + { + var type = isHeal ? ConsoleHelper.Type.Heal : ConsoleHelper.Type.Damage; + var color = isHeal ? ConsoleColor.DarkGreen + : playerPercentHealth < 25 + ? ConsoleColor.Red + : playerPercentHealth < 50 + ? ConsoleColor.Yellow + : ConsoleColor.Green; - public void DropItem(int id, int amountDropped) - { - } + ConsoleHelper.WriteMessage(type, $"{damageTaken,7} - {playerPercentHealth,3}% HP", color); - public void JunkItem(int id, int amountRemoved) + var hp = _characterProvider.MainCharacter.Stats[CharacterStat.HP]; + if (!isHeal && hp - damageTaken <= 0) { - var inventoryCount = _characterInventoryProvider.ItemInventory.SingleOrDefault(x => x.ItemID == id); - var weight = _characterProvider.MainCharacter.Stats[CharacterStat.Weight]; - var maxWeight = _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.JunkItem, $"{weight,3}/{maxWeight,3} - weight - {inventoryCount?.Amount ?? 0} in inventory"); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Dead, "**** YOU DIED ****", ConsoleColor.DarkRed); } + } - public void MakeDrunk() { } + public void TakeItemFromMap(int id, int amountTaken) + { + var inventoryCount = _characterInventoryProvider.ItemInventory.SingleOrDefault(x => x.ItemID == id); + var weight = _characterProvider.MainCharacter.Stats[CharacterStat.Weight]; + var maxWeight = _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Item, $"{weight,3}/{maxWeight,3} - weight - {inventoryCount.Amount} in inventory"); } - [AutoMappedType] - class CharacterAnimationNotifier : IOtherCharacterAnimationNotifier + public void DropItem(int id, int amountDropped) { - private readonly ICharacterProvider _characterProvider; + } - public CharacterAnimationNotifier(ICharacterProvider characterProvider) - { - _characterProvider = characterProvider; - } + public void JunkItem(int id, int amountRemoved) + { + var inventoryCount = _characterInventoryProvider.ItemInventory.SingleOrDefault(x => x.ItemID == id); + var weight = _characterProvider.MainCharacter.Stats[CharacterStat.Weight]; + var maxWeight = _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.JunkItem, $"{weight,3}/{maxWeight,3} - weight - {inventoryCount?.Amount ?? 0} in inventory"); + } - public void NotifySelfSpellCast(int playerId, int spellId, int spellHp, int percentHealth) - { - if (playerId == _characterProvider.MainCharacter.ID && spellHp > 0) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Heal, $"{spellHp,7} - {percentHealth}% HP", ConsoleColor.DarkGreen); - } + public void MakeDrunk() { } + } - public void NotifyStartSpellCast(int playerId, int spellId) { } - public void NotifyTargetNpcSpellCast(int playerId) { } - public void NotifyTargetOtherSpellCast(int sourcePlayerID, int targetPlayerID, int spellId, int recoveredHP, int targetPercentHealth) { } - public void StartOtherCharacterAttackAnimation(int characterID, int noteIndex) { } - public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) { } - public void NotifyGroupSpellCast(int playerId, int spellId, int spellHp, List spellTargets) { } + [AutoMappedType] + class CharacterAnimationNotifier : IOtherCharacterAnimationNotifier + { + private readonly ICharacterProvider _characterProvider; + + public CharacterAnimationNotifier(ICharacterProvider characterProvider) + { + _characterProvider = characterProvider; } - static async Task Main(string[] args) + public void NotifySelfSpellCast(int playerId, int spellId, int spellHp, int percentHealth) { - var assemblyNames = new[] - { - "EOBot", - "EOLib", - "EOLib.Config", - "EOLib.IO", - "EOLib.Localization", - "EOLib.Logger" - }; + if (playerId == _characterProvider.MainCharacter.ID && spellHp > 0) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Heal, $"{spellHp,7} - {percentHealth}% HP", ConsoleColor.DarkGreen); + } - Console.CancelKeyPress += HandleCtrlC; + public void NotifyStartSpellCast(int playerId, int spellId) { } + public void NotifyTargetNpcSpellCast(int playerId) { } + public void NotifyTargetOtherSpellCast(int sourcePlayerID, int targetPlayerID, int spellId, int recoveredHP, int targetPercentHealth) { } + public void StartOtherCharacterAttackAnimation(int characterID, int noteIndex) { } + public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) { } + public void NotifyGroupSpellCast(int playerId, int spellId, int spellHp, List spellTargets) { } + } - ArgumentsParser parsedArgs = new ArgumentsParser(args); + static async Task Main(string[] args) + { + var assemblyNames = new[] + { + "EOBot", + "EOLib", + "EOLib.Config", + "EOLib.IO", + "EOLib.Localization", + "EOLib.Logger" + }; - if (parsedArgs.Error != ArgsError.NoError || parsedArgs.ExtendedHelp) - { - ShowError(parsedArgs); - return 1; - } + Console.CancelKeyPress += HandleCtrlC; - DependencyMaster.TypeRegistry = new ITypeRegistry[parsedArgs.NumBots]; - for (int i = 0; i < parsedArgs.NumBots; ++i) - { - DependencyMaster.TypeRegistry[i] = new UnityRegistry(assemblyNames); - DependencyMaster.TypeRegistry[i].RegisterDiscoveredTypes(); - } + ArgumentsParser parsedArgs = new ArgumentsParser(args); - IBotFactory botFactory; - if (parsedArgs.ScriptFile != null) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Executing script {parsedArgs.ScriptFile}..."); - botFactory = new ScriptedBotFactory(parsedArgs); - } - else - { - botFactory = new TrainerBotFactory(parsedArgs); - } + if (parsedArgs.Error != ArgsError.NoError || parsedArgs.ExtendedHelp) + { + ShowError(parsedArgs); + return 1; + } - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "Starting bots..."); + DependencyMaster.TypeRegistry = new ITypeRegistry[parsedArgs.NumBots]; + for (int i = 0; i < parsedArgs.NumBots; ++i) + { + DependencyMaster.TypeRegistry[i] = new UnityRegistry(assemblyNames); + DependencyMaster.TypeRegistry[i].RegisterDiscoveredTypes(); + } - try - { - using (f = new BotFramework(parsedArgs)) - { - await f.InitializeAsync(botFactory, parsedArgs.InitDelay); - await f.RunAsync(); - } - - Console.WriteLine(); - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "All bots completed."); - } - catch (BotException bex) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, bex.Message, ConsoleColor.DarkRed); - return 1; - } - catch (BotScriptErrorException bse) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, bse.Message, ConsoleColor.DarkRed); - return 1; - } - catch (AggregateException ae) - { - var botExceptions = ae.InnerExceptions.OfType().ToList(); - foreach (var ie in botExceptions) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, ie.Message, ConsoleColor.DarkRed); + IBotFactory botFactory; + if (parsedArgs.ScriptFile != null) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Executing script {parsedArgs.ScriptFile}..."); + botFactory = new ScriptedBotFactory(parsedArgs); + } + else + { + botFactory = new TrainerBotFactory(parsedArgs); + } - var otherExceptions = ae.InnerExceptions.Except(botExceptions); - foreach (var ie in otherExceptions) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Unhandled error: {ie.Message}\nStack Trace:\n{ie.StackTrace}", ConsoleColor.DarkRed); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "Starting bots..."); - return 1; - } - catch (Exception ex) + try + { + using (f = new BotFramework(parsedArgs)) { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Unhandled error: {ex.Message}\nStack Trace:\n{ex.StackTrace}", ConsoleColor.DarkRed); - return 1; + await f.InitializeAsync(botFactory, parsedArgs.InitDelay); + await f.RunAsync(); } - return 0; + Console.WriteLine(); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "All bots completed."); } - - static void HandleCtrlC(object sender, ConsoleCancelEventArgs e) + catch (BotException bex) { - var name = Enum.GetName(e.SpecialKey.GetType(), e.SpecialKey); - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Exiting due to {name} event from system"); - - f?.TerminateBots(); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, bex.Message, ConsoleColor.DarkRed); + return 1; + } + catch (BotScriptErrorException bse) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, bse.Message, ConsoleColor.DarkRed); + return 1; } + catch (AggregateException ae) + { + var botExceptions = ae.InnerExceptions.OfType().ToList(); + foreach (var ie in botExceptions) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, ie.Message, ConsoleColor.DarkRed); + + var otherExceptions = ae.InnerExceptions.Except(botExceptions); + foreach (var ie in otherExceptions) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Unhandled error: {ie.Message}\nStack Trace:\n{ie.StackTrace}", ConsoleColor.DarkRed); - static void ShowError(ArgumentsParser args) + return 1; + } + catch (Exception ex) { - switch (args.Error) - { - case ArgsError.WrongNumberOfArgs: - Console.WriteLine("Invalid: specify host, port, and the number of bots to run"); - break; - case ArgsError.InvalidPort: - Console.WriteLine("Invalid: port number could not be parsed!"); - break; - case ArgsError.InvalidNumberOfBots: - Console.WriteLine("Invalid: specify an integer argument for number of bots."); - break; - case ArgsError.TooManyBots: - Console.WriteLine("Invalid: unable to launch > 25 threads of execution. Please use 25 or less."); - break; - case ArgsError.NotEnoughBots: - Console.WriteLine("Invalid: unable to launch < 1 thread of execution. Please use 1 or more."); - break; - case ArgsError.BadFormat: - Console.WriteLine("Badly formatted argument. Enter args like \"argument=value\"."); - break; - case ArgsError.InvalidSimultaneousNumberOfBots: - Console.WriteLine("Invalid: Simultaneous number of bots must not be more than total number of bots."); - break; - case ArgsError.InvalidWaitFlag: - Console.WriteLine("Invalid: Wait flag could not be parsed. Use 0, 1, false, true, no, or yes."); - break; - case ArgsError.InvalidInitDelay: - Console.WriteLine("Invalid: specify an integer argument for delay between inits (> 1100ms)."); - break; - case ArgsError.InvalidPath: - Console.WriteLine("Invalid: Script file does not exist or is not a valid path."); - break; - case ArgsError.InvalidScriptArgs: - Console.WriteLine("Invalid: User-defined arguments and disabling autoconnect require a script."); - break; - case ArgsError.AutoConnectRequired: - Console.WriteLine("Invalid: AutoConnect is required when using a script with more than 1 bot due to eoserv connection throttling."); - break; - } + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Unhandled error: {ex.Message}\nStack Trace:\n{ex.StackTrace}", ConsoleColor.DarkRed); + return 1; + } - Console.WriteLine("\n\nUsage: (enter arguments in any order) (angle brackets is entry) (square brackets is optional)"); - Console.WriteLine("EOBot.exe host=\n" + - " port=\n" + - " bots=[,]\n" + - " initDelay=\n" + - " account=\n" + - " password=\n" + - " character=\n" + - " script=\n" + - " autoconnect=" + - " [-- arg1, [arg2..argn]]"); - Console.WriteLine("\t host: hostname or IP address"); - Console.WriteLine("\t port: port to connect on (probably 8078)"); - Console.WriteLine("\t bots: number of bots to execute. \n\t numBots is the total number, simultaneousBots is how many will run at once"); - Console.WriteLine("\t initDelay: time in milliseconds to delay between doing the INIT handshake with the server"); - Console.WriteLine("\t account: account to connect with (created if it does not exist)"); - Console.WriteLine("\t password: password for account"); - Console.WriteLine("\t character: character to use (created if it does not exist)"); - Console.WriteLine("\t script: script file to execute\n\t if script is not specified, default trainer bot will be used"); - Console.WriteLine("\t autoconnect: (default true) true to automatically connect/disconnect to server with initDelay timeout between connection attempts for bots, false otherwise"); - Console.WriteLine("\t --: Any arguments passed after '--' will be available in a script under the '$args' array"); - - if (!args.ExtendedHelp) - return; + return 0; + } + + static void HandleCtrlC(object sender, ConsoleCancelEventArgs e) + { + var name = Enum.GetName(e.SpecialKey.GetType(), e.SpecialKey); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Exiting due to {name} event from system"); - Console.WriteLine(@" + f?.TerminateBots(); + } + + static void ShowError(ArgumentsParser args) + { + switch (args.Error) + { + case ArgsError.WrongNumberOfArgs: + Console.WriteLine("Invalid: specify host, port, and the number of bots to run"); + break; + case ArgsError.InvalidPort: + Console.WriteLine("Invalid: port number could not be parsed!"); + break; + case ArgsError.InvalidNumberOfBots: + Console.WriteLine("Invalid: specify an integer argument for number of bots."); + break; + case ArgsError.TooManyBots: + Console.WriteLine("Invalid: unable to launch > 25 threads of execution. Please use 25 or less."); + break; + case ArgsError.NotEnoughBots: + Console.WriteLine("Invalid: unable to launch < 1 thread of execution. Please use 1 or more."); + break; + case ArgsError.BadFormat: + Console.WriteLine("Badly formatted argument. Enter args like \"argument=value\"."); + break; + case ArgsError.InvalidSimultaneousNumberOfBots: + Console.WriteLine("Invalid: Simultaneous number of bots must not be more than total number of bots."); + break; + case ArgsError.InvalidWaitFlag: + Console.WriteLine("Invalid: Wait flag could not be parsed. Use 0, 1, false, true, no, or yes."); + break; + case ArgsError.InvalidInitDelay: + Console.WriteLine("Invalid: specify an integer argument for delay between inits (> 1100ms)."); + break; + case ArgsError.InvalidPath: + Console.WriteLine("Invalid: Script file does not exist or is not a valid path."); + break; + case ArgsError.InvalidScriptArgs: + Console.WriteLine("Invalid: User-defined arguments and disabling autoconnect require a script."); + break; + case ArgsError.AutoConnectRequired: + Console.WriteLine("Invalid: AutoConnect is required when using a script with more than 1 bot due to eoserv connection throttling."); + break; + } + + Console.WriteLine("\n\nUsage: (enter arguments in any order) (angle brackets is entry) (square brackets is optional)"); + Console.WriteLine("EOBot.exe host=\n" + + " port=\n" + + " bots=[,]\n" + + " initDelay=\n" + + " account=\n" + + " password=\n" + + " character=\n" + + " script=\n" + + " autoconnect=" + + " [-- arg1, [arg2..argn]]"); + Console.WriteLine("\t host: hostname or IP address"); + Console.WriteLine("\t port: port to connect on (probably 8078)"); + Console.WriteLine("\t bots: number of bots to execute. \n\t numBots is the total number, simultaneousBots is how many will run at once"); + Console.WriteLine("\t initDelay: time in milliseconds to delay between doing the INIT handshake with the server"); + Console.WriteLine("\t account: account to connect with (created if it does not exist)"); + Console.WriteLine("\t password: password for account"); + Console.WriteLine("\t character: character to use (created if it does not exist)"); + Console.WriteLine("\t script: script file to execute\n\t if script is not specified, default trainer bot will be used"); + Console.WriteLine("\t autoconnect: (default true) true to automatically connect/disconnect to server with initDelay timeout between connection attempts for bots, false otherwise"); + Console.WriteLine("\t --: Any arguments passed after '--' will be available in a script under the '$args' array"); + + if (!args.ExtendedHelp) + return; + + Console.WriteLine(@" =============================================================== Bot Script Info =============================================================== @@ -409,6 +409,5 @@ TIME THE SCRIPT FINISHES EXECUTING $character - object: reserved $mapstate - object : reserved "); - } } } \ No newline at end of file diff --git a/EOBot/ScriptedBot.cs b/EOBot/ScriptedBot.cs index bd5c2a5d5..6bbbe8194 100644 --- a/EOBot/ScriptedBot.cs +++ b/EOBot/ScriptedBot.cs @@ -5,53 +5,52 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot +namespace EOBot; + +public class ScriptedBot : BotBase { - public class ScriptedBot : BotBase + private readonly BotInterpreter _interpreter; + private readonly ArgumentsParser _parsedArgs; + private ProgramState _programState; + + public ScriptedBot(int index, ArgumentsParser parsedArgs) + : base(index) { - private readonly BotInterpreter _interpreter; - private readonly ArgumentsParser _parsedArgs; - private ProgramState _programState; + _interpreter = new BotInterpreter(parsedArgs.ScriptFile); + _parsedArgs = parsedArgs; + } - public ScriptedBot(int index, ArgumentsParser parsedArgs) - : base(index) - { - _interpreter = new BotInterpreter(parsedArgs.ScriptFile); - _parsedArgs = parsedArgs; - } + public override async Task InitializeAsync(string host, int port) + { + var tokens = _interpreter.Parse(); + _programState = _interpreter.Prepare(_index, _parsedArgs, tokens); - public override async Task InitializeAsync(string host, int port) + if (_parsedArgs.AutoConnect) { - var tokens = _interpreter.Parse(); - _programState = _interpreter.Prepare(_index, _parsedArgs, tokens); - - if (_parsedArgs.AutoConnect) - { - var connectFunction = _programState.SymbolTable[PredefinedIdentifiers.CONNECT_FUNC].Identifiable as AsyncVoidFunction; - if (connectFunction == null) - throw new InvalidOperationException("Something went wrong getting the connect function out of the symbol table"); + var connectFunction = _programState.SymbolTable[PredefinedIdentifiers.CONNECT_FUNC].Identifiable as AsyncVoidFunction; + if (connectFunction == null) + throw new InvalidOperationException("Something went wrong getting the connect function out of the symbol table"); - // call connect function that uses user-defined $version variable instead of base logic that has it hard-coded - await connectFunction.CallAsync(new StringVariable(_parsedArgs.Host), new IntVariable(_parsedArgs.Port)); + // call connect function that uses user-defined $version variable instead of base logic that has it hard-coded + await connectFunction.CallAsync(new StringVariable(_parsedArgs.Host), new IntVariable(_parsedArgs.Port)); - WorkCompleted += () => - { - Thread.Sleep(2000); - - var disconnectionFunction = _programState.SymbolTable[PredefinedIdentifiers.DISCONNECT_FUNC].Identifiable as VoidFunction; - disconnectionFunction.Call(); - }; - } + WorkCompleted += () => + { + Thread.Sleep(2000); - _initialized = true; + var disconnectionFunction = _programState.SymbolTable[PredefinedIdentifiers.DISCONNECT_FUNC].Identifiable as VoidFunction; + disconnectionFunction.Call(); + }; } - protected override async Task DoWorkAsync(CancellationToken ct) - { - if (_programState == null) - throw new InvalidOperationException("Scripted bot must be initialized before it is run"); + _initialized = true; + } - await _interpreter.Run(_programState); - } + protected override async Task DoWorkAsync(CancellationToken ct) + { + if (_programState == null) + throw new InvalidOperationException("Scripted bot must be initialized before it is run"); + + await _interpreter.Run(_programState); } } \ No newline at end of file diff --git a/EOBot/ScriptedBotFactory.cs b/EOBot/ScriptedBotFactory.cs index fa27d634e..062fd62b9 100644 --- a/EOBot/ScriptedBotFactory.cs +++ b/EOBot/ScriptedBotFactory.cs @@ -1,17 +1,16 @@ -namespace EOBot +namespace EOBot; + +public class ScriptedBotFactory : IBotFactory { - public class ScriptedBotFactory : IBotFactory - { - private readonly ArgumentsParser _parser; + private readonly ArgumentsParser _parser; - public ScriptedBotFactory(ArgumentsParser parser) - { - _parser = parser; - } + public ScriptedBotFactory(ArgumentsParser parser) + { + _parser = parser; + } - public IBot CreateBot(int index) - { - return new ScriptedBot(index, _parser); - } + public IBot CreateBot(int index) + { + return new ScriptedBot(index, _parser); } } \ No newline at end of file diff --git a/EOBot/TrainerBot.cs b/EOBot/TrainerBot.cs index ad1245c55..c2316e998 100644 --- a/EOBot/TrainerBot.cs +++ b/EOBot/TrainerBot.cs @@ -18,395 +18,394 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot +namespace EOBot; + +internal class TrainerBot : BotBase { - internal class TrainerBot : BotBase + private const int CONSECUTIVE_ATTACK_COUNT = 150; + private const int ATTACK_BACKOFF_MS = 600; + private const int WALK_BACKOFF_MS = 480; + private const int FACE_BACKOFF_MS = 120; + + private static readonly int[] JunkItemIds = new[] { - private const int CONSECUTIVE_ATTACK_COUNT = 150; - private const int ATTACK_BACKOFF_MS = 600; - private const int WALK_BACKOFF_MS = 480; - private const int FACE_BACKOFF_MS = 120; + // Dragon Blade, enchanted boots (red/green/blue) + 37, 124, 125, 126 + // cava staff + //329 + }; - private static readonly int[] JunkItemIds = new[] - { - // Dragon Blade, enchanted boots (red/green/blue) - 37, 124, 125, 126 - // cava staff - //329 - }; + private readonly string _account; + private readonly string _password; + private readonly string _character; - private readonly string _account; - private readonly string _password; - private readonly string _character; + private ICharacterActions _characterActions; + private IMapActions _mapActions; + private IItemActions _itemActions; - private ICharacterActions _characterActions; - private IMapActions _mapActions; - private IItemActions _itemActions; + private ICharacterRepository _characterRepository; + private IFixedTimeStepRepository _fixedTimeStepRepository; - private ICharacterRepository _characterRepository; - private IFixedTimeStepRepository _fixedTimeStepRepository; + private IPubFile _itemData; + private IPubFile _npcData; + private IPubFile _spellData; - private IPubFile _itemData; - private IPubFile _npcData; - private IPubFile _spellData; + private IChatProvider _chatProvider; + private HashSet _cachedChat; - private IChatProvider _chatProvider; - private HashSet _cachedChat; + public TrainerBot(int botIndex, string account, string password, string character) + : base(botIndex) + { + _account = account; + _password = password; + _character = character; + } - public TrainerBot(int botIndex, string account, string password, string character) - : base(botIndex) - { - _account = account; - _password = password; - _character = character; - } + protected override async Task DoWorkAsync(CancellationToken ct) + { + var helper = new BotHelper(_index); - protected override async Task DoWorkAsync(CancellationToken ct) + var res = await helper.LoginToAccountAsync(_account, _password); + if (res == LoginReply.WrongUser) { - var helper = new BotHelper(_index); + var createRes = await helper.CreateAccountAsync(_account, _password); + if (createRes != AccountReply.Created) + throw new InvalidOperationException($"Unable to create account: invalid response {Enum.GetName(typeof(AccountReply), createRes)}"); - var res = await helper.LoginToAccountAsync(_account, _password); - if (res == LoginReply.WrongUser) - { - var createRes = await helper.CreateAccountAsync(_account, _password); - if (createRes != AccountReply.Created) - throw new InvalidOperationException($"Unable to create account: invalid response {Enum.GetName(typeof(AccountReply), createRes)}"); + res = await helper.LoginToAccountAsync(_account, _password); + } - res = await helper.LoginToAccountAsync(_account, _password); - } + if (res != LoginReply.Ok) + throw new InvalidOperationException($"Unable to log in to account: invalid response {Enum.GetName(typeof(LoginReply), res)}"); - if (res != LoginReply.Ok) - throw new InvalidOperationException($"Unable to log in to account: invalid response {Enum.GetName(typeof(LoginReply), res)}"); + await helper.LoginToCharacterAsync(_character); - await helper.LoginToCharacterAsync(_character); + var c = DependencyMaster.TypeRegistry[_index]; - var c = DependencyMaster.TypeRegistry[_index]; + _mapActions = c.Resolve(); + _itemActions = c.Resolve(); + _characterRepository = c.Resolve(); + _characterActions = c.Resolve(); + var mapCellStateProvider = c.Resolve(); + var mapStateProvider = c.Resolve(); + var handler = c.Resolve(); + _itemData = c.Resolve().EIFFile; + _npcData = c.Resolve().ENFFile; + _spellData = c.Resolve().ESFFile; + var charInventoryRepo = c.Resolve(); + var walkValidator = c.Resolve(); - _mapActions = c.Resolve(); - _itemActions = c.Resolve(); - _characterRepository = c.Resolve(); - _characterActions = c.Resolve(); - var mapCellStateProvider = c.Resolve(); - var mapStateProvider = c.Resolve(); - var handler = c.Resolve(); - _itemData = c.Resolve().EIFFile; - _npcData = c.Resolve().ENFFile; - _spellData = c.Resolve().ESFFile; - var charInventoryRepo = c.Resolve(); - var walkValidator = c.Resolve(); + _chatProvider = c.Resolve(); + _cachedChat = new HashSet(); - _chatProvider = c.Resolve(); - _cachedChat = new HashSet(); + _fixedTimeStepRepository = c.Resolve(); - _fixedTimeStepRepository = c.Resolve(); + var healItems = new List(); + var healSpells = new List(); - var healItems = new List(); - var healSpells = new List(); + int attackCount = 0, cachedPlayerCount = 0; + bool time_to_die = false; - int attackCount = 0, cachedPlayerCount = 0; - bool time_to_die = false; + MapCoordinate? priorityCoord = null; + while (!ct.IsCancellationRequested) + { + handler.PollForPacketsAndHandle(); - MapCoordinate? priorityCoord = null; - while (!ct.IsCancellationRequested) + if (!_cachedChat.SetEquals(_chatProvider.AllChat[ChatTab.Local])) { - handler.PollForPacketsAndHandle(); + foreach (var message in _chatProvider.AllChat[ChatTab.Local].Except(_cachedChat)) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Chat, $"{message.Who}: {message.Message}", ConsoleColor.Cyan); - if (!_cachedChat.SetEquals(_chatProvider.AllChat[ChatTab.Local])) + _cachedChat = _chatProvider.AllChat[ChatTab.Local].ToHashSet(); + if (OperatingSystem.IsWindows()) { - foreach (var message in _chatProvider.AllChat[ChatTab.Local].Except(_cachedChat)) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Chat, $"{message.Who}: {message.Message}", ConsoleColor.Cyan); - - _cachedChat = _chatProvider.AllChat[ChatTab.Local].ToHashSet(); - if (OperatingSystem.IsWindows()) - { - Console.Beep(261, 1500); - } + Console.Beep(261, 1500); } + } - var character = _characterRepository.MainCharacter; - var charRenderProps = character.RenderProperties; + var character = _characterRepository.MainCharacter; + var charRenderProps = character.RenderProperties; - var currentPositionCellState = mapCellStateProvider.GetCellStateAt(charRenderProps.MapX, charRenderProps.MapY); + var currentPositionCellState = mapCellStateProvider.GetCellStateAt(charRenderProps.MapX, charRenderProps.MapY); - if (cachedPlayerCount != mapStateProvider.Characters.Count()) - { - cachedPlayerCount = mapStateProvider.Characters.Count(); - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"{cachedPlayerCount,7} - Players on map - You may not be able to train here", ConsoleColor.DarkYellow); + if (cachedPlayerCount != mapStateProvider.Characters.Count()) + { + cachedPlayerCount = mapStateProvider.Characters.Count(); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"{cachedPlayerCount,7} - Players on map - You may not be able to train here", ConsoleColor.DarkYellow); - if (OperatingSystem.IsWindows()) - { - Console.Beep(220, 500); - Console.Beep(247, 500); - Console.Beep(220, 500); - } + if (OperatingSystem.IsWindows()) + { + Console.Beep(220, 500); + Console.Beep(247, 500); + Console.Beep(220, 500); } + } - var coords = new MapCoordinate[] - { - new MapCoordinate(charRenderProps.MapX + 1, charRenderProps.MapY), - new MapCoordinate(charRenderProps.MapX - 1, charRenderProps.MapY), - new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY + 1), - new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY - 1) - }; + var coords = new MapCoordinate[] + { + new MapCoordinate(charRenderProps.MapX + 1, charRenderProps.MapY), + new MapCoordinate(charRenderProps.MapX - 1, charRenderProps.MapY), + new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY + 1), + new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY - 1) + }; - if (priorityCoord != null) - { - // ensure if there's an attack in progress that we finish killing that NPC before moving around - var tmp = new[] { priorityCoord.Value }; - coords = tmp.Concat(coords.Except(tmp)).ToArray(); - } + if (priorityCoord != null) + { + // ensure if there's an attack in progress that we finish killing that NPC before moving around + var tmp = new[] { priorityCoord.Value }; + coords = tmp.Concat(coords.Except(tmp)).ToArray(); + } - var action_taken = false; - foreach (var coord in coords) - { - if (action_taken) - break; + var action_taken = false; + foreach (var coord in coords) + { + if (action_taken) + break; - if (!time_to_die) - { - var cellState = mapCellStateProvider.GetCellStateAt(coord.X, coord.Y); + if (!time_to_die) + { + var cellState = mapCellStateProvider.GetCellStateAt(coord.X, coord.Y); - if (priorityCoord.HasValue && !cellState.NPC.HasValue) - priorityCoord = null; + if (priorityCoord.HasValue && !cellState.NPC.HasValue) + priorityCoord = null; - if (character.Stats[CharacterStat.Weight] >= character.Stats[CharacterStat.MaxWeight]) + if (character.Stats[CharacterStat.Weight] >= character.Stats[CharacterStat.MaxWeight]) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"OVER WEIGHT LIMIT - TIME TO DIE", ConsoleColor.DarkYellow); + await ToggleSit(); + action_taken = true; + time_to_die = true; + } + else if ((attackCount < CONSECUTIVE_ATTACK_COUNT && !currentPositionCellState.NPC.HasValue) || cellState.NPC.HasValue) + { + if (cellState.NPC.HasValue && character.Stats[CharacterStat.HP] > character.Stats[CharacterStat.MaxHP] * .1) { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"OVER WEIGHT LIMIT - TIME TO DIE", ConsoleColor.DarkYellow); - await ToggleSit(); + await FaceCoordinateIfNeeded(new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY), coord); + await Attack(cellState); + attackCount++; action_taken = true; - time_to_die = true; + priorityCoord = coord; } - else if ((attackCount < CONSECUTIVE_ATTACK_COUNT && !currentPositionCellState.NPC.HasValue) || cellState.NPC.HasValue) + else if (cellState.Items.Any()) { - if (cellState.NPC.HasValue && character.Stats[CharacterStat.HP] > character.Stats[CharacterStat.MaxHP] * .1) - { - await FaceCoordinateIfNeeded(new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY), coord); - await Attack(cellState); - attackCount++; - action_taken = true; - priorityCoord = coord; - } - else if (cellState.Items.Any()) - { - await PickUpItems(cellState); - action_taken = true; - } - else if (healItems.Any() && character.Stats[CharacterStat.HP] < character.Stats[CharacterStat.MaxHP] * .3) - { - var stats = _characterRepository.MainCharacter.Stats; - while (!ct.IsCancellationRequested && stats[CharacterStat.HP] < stats[CharacterStat.MaxHP] * .6) - { - await UseHealItem(healItems); - handler.PollForPacketsAndHandle(); - stats = _characterRepository.MainCharacter.Stats; - } - - action_taken = true; - } - else if (healSpells.Any() && character.Stats[CharacterStat.HP] < character.Stats[CharacterStat.MaxHP] * .9 - && character.Stats[CharacterStat.TP] > character.Stats[CharacterStat.MaxTP] * .5) + await PickUpItems(cellState); + action_taken = true; + } + else if (healItems.Any() && character.Stats[CharacterStat.HP] < character.Stats[CharacterStat.MaxHP] * .3) + { + var stats = _characterRepository.MainCharacter.Stats; + while (!ct.IsCancellationRequested && stats[CharacterStat.HP] < stats[CharacterStat.MaxHP] * .6) { - await CastHealSpell(healSpells); - action_taken = true; + await UseHealItem(healItems); + handler.PollForPacketsAndHandle(); + stats = _characterRepository.MainCharacter.Stats; } - healItems = charInventoryRepo.ItemInventory - .Where(x => _itemData.Any(y => y.ID == x.ItemID && y.Type == ItemType.Heal)) - .ToList(); - - healSpells = charInventoryRepo.SpellInventory - .Where(x => _spellData.Any(y => y.ID == x.ID && y.Type == SpellType.Heal)) - .ToList(); + action_taken = true; } - else + else if (healSpells.Any() && character.Stats[CharacterStat.HP] < character.Stats[CharacterStat.MaxHP] * .9 + && character.Stats[CharacterStat.TP] > character.Stats[CharacterStat.MaxTP] * .5) { - if (!currentPositionCellState.NPC.HasValue) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Move, $"Walking due to consecutive attacks: {attackCount}"); - else - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Move, $"Killing NPC at player location"); - - // find a direction that's open to walk to - var targetWalkCell = coords.Select(z => mapCellStateProvider.GetCellStateAt(z.X, z.Y)) - .FirstOrDefault(z => walkValidator.IsCellStateWalkable(z) == WalkValidationResult.Walkable); - if (targetWalkCell == null) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Couldn't find open space to walk!", ConsoleColor.DarkYellow); - break; - } + await CastHealSpell(healSpells); + action_taken = true; + } - await FaceCoordinateIfNeeded(new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY), targetWalkCell.Coordinate); + healItems = charInventoryRepo.ItemInventory + .Where(x => _itemData.Any(y => y.ID == x.ItemID && y.Type == ItemType.Heal)) + .ToList(); - var originalDirection = charRenderProps.Direction; - await Walk(); - await Face(originalDirection.Opposite()); + healSpells = charInventoryRepo.SpellInventory + .Where(x => _spellData.Any(y => y.ID == x.ID && y.Type == SpellType.Heal)) + .ToList(); + } + else + { + if (!currentPositionCellState.NPC.HasValue) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Move, $"Walking due to consecutive attacks: {attackCount}"); + else + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Move, $"Killing NPC at player location"); - // kill NPC if it was in our starting point - while (currentPositionCellState.NPC.HasValue && !ct.IsCancellationRequested) - { - await Attack(currentPositionCellState); + // find a direction that's open to walk to + var targetWalkCell = coords.Select(z => mapCellStateProvider.GetCellStateAt(z.X, z.Y)) + .FirstOrDefault(z => walkValidator.IsCellStateWalkable(z) == WalkValidationResult.Walkable); + if (targetWalkCell == null) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Couldn't find open space to walk!", ConsoleColor.DarkYellow); + break; + } - handler.PollForPacketsAndHandle(); - currentPositionCellState = mapCellStateProvider.GetCellStateAt(charRenderProps.MapX, charRenderProps.MapY); - } + await FaceCoordinateIfNeeded(new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY), targetWalkCell.Coordinate); - await PickUpItems(currentPositionCellState); + var originalDirection = charRenderProps.Direction; + await Walk(); + await Face(originalDirection.Opposite()); - await Walk(); - await Face(originalDirection); + // kill NPC if it was in our starting point + while (currentPositionCellState.NPC.HasValue && !ct.IsCancellationRequested) + { + await Attack(currentPositionCellState); - attackCount = 0; - action_taken = true; + handler.PollForPacketsAndHandle(); + currentPositionCellState = mapCellStateProvider.GetCellStateAt(charRenderProps.MapX, charRenderProps.MapY); } + + await PickUpItems(currentPositionCellState); + + await Walk(); + await Face(originalDirection); + + attackCount = 0; + action_taken = true; } } - - await Delay(120); } - } - private async Task Attack(IMapCellState cellState) - { - cellState.NPC.MatchSome(npc => ConsoleHelper.WriteMessage(ConsoleHelper.Type.Attack, $"{npc.Index,7} - {_npcData.Single(x => x.ID == npc.ID).Name}")); - await TrySend(_characterActions.Attack); - await Delay(ATTACK_BACKOFF_MS); + await Delay(120); } + } - private async Task Walk() - { - var renderProps = _characterRepository.MainCharacter.RenderProperties; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Walk, $"{renderProps.GetDestinationX(),3},{renderProps.GetDestinationY(),3}"); - await TrySend(() => _characterActions.Walk(false)); - await Delay(WALK_BACKOFF_MS); - } + private async Task Attack(IMapCellState cellState) + { + cellState.NPC.MatchSome(npc => ConsoleHelper.WriteMessage(ConsoleHelper.Type.Attack, $"{npc.Index,7} - {_npcData.Single(x => x.ID == npc.ID).Name}")); + await TrySend(_characterActions.Attack); + await Delay(ATTACK_BACKOFF_MS); + } - private async Task Face(EODirection direction) - { - var rp = _characterRepository.MainCharacter.RenderProperties; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Face, $"{Enum.GetName(typeof(EODirection), direction),7} - at {rp.MapX},{rp.MapY}"); - await TrySend(() => _characterActions.Face(direction)); + private async Task Walk() + { + var renderProps = _characterRepository.MainCharacter.RenderProperties; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Walk, $"{renderProps.GetDestinationX(),3},{renderProps.GetDestinationY(),3}"); + await TrySend(() => _characterActions.Walk(false)); + await Delay(WALK_BACKOFF_MS); + } - // todo: character actions Face() should also change the character's direction instead of relying on client to update it separately - _characterRepository.MainCharacter = _characterRepository.MainCharacter - .WithRenderProperties(_characterRepository.MainCharacter.RenderProperties.WithDirection(direction)); + private async Task Face(EODirection direction) + { + var rp = _characterRepository.MainCharacter.RenderProperties; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Face, $"{Enum.GetName(typeof(EODirection), direction),7} - at {rp.MapX},{rp.MapY}"); + await TrySend(() => _characterActions.Face(direction)); - await Delay(FACE_BACKOFF_MS); - } + // todo: character actions Face() should also change the character's direction instead of relying on client to update it separately + _characterRepository.MainCharacter = _characterRepository.MainCharacter + .WithRenderProperties(_characterRepository.MainCharacter.RenderProperties.WithDirection(direction)); + + await Delay(FACE_BACKOFF_MS); + } - private async Task FaceCoordinateIfNeeded(MapCoordinate originalCoord, MapCoordinate targetCoord) + private async Task FaceCoordinateIfNeeded(MapCoordinate originalCoord, MapCoordinate targetCoord) + { + var charRenderProps = _characterRepository.MainCharacter.RenderProperties; + var nextCoord = new MapCoordinate(charRenderProps.GetDestinationX(), charRenderProps.GetDestinationY()); + if (nextCoord != targetCoord) { - var charRenderProps = _characterRepository.MainCharacter.RenderProperties; - var nextCoord = new MapCoordinate(charRenderProps.GetDestinationX(), charRenderProps.GetDestinationY()); - if (nextCoord != targetCoord) - { - var diff = targetCoord - originalCoord; - var direction = diff.X > 0 ? EODirection.Right - : diff.X < 0 ? EODirection.Left - : diff.Y > 0 ? EODirection.Down - : diff.Y < 0 ? EODirection.Up : charRenderProps.Direction; - - if (direction != charRenderProps.Direction) - await Face(direction); - } + var diff = targetCoord - originalCoord; + var direction = diff.X > 0 ? EODirection.Right + : diff.X < 0 ? EODirection.Left + : diff.Y > 0 ? EODirection.Down + : diff.Y < 0 ? EODirection.Up : charRenderProps.Direction; + + if (direction != charRenderProps.Direction) + await Face(direction); } + } - private async Task PickUpItems(IMapCellState cellState) + private async Task PickUpItems(IMapCellState cellState) + { + foreach (var item in cellState.Items) { - foreach (var item in cellState.Items) - { - await PickUpItem(item); + await PickUpItem(item); - if (JunkItemIds.Contains(item.ItemID)) - { - await Delay(1000); - await JunkItem(item); - } + if (JunkItemIds.Contains(item.ItemID)) + { + await Delay(1000); + await JunkItem(item); } } + } - private async Task PickUpItem(MapItem item) + private async Task PickUpItem(MapItem item) + { + await TrySend(() => { - await TrySend(() => - { - var itemName = _itemData.Single(x => x.ID == item.ItemID).Name; - var pickupResult = _mapActions.PickUpItem(item); - if (pickupResult == ItemPickupResult.Ok) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.TakeItem, $"{item.Amount,7} - {itemName}"); - else - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Ignoring item {itemName} x{item.Amount} due to pickup error {pickupResult}", ConsoleColor.DarkYellow); - }); - await Delay(ATTACK_BACKOFF_MS); - } + var itemName = _itemData.Single(x => x.ID == item.ItemID).Name; + var pickupResult = _mapActions.PickUpItem(item); + if (pickupResult == ItemPickupResult.Ok) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.TakeItem, $"{item.Amount,7} - {itemName}"); + else + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Ignoring item {itemName} x{item.Amount} due to pickup error {pickupResult}", ConsoleColor.DarkYellow); + }); + await Delay(ATTACK_BACKOFF_MS); + } - private async Task JunkItem(MapItem item) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.JunkItem, $"{item.Amount,7} - {_itemData.Single(x => x.ID == item.ItemID).Name}"); - await TrySend(() => _itemActions.JunkItem(item.ItemID, item.Amount)); - await Delay(ATTACK_BACKOFF_MS); - } + private async Task JunkItem(MapItem item) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.JunkItem, $"{item.Amount,7} - {_itemData.Single(x => x.ID == item.ItemID).Name}"); + await TrySend(() => _itemActions.JunkItem(item.ItemID, item.Amount)); + await Delay(ATTACK_BACKOFF_MS); + } - private async Task CastHealSpell(IEnumerable healSpells) - { - var spellToUse = _spellData - .Where(x => healSpells.Any(y => y.ID == x.ID) && x.Target != SpellTarget.Group) - .OrderByDescending(x => x.HP) - .First(); + private async Task CastHealSpell(IEnumerable healSpells) + { + var spellToUse = _spellData + .Where(x => healSpells.Any(y => y.ID == x.ID) && x.Target != SpellTarget.Group) + .OrderByDescending(x => x.HP) + .First(); - var stats = _characterRepository.MainCharacter.Stats.Stats; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Cast, $"{spellToUse.HP,4} HP - {spellToUse.Name} - TP {stats[CharacterStat.TP]}/{stats[CharacterStat.MaxTP]}"); + var stats = _characterRepository.MainCharacter.Stats.Stats; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Cast, $"{spellToUse.HP,4} HP - {spellToUse.Name} - TP {stats[CharacterStat.TP]}/{stats[CharacterStat.MaxTP]}"); - await TrySend(() => _characterActions.PrepareCastSpell(spellToUse.ID)); - await Delay((uint)spellToUse.CastTime * 480); + await TrySend(() => _characterActions.PrepareCastSpell(spellToUse.ID)); + await Delay((uint)spellToUse.CastTime * 480); - await TrySend(() => _characterActions.CastSpell(spellToUse.ID, _characterRepository.MainCharacter)); - await Delay(ATTACK_BACKOFF_MS); // 600ms cooldown between spell casts - } + await TrySend(() => _characterActions.CastSpell(spellToUse.ID, _characterRepository.MainCharacter)); + await Delay(ATTACK_BACKOFF_MS); // 600ms cooldown between spell casts + } - private async Task UseHealItem(IEnumerable healItems) - { - var itemToUse = _itemData - .Where(x => healItems.Any(y => y.ItemID == x.ID)) - .OrderBy(x => x.HP) - .First(); - var amount = healItems.Single(x => x.ItemID == itemToUse.ID).Amount; + private async Task UseHealItem(IEnumerable healItems) + { + var itemToUse = _itemData + .Where(x => healItems.Any(y => y.ItemID == x.ID)) + .OrderBy(x => x.HP) + .First(); + var amount = healItems.Single(x => x.ItemID == itemToUse.ID).Amount; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.UseItem, $"{itemToUse.Name} - {itemToUse.HP} HP - inventory: {amount - 1} - (other heal item types: {healItems.Count() - 1})"); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.UseItem, $"{itemToUse.Name} - {itemToUse.HP} HP - inventory: {amount - 1} - (other heal item types: {healItems.Count() - 1})"); - await TrySend(() => _itemActions.UseItem(itemToUse.ID)); - await Delay(ATTACK_BACKOFF_MS); - } + await TrySend(() => _itemActions.UseItem(itemToUse.ID)); + await Delay(ATTACK_BACKOFF_MS); + } - private async Task ToggleSit() - { - var renderProps = _characterRepository.MainCharacter.RenderProperties; - var nextState = renderProps.SitState == EOLib.Domain.Character.SitState.Standing ? "Floor" : "Stand"; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Sit, $"{nextState,7} - Toggling from: {Enum.GetName(typeof(EOLib.Domain.Character.SitState), renderProps.SitState)}"); - await TrySend(() => _characterActions.Sit(MapCoordinate.Zero)); - } + private async Task ToggleSit() + { + var renderProps = _characterRepository.MainCharacter.RenderProperties; + var nextState = renderProps.SitState == EOLib.Domain.Character.SitState.Standing ? "Floor" : "Stand"; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Sit, $"{nextState,7} - Toggling from: {Enum.GetName(typeof(EOLib.Domain.Character.SitState), renderProps.SitState)}"); + await TrySend(() => _characterActions.Sit(MapCoordinate.Zero)); + } - private async Task TrySend(Action action, uint attempts = 3) + private async Task TrySend(Action action, uint attempts = 3) + { + for (uint i = 1; i <= attempts; i++) { - for (uint i = 1; i <= attempts; i++) + try { - try - { - action(); - break; - } - catch (NoDataSentException) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"{i} / {attempts} - No data sent", ConsoleColor.DarkRed); - if (i == attempts) - throw; + action(); + break; + } + catch (NoDataSentException) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"{i} / {attempts} - No data sent", ConsoleColor.DarkRed); + if (i == attempts) + throw; - await Delay(i * i * 1000); - } + await Delay(i * i * 1000); } } + } - private Task Delay(uint milliseconds) - { - _fixedTimeStepRepository.Tick(milliseconds / 10); - return Task.Delay((int)milliseconds); - } + private Task Delay(uint milliseconds) + { + _fixedTimeStepRepository.Tick(milliseconds / 10); + return Task.Delay((int)milliseconds); } } \ No newline at end of file diff --git a/EOBot/TrainerBotFactory.cs b/EOBot/TrainerBotFactory.cs index 68df168fa..87c077216 100644 --- a/EOBot/TrainerBotFactory.cs +++ b/EOBot/TrainerBotFactory.cs @@ -1,17 +1,16 @@ -namespace EOBot +namespace EOBot; + +public class TrainerBotFactory : IBotFactory { - public class TrainerBotFactory : IBotFactory - { - private readonly ArgumentsParser _parser; + private readonly ArgumentsParser _parser; - public TrainerBotFactory(ArgumentsParser parser) - { - _parser = parser; - } + public TrainerBotFactory(ArgumentsParser parser) + { + _parser = parser; + } - public IBot CreateBot(int index) - { - return new TrainerBot(index, _parser.Account, _parser.Password, _parser.Character); - } + public IBot CreateBot(int index) + { + return new TrainerBot(index, _parser.Account, _parser.Password, _parser.Character); } } \ No newline at end of file diff --git a/EOLib.Config.Test/ConfigFileLoadActionsTest.cs b/EOLib.Config.Test/ConfigFileLoadActionsTest.cs index 3b7fa6496..c795ae784 100644 --- a/EOLib.Config.Test/ConfigFileLoadActionsTest.cs +++ b/EOLib.Config.Test/ConfigFileLoadActionsTest.cs @@ -2,73 +2,73 @@ using System.Diagnostics.CodeAnalysis; using System.IO; -namespace EOLib.Config.Test +namespace EOLib.Config.Test; + +[TestFixture, ExcludeFromCodeCoverage] +public class ConfigFileLoadActionsTest { - [TestFixture, ExcludeFromCodeCoverage] - public class ConfigFileLoadActionsTest + private const string ConfigDirectory = "config"; + + private IConfigFileLoadActions _configFileLoadActions; + private IConfigurationRepository _configurationRepository; + + [SetUp] + public void SetUp() + { + _configurationRepository = new ConfigurationRepository(); + _configFileLoadActions = new ConfigFileLoadActions(_configurationRepository); + } + + [TearDown] + public static void TearDown() + { + if (Directory.Exists(ConfigDirectory)) + Directory.Delete(ConfigDirectory, true); + } + + [Test] + public void MissingConfigurationFile_ThrowsConfigLoadException() + { + Assert.Throws(() => _configFileLoadActions.LoadConfigFile()); + } + + [Test] + public void InvalidConfigFileThatExists_UsesConfigurationValueDefaults() { - private const string ConfigDirectory = "config"; - - private IConfigFileLoadActions _configFileLoadActions; - private IConfigurationRepository _configurationRepository; - - [SetUp] - public void SetUp() - { - _configurationRepository = new ConfigurationRepository(); - _configFileLoadActions = new ConfigFileLoadActions(_configurationRepository); - } - - [TearDown] - public static void TearDown() - { - if (Directory.Exists(ConfigDirectory)) - Directory.Delete(ConfigDirectory, true); - } - - [Test] - public void MissingConfigurationFile_ThrowsConfigLoadException() - { - Assert.Throws(() => _configFileLoadActions.LoadConfigFile()); - } - - [Test] - public void InvalidConfigFileThatExists_UsesConfigurationValueDefaults() - { - CreateTestConfigurationInDirectory("[Invalid]\nContents=heyayayayay"); - _configFileLoadActions.LoadConfigFile(); - - Assert.AreEqual(ConfigDefaults.MajorVersion, _configurationRepository.VersionMajor); - Assert.AreEqual(ConfigDefaults.MinorVersion, _configurationRepository.VersionMinor); - Assert.AreEqual(ConfigDefaults.ClientVersion, _configurationRepository.VersionBuild); - - Assert.AreEqual(ConfigDefaults.Host, _configurationRepository.Host); - Assert.AreEqual(ConfigDefaults.Port, _configurationRepository.Port); - - Assert.AreEqual(ConfigDefaults.NPCDropProtectionSeconds, _configurationRepository.NPCDropProtectTime); - Assert.AreEqual(ConfigDefaults.PlayerDropProtectionSeconds, _configurationRepository.PlayerDropProtectTime); - - Assert.AreEqual(EOLanguage.English, _configurationRepository.Language); - Assert.IsFalse(_configurationRepository.CurseFilterEnabled); - Assert.IsFalse(_configurationRepository.StrictFilterEnabled); - - Assert.IsTrue(_configurationRepository.ShowShadows); - Assert.IsTrue(_configurationRepository.ShowChatBubbles); - Assert.IsFalse(_configurationRepository.ShowTransition); - - Assert.IsFalse(_configurationRepository.MusicEnabled); - Assert.IsFalse(_configurationRepository.SoundEnabled); - - Assert.IsTrue(_configurationRepository.HearWhispers); - Assert.IsTrue(_configurationRepository.Interaction); - Assert.IsFalse(_configurationRepository.LogChatToFile); - Assert.IsFalse(_configurationRepository.EnableLog); - } - - [Test] - public void ValidConfigFile_LoadsSpecifiedSettings() - { - const string contents = @"[CONNECTION] + CreateTestConfigurationInDirectory("[Invalid]\nContents=heyayayayay"); + _configFileLoadActions.LoadConfigFile(); + + Assert.AreEqual(ConfigDefaults.MajorVersion, _configurationRepository.VersionMajor); + Assert.AreEqual(ConfigDefaults.MinorVersion, _configurationRepository.VersionMinor); + Assert.AreEqual(ConfigDefaults.ClientVersion, _configurationRepository.VersionBuild); + + Assert.AreEqual(ConfigDefaults.Host, _configurationRepository.Host); + Assert.AreEqual(ConfigDefaults.Port, _configurationRepository.Port); + + Assert.AreEqual(ConfigDefaults.NPCDropProtectionSeconds, _configurationRepository.NPCDropProtectTime); + Assert.AreEqual(ConfigDefaults.PlayerDropProtectionSeconds, _configurationRepository.PlayerDropProtectTime); + + Assert.AreEqual(EOLanguage.English, _configurationRepository.Language); + Assert.IsFalse(_configurationRepository.CurseFilterEnabled); + Assert.IsFalse(_configurationRepository.StrictFilterEnabled); + + Assert.IsTrue(_configurationRepository.ShowShadows); + Assert.IsTrue(_configurationRepository.ShowChatBubbles); + Assert.IsFalse(_configurationRepository.ShowTransition); + + Assert.IsFalse(_configurationRepository.MusicEnabled); + Assert.IsFalse(_configurationRepository.SoundEnabled); + + Assert.IsTrue(_configurationRepository.HearWhispers); + Assert.IsTrue(_configurationRepository.Interaction); + Assert.IsFalse(_configurationRepository.LogChatToFile); + Assert.IsFalse(_configurationRepository.EnableLog); + } + + [Test] + public void ValidConfigFile_LoadsSpecifiedSettings() + { + const string contents = @"[CONNECTION] Host=ewmoffat.ddns.net Port=12345 [VERSION] @@ -96,45 +96,44 @@ public void ValidConfigFile_LoadsSpecifiedSettings() LogFile=CHATLOG.TXT HearWhisper=off Interaction=false"; - CreateTestConfigurationInDirectory(contents); + CreateTestConfigurationInDirectory(contents); - _configFileLoadActions.LoadConfigFile(); + _configFileLoadActions.LoadConfigFile(); - Assert.AreEqual(10, _configurationRepository.VersionMajor); - Assert.AreEqual(20, _configurationRepository.VersionMinor); - Assert.AreEqual(30, _configurationRepository.VersionBuild); + Assert.AreEqual(10, _configurationRepository.VersionMajor); + Assert.AreEqual(20, _configurationRepository.VersionMinor); + Assert.AreEqual(30, _configurationRepository.VersionBuild); - Assert.AreEqual("ewmoffat.ddns.net", _configurationRepository.Host); - Assert.AreEqual(12345, _configurationRepository.Port); + Assert.AreEqual("ewmoffat.ddns.net", _configurationRepository.Host); + Assert.AreEqual(12345, _configurationRepository.Port); - Assert.AreEqual(5000, _configurationRepository.NPCDropProtectTime); - Assert.AreEqual(10000, _configurationRepository.PlayerDropProtectTime); + Assert.AreEqual(5000, _configurationRepository.NPCDropProtectTime); + Assert.AreEqual(10000, _configurationRepository.PlayerDropProtectTime); - Assert.AreEqual(EOLanguage.Swedish, _configurationRepository.Language); - Assert.IsTrue(_configurationRepository.CurseFilterEnabled); - Assert.IsTrue(_configurationRepository.StrictFilterEnabled); + Assert.AreEqual(EOLanguage.Swedish, _configurationRepository.Language); + Assert.IsTrue(_configurationRepository.CurseFilterEnabled); + Assert.IsTrue(_configurationRepository.StrictFilterEnabled); - Assert.IsFalse(_configurationRepository.ShowShadows); - Assert.IsFalse(_configurationRepository.ShowChatBubbles); - Assert.IsTrue(_configurationRepository.ShowTransition); - Assert.AreEqual(123, _configurationRepository.InGameWidth); - Assert.AreEqual(321, _configurationRepository.InGameHeight); + Assert.IsFalse(_configurationRepository.ShowShadows); + Assert.IsFalse(_configurationRepository.ShowChatBubbles); + Assert.IsTrue(_configurationRepository.ShowTransition); + Assert.AreEqual(123, _configurationRepository.InGameWidth); + Assert.AreEqual(321, _configurationRepository.InGameHeight); - Assert.IsTrue(_configurationRepository.MusicEnabled); - Assert.IsTrue(_configurationRepository.SoundEnabled); + Assert.IsTrue(_configurationRepository.MusicEnabled); + Assert.IsTrue(_configurationRepository.SoundEnabled); - Assert.IsFalse(_configurationRepository.HearWhispers); - Assert.IsFalse(_configurationRepository.Interaction); - Assert.IsTrue(_configurationRepository.LogChatToFile); - Assert.IsTrue(_configurationRepository.EnableLog); - } + Assert.IsFalse(_configurationRepository.HearWhispers); + Assert.IsFalse(_configurationRepository.Interaction); + Assert.IsTrue(_configurationRepository.LogChatToFile); + Assert.IsTrue(_configurationRepository.EnableLog); + } - private static void CreateTestConfigurationInDirectory(string contents) - { - if (!Directory.Exists(ConfigDirectory)) - Directory.CreateDirectory(ConfigDirectory); + private static void CreateTestConfigurationInDirectory(string contents) + { + if (!Directory.Exists(ConfigDirectory)) + Directory.CreateDirectory(ConfigDirectory); - File.WriteAllText(ConfigStrings.Default_Config_File, contents); - } + File.WriteAllText(ConfigStrings.Default_Config_File, contents); } } \ No newline at end of file diff --git a/EOLib.Config.Test/IniReaderTest.cs b/EOLib.Config.Test/IniReaderTest.cs index 3b45a75d1..91d1f47e4 100644 --- a/EOLib.Config.Test/IniReaderTest.cs +++ b/EOLib.Config.Test/IniReaderTest.cs @@ -2,309 +2,308 @@ using System.Diagnostics.CodeAnalysis; using System.IO; -namespace EOLib.Config.Test +namespace EOLib.Config.Test; + +[TestFixture, ExcludeFromCodeCoverage] +public class IniReaderTest { - [TestFixture, ExcludeFromCodeCoverage] - public class IniReaderTest + private const string TestDirectory = "IniReaderTest"; + private const string TestFile = "SomeFile.ini"; + private static readonly string FullPath = Path.Combine(TestDirectory, TestFile); + + [TearDown] + public void TearDown() { - private const string TestDirectory = "IniReaderTest"; - private const string TestFile = "SomeFile.ini"; - private static readonly string FullPath = Path.Combine(TestDirectory, TestFile); + if (Directory.Exists(TestDirectory)) + Directory.Delete(TestDirectory, true); + } - [TearDown] - public void TearDown() - { - if (Directory.Exists(TestDirectory)) - Directory.Delete(TestDirectory, true); - } + [Test] + public void Load_CreatesDirectoryAndFile_IfTheyDoNotExist_AndReturnsFalse() + { + var reader = new IniReader(FullPath); - [Test] - public void Load_CreatesDirectoryAndFile_IfTheyDoNotExist_AndReturnsFalse() - { - var reader = new IniReader(FullPath); + Assert.IsFalse(Directory.Exists(TestDirectory)); + Assert.IsFalse(File.Exists(FullPath)); - Assert.IsFalse(Directory.Exists(TestDirectory)); - Assert.IsFalse(File.Exists(FullPath)); + var result = reader.Load(); - var result = reader.Load(); + Assert.IsFalse(result); + Assert.IsTrue(Directory.Exists(TestDirectory)); + Assert.IsTrue(File.Exists(FullPath)); + } - Assert.IsFalse(result); - Assert.IsTrue(Directory.Exists(TestDirectory)); - Assert.IsTrue(File.Exists(FullPath)); - } + [Test] + public void Load_HandlesEmptyLines() + { + var contents = "[Header]\nTestdata=aaaa\n\nTest2=bbbb"; + CreateTestFileWithData(contents); - [Test] - public void Load_HandlesEmptyLines() - { - var contents = "[Header]\nTestdata=aaaa\n\nTest2=bbbb"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var result = reader.Load(); - var reader = new IniReader(FullPath); - var result = reader.Load(); + Assert.IsTrue(result); + } - Assert.IsTrue(result); - } + [Test] + public void Load_HandlesCommentLines() + { + var contents = "[Header]\nTestdata=aaaa\n#this is a comment line\nTest2=bbbb"; + CreateTestFileWithData(contents); - [Test] - public void Load_HandlesCommentLines() - { - var contents = "[Header]\nTestdata=aaaa\n#this is a comment line\nTest2=bbbb"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var result = reader.Load(); - var reader = new IniReader(FullPath); - var result = reader.Load(); + Assert.IsTrue(result); + } - Assert.IsTrue(result); - } + [Test] + public void Load_HandlesCommentsOnHeaderLines() + { + var contents = "[Header]#some header comment\nTestdata=aaaa\n\n#this is a comment line\nTest2=bbbb"; + CreateTestFileWithData(contents); - [Test] - public void Load_HandlesCommentsOnHeaderLines() - { - var contents = "[Header]#some header comment\nTestdata=aaaa\n\n#this is a comment line\nTest2=bbbb"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var result = reader.Load(); - var reader = new IniReader(FullPath); - var result = reader.Load(); + Assert.IsTrue(result); + } - Assert.IsTrue(result); - } + [Test] + public void Load_HandlesCommentsOnDataLines() + { + var contents = "[Header]\nTestdata=aaaa #some other comment\n\n#this is a comment line\nTest2=bbbb"; + CreateTestFileWithData(contents); - [Test] - public void Load_HandlesCommentsOnDataLines() - { - var contents = "[Header]\nTestdata=aaaa #some other comment\n\n#this is a comment line\nTest2=bbbb"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var result = reader.Load(); - var reader = new IniReader(FullPath); - var result = reader.Load(); + Assert.IsTrue(result); + } - Assert.IsTrue(result); - } + [Test] + public void Load_HandlesMultipleEqualsOnDataLines() + { + var contents = "[Header]\nTestdata=aaaa=something #some other comment\n\n#this is a comment line\nTest2=bbbb"; + CreateTestFileWithData(contents); - [Test] - public void Load_HandlesMultipleEqualsOnDataLines() - { - var contents = "[Header]\nTestdata=aaaa=something #some other comment\n\n#this is a comment line\nTest2=bbbb"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var result = reader.Load(); - var reader = new IniReader(FullPath); - var result = reader.Load(); + Assert.IsTrue(result); + } - Assert.IsTrue(result); - } + [Test] + public void GetValue_String_FalseIfNonExistentSection() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_String_FalseIfNonExistentSection() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + string value; + var result = reader.GetValue("BadHeader", "Testdata", out value); + Assert.IsFalse(result); + } - string value; - var result = reader.GetValue("BadHeader", "Testdata", out value); - Assert.IsFalse(result); - } + [Test] + public void GetValue_String_FalseIfNonExistentKey() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_String_FalseIfNonExistentKey() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + string value; + var result = reader.GetValue("Header", "BadTestdata", out value); + Assert.IsFalse(result); + } - string value; - var result = reader.GetValue("Header", "BadTestdata", out value); - Assert.IsFalse(result); - } + [Test] + public void GetValue_Int_FalseIfNonExistentSection() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_Int_FalseIfNonExistentSection() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + int value; + var result = reader.GetValue("BadHeader", "Testdata", out value); + Assert.IsFalse(result); + } - int value; - var result = reader.GetValue("BadHeader", "Testdata", out value); - Assert.IsFalse(result); - } + [Test] + public void GetValue_Int_FalseIfNonExistentKey() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_Int_FalseIfNonExistentKey() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + int value; + var result = reader.GetValue("Header", "BadTestdata", out value); + Assert.IsFalse(result); + } - int value; - var result = reader.GetValue("Header", "BadTestdata", out value); - Assert.IsFalse(result); - } + [Test] + public void GetValue_Int_FalseIfNotAnInteger() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_Int_FalseIfNotAnInteger() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + int value; + var result = reader.GetValue("Header", "Testdata", out value); + Assert.IsFalse(result); + } - int value; - var result = reader.GetValue("Header", "Testdata", out value); - Assert.IsFalse(result); - } + [Test] + public void GetValue_Bool_FalseIfNonExistentSection() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_Bool_FalseIfNonExistentSection() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + bool value; + var result = reader.GetValue("BadHeader", "Testdata", out value); + Assert.IsFalse(result); + } - bool value; - var result = reader.GetValue("BadHeader", "Testdata", out value); - Assert.IsFalse(result); - } + [Test] + public void GetValue_Bool_FalseIfNonExistentKey() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_Bool_FalseIfNonExistentKey() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + bool value; + var result = reader.GetValue("Header", "BadTestdata", out value); + Assert.IsFalse(result); + } - bool value; - var result = reader.GetValue("Header", "BadTestdata", out value); - Assert.IsFalse(result); - } + [Test] + public void GetValue_Bool_FalseIfNotBoolean() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_Bool_FalseIfNotBoolean() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + bool value; + var result = reader.GetValue("Header", "Testdata", out value); + Assert.IsFalse(result); + } - bool value; - var result = reader.GetValue("Header", "Testdata", out value); - Assert.IsFalse(result); - } + [Test] + public void GetValue_String_ReturnsValueAsString() + { + var contents = "[Header]\nTestdata=123"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_String_ReturnsValueAsString() - { - var contents = "[Header]\nTestdata=123"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + string value; + var result = reader.GetValue("Header", "Testdata", out value); + Assert.IsTrue(result); + Assert.AreEqual("123", value); + } - string value; - var result = reader.GetValue("Header", "Testdata", out value); - Assert.IsTrue(result); - Assert.AreEqual("123", value); - } + [Test] + public void GetValue_Int_ReturnsValueAsInteger() + { + var contents = "[Header]\nTestdata=123"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_Int_ReturnsValueAsInteger() - { - var contents = "[Header]\nTestdata=123"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + int value; + var result = reader.GetValue("Header", "Testdata", out value); + Assert.IsTrue(result); + Assert.AreEqual(123, value); + } - int value; - var result = reader.GetValue("Header", "Testdata", out value); - Assert.IsTrue(result); - Assert.AreEqual(123, value); - } + [Test] + public void GetValue_Bool_ReturnsValueAsBoolean() + { + var contents = "[Header]\nTestdata=true"; + CreateTestFileWithData(contents); - [Test] - public void GetValue_Bool_ReturnsValueAsBoolean() - { - var contents = "[Header]\nTestdata=true"; - CreateTestFileWithData(contents); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); + + bool value; + var result = reader.GetValue("Header", "Testdata", out value); + Assert.IsTrue(result); + Assert.IsTrue(value); + } + + [Test] + public void GetValue_Bool_ConvertsBoolEquivalentsToTrue() + { + var contents = "[Header]\nItem1=yes\nItem2=1\nItem3=on"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); + for (int i = 1; i <= 3; ++i) + { bool value; - var result = reader.GetValue("Header", "Testdata", out value); + var result = reader.GetValue("Header", "Item" + i, out value); Assert.IsTrue(result); Assert.IsTrue(value); } + } - [Test] - public void GetValue_Bool_ConvertsBoolEquivalentsToTrue() - { - var contents = "[Header]\nItem1=yes\nItem2=1\nItem3=on"; - CreateTestFileWithData(contents); - - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); - - for (int i = 1; i <= 3; ++i) - { - bool value; - var result = reader.GetValue("Header", "Item" + i, out value); - Assert.IsTrue(result); - Assert.IsTrue(value); - } - } + [Test] + public void GetValue_Bool_ConvertsBoolEquivalentsToFalse() + { + var contents = "[Header]\nItem1=no\nItem2=0\nItem3=off"; + CreateTestFileWithData(contents); + + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - [Test] - public void GetValue_Bool_ConvertsBoolEquivalentsToFalse() + for (int i = 1; i <= 3; ++i) { - var contents = "[Header]\nItem1=no\nItem2=0\nItem3=off"; - CreateTestFileWithData(contents); - - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); - - for (int i = 1; i <= 3; ++i) - { - bool value; - var result = reader.GetValue("Header", "Item" + i, out value); - Assert.IsTrue(result); - Assert.IsFalse(value); - } + bool value; + var result = reader.GetValue("Header", "Item" + i, out value); + Assert.IsTrue(result); + Assert.IsFalse(value); } + } - private static void CreateTestFileWithData(string contents) - { - if (!Directory.Exists(TestDirectory)) - Directory.CreateDirectory(TestDirectory); + private static void CreateTestFileWithData(string contents) + { + if (!Directory.Exists(TestDirectory)) + Directory.CreateDirectory(TestDirectory); - File.WriteAllText(FullPath, contents); - } + File.WriteAllText(FullPath, contents); } } \ No newline at end of file diff --git a/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs b/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs index b0d45a271..28dda8191 100644 --- a/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs +++ b/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs @@ -4,40 +4,39 @@ using System.ComponentModel.Design; using System.Diagnostics.CodeAnalysis; -namespace EOLib.Graphics.Test +namespace EOLib.Graphics.Test; + +[ExcludeFromCodeCoverage] +internal sealed class GraphicsDeviceTestHelper : IDisposable { - [ExcludeFromCodeCoverage] - internal sealed class GraphicsDeviceTestHelper : IDisposable - { - private readonly Game _game; + private readonly Game _game; - public GraphicsDeviceManager GraphicsDeviceManager { get; } + public GraphicsDeviceManager GraphicsDeviceManager { get; } - public GraphicsDeviceTestHelper() - { - _game = new Game(); - GraphicsDeviceManager = new GraphicsDeviceManager(_game); - _game.RunOneFrame(); - } + public GraphicsDeviceTestHelper() + { + _game = new Game(); + GraphicsDeviceManager = new GraphicsDeviceManager(_game); + _game.RunOneFrame(); + } - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } - ~GraphicsDeviceTestHelper() - { - Dispose(false); - } + ~GraphicsDeviceTestHelper() + { + Dispose(false); + } - private void Dispose(bool disposing) + private void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - GraphicsDeviceManager.Dispose(); - _game.Dispose(); - } + GraphicsDeviceManager.Dispose(); + _game.Dispose(); } } } \ No newline at end of file diff --git a/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs b/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs index e0442036c..24cff60e3 100644 --- a/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs +++ b/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs @@ -6,73 +6,72 @@ using System.Diagnostics.CodeAnalysis; using System.IO; -namespace EOLib.Graphics.Test +namespace EOLib.Graphics.Test; + +[TestFixture, ExcludeFromCodeCoverage, Category("GraphicsDevice")] +public class NativeGraphicsLoaderTest { - [TestFixture, ExcludeFromCodeCoverage, Category("GraphicsDevice")] - public class NativeGraphicsLoaderTest - { - private IPEFileCollection _modules; - private INativeGraphicsLoader _nativeGraphicsLoader; + private IPEFileCollection _modules; + private INativeGraphicsLoader _nativeGraphicsLoader; - private const int ExpectedCulture = -1; + private const int ExpectedCulture = -1; - [SetUp] - public void SetUp() - { - _modules = Mock.Of(); - _nativeGraphicsLoader = new NativeGraphicsLoader(_modules); - } + [SetUp] + public void SetUp() + { + _modules = Mock.Of(); + _nativeGraphicsLoader = new NativeGraphicsLoader(_modules); + } - [Test] - public void WhenLoadGFX_CallsPEFile_GetEmbeddedBitmapResourceByID() - { - var peFileMock = SetupPEFileForGFXType(GFXTypes.PreLoginUI, CreateDataArrayForBitmap()); + [Test] + public void WhenLoadGFX_CallsPEFile_GetEmbeddedBitmapResourceByID() + { + var peFileMock = SetupPEFileForGFXType(GFXTypes.PreLoginUI, CreateDataArrayForBitmap()); - var data = _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, 1); - peFileMock.Verify(x => x.GetEmbeddedBitmapResourceByID(It.IsAny(), ExpectedCulture), Times.Once()); - } + var data = _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, 1); + peFileMock.Verify(x => x.GetEmbeddedBitmapResourceByID(It.IsAny(), ExpectedCulture), Times.Once()); + } - [Test] - public void WhenLoadGFX_CallsPEFile_WithResourceValueIncreasedBy100() - { - const int requestedResourceID = 1; - const int expectedResourceID = 101; + [Test] + public void WhenLoadGFX_CallsPEFile_WithResourceValueIncreasedBy100() + { + const int requestedResourceID = 1; + const int expectedResourceID = 101; - var peFileMock = SetupPEFileForGFXType(GFXTypes.PreLoginUI, CreateDataArrayForBitmap()); + var peFileMock = SetupPEFileForGFXType(GFXTypes.PreLoginUI, CreateDataArrayForBitmap()); - var data = _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID); - peFileMock.Verify(x => x.GetEmbeddedBitmapResourceByID(expectedResourceID, ExpectedCulture)); - } + var data = _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID); + peFileMock.Verify(x => x.GetEmbeddedBitmapResourceByID(expectedResourceID, ExpectedCulture)); + } - [Test] - public void WhenLoadGFX_EmptyDataArray_ThrowsInDebug_EmptyInRelease() - { - const int requestedResourceID = 1; + [Test] + public void WhenLoadGFX_EmptyDataArray_ThrowsInDebug_EmptyInRelease() + { + const int requestedResourceID = 1; - SetupPEFileForGFXType(GFXTypes.PreLoginUI, new byte[] { }); + SetupPEFileForGFXType(GFXTypes.PreLoginUI, new byte[] { }); #if DEBUG - Assert.Throws(() => _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID)); + Assert.Throws(() => _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID)); #else - Assert.That(_nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID), Has.Length.EqualTo(0)); + Assert.That(_nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID), Has.Length.EqualTo(0)); #endif - } + } - private byte[] CreateDataArrayForBitmap() - { - return new byte[1]; - } + private byte[] CreateDataArrayForBitmap() + { + return new byte[1]; + } - private Mock SetupPEFileForGFXType(GFXTypes type, byte[] array) - { - var collectionMock = Mock.Get(_modules); - var peFile = new Mock(); - collectionMock.Setup(x => x[type]).Returns(peFile.Object); + private Mock SetupPEFileForGFXType(GFXTypes type, byte[] array) + { + var collectionMock = Mock.Get(_modules); + var peFile = new Mock(); + collectionMock.Setup(x => x[type]).Returns(peFile.Object); - peFile.Setup(x => x.GetEmbeddedBitmapResourceByID(It.IsAny(), ExpectedCulture)) - .Returns(array); + peFile.Setup(x => x.GetEmbeddedBitmapResourceByID(It.IsAny(), ExpectedCulture)) + .Returns(array); - return peFile; - } + return peFile; } } \ No newline at end of file diff --git a/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs b/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs index 2373ed3d6..143224144 100644 --- a/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs +++ b/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs @@ -6,235 +6,234 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.Graphics.Test +namespace EOLib.Graphics.Test; + +[TestFixture, ExcludeFromCodeCoverage, Category("GraphicsDevice")] +public class NativeGraphicsManagerTest { - [TestFixture, ExcludeFromCodeCoverage, Category("GraphicsDevice")] - public class NativeGraphicsManagerTest - { - private GraphicsDeviceTestHelper _graphicsDeviceTestHelper; + private GraphicsDeviceTestHelper _graphicsDeviceTestHelper; - private INativeGraphicsLoader _graphicsLoader; - private IGraphicsDeviceProvider _graphicsDeviceProvider; + private INativeGraphicsLoader _graphicsLoader; + private IGraphicsDeviceProvider _graphicsDeviceProvider; - private bool _keepFromInfiniteLoop = false; + private bool _keepFromInfiniteLoop = false; - private INativeGraphicsManager _nativeGraphicsManager; + private INativeGraphicsManager _nativeGraphicsManager; - [SetUp] - public void SetUp() - { - _graphicsDeviceTestHelper = new GraphicsDeviceTestHelper(); - - _graphicsLoader = Mock.Of(); + [SetUp] + public void SetUp() + { + _graphicsDeviceTestHelper = new GraphicsDeviceTestHelper(); - var graphicsDeviceProviderMock = new Mock(); - graphicsDeviceProviderMock.Setup(x => x.GraphicsDevice) - .Returns(_graphicsDeviceTestHelper.GraphicsDeviceManager.GraphicsDevice); + _graphicsLoader = Mock.Of(); - _graphicsDeviceProvider = graphicsDeviceProviderMock.Object; + var graphicsDeviceProviderMock = new Mock(); + graphicsDeviceProviderMock.Setup(x => x.GraphicsDevice) + .Returns(_graphicsDeviceTestHelper.GraphicsDeviceManager.GraphicsDevice); - _nativeGraphicsManager = new NativeGraphicsManager(_graphicsLoader, _graphicsDeviceProvider); - } + _graphicsDeviceProvider = graphicsDeviceProviderMock.Object; - [TearDown] - public void TearDown() - { - _nativeGraphicsManager.Dispose(); - _graphicsDeviceTestHelper.Dispose(); - } + _nativeGraphicsManager = new NativeGraphicsManager(_graphicsLoader, _graphicsDeviceProvider); + } - [Test] - public void WhenLoadTexture_CallGraphicsLoader() - { - const int requestedResource = 1; + [TearDown] + public void TearDown() + { + _nativeGraphicsManager.Dispose(); + _graphicsDeviceTestHelper.Dispose(); + } - var graphicsLoaderMock = Mock.Get(_graphicsLoader); - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + [Test] + public void WhenLoadTexture_CallGraphicsLoader() + { + const int requestedResource = 1; - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Once()); - } + var graphicsLoaderMock = Mock.Get(_graphicsLoader); + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - [Test] - public void WhenLoadCachedTexture_DoNotCallGraphicsLoader() - { - const int requestedResource = 1; + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Once()); + } - var graphicsLoaderMock = Mock.Get(_graphicsLoader); - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + [Test] + public void WhenLoadCachedTexture_DoNotCallGraphicsLoader() + { + const int requestedResource = 1; - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Once()); - } + var graphicsLoaderMock = Mock.Get(_graphicsLoader); + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - [Test] - public void WhenLoadCachedTexture_WhenReloadFromFile_CallGraphicsLoader() - { - const int requestedResource = 1; + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Once()); + } - var graphicsLoaderMock = Mock.Get(_graphicsLoader); - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, reloadFromFile: true); + [Test] + public void WhenLoadCachedTexture_WhenReloadFromFile_CallGraphicsLoader() + { + const int requestedResource = 1; - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Exactly(2)); - } + var graphicsLoaderMock = Mock.Get(_graphicsLoader); + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, reloadFromFile: true); - [Test] - public void WhenLoadCachedTexture_WhenReloadFromFile_DisposesOriginalTextue() - { - const int requestedResource = 1; + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Exactly(2)); + } - var textureHasBeenDisposed = false; + [Test] + public void WhenLoadCachedTexture_WhenReloadFromFile_DisposesOriginalTextue() + { + const int requestedResource = 1; - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - var texture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - texture.Disposing += (o, e) => textureHasBeenDisposed = true; + var textureHasBeenDisposed = false; - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, reloadFromFile: true); + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + var texture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + texture.Disposing += (o, e) => textureHasBeenDisposed = true; - Assert.IsTrue(textureHasBeenDisposed); - } + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, reloadFromFile: true); - [Test] - public void WhenLoadManyTextures_CallsGraphicsLoaderSameNumberOfTimes() - { - var graphicsLoaderMock = Mock.Get(_graphicsLoader); + Assert.IsTrue(textureHasBeenDisposed); + } - const int totalRequestedResources = 100; - for (int requestedResource = 1; requestedResource <= totalRequestedResources; ++requestedResource) - { - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + [Test] + public void WhenLoadManyTextures_CallsGraphicsLoaderSameNumberOfTimes() + { + var graphicsLoaderMock = Mock.Get(_graphicsLoader); - var localRequestedResource = requestedResource; - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, localRequestedResource), Times.Once()); - } + const int totalRequestedResources = 100; + for (int requestedResource = 1; requestedResource <= totalRequestedResources; ++requestedResource) + { + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, It.IsAny()), Times.Exactly(totalRequestedResources)); + var localRequestedResource = requestedResource; + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, localRequestedResource), Times.Once()); } - [Test] - public void WhenLoadCachedTexture_ManyTimes_CallsGraphicsLoaderOnce() - { - var graphicsLoaderMock = Mock.Get(_graphicsLoader); + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, It.IsAny()), Times.Exactly(totalRequestedResources)); + } - const int requestedResource = 1; - for (int i = 1; i <= 100; ++i) - { - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - } + [Test] + public void WhenLoadCachedTexture_ManyTimes_CallsGraphicsLoaderOnce() + { + var graphicsLoaderMock = Mock.Get(_graphicsLoader); - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, It.IsAny()), Times.Once()); + const int requestedResource = 1; + for (int i = 1; i <= 100; ++i) + { + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); } - [Test] - public void WhenLoadTexture_Transparent_SetsBlackToTransparent() - { - const int requestedResource = 1; + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, It.IsAny()), Times.Once()); + } - Texture2D resultTexture; - var bmp = LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - FillBitmapWithColor(bmp, Color.Black); - resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, true); + [Test] + public void WhenLoadTexture_Transparent_SetsBlackToTransparent() + { + const int requestedResource = 1; - var data = new Microsoft.Xna.Framework.Color[resultTexture.Width * resultTexture.Height]; - resultTexture.GetData(data); + Texture2D resultTexture; + var bmp = LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + FillBitmapWithColor(bmp, Color.Black); + resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, true); - Assert.IsTrue(data.All(x => x.A == 0)); - } + var data = new Microsoft.Xna.Framework.Color[resultTexture.Width * resultTexture.Height]; + resultTexture.GetData(data); - [Test] - public void WhenLoadTexture_MaleHat_Transparent_SetsSpecialColorToTransparent() - { - const int requestedResource = 1; + Assert.IsTrue(data.All(x => x.A == 0)); + } - Texture2D resultTexture; - var bmp = LoadGFXReturnsBitmap(GFXTypes.MaleHat, requestedResource); - FillBitmapWithColor(bmp, new Color(0xff000008)); - resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MaleHat, requestedResource, true); + [Test] + public void WhenLoadTexture_MaleHat_Transparent_SetsSpecialColorToTransparent() + { + const int requestedResource = 1; - var data = new Microsoft.Xna.Framework.Color[resultTexture.Width * resultTexture.Height]; - resultTexture.GetData(data); + Texture2D resultTexture; + var bmp = LoadGFXReturnsBitmap(GFXTypes.MaleHat, requestedResource); + FillBitmapWithColor(bmp, new Color(0xff000008)); + resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MaleHat, requestedResource, true); - Assert.IsTrue(data.All(x => x.A == 0)); - } + var data = new Microsoft.Xna.Framework.Color[resultTexture.Width * resultTexture.Height]; + resultTexture.GetData(data); - [Test] - public void WhenLoadTexture_FemaleHat_Transparent_SetsSpecialColorToTransparent() - { - const int requestedResource = 1; + Assert.IsTrue(data.All(x => x.A == 0)); + } - Texture2D resultTexture; - var bmp = LoadGFXReturnsBitmap(GFXTypes.FemaleHat, requestedResource); - FillBitmapWithColor(bmp, new Color(0xff000008)); - resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.FemaleHat, requestedResource, true); + [Test] + public void WhenLoadTexture_FemaleHat_Transparent_SetsSpecialColorToTransparent() + { + const int requestedResource = 1; - var data = new Color[resultTexture.Width * resultTexture.Height]; - resultTexture.GetData(data); + Texture2D resultTexture; + var bmp = LoadGFXReturnsBitmap(GFXTypes.FemaleHat, requestedResource); + FillBitmapWithColor(bmp, new Color(0xff000008)); + resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.FemaleHat, requestedResource, true); - Assert.IsTrue(data.All(x => x.A == 0)); - } + var data = new Color[resultTexture.Width * resultTexture.Height]; + resultTexture.GetData(data); - [Test] - public void WhenLoadTexture_RaceCondition_DisposesExistingCachedTextureAndReturnsSecondOne() - { - const int requestedResource = 1; + Assert.IsTrue(data.All(x => x.A == 0)); + } - Texture2D resultTexture; - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource, () => GetTextureAgain(GFXTypes.PreLoginUI, requestedResource)); - resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + [Test] + public void WhenLoadTexture_RaceCondition_DisposesExistingCachedTextureAndReturnsSecondOne() + { + const int requestedResource = 1; - Assert.IsFalse(resultTexture.IsDisposed); - } + Texture2D resultTexture; + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource, () => GetTextureAgain(GFXTypes.PreLoginUI, requestedResource)); + resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - // Manually builds a byte array that is a valid bitmap image (10x10 pixels, 32bpp) - // Mocks the native graphics loader to return this array, and passes it back to the caller - private Memory LoadGFXReturnsBitmap(GFXTypes whichFile, int requestedResource, Action loadCallback = null) - { - // 32bpp 10x10 image + 14 byte BMP header + 40 byte BITMAPINFO header - // (4 * 100) + 14 + 40 = 454 - var bitmapToReturn = new byte[454]; - Array.Copy(new[] { (byte)'B', (byte)'M', }, bitmapToReturn, 2); - Array.Copy(BitConverter.GetBytes(454), 0, bitmapToReturn, 2, 4); // total image size [2..5] - Array.Copy(BitConverter.GetBytes(54), 0, bitmapToReturn, 10, 4); // image data offset [10..13] - - Array.Copy(BitConverter.GetBytes(40), 0, bitmapToReturn, 14, 4); // bitmap header size [14..17] - Array.Copy(BitConverter.GetBytes(10), 0, bitmapToReturn, 18, 4); // width [18..21] - Array.Copy(BitConverter.GetBytes(10), 0, bitmapToReturn, 22, 4); // height [22..25] - Array.Copy(BitConverter.GetBytes((short)1), 0, bitmapToReturn, 26, 2); // planes (1) [26..27] - Array.Copy(BitConverter.GetBytes((short)32), 0, bitmapToReturn, 28, 2); // bpp [28..29] - - var graphicsLoaderMock = Mock.Get(_graphicsLoader); - graphicsLoaderMock.Setup(x => x.LoadGFX(whichFile, requestedResource)) - .Returns(bitmapToReturn) - .Callback(loadCallback ?? (() => { })); - - return bitmapToReturn; - } + Assert.IsFalse(resultTexture.IsDisposed); + } - private static void FillBitmapWithColor(Memory image, Color color) + // Manually builds a byte array that is a valid bitmap image (10x10 pixels, 32bpp) + // Mocks the native graphics loader to return this array, and passes it back to the caller + private Memory LoadGFXReturnsBitmap(GFXTypes whichFile, int requestedResource, Action loadCallback = null) + { + // 32bpp 10x10 image + 14 byte BMP header + 40 byte BITMAPINFO header + // (4 * 100) + 14 + 40 = 454 + var bitmapToReturn = new byte[454]; + Array.Copy(new[] { (byte)'B', (byte)'M', }, bitmapToReturn, 2); + Array.Copy(BitConverter.GetBytes(454), 0, bitmapToReturn, 2, 4); // total image size [2..5] + Array.Copy(BitConverter.GetBytes(54), 0, bitmapToReturn, 10, 4); // image data offset [10..13] + + Array.Copy(BitConverter.GetBytes(40), 0, bitmapToReturn, 14, 4); // bitmap header size [14..17] + Array.Copy(BitConverter.GetBytes(10), 0, bitmapToReturn, 18, 4); // width [18..21] + Array.Copy(BitConverter.GetBytes(10), 0, bitmapToReturn, 22, 4); // height [22..25] + Array.Copy(BitConverter.GetBytes((short)1), 0, bitmapToReturn, 26, 2); // planes (1) [26..27] + Array.Copy(BitConverter.GetBytes((short)32), 0, bitmapToReturn, 28, 2); // bpp [28..29] + + var graphicsLoaderMock = Mock.Get(_graphicsLoader); + graphicsLoaderMock.Setup(x => x.LoadGFX(whichFile, requestedResource)) + .Returns(bitmapToReturn) + .Callback(loadCallback ?? (() => { })); + + return bitmapToReturn; + } + + private static void FillBitmapWithColor(Memory image, Color color) + { + for (int i = 54; i < image.Length; i += 4) { - for (int i = 54; i < image.Length; i += 4) - { - image.Span[i] = color.B; - image.Span[i + 1] = color.G; - image.Span[i + 2] = color.R; - image.Span[i + 3] = color.A; - } + image.Span[i] = color.B; + image.Span[i + 1] = color.G; + image.Span[i + 2] = color.R; + image.Span[i + 3] = color.A; } + } - private void GetTextureAgain(GFXTypes whichFile, int requestedResource) - { - if (_keepFromInfiniteLoop) return; - _keepFromInfiniteLoop = true; + private void GetTextureAgain(GFXTypes whichFile, int requestedResource) + { + if (_keepFromInfiniteLoop) return; + _keepFromInfiniteLoop = true; - LoadGFXReturnsBitmap(whichFile, requestedResource); - _nativeGraphicsManager.TextureFromResource(whichFile, requestedResource); - } + LoadGFXReturnsBitmap(whichFile, requestedResource); + _nativeGraphicsManager.TextureFromResource(whichFile, requestedResource); } } \ No newline at end of file diff --git a/EOLib.Graphics.Test/PEFileCollectionTest.cs b/EOLib.Graphics.Test/PEFileCollectionTest.cs index 229246829..4f089f5f4 100644 --- a/EOLib.Graphics.Test/PEFileCollectionTest.cs +++ b/EOLib.Graphics.Test/PEFileCollectionTest.cs @@ -6,72 +6,71 @@ using System.IO; using System.Linq; -namespace EOLib.Graphics.Test +namespace EOLib.Graphics.Test; + +[TestFixture, ExcludeFromCodeCoverage] +public class PEFileCollectionTest { - [TestFixture, ExcludeFromCodeCoverage] - public class PEFileCollectionTest - { - private const string ExpectedDirectory = "gfx"; + private const string ExpectedDirectory = "gfx"; - private IPEFileCollection _collection; + private IPEFileCollection _collection; - [SetUp] - public void SetUp() - { - _collection = new PEFileCollection(); - } + [SetUp] + public void SetUp() + { + _collection = new PEFileCollection(); + } - [TearDown] - public void TearDown() - { - _collection.Dispose(); + [TearDown] + public void TearDown() + { + _collection.Dispose(); - if (Directory.Exists(ExpectedDirectory)) - Directory.Delete(ExpectedDirectory, true); - } + if (Directory.Exists(ExpectedDirectory)) + Directory.Delete(ExpectedDirectory, true); + } - [Test] - public void PopulateCollection_ThrowsDirectoryNotFound_ForMissingDirectory() - { - Assert.Throws(() => _collection.PopulateCollectionWithStandardGFX()); - } + [Test] + public void PopulateCollection_ThrowsDirectoryNotFound_ForMissingDirectory() + { + Assert.Throws(() => _collection.PopulateCollectionWithStandardGFX()); + } - [Test] - public void PopulateCollection_ThrowsFileNotFound_ForMissingFilesInDirectory() - { - CreateExpectedDirectoryWithFiles(5); - Assert.Throws(() => _collection.PopulateCollectionWithStandardGFX()); - } + [Test] + public void PopulateCollection_ThrowsFileNotFound_ForMissingFilesInDirectory() + { + CreateExpectedDirectoryWithFiles(5); + Assert.Throws(() => _collection.PopulateCollectionWithStandardGFX()); + } - [Test] - public void Constructor_FillsCollection_WithExpectedPEFiles() - { - var expectedKeys = Enum.GetValues(typeof(GFXTypes)); - CreateExpectedDirectoryWithFiles(25); + [Test] + public void Constructor_FillsCollection_WithExpectedPEFiles() + { + var expectedKeys = Enum.GetValues(typeof(GFXTypes)); + CreateExpectedDirectoryWithFiles(25); - _collection.PopulateCollectionWithStandardGFX(); + _collection.PopulateCollectionWithStandardGFX(); - Assert.AreEqual(25, _collection.Count); - CollectionAssert.AreEqual(expectedKeys, _collection.Keys.ToList()); - } + Assert.AreEqual(25, _collection.Count); + CollectionAssert.AreEqual(expectedKeys, _collection.Keys.ToList()); + } - [Test] - public void Dispose_DisposesAllFiles() - { - _collection.Add(GFXTypes.PreLoginUI, Mock.Of()); - _collection.Add(GFXTypes.PostLoginUI, Mock.Of()); + [Test] + public void Dispose_DisposesAllFiles() + { + _collection.Add(GFXTypes.PreLoginUI, Mock.Of()); + _collection.Add(GFXTypes.PostLoginUI, Mock.Of()); - _collection.Dispose(); + _collection.Dispose(); - foreach (var file in _collection.Values) - Mock.Get(file).Verify(x => x.Dispose(), Times.Once); - } + foreach (var file in _collection.Values) + Mock.Get(file).Verify(x => x.Dispose(), Times.Once); + } - private void CreateExpectedDirectoryWithFiles(int numFiles = 0, string fileNameFormat = "gfx{0:D3}.egf") - { - Directory.CreateDirectory(ExpectedDirectory); - for (int i = 1; i <= numFiles; ++i) - File.WriteAllText(string.Format(Path.Combine(ExpectedDirectory, fileNameFormat), i), "test contents"); - } + private void CreateExpectedDirectoryWithFiles(int numFiles = 0, string fileNameFormat = "gfx{0:D3}.egf") + { + Directory.CreateDirectory(ExpectedDirectory); + for (int i = 1; i <= numFiles; ++i) + File.WriteAllText(string.Format(Path.Combine(ExpectedDirectory, fileNameFormat), i), "test contents"); } } \ No newline at end of file diff --git a/EOLib.Graphics.Test/RectangleExtensionTest.cs b/EOLib.Graphics.Test/RectangleExtensionTest.cs index 173fed9df..126a54b5a 100644 --- a/EOLib.Graphics.Test/RectangleExtensionTest.cs +++ b/EOLib.Graphics.Test/RectangleExtensionTest.cs @@ -2,41 +2,40 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.Graphics.Test +namespace EOLib.Graphics.Test; + +[TestFixture, ExcludeFromCodeCoverage] +public class RectangleExtensionTest { - [TestFixture, ExcludeFromCodeCoverage] - public class RectangleExtensionTest + [Test] + public void WithPosition_ReturnsNewRectangle_WithExpectedSizeAndOffset() { - [Test] - public void WithPosition_ReturnsNewRectangle_WithExpectedSizeAndOffset() - { - var rectangle = new Rectangle(5, 10, 15, 20); - var newX = 105; - var newY = 110; + var rectangle = new Rectangle(5, 10, 15, 20); + var newX = 105; + var newY = 110; - var newRectangle = rectangle.WithPosition(new Vector2(newX, newY)); + var newRectangle = rectangle.WithPosition(new Vector2(newX, newY)); - Assert.AreEqual(105, newRectangle.X); - Assert.AreEqual(110, newRectangle.Y); - Assert.AreEqual(15, newRectangle.Width); - Assert.AreEqual(20, newRectangle.Height); - Assert.AreNotEqual(newRectangle, rectangle); - } + Assert.AreEqual(105, newRectangle.X); + Assert.AreEqual(110, newRectangle.Y); + Assert.AreEqual(15, newRectangle.Width); + Assert.AreEqual(20, newRectangle.Height); + Assert.AreNotEqual(newRectangle, rectangle); + } - [Test] - public void WithPosition_DoesNotModify_OriginalRectangle() - { - var rectangle = new Rectangle(5, 10, 15, 20); - var newX = 105; - var newY = 110; + [Test] + public void WithPosition_DoesNotModify_OriginalRectangle() + { + var rectangle = new Rectangle(5, 10, 15, 20); + var newX = 105; + var newY = 110; - var newRectangle = rectangle.WithPosition(new Vector2(newX, newY)); + var newRectangle = rectangle.WithPosition(new Vector2(newX, newY)); - Assert.AreEqual(5, rectangle.X); - Assert.AreEqual(10, rectangle.Y); - Assert.AreEqual(15, rectangle.Width); - Assert.AreEqual(20, rectangle.Height); - Assert.AreNotEqual(newRectangle, rectangle); - } + Assert.AreEqual(5, rectangle.X); + Assert.AreEqual(10, rectangle.Y); + Assert.AreEqual(15, rectangle.Width); + Assert.AreEqual(20, rectangle.Height); + Assert.AreNotEqual(newRectangle, rectangle); } } \ No newline at end of file diff --git a/EOLib.Graphics/ColorConstants.cs b/EOLib.Graphics/ColorConstants.cs index 263e332c4..ffd9e45fb 100644 --- a/EOLib.Graphics/ColorConstants.cs +++ b/EOLib.Graphics/ColorConstants.cs @@ -1,16 +1,15 @@ using Microsoft.Xna.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.Graphics +namespace EOLib.Graphics; + +[ExcludeFromCodeCoverage] +public static class ColorConstants { - [ExcludeFromCodeCoverage] - public static class ColorConstants - { - public static readonly Color LightGrayText = Color.FromNonPremultiplied(0xc8, 0xc8, 0xc8, 0xff); - public static readonly Color LightYellowText = Color.FromNonPremultiplied(0xf0, 0xf0, 0xc8, 0xff); - public static readonly Color BeigeText = Color.FromNonPremultiplied(0xb4, 0xa0, 0x8c, 0xff); - public static readonly Color LightBeigeText = Color.FromNonPremultiplied(0xdc, 0xc8, 0xb4, 0xff); - public static readonly Color LightGrayDialogMessage = Color.FromNonPremultiplied(0xe6, 0xe6, 0xd6, 0xff); - public static readonly Color MediumGrayText = Color.FromNonPremultiplied(0xb9, 0xb9, 0xb9, 0xff); - } + public static readonly Color LightGrayText = Color.FromNonPremultiplied(0xc8, 0xc8, 0xc8, 0xff); + public static readonly Color LightYellowText = Color.FromNonPremultiplied(0xf0, 0xf0, 0xc8, 0xff); + public static readonly Color BeigeText = Color.FromNonPremultiplied(0xb4, 0xa0, 0x8c, 0xff); + public static readonly Color LightBeigeText = Color.FromNonPremultiplied(0xdc, 0xc8, 0xb4, 0xff); + public static readonly Color LightGrayDialogMessage = Color.FromNonPremultiplied(0xe6, 0xe6, 0xd6, 0xff); + public static readonly Color MediumGrayText = Color.FromNonPremultiplied(0xb9, 0xb9, 0xb9, 0xff); } \ No newline at end of file diff --git a/EOLib.Graphics/GFXTypes.cs b/EOLib.Graphics/GFXTypes.cs index 7e63789c0..9fa480375 100644 --- a/EOLib.Graphics/GFXTypes.cs +++ b/EOLib.Graphics/GFXTypes.cs @@ -1,106 +1,105 @@ -namespace EOLib.Graphics +namespace EOLib.Graphics; + +public enum GFXTypes { - public enum GFXTypes - { - /// - /// 001 - /// - PreLoginUI = 1, - /// - /// 002 - /// - PostLoginUI, - /// - /// 003 - /// - MapTiles, - /// - /// 004 - /// - MapObjects, - /// - /// 005 - /// - MapOverlay, - /// - /// 006 - /// - MapWalls, - /// - /// 007 - /// - MapWallTop, - /// - /// 008 - /// - SkinSprites, - /// - /// 009 - /// - MaleHair, - /// - /// 010 - /// - FemaleHair, - /// - /// 011 - /// - MaleShoes, - /// - /// 012 - /// - FemaleShoes, - /// - /// 013 - /// - MaleArmor, - /// - /// 014 - /// - FemaleArmor, - /// - /// 015 - /// - MaleHat, - /// - /// 016 - /// - FemaleHat, - /// - /// 017 - /// - MaleWeapons, - /// - /// 018 - /// - FemaleWeapons, - /// - /// 019 - /// - MaleBack, - /// - /// 020 - /// - FemaleBack, - /// - /// 021 - /// - NPC, - /// - /// 022 - /// - Shadows, - /// - /// 023 - /// - Items, - /// - /// 024 - /// - Spells, - /// - /// 025 - /// - SpellIcons - } + /// + /// 001 + /// + PreLoginUI = 1, + /// + /// 002 + /// + PostLoginUI, + /// + /// 003 + /// + MapTiles, + /// + /// 004 + /// + MapObjects, + /// + /// 005 + /// + MapOverlay, + /// + /// 006 + /// + MapWalls, + /// + /// 007 + /// + MapWallTop, + /// + /// 008 + /// + SkinSprites, + /// + /// 009 + /// + MaleHair, + /// + /// 010 + /// + FemaleHair, + /// + /// 011 + /// + MaleShoes, + /// + /// 012 + /// + FemaleShoes, + /// + /// 013 + /// + MaleArmor, + /// + /// 014 + /// + FemaleArmor, + /// + /// 015 + /// + MaleHat, + /// + /// 016 + /// + FemaleHat, + /// + /// 017 + /// + MaleWeapons, + /// + /// 018 + /// + FemaleWeapons, + /// + /// 019 + /// + MaleBack, + /// + /// 020 + /// + FemaleBack, + /// + /// 021 + /// + NPC, + /// + /// 022 + /// + Shadows, + /// + /// 023 + /// + Items, + /// + /// 024 + /// + Spells, + /// + /// 025 + /// + SpellIcons } \ No newline at end of file diff --git a/EOLib.Graphics/IGraphicsDeviceRepository.cs b/EOLib.Graphics/IGraphicsDeviceRepository.cs index 994b89848..d28a88bdd 100644 --- a/EOLib.Graphics/IGraphicsDeviceRepository.cs +++ b/EOLib.Graphics/IGraphicsDeviceRepository.cs @@ -2,28 +2,27 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EOLib.Graphics +namespace EOLib.Graphics; + +public interface IGraphicsDeviceRepository { - public interface IGraphicsDeviceRepository - { - GraphicsDevice GraphicsDevice { get; set; } + GraphicsDevice GraphicsDevice { get; set; } - GraphicsDeviceManager GraphicsDeviceManager { get; set; } - } + GraphicsDeviceManager GraphicsDeviceManager { get; set; } +} - public interface IGraphicsDeviceProvider - { - GraphicsDevice GraphicsDevice { get; } +public interface IGraphicsDeviceProvider +{ + GraphicsDevice GraphicsDevice { get; } - GraphicsDeviceManager GraphicsDeviceManager { get; } - } + GraphicsDeviceManager GraphicsDeviceManager { get; } +} - [MappedType(BaseType = typeof(IGraphicsDeviceRepository), IsSingleton = true)] - [MappedType(BaseType = typeof(IGraphicsDeviceProvider), IsSingleton = true)] - public class GraphicsDeviceRepository : IGraphicsDeviceRepository, IGraphicsDeviceProvider - { - public GraphicsDevice GraphicsDevice { get; set; } +[MappedType(BaseType = typeof(IGraphicsDeviceRepository), IsSingleton = true)] +[MappedType(BaseType = typeof(IGraphicsDeviceProvider), IsSingleton = true)] +public class GraphicsDeviceRepository : IGraphicsDeviceRepository, IGraphicsDeviceProvider +{ + public GraphicsDevice GraphicsDevice { get; set; } - public GraphicsDeviceManager GraphicsDeviceManager { get; set; } - } + public GraphicsDeviceManager GraphicsDeviceManager { get; set; } } \ No newline at end of file diff --git a/EOLib.Graphics/INativeGraphicsLoader.cs b/EOLib.Graphics/INativeGraphicsLoader.cs index e1f6b4613..77d2474ab 100644 --- a/EOLib.Graphics/INativeGraphicsLoader.cs +++ b/EOLib.Graphics/INativeGraphicsLoader.cs @@ -1,9 +1,8 @@ using System; -namespace EOLib.Graphics +namespace EOLib.Graphics; + +public interface INativeGraphicsLoader { - public interface INativeGraphicsLoader - { - ReadOnlyMemory LoadGFX(GFXTypes file, int resourceValue); - } + ReadOnlyMemory LoadGFX(GFXTypes file, int resourceValue); } \ No newline at end of file diff --git a/EOLib.Graphics/INativeGraphicsManager.cs b/EOLib.Graphics/INativeGraphicsManager.cs index 369272294..d256dc3ea 100644 --- a/EOLib.Graphics/INativeGraphicsManager.cs +++ b/EOLib.Graphics/INativeGraphicsManager.cs @@ -1,20 +1,19 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EOLib.Graphics +namespace EOLib.Graphics; + +public interface INativeGraphicsManager : IDisposable { - public interface INativeGraphicsManager : IDisposable - { - /// - /// Returns a byte array of image data from a single image within an endless online *.egf file - /// Image is specified by the library file (GFXTypes) and the resourceName (number) - /// - /// Name (number) of the image resource - /// File type to load from - /// Whether or not to make the background black color transparent - /// True to force reload the gfx from the gfx file, false to use the in-memory cache - /// True to make the gfx "fully" transparent; that is, to hide all transparent colors (0x08 blacks and full black) - /// Texture2D containing the image from the *.egf file - Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transparent = false, bool reloadFromFile = false, bool fullTransparent = false); - } + /// + /// Returns a byte array of image data from a single image within an endless online *.egf file + /// Image is specified by the library file (GFXTypes) and the resourceName (number) + /// + /// Name (number) of the image resource + /// File type to load from + /// Whether or not to make the background black color transparent + /// True to force reload the gfx from the gfx file, false to use the in-memory cache + /// True to make the gfx "fully" transparent; that is, to hide all transparent colors (0x08 blacks and full black) + /// Texture2D containing the image from the *.egf file + Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transparent = false, bool reloadFromFile = false, bool fullTransparent = false); } \ No newline at end of file diff --git a/EOLib.Graphics/LibraryLoadException.cs b/EOLib.Graphics/LibraryLoadException.cs index 313fe9bf5..ad2d5299f 100644 --- a/EOLib.Graphics/LibraryLoadException.cs +++ b/EOLib.Graphics/LibraryLoadException.cs @@ -1,19 +1,18 @@ using System; using System.Runtime.InteropServices; -namespace EOLib.Graphics +namespace EOLib.Graphics; + +public class LibraryLoadException : Exception { - public class LibraryLoadException : Exception - { - public GFXTypes WhichGFX { get; private set; } + public GFXTypes WhichGFX { get; private set; } - public LibraryLoadException(string libraryNumber, GFXTypes which) - : base(string.Format("Error {1} when loading library {0}\n{2}", - libraryNumber, - Marshal.GetLastWin32Error(), - new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message)) - { - WhichGFX = which; - } + public LibraryLoadException(string libraryNumber, GFXTypes which) + : base(string.Format("Error {1} when loading library {0}\n{2}", + libraryNumber, + Marshal.GetLastWin32Error(), + new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message)) + { + WhichGFX = which; } } \ No newline at end of file diff --git a/EOLib.Graphics/NativeGraphicsLoader.cs b/EOLib.Graphics/NativeGraphicsLoader.cs index 208c961b4..f37d99058 100644 --- a/EOLib.Graphics/NativeGraphicsLoader.cs +++ b/EOLib.Graphics/NativeGraphicsLoader.cs @@ -1,42 +1,41 @@ using AutomaticTypeMapper; using System; -namespace EOLib.Graphics +namespace EOLib.Graphics; + +[MappedType(BaseType = typeof(INativeGraphicsLoader), IsSingleton = true)] +public class NativeGraphicsLoader : INativeGraphicsLoader { - [MappedType(BaseType = typeof(INativeGraphicsLoader), IsSingleton = true)] - public class NativeGraphicsLoader : INativeGraphicsLoader + private readonly IPEFileCollection _modules; + + public NativeGraphicsLoader(IPEFileCollection modules) { - private readonly IPEFileCollection _modules; + _modules = modules; + } - public NativeGraphicsLoader(IPEFileCollection modules) + public ReadOnlyMemory LoadGFX(GFXTypes file, int resourceValue) + { + var fileBytes = ReadOnlyMemory.Empty; + try { - _modules = modules; + fileBytes = _modules[file].GetEmbeddedBitmapResourceByID(resourceValue + 100); } - - public ReadOnlyMemory LoadGFX(GFXTypes file, int resourceValue) + catch (ArgumentException) { - var fileBytes = ReadOnlyMemory.Empty; - try - { - fileBytes = _modules[file].GetEmbeddedBitmapResourceByID(resourceValue + 100); - } - catch (ArgumentException) - { #if DEBUG - throw; + throw; #endif - } + } - if (fileBytes.Length == 0) - { + if (fileBytes.Length == 0) + { #if DEBUG - throw new GFXLoadException(resourceValue, file); + throw new GFXLoadException(resourceValue, file); #else - return Array.Empty(); + return Array.Empty(); #endif - } - - return fileBytes; } + + return fileBytes; } } \ No newline at end of file diff --git a/EOLib.Graphics/NativeGraphicsManager.cs b/EOLib.Graphics/NativeGraphicsManager.cs index 9e68c5513..08f03b824 100644 --- a/EOLib.Graphics/NativeGraphicsManager.cs +++ b/EOLib.Graphics/NativeGraphicsManager.cs @@ -7,135 +7,134 @@ using System.Collections.Generic; using System.Linq; -namespace EOLib.Graphics +namespace EOLib.Graphics; + +[MappedType(BaseType = typeof(INativeGraphicsManager), IsSingleton = true)] +public sealed class NativeGraphicsManager : INativeGraphicsManager { - [MappedType(BaseType = typeof(INativeGraphicsManager), IsSingleton = true)] - public sealed class NativeGraphicsManager : INativeGraphicsManager - { - private readonly ConcurrentDictionary> _cache; + private readonly ConcurrentDictionary> _cache; - private readonly INativeGraphicsLoader _gfxLoader; - private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; + private readonly INativeGraphicsLoader _gfxLoader; + private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; - public NativeGraphicsManager(INativeGraphicsLoader gfxLoader, IGraphicsDeviceProvider graphicsDeviceProvider) - { - _cache = new ConcurrentDictionary>(); - _gfxLoader = gfxLoader; - _graphicsDeviceProvider = graphicsDeviceProvider; - } + public NativeGraphicsManager(INativeGraphicsLoader gfxLoader, IGraphicsDeviceProvider graphicsDeviceProvider) + { + _cache = new ConcurrentDictionary>(); + _gfxLoader = gfxLoader; + _graphicsDeviceProvider = graphicsDeviceProvider; + } - // todo: instead of having a bunch of bool params, maybe an enum param with [Flags] for the different options would be better - public Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transparent = false, bool reloadFromFile = false, bool fullTransparent = false) + // todo: instead of having a bunch of bool params, maybe an enum param with [Flags] for the different options would be better + public Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transparent = false, bool reloadFromFile = false, bool fullTransparent = false) + { + if (_cache.ContainsKey(file) && _cache[file].ContainsKey(resourceVal)) { - if (_cache.ContainsKey(file) && _cache[file].ContainsKey(resourceVal)) + if (reloadFromFile) { - if (reloadFromFile) - { - _cache[file][resourceVal]?.Dispose(); - _cache[file].Remove(resourceVal, out _); - } - else - { - return _cache[file][resourceVal]; - } + _cache[file][resourceVal]?.Dispose(); + _cache[file].Remove(resourceVal, out _); } - - var ret = LoadTexture(file, resourceVal, transparent, fullTransparent); - if (_cache.ContainsKey(file) || - _cache.TryAdd(file, new ConcurrentDictionary())) + else { - _cache[file].TryAdd(resourceVal, ret); + return _cache[file][resourceVal]; } - - return ret; } - private Texture2D LoadTexture(GFXTypes file, int resourceVal, bool transparent, bool fullTransparent) + var ret = LoadTexture(file, resourceVal, transparent, fullTransparent); + if (_cache.ContainsKey(file) || + _cache.TryAdd(file, new ConcurrentDictionary())) { - var rawData = _gfxLoader.LoadGFX(file, resourceVal); + _cache[file].TryAdd(resourceVal, ret); + } - if (rawData.IsEmpty) - return new Texture2D(_graphicsDeviceProvider.GraphicsDevice, 1, 1); + return ret; + } - Action processAction = null; + private Texture2D LoadTexture(GFXTypes file, int resourceVal, bool transparent, bool fullTransparent) + { + var rawData = _gfxLoader.LoadGFX(file, resourceVal); - if (transparent) - { - processAction = data => CrossPlatformMakeTransparent(data); + if (rawData.IsEmpty) + return new Texture2D(_graphicsDeviceProvider.GraphicsDevice, 1, 1); - if (fullTransparent) - { - processAction = data => CrossPlatformMakeTransparent(data, isHat: true); - } - else if (file == GFXTypes.FemaleHat || file == GFXTypes.MaleHat) - { - processAction = data => CrossPlatformMakeTransparent(data, checkClip: true, isHat: true); - } - } + Action processAction = null; - using var ms = rawData.AsStream(); - var ret = Texture2D.FromStream(_graphicsDeviceProvider.GraphicsDevice, ms, processAction); + if (transparent) + { + processAction = data => CrossPlatformMakeTransparent(data); - return ret; + if (fullTransparent) + { + processAction = data => CrossPlatformMakeTransparent(data, isHat: true); + } + else if (file == GFXTypes.FemaleHat || file == GFXTypes.MaleHat) + { + processAction = data => CrossPlatformMakeTransparent(data, checkClip: true, isHat: true); + } } - private static unsafe void CrossPlatformMakeTransparent(byte[] data, bool isHat = false, bool checkClip = false) + using var ms = rawData.AsStream(); + var ret = Texture2D.FromStream(_graphicsDeviceProvider.GraphicsDevice, ms, processAction); + + return ret; + } + + private static unsafe void CrossPlatformMakeTransparent(byte[] data, bool isHat = false, bool checkClip = false) + { + var shouldClip = false; + if (checkClip) { - var shouldClip = false; - if (checkClip) + fixed (byte* ptr = data) { - fixed (byte* ptr = data) + for (int i = 0; i < data.Length; i += 4) { - for (int i = 0; i < data.Length; i += 4) + uint* addr = (uint*)(ptr + i); + if (*addr == 0xff000008) { - uint* addr = (uint*)(ptr + i); - if (*addr == 0xff000008) - { - shouldClip = true; - break; - } + shouldClip = true; + break; } } } + } - // for all gfx: 0,0,0 is transparent + // for all gfx: 0,0,0 is transparent - // for some hats: 8,0,0 and 0,0,0 are both transparent + // for some hats: 8,0,0 and 0,0,0 are both transparent - // for hats: R=8 G=0 B=0 is transparent - // some default gfx use R=0 G=8 B=0 as black - // 0,0,0 clips pixels below it if 8,0,0 is present on the frame + // for hats: R=8 G=0 B=0 is transparent + // some default gfx use R=0 G=8 B=0 as black + // 0,0,0 clips pixels below it if 8,0,0 is present on the frame - var transparentColors = isHat - ? shouldClip - ? new Color[] { new Color(0xff000008) } // check clip: make ff000008 transparent only, use black for clipping if present - : new Color[] { Color.Black, new Color(0xff000008) } // isHat: make both colors transparent - : new Color[] { Color.Black }; // default: make only black transparent + var transparentColors = isHat + ? shouldClip + ? new Color[] { new Color(0xff000008) } // check clip: make ff000008 transparent only, use black for clipping if present + : new Color[] { Color.Black, new Color(0xff000008) } // isHat: make both colors transparent + : new Color[] { Color.Black }; // default: make only black transparent - fixed (byte* ptr = data) + fixed (byte* ptr = data) + { + for (int i = 0; i < data.Length; i += 4) { - for (int i = 0; i < data.Length; i += 4) - { - uint* addr = (uint*)(ptr + i); - if (transparentColors.Contains(new Color(*addr))) - *addr = 0; - } + uint* addr = (uint*)(ptr + i); + if (transparentColors.Contains(new Color(*addr))) + *addr = 0; } } - - public void Dispose() - { - foreach (var text in _cache.SelectMany(x => x.Value.Values)) - text.Dispose(); - - _cache.Clear(); - } } - [Serializable] - public class GFXLoadException : Exception + public void Dispose() { - public GFXLoadException(int resource, GFXTypes gfx) - : base($"Unable to load graphic {resource + 100} from file gfx{(int)gfx:000}.egf") { } + foreach (var text in _cache.SelectMany(x => x.Value.Values)) + text.Dispose(); + + _cache.Clear(); } +} + +[Serializable] +public class GFXLoadException : Exception +{ + public GFXLoadException(int resource, GFXTypes gfx) + : base($"Unable to load graphic {resource + 100} from file gfx{(int)gfx:000}.egf") { } } \ No newline at end of file diff --git a/EOLib.Graphics/PEFileCollection.cs b/EOLib.Graphics/PEFileCollection.cs index 01671d0d4..e20c527e4 100644 --- a/EOLib.Graphics/PEFileCollection.cs +++ b/EOLib.Graphics/PEFileCollection.cs @@ -4,35 +4,34 @@ using System.Collections.Generic; using System.IO; -namespace EOLib.Graphics +namespace EOLib.Graphics; + +[MappedType(BaseType = typeof(IPEFileCollection), IsSingleton = true)] +public sealed class PEFileCollection : Dictionary, IPEFileCollection { - [MappedType(BaseType = typeof(IPEFileCollection), IsSingleton = true)] - public sealed class PEFileCollection : Dictionary, IPEFileCollection + public void PopulateCollectionWithStandardGFX() { - public void PopulateCollectionWithStandardGFX() - { - var gfxTypes = (GFXTypes[])Enum.GetValues(typeof(GFXTypes)); - foreach (var type in gfxTypes) - Add(type, CreateGFXFile(type)); - } - - private IPEFile CreateGFXFile(GFXTypes file) - { - var number = ((int)file).ToString("D3"); - var fName = Path.Combine("gfx", "gfx" + number + ".egf"); + var gfxTypes = (GFXTypes[])Enum.GetValues(typeof(GFXTypes)); + foreach (var type in gfxTypes) + Add(type, CreateGFXFile(type)); + } - return new PEFile(fName); - } + private IPEFile CreateGFXFile(GFXTypes file) + { + var number = ((int)file).ToString("D3"); + var fName = Path.Combine("gfx", "gfx" + number + ".egf"); - public void Dispose() - { - foreach (var pair in this) - pair.Value.Dispose(); - } + return new PEFile(fName); } - public interface IPEFileCollection : IDictionary, IDisposable + public void Dispose() { - void PopulateCollectionWithStandardGFX(); + foreach (var pair in this) + pair.Value.Dispose(); } +} + +public interface IPEFileCollection : IDictionary, IDisposable +{ + void PopulateCollectionWithStandardGFX(); } \ No newline at end of file diff --git a/EOLib.Graphics/RectangleExtension.cs b/EOLib.Graphics/RectangleExtension.cs index c170f2c29..3fbfd12bc 100644 --- a/EOLib.Graphics/RectangleExtension.cs +++ b/EOLib.Graphics/RectangleExtension.cs @@ -1,30 +1,29 @@ using Microsoft.Xna.Framework; -namespace EOLib.Graphics +namespace EOLib.Graphics; + +public static class RectangleExtension { - public static class RectangleExtension + /// + /// Returns a new rectangle with the position set to the specified location + /// + /// + /// New position for the rectangle + /// + public static Rectangle WithPosition(this Rectangle orig, Vector2 loc) { - /// - /// Returns a new rectangle with the position set to the specified location - /// - /// - /// New position for the rectangle - /// - public static Rectangle WithPosition(this Rectangle orig, Vector2 loc) - { - return new Rectangle((int)loc.X, (int)loc.Y, orig.Width, orig.Height); - } + return new Rectangle((int)loc.X, (int)loc.Y, orig.Width, orig.Height); + } - /// - /// Returns a new rectangle with the size set to the specified dimensions - /// - /// - /// Width of the new rectangle - /// Height of the new rectangle - /// - public static Rectangle WithSize(this Rectangle orig, int width, int height) - { - return new Rectangle(orig.X, orig.Y, width, height); - } + /// + /// Returns a new rectangle with the size set to the specified dimensions + /// + /// + /// Width of the new rectangle + /// Height of the new rectangle + /// + public static Rectangle WithSize(this Rectangle orig, int width, int height) + { + return new Rectangle(orig.X, orig.Y, width, height); } } \ No newline at end of file diff --git a/EOLib.IO.Test/EIFRecordExtensionsTest.cs b/EOLib.IO.Test/EIFRecordExtensionsTest.cs index d0dc6f4d2..fa86b36d1 100644 --- a/EOLib.IO.Test/EIFRecordExtensionsTest.cs +++ b/EOLib.IO.Test/EIFRecordExtensionsTest.cs @@ -3,46 +3,45 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test +namespace EOLib.IO.Test; + +[TestFixture, ExcludeFromCodeCoverage] +public class EIFRecordExtensionsTest { - [TestFixture, ExcludeFromCodeCoverage] - public class EIFRecordExtensionsTest + [TestCase(EquipLocation.Accessory, ItemType.Accessory)] + [TestCase(EquipLocation.Armlet1, ItemType.Armlet)] + [TestCase(EquipLocation.Armor, ItemType.Armor)] + [TestCase(EquipLocation.Belt, ItemType.Belt)] + [TestCase(EquipLocation.Boots, ItemType.Boots)] + [TestCase(EquipLocation.Bracer1, ItemType.Bracer)] + [TestCase(EquipLocation.Gloves, ItemType.Gloves)] + [TestCase(EquipLocation.Hat, ItemType.Hat)] + [TestCase(EquipLocation.Necklace, ItemType.Necklace)] + [TestCase(EquipLocation.Ring1, ItemType.Ring)] + [TestCase(EquipLocation.Shield, ItemType.Shield)] + [TestCase(EquipLocation.Weapon, ItemType.Weapon)] + public void GetEquipLocation_Matches_ItemType(EquipLocation equipLocation, ItemType itemType) { - [TestCase(EquipLocation.Accessory, ItemType.Accessory)] - [TestCase(EquipLocation.Armlet1, ItemType.Armlet)] - [TestCase(EquipLocation.Armor, ItemType.Armor)] - [TestCase(EquipLocation.Belt, ItemType.Belt)] - [TestCase(EquipLocation.Boots, ItemType.Boots)] - [TestCase(EquipLocation.Bracer1, ItemType.Bracer)] - [TestCase(EquipLocation.Gloves, ItemType.Gloves)] - [TestCase(EquipLocation.Hat, ItemType.Hat)] - [TestCase(EquipLocation.Necklace, ItemType.Necklace)] - [TestCase(EquipLocation.Ring1, ItemType.Ring)] - [TestCase(EquipLocation.Shield, ItemType.Shield)] - [TestCase(EquipLocation.Weapon, ItemType.Weapon)] - public void GetEquipLocation_Matches_ItemType(EquipLocation equipLocation, ItemType itemType) - { - Assert.That(WithItemType(itemType).GetEquipLocation(), Is.EqualTo(equipLocation)); - } - - [TestCase(ItemType.Beer)] - [TestCase(ItemType.CureCurse)] - [TestCase(ItemType.EXPReward)] - [TestCase(ItemType.EffectPotion)] - [TestCase(ItemType.HairDye)] - [TestCase(ItemType.Heal)] - [TestCase(ItemType.Key)] - [TestCase(ItemType.Money)] - [TestCase(ItemType.SkillReward)] - [TestCase(ItemType.StatReward)] - [TestCase(ItemType.Static)] - [TestCase(ItemType.Teleport)] - [TestCase(ItemType.UnknownType1)] - public void GetEquipLocation_Unsupported_ReturnsPaperdollMax(ItemType type) - { - Assert.That(WithItemType(type).GetEquipLocation(), Is.EqualTo(EquipLocation.PAPERDOLL_MAX)); - } + Assert.That(WithItemType(itemType).GetEquipLocation(), Is.EqualTo(equipLocation)); + } - private static EIFRecord WithItemType(ItemType type) => (EIFRecord)new EIFRecord().WithProperty(PubRecordProperty.ItemType, (int)type); + [TestCase(ItemType.Beer)] + [TestCase(ItemType.CureCurse)] + [TestCase(ItemType.EXPReward)] + [TestCase(ItemType.EffectPotion)] + [TestCase(ItemType.HairDye)] + [TestCase(ItemType.Heal)] + [TestCase(ItemType.Key)] + [TestCase(ItemType.Money)] + [TestCase(ItemType.SkillReward)] + [TestCase(ItemType.StatReward)] + [TestCase(ItemType.Static)] + [TestCase(ItemType.Teleport)] + [TestCase(ItemType.UnknownType1)] + public void GetEquipLocation_Unsupported_ReturnsPaperdollMax(ItemType type) + { + Assert.That(WithItemType(type).GetEquipLocation(), Is.EqualTo(EquipLocation.PAPERDOLL_MAX)); } + + private static EIFRecord WithItemType(ItemType type) => (EIFRecord)new EIFRecord().WithProperty(PubRecordProperty.ItemType, (int)type); } \ No newline at end of file diff --git a/EOLib.IO.Test/Map/MapFilePropertiesTest.cs b/EOLib.IO.Test/Map/MapFilePropertiesTest.cs index 08a70bc5f..eb46d4015 100644 --- a/EOLib.IO.Test/Map/MapFilePropertiesTest.cs +++ b/EOLib.IO.Test/Map/MapFilePropertiesTest.cs @@ -10,135 +10,134 @@ using System.Reflection; using System.Text; -namespace EOLib.IO.Test.Map +namespace EOLib.IO.Test.Map; + +[TestFixture, ExcludeFromCodeCoverage] +public class MapFilePropertiesTest { - [TestFixture, ExcludeFromCodeCoverage] - public class MapFilePropertiesTest - { - private IMapEntitySerializer _mapPropertiesSerializer; - private IMapFileProperties _props; + private IMapEntitySerializer _mapPropertiesSerializer; + private IMapFileProperties _props; - [SetUp] - public void SetUp() - { - _props = new MapFileProperties(); + [SetUp] + public void SetUp() + { + _props = new MapFileProperties(); - _mapPropertiesSerializer = new MapPropertiesSerializer( - new NumberEncoderService(), new MapStringEncoderService()); - } + _mapPropertiesSerializer = new MapPropertiesSerializer( + new NumberEncoderService(), new MapStringEncoderService()); + } - [Test] - public void MapFileProperties_HasExpectedFileHeader() - { - Assert.AreEqual("EMF", _props.FileType); - } + [Test] + public void MapFileProperties_HasExpectedFileHeader() + { + Assert.AreEqual("EMF", _props.FileType); + } - [Test] - public void MapFileProperties_SerializeToByteArray_HasExpectedFormat() - { - _props = CreateMapPropertiesWithSomeTestData(_props); + [Test] + public void MapFileProperties_SerializeToByteArray_HasExpectedFormat() + { + _props = CreateMapPropertiesWithSomeTestData(_props); - var expectedBytes = CreateExpectedBytes(_props); - var actualBytes = _mapPropertiesSerializer.SerializeToByteArray(_props); + var expectedBytes = CreateExpectedBytes(_props); + var actualBytes = _mapPropertiesSerializer.SerializeToByteArray(_props); - CollectionAssert.AreEqual(expectedBytes, actualBytes); - } + CollectionAssert.AreEqual(expectedBytes, actualBytes); + } - [Test] - public void MapFileProperties_DeserializeFromByteArray_HasExpectedValues() - { - var expected = CreateMapPropertiesWithSomeTestData(_props); - var bytes = CreateExpectedBytes(expected); + [Test] + public void MapFileProperties_DeserializeFromByteArray_HasExpectedValues() + { + var expected = CreateMapPropertiesWithSomeTestData(_props); + var bytes = CreateExpectedBytes(expected); - _props = _mapPropertiesSerializer.DeserializeFromByteArray(bytes); + _props = _mapPropertiesSerializer.DeserializeFromByteArray(bytes); - foreach (var property in expected.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) - { - var expectedValue = property.GetValue(expected); - var actualValue = property.GetValue(_props); + foreach (var property in expected.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) + { + var expectedValue = property.GetValue(expected); + var actualValue = property.GetValue(_props); - if (expectedValue is ICollection && actualValue is ICollection) - CollectionAssert.AreEqual((ICollection)expectedValue, (ICollection)actualValue); - else - Assert.AreEqual(expectedValue, actualValue, "Property {0} is not equal!", property.Name); - } + if (expectedValue is ICollection && actualValue is ICollection) + CollectionAssert.AreEqual((ICollection)expectedValue, (ICollection)actualValue); + else + Assert.AreEqual(expectedValue, actualValue, "Property {0} is not equal!", property.Name); } + } - [Test] - public void MapFileProperties_CustomProperties_NotChangedWhenDeserialized() - { - var expected = CreateMapPropertiesWithSomeTestData(_props); - var bytes = CreateExpectedBytes(expected); + [Test] + public void MapFileProperties_CustomProperties_NotChangedWhenDeserialized() + { + var expected = CreateMapPropertiesWithSomeTestData(_props); + var bytes = CreateExpectedBytes(expected); - _props = _mapPropertiesSerializer.DeserializeFromByteArray(bytes); + _props = _mapPropertiesSerializer.DeserializeFromByteArray(bytes); - Assert.AreEqual(new MapFileProperties().MapID, _props.MapID); - Assert.AreEqual(new MapFileProperties().FileSize, _props.FileSize); - Assert.AreEqual(new MapFileProperties().HasTimedSpikes, _props.HasTimedSpikes); - } + Assert.AreEqual(new MapFileProperties().MapID, _props.MapID); + Assert.AreEqual(new MapFileProperties().FileSize, _props.FileSize); + Assert.AreEqual(new MapFileProperties().HasTimedSpikes, _props.HasTimedSpikes); + } - [Test] - public void MapFileProperties_DeserializeFromByteArray_ThrowsExceptionWhenIncorrectSize() - { - var bytes = new byte[] { 1, 2 }; - Assert.Throws(() => _mapPropertiesSerializer.DeserializeFromByteArray(bytes)); - } + [Test] + public void MapFileProperties_DeserializeFromByteArray_ThrowsExceptionWhenIncorrectSize() + { + var bytes = new byte[] { 1, 2 }; + Assert.Throws(() => _mapPropertiesSerializer.DeserializeFromByteArray(bytes)); + } - [Test] - public void MapFileProperties_DeserializeFromByteArray_ThrowsExceptionWhenNotEMF() - { - var bytes = Enumerable.Repeat((byte)254, MapFileProperties.DATA_SIZE).ToArray(); - Assert.Throws(() => _mapPropertiesSerializer.DeserializeFromByteArray(bytes)); - } + [Test] + public void MapFileProperties_DeserializeFromByteArray_ThrowsExceptionWhenNotEMF() + { + var bytes = Enumerable.Repeat((byte)254, MapFileProperties.DATA_SIZE).ToArray(); + Assert.Throws(() => _mapPropertiesSerializer.DeserializeFromByteArray(bytes)); + } - private static IMapFileProperties CreateMapPropertiesWithSomeTestData(IMapFileProperties props) - { - return props.WithChecksum(new List { 1, 2 }) - .WithName("Some test name") - .WithWidth(200) - .WithHeight(100) - .WithEffect(MapEffect.Quake1) - .WithMusic(123) - .WithControl(MusicControl.InterruptIfDifferentPlayOnce) - .WithAmbientNoise(4567) - .WithFillTile(6969) - .WithRelogX(33) - .WithRelogY(22) - .WithUnknown2(100) - .WithMapAvailable(true) - .WithScrollAvailable(false) - .WithPKAvailable(true); - } + private static IMapFileProperties CreateMapPropertiesWithSomeTestData(IMapFileProperties props) + { + return props.WithChecksum(new List { 1, 2 }) + .WithName("Some test name") + .WithWidth(200) + .WithHeight(100) + .WithEffect(MapEffect.Quake1) + .WithMusic(123) + .WithControl(MusicControl.InterruptIfDifferentPlayOnce) + .WithAmbientNoise(4567) + .WithFillTile(6969) + .WithRelogX(33) + .WithRelogY(22) + .WithUnknown2(100) + .WithMapAvailable(true) + .WithScrollAvailable(false) + .WithPKAvailable(true); + } - private static byte[] CreateExpectedBytes(IMapFileProperties props) - { - var numberEncoderService = new NumberEncoderService(); - var mapStringEncoderService = new MapStringEncoderService(); - var ret = new List(); - - ret.AddRange(Encoding.ASCII.GetBytes(props.FileType)); - ret.AddRange(props.Checksum.SelectMany(x => numberEncoderService.EncodeNumber(x, 2))); - - var fullName = Enumerable.Repeat((byte)0xFF, 24).ToArray(); - var encodedName = mapStringEncoderService.EncodeMapString(props.Name, props.Name.Length); - Array.Copy(encodedName, 0, fullName, fullName.Length - encodedName.Length, encodedName.Length); - ret.AddRange(fullName); - - ret.AddRange(numberEncoderService.EncodeNumber(props.PKAvailable ? 3 : 0, 1)); - ret.AddRange(numberEncoderService.EncodeNumber((int)props.Effect, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.Music, 1)); - ret.AddRange(numberEncoderService.EncodeNumber((int)props.Control, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.AmbientNoise, 2)); - ret.AddRange(numberEncoderService.EncodeNumber(props.Width, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.Height, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.FillTile, 2)); - ret.AddRange(numberEncoderService.EncodeNumber(props.MapAvailable ? 1 : 0, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.CanScroll ? 1 : 0, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.RelogX, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.RelogY, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.Unknown2, 1)); - - return ret.ToArray(); - } + private static byte[] CreateExpectedBytes(IMapFileProperties props) + { + var numberEncoderService = new NumberEncoderService(); + var mapStringEncoderService = new MapStringEncoderService(); + var ret = new List(); + + ret.AddRange(Encoding.ASCII.GetBytes(props.FileType)); + ret.AddRange(props.Checksum.SelectMany(x => numberEncoderService.EncodeNumber(x, 2))); + + var fullName = Enumerable.Repeat((byte)0xFF, 24).ToArray(); + var encodedName = mapStringEncoderService.EncodeMapString(props.Name, props.Name.Length); + Array.Copy(encodedName, 0, fullName, fullName.Length - encodedName.Length, encodedName.Length); + ret.AddRange(fullName); + + ret.AddRange(numberEncoderService.EncodeNumber(props.PKAvailable ? 3 : 0, 1)); + ret.AddRange(numberEncoderService.EncodeNumber((int)props.Effect, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.Music, 1)); + ret.AddRange(numberEncoderService.EncodeNumber((int)props.Control, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.AmbientNoise, 2)); + ret.AddRange(numberEncoderService.EncodeNumber(props.Width, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.Height, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.FillTile, 2)); + ret.AddRange(numberEncoderService.EncodeNumber(props.MapAvailable ? 1 : 0, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.CanScroll ? 1 : 0, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.RelogX, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.RelogY, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.Unknown2, 1)); + + return ret.ToArray(); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Map/MapFileTest.cs b/EOLib.IO.Test/Map/MapFileTest.cs index 7b4d7e272..93237d607 100644 --- a/EOLib.IO.Test/Map/MapFileTest.cs +++ b/EOLib.IO.Test/Map/MapFileTest.cs @@ -7,167 +7,166 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.IO.Test.Map +namespace EOLib.IO.Test.Map; + +[TestFixture, ExcludeFromCodeCoverage] +public class MapFileTest { - [TestFixture, ExcludeFromCodeCoverage] - public class MapFileTest - { - private IMapFile _mapFile; - private IMapStringEncoderService ses; - private INumberEncoderService nes; + private IMapFile _mapFile; + private IMapStringEncoderService ses; + private INumberEncoderService nes; - private IMapFileSerializer _serializer; + private IMapFileSerializer _serializer; - [SetUp] - public void SetUp() - { - ses = new MapStringEncoderService(); - nes = new NumberEncoderService(); - - _serializer = new MapFileSerializer( - new MapPropertiesSerializer(nes, ses), - new NPCSpawnMapEntitySerializer(nes), - new ChestSpawnMapEntitySerializer(nes), - new WarpMapEntitySerializer(nes), - new SignMapEntitySerializer(nes, ses), - new UnknownMapEntitySerializer(nes), - nes); - } + [SetUp] + public void SetUp() + { + ses = new MapStringEncoderService(); + nes = new NumberEncoderService(); + + _serializer = new MapFileSerializer( + new MapPropertiesSerializer(nes, ses), + new NPCSpawnMapEntitySerializer(nes), + new ChestSpawnMapEntitySerializer(nes), + new WarpMapEntitySerializer(nes), + new SignMapEntitySerializer(nes, ses), + new UnknownMapEntitySerializer(nes), + nes); + } - [Test] - public void MapFile_Properties_HasExpectedInitialParameters() - { - _mapFile = new MapFile().WithMapID(123); - - Assert.AreEqual(123, _mapFile.Properties.MapID); - Assert.IsNotNull(_mapFile.NPCSpawns); - Assert.IsNotNull(_mapFile.Unknowns); - Assert.IsNotNull(_mapFile.Chests); - Assert.IsNotNull(_mapFile.Tiles); - Assert.IsNotNull(_mapFile.Warps); - Assert.IsNotNull(_mapFile.GFX); - Assert.IsNotNull(_mapFile.Signs); - } + [Test] + public void MapFile_Properties_HasExpectedInitialParameters() + { + _mapFile = new MapFile().WithMapID(123); + + Assert.AreEqual(123, _mapFile.Properties.MapID); + Assert.IsNotNull(_mapFile.NPCSpawns); + Assert.IsNotNull(_mapFile.Unknowns); + Assert.IsNotNull(_mapFile.Chests); + Assert.IsNotNull(_mapFile.Tiles); + Assert.IsNotNull(_mapFile.Warps); + Assert.IsNotNull(_mapFile.GFX); + Assert.IsNotNull(_mapFile.Signs); + } - [Test] - public void MapFile_DeserializeFromByteArray_HasCorrectFileSizeInMapProperties() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_DeserializeFromByteArray_HasCorrectFileSizeInMapProperties() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.None); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.None); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.AreEqual(mapData.Length, _mapFile.Properties.FileSize); - } + Assert.AreEqual(mapData.Length, _mapFile.Properties.FileSize); + } - [Test] - public void MapFile_DeserializeFromByteArray_NoTileSpecIsTimedSpikes_FlagIsNotSetInProperties() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_DeserializeFromByteArray_NoTileSpecIsTimedSpikes_FlagIsNotSetInProperties() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.AmbientSource); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.AmbientSource); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.IsFalse(_mapFile.Properties.HasTimedSpikes); - } + Assert.IsFalse(_mapFile.Properties.HasTimedSpikes); + } - [Test] - public void MapFile_DeserializeFromByteArray_AnyTileSpecIsTimedSpikes_FlagIsSetInProperties() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_DeserializeFromByteArray_AnyTileSpecIsTimedSpikes_FlagIsSetInProperties() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.SpikesTimed); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.SpikesTimed); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.IsTrue(_mapFile.Properties.HasTimedSpikes); - } + Assert.IsTrue(_mapFile.Properties.HasTimedSpikes); + } - [Test] - public void MapFile_SerializeToByteArray_HasCorrectFormat() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_SerializeToByteArray_HasCorrectFormat() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(2).WithHeight(2), TileSpec.Arena, 432); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(2).WithHeight(2), TileSpec.Arena, 432); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - var actualData = _serializer.SerializeToByteArray(_mapFile, rewriteChecksum: false); + var actualData = _serializer.SerializeToByteArray(_mapFile, rewriteChecksum: false); - CollectionAssert.AreEqual(mapData, actualData); - } + CollectionAssert.AreEqual(mapData, actualData); + } - [Test] - public void MapFile_Width1Height1_HasExpectedGFXAndTiles() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_Width1Height1_HasExpectedGFXAndTiles() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.Board5, 999); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.Board5, 999); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.AreEqual(TileSpec.Board5, _mapFile.Tiles[1, 1]); - foreach (var kvp in _mapFile.GFX) - Assert.AreEqual(999, kvp.Value[1, 1]); - } + Assert.AreEqual(TileSpec.Board5, _mapFile.Tiles[1, 1]); + foreach (var kvp in _mapFile.GFX) + Assert.AreEqual(999, kvp.Value[1, 1]); + } - [Test] - public void MapFile_StoresEmptyWarpRows() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_StoresEmptyWarpRows() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.BankVault, 1234); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.BankVault, 1234); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.That(_mapFile.EmptyWarpRows, Has.Count.EqualTo(1)); - } + Assert.That(_mapFile.EmptyWarpRows, Has.Count.EqualTo(1)); + } - [Test] - public void MapFile_StoresEmptyTileRows() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_StoresEmptyTileRows() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.VultTypo, 4321); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.VultTypo, 4321); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.That(_mapFile.EmptyTileRows, Has.Count.EqualTo(1)); - } + Assert.That(_mapFile.EmptyTileRows, Has.Count.EqualTo(1)); + } - private byte[] CreateDataForMap(IMapFileProperties mapFileProperties, TileSpec spec, int gfx = 1) + private byte[] CreateDataForMap(IMapFileProperties mapFileProperties, TileSpec spec, int gfx = 1) + { + var ret = new List(); + + var serializer = new MapPropertiesSerializer(nes, ses); + + ret.AddRange(serializer.SerializeToByteArray(mapFileProperties)); + ret.AddRange(nes.EncodeNumber(0, 1)); //npc spawns + ret.AddRange(nes.EncodeNumber(0, 1)); //unknowns + ret.AddRange(nes.EncodeNumber(0, 1)); //chest spawns + + //tiles + ret.AddRange(nes.EncodeNumber(2, 1)); //count (rows) + ret.AddRange(nes.EncodeNumber(1, 1)); //y + ret.AddRange(nes.EncodeNumber(1, 1)); //count (cols) + ret.AddRange(nes.EncodeNumber(1, 1)); //x + ret.AddRange(nes.EncodeNumber((int)spec, 1)); //tilespec + ret.AddRange(nes.EncodeNumber(0, 1)); //y + ret.AddRange(nes.EncodeNumber(0, 1)); //count (cols) (empty row) + + //warps (empty row) + ret.AddRange(nes.EncodeNumber(1, 1)); //count + ret.AddRange(nes.EncodeNumber(1, 1)); //y + ret.AddRange(nes.EncodeNumber(0, 1)); //count + + //gfx + foreach (var layer in (MapLayer[])Enum.GetValues(typeof(MapLayer))) { - var ret = new List(); - - var serializer = new MapPropertiesSerializer(nes, ses); - - ret.AddRange(serializer.SerializeToByteArray(mapFileProperties)); - ret.AddRange(nes.EncodeNumber(0, 1)); //npc spawns - ret.AddRange(nes.EncodeNumber(0, 1)); //unknowns - ret.AddRange(nes.EncodeNumber(0, 1)); //chest spawns - - //tiles - ret.AddRange(nes.EncodeNumber(2, 1)); //count (rows) - ret.AddRange(nes.EncodeNumber(1, 1)); //y - ret.AddRange(nes.EncodeNumber(1, 1)); //count (cols) - ret.AddRange(nes.EncodeNumber(1, 1)); //x - ret.AddRange(nes.EncodeNumber((int)spec, 1)); //tilespec - ret.AddRange(nes.EncodeNumber(0, 1)); //y - ret.AddRange(nes.EncodeNumber(0, 1)); //count (cols) (empty row) - - //warps (empty row) ret.AddRange(nes.EncodeNumber(1, 1)); //count ret.AddRange(nes.EncodeNumber(1, 1)); //y - ret.AddRange(nes.EncodeNumber(0, 1)); //count - - //gfx - foreach (var layer in (MapLayer[])Enum.GetValues(typeof(MapLayer))) - { - ret.AddRange(nes.EncodeNumber(1, 1)); //count - ret.AddRange(nes.EncodeNumber(1, 1)); //y - ret.AddRange(nes.EncodeNumber(1, 1)); //count - ret.AddRange(nes.EncodeNumber(1, 1)); //x - ret.AddRange(nes.EncodeNumber(gfx, 2)); //gfx value - } + ret.AddRange(nes.EncodeNumber(1, 1)); //count + ret.AddRange(nes.EncodeNumber(1, 1)); //x + ret.AddRange(nes.EncodeNumber(gfx, 2)); //gfx value + } - ret.AddRange(nes.EncodeNumber(0, 1)); //signs + ret.AddRange(nes.EncodeNumber(0, 1)); //signs - return ret.ToArray(); - } + return ret.ToArray(); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs b/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs index c335b98c5..e890cb352 100644 --- a/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs +++ b/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs @@ -5,90 +5,89 @@ using System.Linq; using System.Text; -namespace EOLib.IO.Test.Map +namespace EOLib.IO.Test.Map; + +[TestFixture, ExcludeFromCodeCoverage] +public class MapStringEncoderServiceTest { - [TestFixture, ExcludeFromCodeCoverage] - public class MapStringEncoderServiceTest - { - private IMapStringEncoderService _service; + private IMapStringEncoderService _service; - [SetUp] - public void SetUp() - { - _service = new MapStringEncoderService(); - } + [SetUp] + public void SetUp() + { + _service = new MapStringEncoderService(); + } - [Test] - public void EncodeThenDecode_ReturnsOriginalString() - { - const string expected = "Test map string to encode"; + [Test] + public void EncodeThenDecode_ReturnsOriginalString() + { + const string expected = "Test map string to encode"; - var bytes = _service.EncodeMapString(expected, expected.Length); - var actual = _service.DecodeMapString(bytes); + var bytes = _service.EncodeMapString(expected, expected.Length); + var actual = _service.DecodeMapString(bytes); - Assert.AreEqual(expected, actual); - } + Assert.AreEqual(expected, actual); + } - [Test] - public void EncodeString_ReturnsExpectedBytes_FromKnownString() + [Test] + public void EncodeString_ReturnsExpectedBytes_FromKnownString() + { + var name = "Aeven" + Encoding.ASCII.GetString(Enumerable.Repeat((byte)0, 19).ToArray()); + var expectedBytes = new byte[] { - var name = "Aeven" + Encoding.ASCII.GetString(Enumerable.Repeat((byte)0, 19).ToArray()); - var expectedBytes = new byte[] - { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 104, 41, 104, 94 - }; + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 104, 41, 104, 94 + }; - var actualBytes = _service.EncodeMapString(name, name.Length); + var actualBytes = _service.EncodeMapString(name, name.Length); - CollectionAssert.AreEqual(expectedBytes, actualBytes); - } + CollectionAssert.AreEqual(expectedBytes, actualBytes); + } - [Test] - public void DecodeString_ReturnsExpectedString_FromKnownBytes() - { - const string expected = "Aeven"; + [Test] + public void DecodeString_ReturnsExpectedString_FromKnownBytes() + { + const string expected = "Aeven"; - var bytes = new byte[] { 49, 104, 41, 104, 94 }; - var fullBytes = Enumerable.Repeat((byte)255, 24).ToArray(); - Array.Copy(bytes, 0, fullBytes, fullBytes.Length - bytes.Length, bytes.Length); + var bytes = new byte[] { 49, 104, 41, 104, 94 }; + var fullBytes = Enumerable.Repeat((byte)255, 24).ToArray(); + Array.Copy(bytes, 0, fullBytes, fullBytes.Length - bytes.Length, bytes.Length); - var actual = _service.DecodeMapString(fullBytes); + var actual = _service.DecodeMapString(fullBytes); - Assert.AreEqual(expected, actual); - } + Assert.AreEqual(expected, actual); + } - [Test] - public void EncodeString_InvalidLength_Throws() - { - Assert.That(() => _service.EncodeMapString("123", 0), Throws.ArgumentException); - } + [Test] + public void EncodeString_InvalidLength_Throws() + { + Assert.That(() => _service.EncodeMapString("123", 0), Throws.ArgumentException); + } - [Test] - public void EncodeString_ExtraLength_PadsData() - { - const string TestString = "12345"; - const int LengthWithPadding = 8; + [Test] + public void EncodeString_ExtraLength_PadsData() + { + const string TestString = "12345"; + const int LengthWithPadding = 8; - var actual = _service.EncodeMapString(TestString, LengthWithPadding); + var actual = _service.EncodeMapString(TestString, LengthWithPadding); - Assert.That(actual, Has.Length.EqualTo(LengthWithPadding)); + Assert.That(actual, Has.Length.EqualTo(LengthWithPadding)); - int i = 0; - for (; i < LengthWithPadding - TestString.Length; i++) - Assert.That(actual[i], Is.EqualTo((byte)0xFF)); - Assert.That(actual[i], Is.Not.EqualTo((byte)0xFF)); - } + int i = 0; + for (; i < LengthWithPadding - TestString.Length; i++) + Assert.That(actual[i], Is.EqualTo((byte)0xFF)); + Assert.That(actual[i], Is.Not.EqualTo((byte)0xFF)); + } - [Test] - public void EncodeString_ExtraLength_DecodesToExpectedValue() - { - const string TestString = "12345"; - const int LengthWithPadding = 8; + [Test] + public void EncodeString_ExtraLength_DecodesToExpectedValue() + { + const string TestString = "12345"; + const int LengthWithPadding = 8; - var encoded = _service.EncodeMapString(TestString, LengthWithPadding); - var original = _service.DecodeMapString(encoded); + var encoded = _service.EncodeMapString(TestString, LengthWithPadding); + var original = _service.DecodeMapString(encoded); - Assert.That(original, Is.EqualTo(TestString)); - } + Assert.That(original, Is.EqualTo(TestString)); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/BasePubFileTest.cs b/EOLib.IO.Test/Pub/BasePubFileTest.cs index e134471e7..c3167486e 100644 --- a/EOLib.IO.Test/Pub/BasePubFileTest.cs +++ b/EOLib.IO.Test/Pub/BasePubFileTest.cs @@ -3,173 +3,172 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test.Pub +namespace EOLib.IO.Test.Pub; + +[TestFixture] +public class BasePubFileTest_EIFImpl : BasePubFileTest { } + +[TestFixture] +public class BasePubFileTest_ENFImpl : BasePubFileTest { } + +[TestFixture] +public class BasePubFileTest_ESFImpl : BasePubFileTest { } + +[TestFixture] +public class BasePubFileTest_ECFImpl : BasePubFileTest { } + +// These tests are run from the implementations +[ExcludeFromCodeCoverage] +public abstract class BasePubFileTest + where T : IPubFile, new() + where U : class, IPubRecord, new() { - [TestFixture] - public class BasePubFileTest_EIFImpl : BasePubFileTest { } + [Test] + public void WithAddedRecord_AddsRecord() + { + var file = new T(); + var record = (U)new U().WithID(1).WithName("My record"); + + var updatedFile = file.WithAddedRecord(record); + + Assert.That(file, Is.Empty); + Assert.That(updatedFile, Has.Length.EqualTo(1)); + Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record)); + } + + [Test] + public void WithAddedRecord_DuplicateID_ThrowsArgumentException() + { + var file = new T(); + var record = (U)new U().WithID(1).WithName("My record"); + + var updatedFile = file.WithAddedRecord(record); + + Assert.That(() => updatedFile.WithAddedRecord(record), Throws.ArgumentException); + } + + [Test] + public void WithAddedRecord_IDOutOfBounds_ThrowsArgumentException() + { + var file = new T(); + var record = (U)new U().WithID(400); + + Assert.That(() => file.WithAddedRecord(record), Throws.ArgumentException); + } + + [Test] + public void WithInsertedRecord_InsertsRecordAtPosition_SpecifiedByID() + { + IPubFile file = new T(); + var record = (U)new U().WithID(1); + + file = file.WithAddedRecord(record); + + var updatedRecord = (U)record.WithName("updated"); + var updatedFile = file.WithInsertedRecord(updatedRecord); + + Assert.That(file, Has.Length.EqualTo(1)); + Assert.That(updatedFile, Has.Length.EqualTo(2)); + Assert.That(updatedFile[1].Name, Is.EqualTo("updated")); + } + + [Test] + public void WithInsertedRecord_UpdatesExistingRecordIDs() + { + IPubFile file = new T(); + var record = (U)new U().WithID(1); + + file = file.WithAddedRecord(record); + + var updatedRecord = (U)record.WithName("updated"); + var updatedFile = file.WithInsertedRecord(updatedRecord) + .WithInsertedRecord((U)updatedRecord.WithName("updated 2")) + .WithInsertedRecord((U)updatedRecord.WithName("updated 3")); + + Assert.That(file, Has.Length.EqualTo(1)); + Assert.That(updatedFile, Has.Length.EqualTo(4)); + Assert.That(updatedFile[1], Has.Property("Name").EqualTo("updated 3").And.Property("ID").EqualTo(1)); + Assert.That(updatedFile[2], Has.Property("Name").EqualTo("updated 2").And.Property("ID").EqualTo(2)); + Assert.That(updatedFile[3], Has.Property("Name").EqualTo("updated").And.Property("ID").EqualTo(3)); + Assert.That(updatedFile[4], Has.Property("Name").EqualTo(string.Empty).And.Property("ID").EqualTo(4)); + } + + [Test] + public void WithInsertedRecord_IDOutOfRange_ThrowsArgumentException() + { + IPubFile file = new T(); + var record = (U)new U().WithID(2); - [TestFixture] - public class BasePubFileTest_ENFImpl : BasePubFileTest { } + Assert.That(() => file.WithInsertedRecord(record), Throws.ArgumentException); + } + + [Test] + public void WithUpdatedRecord_UpdatesRecordProperties_ByRecordID() + { + IPubFile file = new T(); + var record = (U)new U().WithID(1); + file = file.WithAddedRecord(record); - [TestFixture] - public class BasePubFileTest_ESFImpl : BasePubFileTest { } + var updatedRecord = (U)record.WithName("Some name"); + var updatedFile = file.WithUpdatedRecord(updatedRecord); - [TestFixture] - public class BasePubFileTest_ECFImpl : BasePubFileTest { } + Assert.That(updatedFile[1].Name, Is.EqualTo("Some name")); + } - // These tests are run from the implementations - [ExcludeFromCodeCoverage] - public abstract class BasePubFileTest - where T : IPubFile, new() - where U : class, IPubRecord, new() + [Test] + public void WithUpdatedRecord_IDOutOfRange_ThrowsArgumentException() { - [Test] - public void WithAddedRecord_AddsRecord() - { - var file = new T(); - var record = (U)new U().WithID(1).WithName("My record"); - - var updatedFile = file.WithAddedRecord(record); - - Assert.That(file, Is.Empty); - Assert.That(updatedFile, Has.Length.EqualTo(1)); - Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record)); - } - - [Test] - public void WithAddedRecord_DuplicateID_ThrowsArgumentException() - { - var file = new T(); - var record = (U)new U().WithID(1).WithName("My record"); - - var updatedFile = file.WithAddedRecord(record); - - Assert.That(() => updatedFile.WithAddedRecord(record), Throws.ArgumentException); - } - - [Test] - public void WithAddedRecord_IDOutOfBounds_ThrowsArgumentException() - { - var file = new T(); - var record = (U)new U().WithID(400); - - Assert.That(() => file.WithAddedRecord(record), Throws.ArgumentException); - } - - [Test] - public void WithInsertedRecord_InsertsRecordAtPosition_SpecifiedByID() - { - IPubFile file = new T(); - var record = (U)new U().WithID(1); - - file = file.WithAddedRecord(record); - - var updatedRecord = (U)record.WithName("updated"); - var updatedFile = file.WithInsertedRecord(updatedRecord); - - Assert.That(file, Has.Length.EqualTo(1)); - Assert.That(updatedFile, Has.Length.EqualTo(2)); - Assert.That(updatedFile[1].Name, Is.EqualTo("updated")); - } - - [Test] - public void WithInsertedRecord_UpdatesExistingRecordIDs() - { - IPubFile file = new T(); - var record = (U)new U().WithID(1); - - file = file.WithAddedRecord(record); - - var updatedRecord = (U)record.WithName("updated"); - var updatedFile = file.WithInsertedRecord(updatedRecord) - .WithInsertedRecord((U)updatedRecord.WithName("updated 2")) - .WithInsertedRecord((U)updatedRecord.WithName("updated 3")); - - Assert.That(file, Has.Length.EqualTo(1)); - Assert.That(updatedFile, Has.Length.EqualTo(4)); - Assert.That(updatedFile[1], Has.Property("Name").EqualTo("updated 3").And.Property("ID").EqualTo(1)); - Assert.That(updatedFile[2], Has.Property("Name").EqualTo("updated 2").And.Property("ID").EqualTo(2)); - Assert.That(updatedFile[3], Has.Property("Name").EqualTo("updated").And.Property("ID").EqualTo(3)); - Assert.That(updatedFile[4], Has.Property("Name").EqualTo(string.Empty).And.Property("ID").EqualTo(4)); - } - - [Test] - public void WithInsertedRecord_IDOutOfRange_ThrowsArgumentException() - { - IPubFile file = new T(); - var record = (U)new U().WithID(2); - - Assert.That(() => file.WithInsertedRecord(record), Throws.ArgumentException); - } - - [Test] - public void WithUpdatedRecord_UpdatesRecordProperties_ByRecordID() - { - IPubFile file = new T(); - var record = (U)new U().WithID(1); - file = file.WithAddedRecord(record); - - var updatedRecord = (U)record.WithName("Some name"); - var updatedFile = file.WithUpdatedRecord(updatedRecord); - - Assert.That(updatedFile[1].Name, Is.EqualTo("Some name")); - } - - [Test] - public void WithUpdatedRecord_IDOutOfRange_ThrowsArgumentException() - { - IPubFile file = new T(); - var record = (U)new U().WithID(1); - file = file.WithAddedRecord(record); - - Assert.That(() => file.WithUpdatedRecord((U)record.WithID(2)), Throws.ArgumentException); - } - - [Test] - public void WithRemovedRecord_RemovesRecord() - { - var record = (U)new U().WithID(1).WithName("My record"); - - var file = new T().WithAddedRecord(record); - var updatedFile = file.WithRemovedRecord(record); - - Assert.That(updatedFile, Is.Empty); - Assert.That(file, Has.Length.EqualTo(1)); - } - - [Test] - public void WithRemovedRecord_RemovesRecord_UpdatesIDs() - { - var record = (U)new U().WithID(1).WithName("My record"); - var record2 = (U)new U().WithID(2).WithName("My record 2"); - var record3 = (U)new U().WithID(3).WithName("My record 3"); - var record4 = (U)new U().WithID(4).WithName("My record 4"); - - var file = new T().WithAddedRecord(record) - .WithAddedRecord(record2) - .WithAddedRecord(record3) - .WithAddedRecord(record4); - var updatedFile = file.WithRemovedRecord(record); - - Assert.That(file, Has.Length.EqualTo(4)); - Assert.That(updatedFile, Has.Length.EqualTo(3)); - - Assert.That(updatedFile[1].ID, Is.EqualTo(1)); - - Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record2.WithID(1))); - Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record3.WithID(2))); - Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record4.WithID(3))); - Assert.That(updatedFile, Has.None.With.Property("ID").EqualTo(4)); - } - - [Test] - public void WithRemovedRecord_IDOutOfrange_ThrowsArgumentException() - { - IPubFile file = new T(); - var record = (U)new U().WithID(1); - file = file.WithAddedRecord(record); - - Assert.That(() => file.WithRemovedRecord((U)record.WithID(2)), Throws.ArgumentException); - } + IPubFile file = new T(); + var record = (U)new U().WithID(1); + file = file.WithAddedRecord(record); + + Assert.That(() => file.WithUpdatedRecord((U)record.WithID(2)), Throws.ArgumentException); + } + + [Test] + public void WithRemovedRecord_RemovesRecord() + { + var record = (U)new U().WithID(1).WithName("My record"); + + var file = new T().WithAddedRecord(record); + var updatedFile = file.WithRemovedRecord(record); + + Assert.That(updatedFile, Is.Empty); + Assert.That(file, Has.Length.EqualTo(1)); + } + + [Test] + public void WithRemovedRecord_RemovesRecord_UpdatesIDs() + { + var record = (U)new U().WithID(1).WithName("My record"); + var record2 = (U)new U().WithID(2).WithName("My record 2"); + var record3 = (U)new U().WithID(3).WithName("My record 3"); + var record4 = (U)new U().WithID(4).WithName("My record 4"); + + var file = new T().WithAddedRecord(record) + .WithAddedRecord(record2) + .WithAddedRecord(record3) + .WithAddedRecord(record4); + var updatedFile = file.WithRemovedRecord(record); + + Assert.That(file, Has.Length.EqualTo(4)); + Assert.That(updatedFile, Has.Length.EqualTo(3)); + + Assert.That(updatedFile[1].ID, Is.EqualTo(1)); + + Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record2.WithID(1))); + Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record3.WithID(2))); + Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record4.WithID(3))); + Assert.That(updatedFile, Has.None.With.Property("ID").EqualTo(4)); + } + + [Test] + public void WithRemovedRecord_IDOutOfrange_ThrowsArgumentException() + { + IPubFile file = new T(); + var record = (U)new U().WithID(1); + file = file.WithAddedRecord(record); + + Assert.That(() => file.WithRemovedRecord((U)record.WithID(2)), Throws.ArgumentException); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ECFFileTest.cs b/EOLib.IO.Test/Pub/ECFFileTest.cs index 62f571cb2..4ff8ccf61 100644 --- a/EOLib.IO.Test/Pub/ECFFileTest.cs +++ b/EOLib.IO.Test/Pub/ECFFileTest.cs @@ -2,15 +2,14 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test.Pub +namespace EOLib.IO.Test.Pub; + +[TestFixture, ExcludeFromCodeCoverage] +public class ECFFileTest { - [TestFixture, ExcludeFromCodeCoverage] - public class ECFFileTest + [Test] + public void HasCorrectFileType() { - [Test] - public void HasCorrectFileType() - { - Assert.That(new ECFFile().FileType, Is.EqualTo("ECF")); - } + Assert.That(new ECFFile().FileType, Is.EqualTo("ECF")); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ECFRecordTest.cs b/EOLib.IO.Test/Pub/ECFRecordTest.cs index 76566a938..9174eb636 100644 --- a/EOLib.IO.Test/Pub/ECFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ECFRecordTest.cs @@ -4,31 +4,30 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.IO.Test.Pub +namespace EOLib.IO.Test.Pub; + +[TestFixture, ExcludeFromCodeCoverage] +public class ECFRecordTest { - [TestFixture, ExcludeFromCodeCoverage] - public class ECFRecordTest + [Test] + public void ECFRecord_HasAllExpectedProperties() { - [Test] - public void ECFRecord_HasAllExpectedProperties() - { - var record = new ECFRecord(); + var record = new ECFRecord(); - var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) - .Where(x => x.HasFlag(PubRecordProperty.Class)) - .Except(new[] { PubRecordProperty.Class }); + var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) + .Where(x => x.HasFlag(PubRecordProperty.Class)) + .Except(new[] { PubRecordProperty.Class }); - Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); + Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); - foreach (var p in expectedProperties) - Assert.That(record.Bag, Does.ContainKey(p)); - } + foreach (var p in expectedProperties) + Assert.That(record.Bag, Does.ContainKey(p)); + } - [Test] - public void ECFRecord_HasExpectedDataSize() - { - const int ExpectedDataSize = 14; - Assert.That(new ECFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); - } + [Test] + public void ECFRecord_HasExpectedDataSize() + { + const int ExpectedDataSize = 14; + Assert.That(new ECFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/EIFFileTest.cs b/EOLib.IO.Test/Pub/EIFFileTest.cs index bb2f90cac..d1e376899 100644 --- a/EOLib.IO.Test/Pub/EIFFileTest.cs +++ b/EOLib.IO.Test/Pub/EIFFileTest.cs @@ -2,15 +2,14 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test.Pub +namespace EOLib.IO.Test.Pub; + +[TestFixture, ExcludeFromCodeCoverage] +public class EIFFileTest { - [TestFixture, ExcludeFromCodeCoverage] - public class EIFFileTest + [Test] + public void HasCorrectFileType() { - [Test] - public void HasCorrectFileType() - { - Assert.That(new EIFFile().FileType, Is.EqualTo("EIF")); - } + Assert.That(new EIFFile().FileType, Is.EqualTo("EIF")); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/EIFRecordTest.cs b/EOLib.IO.Test/Pub/EIFRecordTest.cs index e3840beea..fb15d5f00 100644 --- a/EOLib.IO.Test/Pub/EIFRecordTest.cs +++ b/EOLib.IO.Test/Pub/EIFRecordTest.cs @@ -4,31 +4,30 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.IO.Test.Pub +namespace EOLib.IO.Test.Pub; + +[TestFixture, ExcludeFromCodeCoverage] +public class EIFRecordTest { - [TestFixture, ExcludeFromCodeCoverage] - public class EIFRecordTest + [Test] + public void EIFRecord_HasAllExpectedProperties() { - [Test] - public void EIFRecord_HasAllExpectedProperties() - { - var record = new EIFRecord(); + var record = new EIFRecord(); - var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) - .Where(x => x.HasFlag(PubRecordProperty.Item)) - .Except(new[] { PubRecordProperty.Item }); + var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) + .Where(x => x.HasFlag(PubRecordProperty.Item)) + .Except(new[] { PubRecordProperty.Item }); - Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); + Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); - foreach (var p in expectedProperties) - Assert.That(record.Bag, Does.ContainKey(p)); - } + foreach (var p in expectedProperties) + Assert.That(record.Bag, Does.ContainKey(p)); + } - [Test] - public void EIFRecord_HasExpectedDataSize() - { - const int ExpectedDataSize = 58; - Assert.That(new EIFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); - } + [Test] + public void EIFRecord_HasExpectedDataSize() + { + const int ExpectedDataSize = 58; + Assert.That(new EIFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ENFFileTest.cs b/EOLib.IO.Test/Pub/ENFFileTest.cs index 89d74be44..d1fce9566 100644 --- a/EOLib.IO.Test/Pub/ENFFileTest.cs +++ b/EOLib.IO.Test/Pub/ENFFileTest.cs @@ -2,15 +2,14 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test.Pub +namespace EOLib.IO.Test.Pub; + +[TestFixture, ExcludeFromCodeCoverage] +public class ENFFileTest { - [TestFixture, ExcludeFromCodeCoverage] - public class ENFFileTest + [Test] + public void HasCorrectFileType() { - [Test] - public void HasCorrectFileType() - { - Assert.That(new ENFFile().FileType, Is.EqualTo("ENF")); - } + Assert.That(new ENFFile().FileType, Is.EqualTo("ENF")); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ENFRecordTest.cs b/EOLib.IO.Test/Pub/ENFRecordTest.cs index 175effd1c..acc905143 100644 --- a/EOLib.IO.Test/Pub/ENFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ENFRecordTest.cs @@ -4,31 +4,30 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.IO.Test.Pub +namespace EOLib.IO.Test.Pub; + +[TestFixture, ExcludeFromCodeCoverage] +public class ENFRecordTest { - [TestFixture, ExcludeFromCodeCoverage] - public class ENFRecordTest + [Test] + public void ENFRecord_HasAllExpectedProperties() { - [Test] - public void ENFRecord_HasAllExpectedProperties() - { - var record = new ENFRecord(); + var record = new ENFRecord(); - var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) - .Where(x => x.HasFlag(PubRecordProperty.NPC)) - .Except(new[] { PubRecordProperty.NPC }); + var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) + .Where(x => x.HasFlag(PubRecordProperty.NPC)) + .Except(new[] { PubRecordProperty.NPC }); - Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); + Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); - foreach (var p in expectedProperties) - Assert.That(record.Bag, Does.ContainKey(p)); - } + foreach (var p in expectedProperties) + Assert.That(record.Bag, Does.ContainKey(p)); + } - [Test] - public void ENFRecord_HasExpectedDataSize() - { - const int ExpectedDataSize = 39; - Assert.That(new ENFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); - } + [Test] + public void ENFRecord_HasExpectedDataSize() + { + const int ExpectedDataSize = 39; + Assert.That(new ENFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ESFFileTest.cs b/EOLib.IO.Test/Pub/ESFFileTest.cs index ec0bfca2d..317c5f4e3 100644 --- a/EOLib.IO.Test/Pub/ESFFileTest.cs +++ b/EOLib.IO.Test/Pub/ESFFileTest.cs @@ -2,15 +2,14 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test.Pub +namespace EOLib.IO.Test.Pub; + +[TestFixture, ExcludeFromCodeCoverage] +public class ESFFileTest { - [TestFixture, ExcludeFromCodeCoverage] - public class ESFFileTest + [Test] + public void HasCorrectFileType() { - [Test] - public void HasCorrectFileType() - { - Assert.That(new ESFFile().FileType, Is.EqualTo("ESF")); - } + Assert.That(new ESFFile().FileType, Is.EqualTo("ESF")); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ESFRecordTest.cs b/EOLib.IO.Test/Pub/ESFRecordTest.cs index 361c8c8b5..d75a27bdf 100644 --- a/EOLib.IO.Test/Pub/ESFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ESFRecordTest.cs @@ -4,31 +4,30 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.IO.Test.Pub +namespace EOLib.IO.Test.Pub; + +[TestFixture, ExcludeFromCodeCoverage] +public class ESFRecordTest { - [TestFixture, ExcludeFromCodeCoverage] - public class ESFRecordTest + [Test] + public void ESFRecord_HasAllExpectedProperties() { - [Test] - public void ESFRecord_HasAllExpectedProperties() - { - var record = new ESFRecord(); + var record = new ESFRecord(); - var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) - .Where(x => x.HasFlag(PubRecordProperty.Spell)) - .Except(new[] { PubRecordProperty.Spell }); + var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) + .Where(x => x.HasFlag(PubRecordProperty.Spell)) + .Except(new[] { PubRecordProperty.Spell }); - Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); + Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); - foreach (var p in expectedProperties) - Assert.That(record.Bag, Does.ContainKey(p)); - } + foreach (var p in expectedProperties) + Assert.That(record.Bag, Does.ContainKey(p)); + } - [Test] - public void ESFRecord_HasExpectedDataSize() - { - const int ExpectedDataSize = 51; - Assert.That(new ESFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); - } + [Test] + public void ESFRecord_HasExpectedDataSize() + { + const int ExpectedDataSize = 51; + Assert.That(new ESFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs b/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs index d27c0a779..4770995e8 100644 --- a/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs +++ b/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs @@ -8,136 +8,135 @@ using System.Linq; using System.Text; -namespace EOLib.IO.Test.Services.Serializers -{ - [TestFixture] - public class PubFileSerializerTest_EIFImpl : PubFileSerializerTest { } +namespace EOLib.IO.Test.Services.Serializers; + +[TestFixture] +public class PubFileSerializerTest_EIFImpl : PubFileSerializerTest { } - [TestFixture] - public class PubFileSerializerTest_ENFImpl : PubFileSerializerTest { } +[TestFixture] +public class PubFileSerializerTest_ENFImpl : PubFileSerializerTest { } - [TestFixture] - public class PubFileSerializerTest_ESFImpl : PubFileSerializerTest { } +[TestFixture] +public class PubFileSerializerTest_ESFImpl : PubFileSerializerTest { } - [TestFixture] - public class PubFileSerializerTest_ECFImpl : PubFileSerializerTest { } +[TestFixture] +public class PubFileSerializerTest_ECFImpl : PubFileSerializerTest { } - [ExcludeFromCodeCoverage] - public abstract class PubFileSerializerTest - where T : IPubFile, new() - where U : class, IPubRecord, new() +[ExcludeFromCodeCoverage] +public abstract class PubFileSerializerTest + where T : IPubFile, new() + where U : class, IPubRecord, new() +{ + [Test] + public void DeserializeFromByteArray_WrongLength_Throws() { - [Test] - public void DeserializeFromByteArray_WrongLength_Throws() - { - const int ExpectedChecksum1 = 12345; - const int ExpectedChecksum2 = 6789; - const int ExpectedLength = 4; - - var expectedChecksum = new List { ExpectedChecksum1, ExpectedChecksum2 }; - - var records = new[] - { - new U().WithID(1).WithName("Rec_1"), - new U().WithID(2).WithName("Rec_2"), - new U().WithID(3).WithName("Rec_3"), - new U().WithID(4).WithName("Rec_4"), - }; - - var pubBytesShort = MakePubFileBytes(expectedChecksum, ExpectedLength - 1, records); - Assert.That(() => CreateSerializer().DeserializeFromByteArray(1, pubBytesShort, () => new T()), Throws.InstanceOf()); - } - - [Test] - public void DeserializeFromByteArray_HasExpectedHeader() - { - const int ExpectedChecksum1 = 12345; - const int ExpectedChecksum2 = 6789; - const int ExpectedLength = 4; + const int ExpectedChecksum1 = 12345; + const int ExpectedChecksum2 = 6789; + const int ExpectedLength = 4; - var expectedChecksum = new List { ExpectedChecksum1, ExpectedChecksum2 }; + var expectedChecksum = new List { ExpectedChecksum1, ExpectedChecksum2 }; - var records = new[] - { - new U().WithID(1).WithName("Rec_1"), - new U().WithID(2).WithName("Rec_2"), - new U().WithID(3).WithName("Rec_3"), - new U().WithID(4).WithName("Rec_4"), - }; + var records = new[] + { + new U().WithID(1).WithName("Rec_1"), + new U().WithID(2).WithName("Rec_2"), + new U().WithID(3).WithName("Rec_3"), + new U().WithID(4).WithName("Rec_4"), + }; + + var pubBytesShort = MakePubFileBytes(expectedChecksum, ExpectedLength - 1, records); + Assert.That(() => CreateSerializer().DeserializeFromByteArray(1, pubBytesShort, () => new T()), Throws.InstanceOf()); + } - var pubBytes = MakePubFileBytes(expectedChecksum, ExpectedLength, records); - var file = CreateSerializer().DeserializeFromByteArray(1, pubBytes, () => new T()); + [Test] + public void DeserializeFromByteArray_HasExpectedHeader() + { + const int ExpectedChecksum1 = 12345; + const int ExpectedChecksum2 = 6789; + const int ExpectedLength = 4; - Assert.That(file.CheckSum, Is.EqualTo(expectedChecksum)); - Assert.That(file.Length, Is.EqualTo(ExpectedLength)); - } + var expectedChecksum = new List { ExpectedChecksum1, ExpectedChecksum2 }; - [Test] - public void SerializeToByteArray_ReturnsExpectedBytes() - { - var expectedBytes = MakePubFileBytes(new List { 5556, 5554 }, - 9, - new U().WithID(1).WithName("TestFixture"), - new U().WithID(2).WithName("Test2"), - new U().WithID(3).WithName("Test3"), - new U().WithID(4).WithName("Test4"), - new U().WithID(5).WithName("Test5"), - new U().WithID(6).WithName("Test6"), - new U().WithID(7).WithName("Test7"), - new U().WithID(8).WithName("Test8"), - new U().WithID(9).WithName("eof")); - - var serializer = CreateSerializer(); - var file = serializer.DeserializeFromByteArray(1, expectedBytes, () => new T()); - - var actualBytes = serializer.SerializeToByteArray(file, rewriteChecksum: false); - - CollectionAssert.AreEqual(expectedBytes, actualBytes); - } - - [Test] - public void DeserializeFromByteArray_HasExpectedIDAndNames() + var records = new[] { - var records = new[] - { - new U().WithID(1).WithName("TestFixture"), - new U().WithID(2).WithName("Test2"), - new U().WithID(3).WithName("Test3"), - new U().WithID(4).WithName("Test4"), - new U().WithID(5).WithName("Test5"), - new U().WithID(6).WithName("Test6"), - new U().WithID(7).WithName("Test7"), - new U().WithID(8).WithName("Test8"), - new U().WithID(9).WithName("eof") - }; - var bytes = MakePubFileBytes(new List { 5556, 5554 }, 9, records); - - var serializer = CreateSerializer(); - var file = serializer.DeserializeFromByteArray(1, bytes, () => new T()); - - CollectionAssert.AreEqual(records.Select(x => new { x.ID, x.Name }).ToList(), - file.Select(x => new { x.ID, x.Name }).ToList()); - } - - private byte[] MakePubFileBytes(List checksum, int length, params IPubRecord[] records) - { - var numberEncoderService = new NumberEncoderService(); - var recordSerializer = new PubRecordSerializer(numberEncoderService); + new U().WithID(1).WithName("Rec_1"), + new U().WithID(2).WithName("Rec_2"), + new U().WithID(3).WithName("Rec_3"), + new U().WithID(4).WithName("Rec_4"), + }; - var bytes = new List(); - bytes.AddRange(Encoding.ASCII.GetBytes(new T().FileType)); - bytes.AddRange(checksum.SelectMany(x => numberEncoderService.EncodeNumber(x, 2))); - bytes.AddRange(numberEncoderService.EncodeNumber(length, 2)); - bytes.Add(numberEncoderService.EncodeNumber(1, 1)[0]); - foreach (var record in records) - bytes.AddRange(recordSerializer.SerializeToByteArray(record)); + var pubBytes = MakePubFileBytes(expectedChecksum, ExpectedLength, records); + var file = CreateSerializer().DeserializeFromByteArray(1, pubBytes, () => new T()); - return bytes.ToArray(); - } + Assert.That(file.CheckSum, Is.EqualTo(expectedChecksum)); + Assert.That(file.Length, Is.EqualTo(ExpectedLength)); + } - private static IPubFileSerializer CreateSerializer() + [Test] + public void SerializeToByteArray_ReturnsExpectedBytes() + { + var expectedBytes = MakePubFileBytes(new List { 5556, 5554 }, + 9, + new U().WithID(1).WithName("TestFixture"), + new U().WithID(2).WithName("Test2"), + new U().WithID(3).WithName("Test3"), + new U().WithID(4).WithName("Test4"), + new U().WithID(5).WithName("Test5"), + new U().WithID(6).WithName("Test6"), + new U().WithID(7).WithName("Test7"), + new U().WithID(8).WithName("Test8"), + new U().WithID(9).WithName("eof")); + + var serializer = CreateSerializer(); + var file = serializer.DeserializeFromByteArray(1, expectedBytes, () => new T()); + + var actualBytes = serializer.SerializeToByteArray(file, rewriteChecksum: false); + + CollectionAssert.AreEqual(expectedBytes, actualBytes); + } + + [Test] + public void DeserializeFromByteArray_HasExpectedIDAndNames() + { + var records = new[] { - return new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); - } + new U().WithID(1).WithName("TestFixture"), + new U().WithID(2).WithName("Test2"), + new U().WithID(3).WithName("Test3"), + new U().WithID(4).WithName("Test4"), + new U().WithID(5).WithName("Test5"), + new U().WithID(6).WithName("Test6"), + new U().WithID(7).WithName("Test7"), + new U().WithID(8).WithName("Test8"), + new U().WithID(9).WithName("eof") + }; + var bytes = MakePubFileBytes(new List { 5556, 5554 }, 9, records); + + var serializer = CreateSerializer(); + var file = serializer.DeserializeFromByteArray(1, bytes, () => new T()); + + CollectionAssert.AreEqual(records.Select(x => new { x.ID, x.Name }).ToList(), + file.Select(x => new { x.ID, x.Name }).ToList()); + } + + private byte[] MakePubFileBytes(List checksum, int length, params IPubRecord[] records) + { + var numberEncoderService = new NumberEncoderService(); + var recordSerializer = new PubRecordSerializer(numberEncoderService); + + var bytes = new List(); + bytes.AddRange(Encoding.ASCII.GetBytes(new T().FileType)); + bytes.AddRange(checksum.SelectMany(x => numberEncoderService.EncodeNumber(x, 2))); + bytes.AddRange(numberEncoderService.EncodeNumber(length, 2)); + bytes.Add(numberEncoderService.EncodeNumber(1, 1)[0]); + foreach (var record in records) + bytes.AddRange(recordSerializer.SerializeToByteArray(record)); + + return bytes.ToArray(); + } + + private static IPubFileSerializer CreateSerializer() + { + return new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); } } \ No newline at end of file diff --git a/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs b/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs index cc0efb3b0..0a0e4ee35 100644 --- a/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs +++ b/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs @@ -4,59 +4,58 @@ using NUnit.Framework; using System.Collections.Generic; -namespace EOLib.IO.Test.Services.Serializers -{ - [TestFixture] - public class PubRecordSerializerTest_EIFRecordImpl : PubRecordSerializerTest { } +namespace EOLib.IO.Test.Services.Serializers; + +[TestFixture] +public class PubRecordSerializerTest_EIFRecordImpl : PubRecordSerializerTest { } - [TestFixture] - public class PubRecordSerializerTest_ENFRecordImpl : PubRecordSerializerTest { } +[TestFixture] +public class PubRecordSerializerTest_ENFRecordImpl : PubRecordSerializerTest { } - [TestFixture] - public class PubRecordSerializerTest_ESFRecordImpl : PubRecordSerializerTest { } +[TestFixture] +public class PubRecordSerializerTest_ESFRecordImpl : PubRecordSerializerTest { } - [TestFixture] - public class PubRecordSerializerTest_ECFRecordImpl : PubRecordSerializerTest { } +[TestFixture] +public class PubRecordSerializerTest_ECFRecordImpl : PubRecordSerializerTest { } - public abstract class PubRecordSerializerTest - where T : class, IPubRecord, new() +public abstract class PubRecordSerializerTest + where T : class, IPubRecord, new() +{ + [Test] + public void SerializeAndDeserialize_HasExpectedProperties() { - [Test] - public void SerializeAndDeserialize_HasExpectedProperties() - { - var record = new T(); + var record = new T(); - var names = new List(); - for (int nameNdx = 0; nameNdx < record.NumberOfNames; nameNdx++) - names.Add($"name {nameNdx + 1}"); - record = (T)record.WithNames(names); + var names = new List(); + for (int nameNdx = 0; nameNdx < record.NumberOfNames; nameNdx++) + names.Add($"name {nameNdx + 1}"); + record = (T)record.WithNames(names); - int i = 1; - var expectedValues = new List<(PubRecordProperty Key, int Value)>(record.Bag.Count); - var offsets = new HashSet(); - foreach (var property in record.Bag.Keys) - { - // don't overwrite values for duplicate offsets (unions in records) - if (offsets.Contains(record.Bag[property].Offset)) - continue; + int i = 1; + var expectedValues = new List<(PubRecordProperty Key, int Value)>(record.Bag.Count); + var offsets = new HashSet(); + foreach (var property in record.Bag.Keys) + { + // don't overwrite values for duplicate offsets (unions in records) + if (offsets.Contains(record.Bag[property].Offset)) + continue; - offsets.Add(record.Bag[property].Offset); + offsets.Add(record.Bag[property].Offset); - record = (T)record.WithProperty(property, i); - expectedValues.Add((property, i++)); - } + record = (T)record.WithProperty(property, i); + expectedValues.Add((property, i++)); + } - var serializer = Create(); - var bytes = serializer.SerializeToByteArray(record); + var serializer = Create(); + var bytes = serializer.SerializeToByteArray(record); - var loadedRecord = serializer.DeserializeFromByteArray(bytes, () => new T()); + var loadedRecord = serializer.DeserializeFromByteArray(bytes, () => new T()); - Assert.That(record, Is.EqualTo(loadedRecord)); - } + Assert.That(record, Is.EqualTo(loadedRecord)); + } - private static IPubRecordSerializer Create() - { - return new PubRecordSerializer(new NumberEncoderService()); - } + private static IPubRecordSerializer Create() + { + return new PubRecordSerializer(new NumberEncoderService()); } } \ No newline at end of file diff --git a/EOLib.Localization.Test/DataFileLoadActionsTest.cs b/EOLib.Localization.Test/DataFileLoadActionsTest.cs index ae1b6cb45..92f43c242 100644 --- a/EOLib.Localization.Test/DataFileLoadActionsTest.cs +++ b/EOLib.Localization.Test/DataFileLoadActionsTest.cs @@ -2,77 +2,76 @@ using System.Diagnostics.CodeAnalysis; using System.IO; -namespace EOLib.Localization.Test +namespace EOLib.Localization.Test; + +[TestFixture, ExcludeFromCodeCoverage] +public class DataFileLoadActionsTest { - [TestFixture, ExcludeFromCodeCoverage] - public class DataFileLoadActionsTest - { - private IDataFileLoadActions _actions; - private IDataFileRepository _dataFileRepository; - private IEDFLoaderService _edfLoaderService; + private IDataFileLoadActions _actions; + private IDataFileRepository _dataFileRepository; + private IEDFLoaderService _edfLoaderService; - [SetUp] - public void SetUp() - { - _dataFileRepository = new DataFileRepository(); - _edfLoaderService = new EDFLoaderService(); - _actions = new DataFileLoadActions(_dataFileRepository, _edfLoaderService); - } + [SetUp] + public void SetUp() + { + _dataFileRepository = new DataFileRepository(); + _edfLoaderService = new EDFLoaderService(); + _actions = new DataFileLoadActions(_dataFileRepository, _edfLoaderService); + } - [TearDown] - public void TearDown() - { - if (Directory.Exists(DataFileConstants.DataFilePath)) - Directory.Delete(DataFileConstants.DataFilePath, true); - } + [TearDown] + public void TearDown() + { + if (Directory.Exists(DataFileConstants.DataFilePath)) + Directory.Delete(DataFileConstants.DataFilePath, true); + } - [Test] - public void GivenMissingDataDirectory_WhenLoadDataFiles_ExpectDataFileLoadException() - { - Assert.Throws(() => _actions.LoadDataFiles()); - } + [Test] + public void GivenMissingDataDirectory_WhenLoadDataFiles_ExpectDataFileLoadException() + { + Assert.Throws(() => _actions.LoadDataFiles()); + } - [Test] - public void GivenIncorrectNumberOfDataFiles_WhenLoadDataFiles_ExpectDataFileLoadException() - { - CreateRequiredDirectory(); - GivenEDFFilesInRequiredDirectory(5, "{0}.edf"); + [Test] + public void GivenIncorrectNumberOfDataFiles_WhenLoadDataFiles_ExpectDataFileLoadException() + { + CreateRequiredDirectory(); + GivenEDFFilesInRequiredDirectory(5, "{0}.edf"); - Assert.Throws(() => _actions.LoadDataFiles()); - } + Assert.Throws(() => _actions.LoadDataFiles()); + } - [Test] - public void WhenLoadDataFiles_DataFilesHaveIncorrectNameFormat_ExpectDataFileLoadException() - { - CreateRequiredDirectory(); - GivenEDFFilesInRequiredDirectory(nameFormat: "{0}.edf"); + [Test] + public void WhenLoadDataFiles_DataFilesHaveIncorrectNameFormat_ExpectDataFileLoadException() + { + CreateRequiredDirectory(); + GivenEDFFilesInRequiredDirectory(nameFormat: "{0}.edf"); - Assert.Throws(() => _actions.LoadDataFiles()); - } + Assert.Throws(() => _actions.LoadDataFiles()); + } - [Test] - public void WhenLoadDataFiles_RepositoryHasExpectedNumberOfFiles() - { - CreateRequiredDirectory(); - GivenEDFFilesInRequiredDirectory(); - _dataFileRepository.DataFiles.Add(DataFiles.Credits, new EDFFile(DataFiles.Credits)); + [Test] + public void WhenLoadDataFiles_RepositoryHasExpectedNumberOfFiles() + { + CreateRequiredDirectory(); + GivenEDFFilesInRequiredDirectory(); + _dataFileRepository.DataFiles.Add(DataFiles.Credits, new EDFFile(DataFiles.Credits)); - _actions.LoadDataFiles(); + _actions.LoadDataFiles(); - Assert.AreEqual(DataFileConstants.ExpectedNumberOfDataFiles, _dataFileRepository.DataFiles.Count); - } + Assert.AreEqual(DataFileConstants.ExpectedNumberOfDataFiles, _dataFileRepository.DataFiles.Count); + } - private void CreateRequiredDirectory() - { - if (!Directory.Exists(DataFileConstants.DataFilePath)) - Directory.CreateDirectory(DataFileConstants.DataFilePath); - } + private void CreateRequiredDirectory() + { + if (!Directory.Exists(DataFileConstants.DataFilePath)) + Directory.CreateDirectory(DataFileConstants.DataFilePath); + } - private void GivenEDFFilesInRequiredDirectory(int numberOfFiles = DataFileConstants.ExpectedNumberOfDataFiles, - string nameFormat = "dat0{0:00}.edf") - { - for (int i = 1; i <= numberOfFiles; ++i) - File.Create(string.Format(Path.Combine(DataFileConstants.DataFilePath, nameFormat), i)).Close(); - } + private void GivenEDFFilesInRequiredDirectory(int numberOfFiles = DataFileConstants.ExpectedNumberOfDataFiles, + string nameFormat = "dat0{0:00}.edf") + { + for (int i = 1; i <= numberOfFiles; ++i) + File.Create(string.Format(Path.Combine(DataFileConstants.DataFilePath, nameFormat), i)).Close(); } } \ No newline at end of file diff --git a/EOLib.Localization.Test/EDFLoaderServiceTest.cs b/EOLib.Localization.Test/EDFLoaderServiceTest.cs index 763494618..a3911ee6e 100644 --- a/EOLib.Localization.Test/EDFLoaderServiceTest.cs +++ b/EOLib.Localization.Test/EDFLoaderServiceTest.cs @@ -5,205 +5,204 @@ using System.IO; using System.Linq; -namespace EOLib.Localization.Test +namespace EOLib.Localization.Test; + +[TestFixture, ExcludeFromCodeCoverage] +public class EDFLoaderServiceTest { - [TestFixture, ExcludeFromCodeCoverage] - public class EDFLoaderServiceTest + private const string FILE_NAME = "test.edf"; + + private IEDFLoaderService _edfLoaderService; + + [SetUp] + public void SetUp() { - private const string FILE_NAME = "test.edf"; + _edfLoaderService = new EDFLoaderService(); + } - private IEDFLoaderService _edfLoaderService; + public void TearDown() + { + if (File.Exists(FILE_NAME)) + File.Delete(FILE_NAME); + } - [SetUp] - public void SetUp() - { - _edfLoaderService = new EDFLoaderService(); - } + [Test] + public void GivenNonExistingFile_Load_ExpectFileNotFoundException() + { + Assert.Throws(() => _edfLoaderService.LoadFile("fileThatDoesNotExist", DataFiles.Checksum)); + } - public void TearDown() - { - if (File.Exists(FILE_NAME)) - File.Delete(FILE_NAME); - } + [Test] + public void GivenCurseFile_DecodeStringDelimitedByColons() + { + const string curseString = "CsusrAs:e5:4C3uErSsReU2C:"; + GivenDataFileWithContents(FILE_NAME, curseString); - [Test] - public void GivenNonExistingFile_Load_ExpectFileNotFoundException() - { - Assert.Throws(() => _edfLoaderService.LoadFile("fileThatDoesNotExist", DataFiles.Checksum)); - } + var file = _edfLoaderService.LoadFile(FILE_NAME, DataFiles.CurseFilter); - [Test] - public void GivenCurseFile_DecodeStringDelimitedByColons() + var expectedCurses = new[] { - const string curseString = "CsusrAs:e5:4C3uErSsReU2C:"; - GivenDataFileWithContents(FILE_NAME, curseString); + "Curse", "Curse2", "CURSE345", "Ass" + }; - var file = _edfLoaderService.LoadFile(FILE_NAME, DataFiles.CurseFilter); + CollectionAssert.AreEqual(expectedCurses, file.Data.Values); + } - var expectedCurses = new[] - { - "Curse", "Curse2", "CURSE345", "Ass" - }; + [Test] + public void GivenCurseFile_EncodeStringDelimitedByColons() + { + const string ExpectedCurseString = "CsusrAs:e5:4C3uErSsReU2C:"; - CollectionAssert.AreEqual(expectedCurses, file.Data.Values); - } + var curses = new[] { "Curse", "Curse2", "CURSE345", "Ass" }; + var edfFile = new EDFFile(DataFiles.CurseFilter, new Dictionary(curses.Select((x, i) => KeyValuePair.Create(i, x)))); - [Test] - public void GivenCurseFile_EncodeStringDelimitedByColons() - { - const string ExpectedCurseString = "CsusrAs:e5:4C3uErSsReU2C:"; + _edfLoaderService.SaveFile(FILE_NAME, edfFile); - var curses = new[] { "Curse", "Curse2", "CURSE345", "Ass" }; - var edfFile = new EDFFile(DataFiles.CurseFilter, new Dictionary(curses.Select((x, i) => KeyValuePair.Create(i, x)))); + AssertFileContent(FILE_NAME, ExpectedCurseString); + } - _edfLoaderService.SaveFile(FILE_NAME, edfFile); + [Test] + public void GivenCurseFile_DecodeStringDelimitedByColons_HandlesMultipleLines() + { + const string curseString = "CsusrAs:e5:4C3uErSsReU2C:\nARBQCPDOEN:MF:GLHKIJ:"; + GivenDataFileWithContents(FILE_NAME, curseString); - AssertFileContent(FILE_NAME, ExpectedCurseString); - } + var file = _edfLoaderService.LoadFile(FILE_NAME, DataFiles.CurseFilter); - [Test] - public void GivenCurseFile_DecodeStringDelimitedByColons_HandlesMultipleLines() + var expectedCurses = new[] { - const string curseString = "CsusrAs:e5:4C3uErSsReU2C:\nARBQCPDOEN:MF:GLHKIJ:"; - GivenDataFileWithContents(FILE_NAME, curseString); + "Curse", "Curse2", "CURSE345", "Ass", + "ABCDE", "FGHI", "JKL", "MNOPQR" + }; - var file = _edfLoaderService.LoadFile(FILE_NAME, DataFiles.CurseFilter); + CollectionAssert.AreEqual(expectedCurses, file.Data.Values); + } - var expectedCurses = new[] - { - "Curse", "Curse2", "CURSE345", "Ass", - "ABCDE", "FGHI", "JKL", "MNOPQR" - }; + [TestCase(DataFiles.Credits, "Created By\nMe :)\nMe again!")] + [TestCase(DataFiles.Checksum, "218:13:2:176")] + public void GivenUnencodedFile_DoesNotDecodeFileContents_SplitsByLines(DataFiles whichFile, string content) + { + GivenDataFileWithContents(FILE_NAME, content); - CollectionAssert.AreEqual(expectedCurses, file.Data.Values); - } + var file = _edfLoaderService.LoadFile(FILE_NAME, whichFile); - [TestCase(DataFiles.Credits, "Created By\nMe :)\nMe again!")] - [TestCase(DataFiles.Checksum, "218:13:2:176")] - public void GivenUnencodedFile_DoesNotDecodeFileContents_SplitsByLines(DataFiles whichFile, string content) - { - GivenDataFileWithContents(FILE_NAME, content); + var expectedLines = content.Split('\n'); + CollectionAssert.AreEqual(expectedLines, file.Data.Values); + } - var file = _edfLoaderService.LoadFile(FILE_NAME, whichFile); + [TestCase(DataFiles.Credits, new[] { "Created By", "Me :)", "Me again!" })] + [TestCase(DataFiles.Checksum, new[] { "218:13:2:176" })] + public void GivenUnencodedFile_DoesNotEncodeFileContents_SplitsByDataKeys(DataFiles whichFile, string[] content) + { + var edfFile = new EDFFile(whichFile, new Dictionary(content.Select((x, i) => KeyValuePair.Create(i, x)))); - var expectedLines = content.Split('\n'); - CollectionAssert.AreEqual(expectedLines, file.Data.Values); - } + _edfLoaderService.SaveFile(FILE_NAME, edfFile); - [TestCase(DataFiles.Credits, new[] { "Created By", "Me :)", "Me again!" })] - [TestCase(DataFiles.Checksum, new[] { "218:13:2:176" })] - public void GivenUnencodedFile_DoesNotEncodeFileContents_SplitsByDataKeys(DataFiles whichFile, string[] content) - { - var edfFile = new EDFFile(whichFile, new Dictionary(content.Select((x, i) => KeyValuePair.Create(i, x)))); + AssertFileContent(FILE_NAME, string.Join(Environment.NewLine, content)); + } - _edfLoaderService.SaveFile(FILE_NAME, edfFile); + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_AreDecodedCorrectly(DataFiles whichFile) + { + const string fileData = "a7b6cg1f2e3d4 5"; + const string expectedString = "abc12345 defg67"; - AssertFileContent(FILE_NAME, string.Join(Environment.NewLine, content)); - } + GivenDataFileWithContents(FILE_NAME, fileData); - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_AreDecodedCorrectly(DataFiles whichFile) - { - const string fileData = "a7b6cg1f2e3d4 5"; - const string expectedString = "abc12345 defg67"; - - GivenDataFileWithContents(FILE_NAME, fileData); + var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); + Assert.AreEqual(expectedString, edf.Data.Values.Single()); + } - var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); - Assert.AreEqual(expectedString, edf.Data.Values.Single()); - } + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_AreDecodedCorrectly_MultipleLines(DataFiles whichFile) + { + const string fileData = "a7b6cg1f2e3d4 5\na7b6cg1f2e3d4 5"; + var expectedStrings = new[] { "abc12345 defg67", "abc12345 defg67" }; - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_AreDecodedCorrectly_MultipleLines(DataFiles whichFile) - { - const string fileData = "a7b6cg1f2e3d4 5\na7b6cg1f2e3d4 5"; - var expectedStrings = new[] { "abc12345 defg67", "abc12345 defg67" }; + GivenDataFileWithContents(FILE_NAME, fileData); - GivenDataFileWithContents(FILE_NAME, fileData); + var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); + CollectionAssert.AreEqual(expectedStrings, edf.Data.Values); + } - var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); - CollectionAssert.AreEqual(expectedStrings, edf.Data.Values); - } + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_Decode_SwapAdjacentCharacterValues_MultiplesOfSeven(DataFiles whichFile) + { + //p, p, and i are adjacent multiples of 7 in this example + //see https://eoserv.net/wiki/EDF_Data_Files for more info + //the expected string would be Crazy steippng without this step + const string fileData = "Cgrnapzpyi est"; + var expectedString = "Crazy stepping"; - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_Decode_SwapAdjacentCharacterValues_MultiplesOfSeven(DataFiles whichFile) - { - //p, p, and i are adjacent multiples of 7 in this example - //see https://eoserv.net/wiki/EDF_Data_Files for more info - //the expected string would be Crazy steippng without this step - const string fileData = "Cgrnapzpyi est"; - var expectedString = "Crazy stepping"; + GivenDataFileWithContents(FILE_NAME, fileData); - GivenDataFileWithContents(FILE_NAME, fileData); + var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); + Assert.AreEqual(expectedString, edf.Data.Values.Single()); + } - var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); - Assert.AreEqual(expectedString, edf.Data.Values.Single()); - } + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_AreEncodedCorrectly(DataFiles whichFile) + { + const string ExpectedFileData = "a7b6cg1f2e3d4 5"; - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_AreEncodedCorrectly(DataFiles whichFile) - { - const string ExpectedFileData = "a7b6cg1f2e3d4 5"; + const string Input = "abc12345 defg67"; + var edfFile = new EDFFile(whichFile, new Dictionary { { 0, Input } }); - const string Input = "abc12345 defg67"; - var edfFile = new EDFFile(whichFile, new Dictionary { { 0, Input } }); + _edfLoaderService.SaveFile(FILE_NAME, edfFile); - _edfLoaderService.SaveFile(FILE_NAME, edfFile); + AssertFileContent(FILE_NAME, ExpectedFileData); + } - AssertFileContent(FILE_NAME, ExpectedFileData); - } + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_AreEncodedCorrectly_MultipleLines(DataFiles whichFile) + { + var expectedFileData = $"a7b6cg1f2e3d4 5{Environment.NewLine}a7b6cg1f2e3d4 5"; - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_AreEncodedCorrectly_MultipleLines(DataFiles whichFile) - { - var expectedFileData = $"a7b6cg1f2e3d4 5{Environment.NewLine}a7b6cg1f2e3d4 5"; + var decodedStrings = new Dictionary { { 0, "abc12345 defg67" }, { 1, "abc12345 defg67" } }; + var edfFile = new EDFFile(whichFile, decodedStrings); - var decodedStrings = new Dictionary { { 0, "abc12345 defg67" }, { 1, "abc12345 defg67" } }; - var edfFile = new EDFFile(whichFile, decodedStrings); + _edfLoaderService.SaveFile(FILE_NAME, edfFile); - _edfLoaderService.SaveFile(FILE_NAME, edfFile); + AssertFileContent(FILE_NAME, expectedFileData); + } - AssertFileContent(FILE_NAME, expectedFileData); - } + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_Encode_SwapAdjacentCharacterValues_MultiplesOfSeven(DataFiles whichFile) + { + const string ExpectedFileData = "Cgrnapzpyi est"; - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_Encode_SwapAdjacentCharacterValues_MultiplesOfSeven(DataFiles whichFile) - { - const string ExpectedFileData = "Cgrnapzpyi est"; + const string Input = "Crazy stepping"; + var edfFile = new EDFFile(whichFile, new Dictionary { { 0, Input } }); - const string Input = "Crazy stepping"; - var edfFile = new EDFFile(whichFile, new Dictionary { { 0, Input } }); + _edfLoaderService.SaveFile(FILE_NAME, edfFile); - _edfLoaderService.SaveFile(FILE_NAME, edfFile); + AssertFileContent(FILE_NAME, ExpectedFileData); + } - AssertFileContent(FILE_NAME, ExpectedFileData); - } + public static DataFiles[] GetStandardEDFFiles() + { + return new[] + { + DataFiles.JukeBoxSongs, + DataFiles.EnglishStatus1, + DataFiles.EnglishStatus2, + DataFiles.DutchStatus1, + DataFiles.DutchStatus2, + DataFiles.SwedishStatus1, + DataFiles.SwedishStatus2, + DataFiles.PortugueseStatus1, + DataFiles.PortugueseStatus2 + }; + } - public static DataFiles[] GetStandardEDFFiles() - { - return new[] - { - DataFiles.JukeBoxSongs, - DataFiles.EnglishStatus1, - DataFiles.EnglishStatus2, - DataFiles.DutchStatus1, - DataFiles.DutchStatus2, - DataFiles.SwedishStatus1, - DataFiles.SwedishStatus2, - DataFiles.PortugueseStatus1, - DataFiles.PortugueseStatus2 - }; - } - - private void GivenDataFileWithContents(string fileName, string fileData) - { - File.WriteAllText(fileName, fileData); - } + private void GivenDataFileWithContents(string fileName, string fileData) + { + File.WriteAllText(fileName, fileData); + } - private void AssertFileContent(string fileName, string fileData) - { - var text = File.ReadAllText(fileName).Trim(); - Assert.That(text, Is.EqualTo(fileData)); - } + private void AssertFileContent(string fileName, string fileData) + { + var text = File.ReadAllText(fileName).Trim(); + Assert.That(text, Is.EqualTo(fileData)); } } \ No newline at end of file diff --git a/EOLib.Localization.Test/LocalizedStringServiceTest.cs b/EOLib.Localization.Test/LocalizedStringServiceTest.cs index 389b1ef31..ada9ede7a 100644 --- a/EOLib.Localization.Test/LocalizedStringServiceTest.cs +++ b/EOLib.Localization.Test/LocalizedStringServiceTest.cs @@ -5,130 +5,129 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -namespace EOLib.Localization.Test +namespace EOLib.Localization.Test; + +[TestFixture, ExcludeFromCodeCoverage] +public class LocalizedStringFinderTest { - [TestFixture, ExcludeFromCodeCoverage] - public class LocalizedStringFinderTest + private IConfigurationProvider _configurationProvider; + private DataFileRepository _dataFileRepository; + + private ILocalizedStringFinder _localizedStringFinder; + + [SetUp] + public void SetUp() + { + _configurationProvider = Mock.Of(); + _dataFileRepository = new DataFileRepository(); + + _localizedStringFinder = new LocalizedStringFinder( + _configurationProvider, + _dataFileRepository); + } + + [Test] + public void GetString_Dialog_InvalidLanguage_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => _localizedStringFinder.GetString((EOLanguage)50, DialogResourceID.ACCOUNT_CREATE_ACCEPTED)); + } + + [Test] + public void GetString_Resource_InvalidLanguage_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => _localizedStringFinder.GetString((EOLanguage)50, EOResourceID.STRING_SERVER)); + } + + [Test] + public void GetString_DialogID_ByLanguage_MapsToCorrectFile() + { + const DialogResourceID testID = DialogResourceID.ACCOUNT_CREATE_ACCEPTED; + + GivenFileHasStringForResourceID(DataFiles.DutchStatus1, testID, "dutch"); + GivenFileHasStringForResourceID(DataFiles.EnglishStatus1, testID, "english"); + GivenFileHasStringForResourceID(DataFiles.PortugueseStatus1, testID, "portuguese"); + GivenFileHasStringForResourceID(DataFiles.SwedishStatus1, testID, "swedish"); + + var dutchActual = _localizedStringFinder.GetString(EOLanguage.Dutch, testID); + var englishActual = _localizedStringFinder.GetString(EOLanguage.English, testID); + var portugueseActual = _localizedStringFinder.GetString(EOLanguage.Portuguese, testID); + var swedishActual = _localizedStringFinder.GetString(EOLanguage.Swedish, testID); + + Assert.AreEqual("dutch", dutchActual); + Assert.AreEqual("english", englishActual); + Assert.AreEqual("portuguese", portugueseActual); + Assert.AreEqual("swedish", swedishActual); + } + + [Test] + public void GetString_ResourceID_ByLanguage_MapsToCorrectFile() + { + const EOResourceID testID = EOResourceID.STATUS_LABEL_YOU_GAINED_EXP; + + GivenFileHasStringForResourceID(DataFiles.DutchStatus2, testID, "dutch"); + GivenFileHasStringForResourceID(DataFiles.EnglishStatus2, testID, "english"); + GivenFileHasStringForResourceID(DataFiles.PortugueseStatus2, testID, "portuguese"); + GivenFileHasStringForResourceID(DataFiles.SwedishStatus2, testID, "swedish"); + + var dutchActual = _localizedStringFinder.GetString(EOLanguage.Dutch, testID); + var englishActual = _localizedStringFinder.GetString(EOLanguage.English, testID); + var portugueseActual = _localizedStringFinder.GetString(EOLanguage.Portuguese, testID); + var swedishActual = _localizedStringFinder.GetString(EOLanguage.Swedish, testID); + + Assert.AreEqual("dutch", dutchActual); + Assert.AreEqual("english", englishActual); + Assert.AreEqual("portuguese", portugueseActual); + Assert.AreEqual("swedish", swedishActual); + } + + [Test] + public void GetString_DialogID_UsesLanguageSetInConfig() + { + const DialogResourceID testID = DialogResourceID.ACCOUNT_CREATE_ACCEPTED; + const string expectedResourceString = "language test"; + + GivenLanguageSetInConfig(EOLanguage.Dutch); + GivenFileHasStringForResourceID(DataFiles.DutchStatus1, testID, expectedResourceString); + + var actualString = _localizedStringFinder.GetString(testID); + + Assert.AreEqual(expectedResourceString, actualString); + } + + [Test] + public void GetString_ResourceID_UsesLanguageSetInConfig() + { + const EOResourceID testID = EOResourceID.STRING_SERVER; + const string expectedResourceString = "language test"; + + GivenLanguageSetInConfig(EOLanguage.Dutch); + GivenFileHasStringForResourceID(DataFiles.DutchStatus2, testID, expectedResourceString); + + var actualString = _localizedStringFinder.GetString(testID); + + Assert.AreEqual(expectedResourceString, actualString); + } + + private void GivenFileHasStringForResourceID(DataFiles file, DialogResourceID id, string str) + { + if (!_dataFileRepository.DataFiles.ContainsKey(file)) + _dataFileRepository.DataFiles.Add(file, new EDFFile(file)); + + _dataFileRepository.DataFiles[file] = _dataFileRepository.DataFiles[file].WithDataEntry((int)id, str); + } + + private void GivenFileHasStringForResourceID(DataFiles file, EOResourceID id, string str) + { + if (!_dataFileRepository.DataFiles.ContainsKey(file)) + _dataFileRepository.DataFiles.Add(file, new EDFFile(file)); + + _dataFileRepository.DataFiles[file] = _dataFileRepository.DataFiles[file].WithDataEntry((int)id, str); + } + + private void GivenLanguageSetInConfig(EOLanguage language) { - private IConfigurationProvider _configurationProvider; - private DataFileRepository _dataFileRepository; - - private ILocalizedStringFinder _localizedStringFinder; - - [SetUp] - public void SetUp() - { - _configurationProvider = Mock.Of(); - _dataFileRepository = new DataFileRepository(); - - _localizedStringFinder = new LocalizedStringFinder( - _configurationProvider, - _dataFileRepository); - } - - [Test] - public void GetString_Dialog_InvalidLanguage_ThrowsArgumentOutOfRangeException() - { - Assert.Throws(() => _localizedStringFinder.GetString((EOLanguage)50, DialogResourceID.ACCOUNT_CREATE_ACCEPTED)); - } - - [Test] - public void GetString_Resource_InvalidLanguage_ThrowsArgumentOutOfRangeException() - { - Assert.Throws(() => _localizedStringFinder.GetString((EOLanguage)50, EOResourceID.STRING_SERVER)); - } - - [Test] - public void GetString_DialogID_ByLanguage_MapsToCorrectFile() - { - const DialogResourceID testID = DialogResourceID.ACCOUNT_CREATE_ACCEPTED; - - GivenFileHasStringForResourceID(DataFiles.DutchStatus1, testID, "dutch"); - GivenFileHasStringForResourceID(DataFiles.EnglishStatus1, testID, "english"); - GivenFileHasStringForResourceID(DataFiles.PortugueseStatus1, testID, "portuguese"); - GivenFileHasStringForResourceID(DataFiles.SwedishStatus1, testID, "swedish"); - - var dutchActual = _localizedStringFinder.GetString(EOLanguage.Dutch, testID); - var englishActual = _localizedStringFinder.GetString(EOLanguage.English, testID); - var portugueseActual = _localizedStringFinder.GetString(EOLanguage.Portuguese, testID); - var swedishActual = _localizedStringFinder.GetString(EOLanguage.Swedish, testID); - - Assert.AreEqual("dutch", dutchActual); - Assert.AreEqual("english", englishActual); - Assert.AreEqual("portuguese", portugueseActual); - Assert.AreEqual("swedish", swedishActual); - } - - [Test] - public void GetString_ResourceID_ByLanguage_MapsToCorrectFile() - { - const EOResourceID testID = EOResourceID.STATUS_LABEL_YOU_GAINED_EXP; - - GivenFileHasStringForResourceID(DataFiles.DutchStatus2, testID, "dutch"); - GivenFileHasStringForResourceID(DataFiles.EnglishStatus2, testID, "english"); - GivenFileHasStringForResourceID(DataFiles.PortugueseStatus2, testID, "portuguese"); - GivenFileHasStringForResourceID(DataFiles.SwedishStatus2, testID, "swedish"); - - var dutchActual = _localizedStringFinder.GetString(EOLanguage.Dutch, testID); - var englishActual = _localizedStringFinder.GetString(EOLanguage.English, testID); - var portugueseActual = _localizedStringFinder.GetString(EOLanguage.Portuguese, testID); - var swedishActual = _localizedStringFinder.GetString(EOLanguage.Swedish, testID); - - Assert.AreEqual("dutch", dutchActual); - Assert.AreEqual("english", englishActual); - Assert.AreEqual("portuguese", portugueseActual); - Assert.AreEqual("swedish", swedishActual); - } - - [Test] - public void GetString_DialogID_UsesLanguageSetInConfig() - { - const DialogResourceID testID = DialogResourceID.ACCOUNT_CREATE_ACCEPTED; - const string expectedResourceString = "language test"; - - GivenLanguageSetInConfig(EOLanguage.Dutch); - GivenFileHasStringForResourceID(DataFiles.DutchStatus1, testID, expectedResourceString); - - var actualString = _localizedStringFinder.GetString(testID); - - Assert.AreEqual(expectedResourceString, actualString); - } - - [Test] - public void GetString_ResourceID_UsesLanguageSetInConfig() - { - const EOResourceID testID = EOResourceID.STRING_SERVER; - const string expectedResourceString = "language test"; - - GivenLanguageSetInConfig(EOLanguage.Dutch); - GivenFileHasStringForResourceID(DataFiles.DutchStatus2, testID, expectedResourceString); - - var actualString = _localizedStringFinder.GetString(testID); - - Assert.AreEqual(expectedResourceString, actualString); - } - - private void GivenFileHasStringForResourceID(DataFiles file, DialogResourceID id, string str) - { - if (!_dataFileRepository.DataFiles.ContainsKey(file)) - _dataFileRepository.DataFiles.Add(file, new EDFFile(file)); - - _dataFileRepository.DataFiles[file] = _dataFileRepository.DataFiles[file].WithDataEntry((int)id, str); - } - - private void GivenFileHasStringForResourceID(DataFiles file, EOResourceID id, string str) - { - if (!_dataFileRepository.DataFiles.ContainsKey(file)) - _dataFileRepository.DataFiles.Add(file, new EDFFile(file)); - - _dataFileRepository.DataFiles[file] = _dataFileRepository.DataFiles[file].WithDataEntry((int)id, str); - } - - private void GivenLanguageSetInConfig(EOLanguage language) - { - Mock.Get(_configurationProvider) - .Setup(x => x.Language) - .Returns(language); - } + Mock.Get(_configurationProvider) + .Setup(x => x.Language) + .Returns(language); } } \ No newline at end of file diff --git a/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs b/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs index 390f36ff0..0a2d76fc0 100644 --- a/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs +++ b/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs @@ -19,263 +19,262 @@ using System.Linq; using System.Text; -namespace EOLib.Test.Net.FileTransfer +namespace EOLib.Test.Net.FileTransfer; + +[TestFixture, ExcludeFromCodeCoverage] +public class FileRequestServiceTest { - [TestFixture, ExcludeFromCodeCoverage] - public class FileRequestServiceTest - { - private IFileRequestService _fileRequestService; + private IFileRequestService _fileRequestService; - private IPacketSendService _packetSendService; - private INumberEncoderService _numberEncoderService; - private IMapDeserializer _mapFileSerializer; - private IPubFileDeserializer _pubFileDeserializer; + private IPacketSendService _packetSendService; + private INumberEncoderService _numberEncoderService; + private IMapDeserializer _mapFileSerializer; + private IPubFileDeserializer _pubFileDeserializer; - [SetUp] - public void SetUp() - { - _packetSendService = Mock.Of(); - _numberEncoderService = new NumberEncoderService(); - _mapFileSerializer = Mock.Of>(); - _pubFileDeserializer = Mock.Of(); - - _fileRequestService = new FileRequestService(_packetSendService, - _mapFileSerializer, - _pubFileDeserializer); - } + [SetUp] + public void SetUp() + { + _packetSendService = Mock.Of(); + _numberEncoderService = new NumberEncoderService(); + _mapFileSerializer = Mock.Of>(); + _pubFileDeserializer = Mock.Of(); + + _fileRequestService = new FileRequestService(_packetSendService, + _mapFileSerializer, + _pubFileDeserializer); + } - #region RequestFile Tests + #region RequestFile Tests - [Test] - public void RequestFile_ResponsePacketHasInvalidHeader_ThrowsEmptyPacketReceivedException() - { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(); - Assert.ThrowsAsync(async () => await _fileRequestService.RequestFile(FileType.Eif, 1)); - } + [Test] + public void RequestFile_ResponsePacketHasInvalidHeader_ThrowsEmptyPacketReceivedException() + { + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(); + Assert.ThrowsAsync(async () => await _fileRequestService.RequestFile(FileType.Eif, 1)); + } - [Test] - public void RequestFile_ResponsePacketInvalidExtraByte_ThrowsMalformedPacketException() - { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader((byte)InitReply.FileEif, 33); - Assert.ThrowsAsync(async () => await _fileRequestService.RequestFile(FileType.Eif, 1)); - } + [Test] + public void RequestFile_ResponsePacketInvalidExtraByte_ThrowsMalformedPacketException() + { + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader((byte)InitReply.FileEif, 33); + Assert.ThrowsAsync(async () => await _fileRequestService.RequestFile(FileType.Eif, 1)); + } - [Test] - public void RequestFile_SendsPacket_BasedOnSpecifiedType() + [Test] + public void RequestFile_SendsPacket_BasedOnSpecifiedType() + { + var types = new[] { FileType.Eif, FileType.Enf, FileType.Esf, FileType.Ecf }; + foreach (var type in types) { - var types = new[] { FileType.Eif, FileType.Enf, FileType.Esf, FileType.Ecf }; - foreach (var type in types) - { - var packetIsCorrect = false; - var localType = type; - Mock.Get(_packetSendService).Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) - .Callback((IPacket packet) => packetIsCorrect = IsCorrectFileRequestPacket(packet, localType)); + var packetIsCorrect = false; + var localType = type; + Mock.Get(_packetSendService).Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) + .Callback((IPacket packet) => packetIsCorrect = IsCorrectFileRequestPacket(packet, localType)); - _fileRequestService.RequestFile(type, 1); + _fileRequestService.RequestFile(type, 1); - Assert.IsTrue(packetIsCorrect, "Incorrect packet for {0}", type); - } + Assert.IsTrue(packetIsCorrect, "Incorrect packet for {0}", type); } + } - [Test] - public void RequestFile_CorrectResponse_ExecutesWithoutFault() + [Test] + public void RequestFile_CorrectResponse_ExecutesWithoutFault() + { + var types = new[] { FileType.Eif, FileType.Enf, FileType.Esf, FileType.Ecf }; + foreach (var type in types) { - var types = new[] { FileType.Eif, FileType.Enf, FileType.Esf, FileType.Ecf }; - foreach (var type in types) - { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(CreateFilePacket(type)); + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(CreateFilePacket(type)); - AggregateException aggEx = null; - switch (type) - { - case FileType.Eif: - Mock.Get(_pubFileDeserializer) - .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) - .Returns(new EIFFile()); - aggEx = _fileRequestService.RequestFile(type, 1).Exception; - break; - case FileType.Enf: - Mock.Get(_pubFileDeserializer) - .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) - .Returns(new ENFFile()); - aggEx = _fileRequestService.RequestFile(type, 1).Exception; - break; - case FileType.Esf: - Mock.Get(_pubFileDeserializer) - .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) - .Returns(new ESFFile()); - aggEx = _fileRequestService.RequestFile(type, 1).Exception; - break; - case FileType.Ecf: - Mock.Get(_pubFileDeserializer) - .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) - .Returns(new ECFFile()); - aggEx = _fileRequestService.RequestFile(type, 1).Exception; - break; - } - - if (aggEx != null) - throw aggEx.InnerException; + AggregateException aggEx = null; + switch (type) + { + case FileType.Eif: + Mock.Get(_pubFileDeserializer) + .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) + .Returns(new EIFFile()); + aggEx = _fileRequestService.RequestFile(type, 1).Exception; + break; + case FileType.Enf: + Mock.Get(_pubFileDeserializer) + .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) + .Returns(new ENFFile()); + aggEx = _fileRequestService.RequestFile(type, 1).Exception; + break; + case FileType.Esf: + Mock.Get(_pubFileDeserializer) + .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) + .Returns(new ESFFile()); + aggEx = _fileRequestService.RequestFile(type, 1).Exception; + break; + case FileType.Ecf: + Mock.Get(_pubFileDeserializer) + .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) + .Returns(new ECFFile()); + aggEx = _fileRequestService.RequestFile(type, 1).Exception; + break; } - } - #endregion - - #region RequestMapFile Tests - - [Test] - public void RequestMapFile_ResponsePacketHasInvalidHeader_ThrowsEmptyPacketReceivedException() - { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(); - Assert.ThrowsAsync(async () => await _fileRequestService.RequestMapFile(1, 1)); + if (aggEx != null) + throw aggEx.InnerException; } + } - [Test] - public void RequestMapFile_ResponsePacketHasIncorrectFileType_ThrowsMalformedPacketException() - { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader((byte)InitReply.FileEsf, 33); - Assert.ThrowsAsync(async () => await _fileRequestService.RequestMapFile(1, 1)); - } + #endregion - [Test] - public void RequestMapFile_SendsPacket_BasedOnSpecifiedMap() - { - var packetIsCorrect = false; - Mock.Get(_packetSendService).Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())).Callback((IPacket packet) => packetIsCorrect = IsCorrectFileRequestPacket(packet, FileType.Emf)); + #region RequestMapFile Tests + + [Test] + public void RequestMapFile_ResponsePacketHasInvalidHeader_ThrowsEmptyPacketReceivedException() + { + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(); + Assert.ThrowsAsync(async () => await _fileRequestService.RequestMapFile(1, 1)); + } - _fileRequestService.RequestMapFile(1, 1); + [Test] + public void RequestMapFile_ResponsePacketHasIncorrectFileType_ThrowsMalformedPacketException() + { + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader((byte)InitReply.FileEsf, 33); + Assert.ThrowsAsync(async () => await _fileRequestService.RequestMapFile(1, 1)); + } - Assert.That(packetIsCorrect, Is.True); - } + [Test] + public void RequestMapFile_SendsPacket_BasedOnSpecifiedMap() + { + var packetIsCorrect = false; + Mock.Get(_packetSendService).Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())).Callback((IPacket packet) => packetIsCorrect = IsCorrectFileRequestPacket(packet, FileType.Emf)); - [Test] - public void RequestMapFile_HasPlayerAndMapID() - { - const short PlayerID = 1234; - const short MapID = 333; + _fileRequestService.RequestMapFile(1, 1); - var packetIsCorrect = false; - Mock.Get(_packetSendService) - .Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) - .Callback((IPacket p) => packetIsCorrect = IsCorrectFileRequestPacket(p, FileType.Emf, PlayerID, MapID)); + Assert.That(packetIsCorrect, Is.True); + } - _fileRequestService.RequestMapFile(MapID, PlayerID); + [Test] + public void RequestMapFile_HasPlayerAndMapID() + { + const short PlayerID = 1234; + const short MapID = 333; - Assert.That(packetIsCorrect, Is.True); - } + var packetIsCorrect = false; + Mock.Get(_packetSendService) + .Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) + .Callback((IPacket p) => packetIsCorrect = IsCorrectFileRequestPacket(p, FileType.Emf, PlayerID, MapID)); - #endregion + _fileRequestService.RequestMapFile(MapID, PlayerID); - #region Helper Methods + Assert.That(packetIsCorrect, Is.True); + } - private static bool IsCorrectFileRequestPacket(IPacket packet, FileType type, short sessionId = 0, short mapId = 0) - { - var waPacket = packet as WelcomeAgreeClientPacket; - var correctTyping = waPacket.FileType == type; + #endregion - var correctData = true; - if (mapId > 0 && sessionId > 0) - { - var emfData = waPacket.FileTypeData as WelcomeAgreeClientPacket.FileTypeDataEmf; - correctData = emfData.FileId == mapId && waPacket.SessionId == sessionId; - } + #region Helper Methods - return correctTyping && correctData; - } + private static bool IsCorrectFileRequestPacket(IPacket packet, FileType type, short sessionId = 0, short mapId = 0) + { + var waPacket = packet as WelcomeAgreeClientPacket; + var correctTyping = waPacket.FileType == type; - private static byte[] CreateFilePacket(FileType type) + var correctData = true; + if (mapId > 0 && sessionId > 0) { - var ret = new InitInitServerPacket(); + var emfData = waPacket.FileTypeData as WelcomeAgreeClientPacket.FileTypeDataEmf; + correctData = emfData.FileId == mapId && waPacket.SessionId == sessionId; + } - var nes = new NumberEncoderService(); - var rs = new PubRecordSerializer(nes); + return correctTyping && correctData; + } - var eoWriter = new EoWriter(); - switch (type) - { - case FileType.Eif: - ret.ReplyCode = InitReply.FileEif; + private static byte[] CreateFilePacket(FileType type) + { + var ret = new InitInitServerPacket(); - eoWriter.AddString("EIF"); - eoWriter.AddInt(1); // RID - eoWriter.AddShort(2); // length - eoWriter.AddByte(1); // version - eoWriter.AddBytes(rs.SerializeToByteArray(new EIFRecord().WithID(1).WithName("Test1"))); - eoWriter.AddBytes(rs.SerializeToByteArray(new EIFRecord().WithID(2).WithName("eof"))); + var nes = new NumberEncoderService(); + var rs = new PubRecordSerializer(nes); - ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEif - { - PubFile = new PubFile - { - FileId = 1, - Content = eoWriter.ToByteArray() - } - }; - break; - case FileType.Enf: - ret.ReplyCode = InitReply.FileEnf; + var eoWriter = new EoWriter(); + switch (type) + { + case FileType.Eif: + ret.ReplyCode = InitReply.FileEif; - eoWriter.AddString("ENF"); - eoWriter.AddInt(1); // RID - eoWriter.AddShort(2); // length - eoWriter.AddByte(1); // version - eoWriter.AddBytes(rs.SerializeToByteArray(new ENFRecord().WithID(1).WithName("Test1"))); - eoWriter.AddBytes(rs.SerializeToByteArray(new ENFRecord().WithID(2).WithName("eof"))); + eoWriter.AddString("EIF"); + eoWriter.AddInt(1); // RID + eoWriter.AddShort(2); // length + eoWriter.AddByte(1); // version + eoWriter.AddBytes(rs.SerializeToByteArray(new EIFRecord().WithID(1).WithName("Test1"))); + eoWriter.AddBytes(rs.SerializeToByteArray(new EIFRecord().WithID(2).WithName("eof"))); - ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEnf + ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEif + { + PubFile = new PubFile { - PubFile = new PubFile - { - FileId = 1, - Content = eoWriter.ToByteArray() - } - }; - break; - case FileType.Esf: - ret.ReplyCode = InitReply.FileEsf; - - eoWriter.AddString("ESF"); - eoWriter.AddInt(1); // RID - eoWriter.AddShort(2); // length - eoWriter.AddByte(1); // version - eoWriter.AddBytes(rs.SerializeToByteArray(new ESFRecord().WithID(1).WithName("Test1"))); - eoWriter.AddBytes(rs.SerializeToByteArray(new ESFRecord().WithID(2).WithName("eof"))); - - ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEsf + FileId = 1, + Content = eoWriter.ToByteArray() + } + }; + break; + case FileType.Enf: + ret.ReplyCode = InitReply.FileEnf; + + eoWriter.AddString("ENF"); + eoWriter.AddInt(1); // RID + eoWriter.AddShort(2); // length + eoWriter.AddByte(1); // version + eoWriter.AddBytes(rs.SerializeToByteArray(new ENFRecord().WithID(1).WithName("Test1"))); + eoWriter.AddBytes(rs.SerializeToByteArray(new ENFRecord().WithID(2).WithName("eof"))); + + ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEnf + { + PubFile = new PubFile { - PubFile = new PubFile - { - FileId = 1, - Content = eoWriter.ToByteArray() - } - }; - break; - case FileType.Ecf: - ret.ReplyCode = InitReply.FileEcf; - - eoWriter.AddString("ECF"); - eoWriter.AddInt(1); // RID - eoWriter.AddShort(2); // length - eoWriter.AddByte(1); // version - eoWriter.AddBytes(rs.SerializeToByteArray(new ECFRecord().WithID(1).WithName("Test1"))); - eoWriter.AddBytes(rs.SerializeToByteArray(new ECFRecord().WithID(2).WithName("eof"))); - - ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEcf + FileId = 1, + Content = eoWriter.ToByteArray() + } + }; + break; + case FileType.Esf: + ret.ReplyCode = InitReply.FileEsf; + + eoWriter.AddString("ESF"); + eoWriter.AddInt(1); // RID + eoWriter.AddShort(2); // length + eoWriter.AddByte(1); // version + eoWriter.AddBytes(rs.SerializeToByteArray(new ESFRecord().WithID(1).WithName("Test1"))); + eoWriter.AddBytes(rs.SerializeToByteArray(new ESFRecord().WithID(2).WithName("eof"))); + + ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEsf + { + PubFile = new PubFile { - PubFile = new PubFile - { - FileId = 1, - Content = eoWriter.ToByteArray() - } - }; - break; - } - - eoWriter = new EoWriter(); - ret.Serialize(eoWriter); - return eoWriter.ToByteArray(); + FileId = 1, + Content = eoWriter.ToByteArray() + } + }; + break; + case FileType.Ecf: + ret.ReplyCode = InitReply.FileEcf; + + eoWriter.AddString("ECF"); + eoWriter.AddInt(1); // RID + eoWriter.AddShort(2); // length + eoWriter.AddByte(1); // version + eoWriter.AddBytes(rs.SerializeToByteArray(new ECFRecord().WithID(1).WithName("Test1"))); + eoWriter.AddBytes(rs.SerializeToByteArray(new ECFRecord().WithID(2).WithName("eof"))); + + ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEcf + { + PubFile = new PubFile + { + FileId = 1, + Content = eoWriter.ToByteArray() + } + }; + break; } - #endregion + eoWriter = new EoWriter(); + ret.Serialize(eoWriter); + return eoWriter.ToByteArray(); } + + #endregion } \ No newline at end of file diff --git a/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs b/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs index ad022e3dd..d87fccd24 100644 --- a/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs +++ b/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs @@ -6,23 +6,22 @@ using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; -namespace EOLib.Test.TestHelpers +namespace EOLib.Test.TestHelpers; + +[ExcludeFromCodeCoverage] +internal static class PacketSendServiceHelpers { - [ExcludeFromCodeCoverage] - internal static class PacketSendServiceHelpers + /// + /// Setup the PacketSendService mock to return a packet with the specified family/action/data from SendEncodedPacketAndWaitAsync + /// + /// The mocked packet send service + /// Packet data payload (any additional data that should be in the packet) + internal static void SetupReceivedPacketHasHeader(this Mock packetSendServiceMock, params byte[] data) + where T : IPacket { - /// - /// Setup the PacketSendService mock to return a packet with the specified family/action/data from SendEncodedPacketAndWaitAsync - /// - /// The mocked packet send service - /// Packet data payload (any additional data that should be in the packet) - internal static void SetupReceivedPacketHasHeader(this Mock packetSendServiceMock, params byte[] data) - where T : IPacket - { - IPacket receivedPacket = (IPacket)Activator.CreateInstance(typeof(T)); - receivedPacket.Deserialize(new EoReader(data)); - packetSendServiceMock.Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) - .Returns(Task.FromResult(receivedPacket)); - } + IPacket receivedPacket = (IPacket)Activator.CreateInstance(typeof(T)); + receivedPacket.Deserialize(new EoReader(data)); + packetSendServiceMock.Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) + .Returns(Task.FromResult(receivedPacket)); } } \ No newline at end of file diff --git a/EndlessClient/Audio/AudioActions.cs b/EndlessClient/Audio/AudioActions.cs index 17ead27e8..758ef1801 100644 --- a/EndlessClient/Audio/AudioActions.cs +++ b/EndlessClient/Audio/AudioActions.cs @@ -4,73 +4,72 @@ using EOLib.Domain.Notifiers; using EOLib.IO.Map; -namespace EndlessClient.Audio +namespace EndlessClient.Audio; + +[AutoMappedType] +public class AudioActions : IAudioActions, ISoundNotifier { - [AutoMappedType] - public class AudioActions : IAudioActions, ISoundNotifier - { - private readonly IConfigurationProvider _configurationProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IMfxPlayer _mfxPlayer; - private readonly ISfxPlayer _sfxPlayer; + private readonly IConfigurationProvider _configurationProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IMfxPlayer _mfxPlayer; + private readonly ISfxPlayer _sfxPlayer; - public AudioActions(IConfigurationProvider configurationProvider, - ICurrentMapProvider currentMapProvider, - IMfxPlayer mfxPlayer, - ISfxPlayer sfxPlayer) - { - _configurationProvider = configurationProvider; - _currentMapProvider = currentMapProvider; - _mfxPlayer = mfxPlayer; - _sfxPlayer = sfxPlayer; - } + public AudioActions(IConfigurationProvider configurationProvider, + ICurrentMapProvider currentMapProvider, + IMfxPlayer mfxPlayer, + ISfxPlayer sfxPlayer) + { + _configurationProvider = configurationProvider; + _currentMapProvider = currentMapProvider; + _mfxPlayer = mfxPlayer; + _sfxPlayer = sfxPlayer; + } - public void ToggleBackgroundMusic() + public void ToggleBackgroundMusic() + { + if (!_configurationProvider.MusicEnabled) { - if (!_configurationProvider.MusicEnabled) - { - _mfxPlayer.StopBackgroundMusic(); - return; - } - - var music = _currentMapProvider.CurrentMap.Properties.Music; - var musicControl = _currentMapProvider.CurrentMap.Properties.Control; - if (music > 0) - _mfxPlayer.PlayBackgroundMusic(_currentMapProvider.CurrentMap.Properties.Music, musicControl); - else - _mfxPlayer.StopBackgroundMusic(); + _mfxPlayer.StopBackgroundMusic(); + return; } - public void ToggleSound() - { - if (!_configurationProvider.SoundEnabled) - { - _sfxPlayer.StopLoopingSfx(); - return; - } - - var noise = _currentMapProvider.CurrentMap.Properties.AmbientNoise; - if (noise > 0) - _sfxPlayer.PlayLoopingSfx((SoundEffectID)noise); - else - _sfxPlayer.StopLoopingSfx(); - } + var music = _currentMapProvider.CurrentMap.Properties.Music; + var musicControl = _currentMapProvider.CurrentMap.Properties.Control; + if (music > 0) + _mfxPlayer.PlayBackgroundMusic(_currentMapProvider.CurrentMap.Properties.Music, musicControl); + else + _mfxPlayer.StopBackgroundMusic(); + } - public void NotifySoundEffect(int soundEffectId) + public void ToggleSound() + { + if (!_configurationProvider.SoundEnabled) { - _sfxPlayer.PlaySfx((SoundEffectID)soundEffectId); + _sfxPlayer.StopLoopingSfx(); + return; } - public void NotifyMusic(int musicEffectId, bool isJukebox) - { - _mfxPlayer.PlayBackgroundMusic(musicEffectId, MusicControl.InterruptIfDifferentPlayOnce, isJukebox); - } + var noise = _currentMapProvider.CurrentMap.Properties.AmbientNoise; + if (noise > 0) + _sfxPlayer.PlayLoopingSfx((SoundEffectID)noise); + else + _sfxPlayer.StopLoopingSfx(); } - public interface IAudioActions + public void NotifySoundEffect(int soundEffectId) { - void ToggleBackgroundMusic(); + _sfxPlayer.PlaySfx((SoundEffectID)soundEffectId); + } - void ToggleSound(); + public void NotifyMusic(int musicEffectId, bool isJukebox) + { + _mfxPlayer.PlayBackgroundMusic(musicEffectId, MusicControl.InterruptIfDifferentPlayOnce, isJukebox); } +} + +public interface IAudioActions +{ + void ToggleBackgroundMusic(); + + void ToggleSound(); } \ No newline at end of file diff --git a/EndlessClient/Audio/MfxPlayer.cs b/EndlessClient/Audio/MfxPlayer.cs index fd3cd231f..aba180ce8 100644 --- a/EndlessClient/Audio/MfxPlayer.cs +++ b/EndlessClient/Audio/MfxPlayer.cs @@ -7,132 +7,131 @@ using System.IO; using System.Linq; -namespace EndlessClient.Audio +namespace EndlessClient.Audio; + +[AutoMappedType(IsSingleton = true)] +public sealed class MfxPlayer : IMfxPlayer { - [AutoMappedType(IsSingleton = true)] - public sealed class MfxPlayer : IMfxPlayer - { - private readonly IConfigurationProvider _configurationProvider; + private readonly IConfigurationProvider _configurationProvider; - private readonly string[] _mfxFiles; - private readonly string[] _jboxFiles; - private readonly IMidiOutput _output; - private MidiPlayer _activePlayer; - private int _activeId; + private readonly string[] _mfxFiles; + private readonly string[] _jboxFiles; + private readonly IMidiOutput _output; + private MidiPlayer _activePlayer; + private int _activeId; - public MfxPlayer(IConfigurationProvider configurationProvider) - { - _configurationProvider = configurationProvider; + public MfxPlayer(IConfigurationProvider configurationProvider) + { + _configurationProvider = configurationProvider; - _mfxFiles = Directory.GetFiles(Constants.MfxDirectory, "*.mid"); - Array.Sort(_mfxFiles); + _mfxFiles = Directory.GetFiles(Constants.MfxDirectory, "*.mid"); + Array.Sort(_mfxFiles); - _jboxFiles = Directory.GetFiles(Constants.JboxDirectory, "*.mid"); - Array.Sort(_jboxFiles); + _jboxFiles = Directory.GetFiles(Constants.JboxDirectory, "*.mid"); + Array.Sort(_jboxFiles); - try - { - var access = MidiAccessManager.Default; - _output = access.OpenOutputAsync(access.Outputs.Last().Id).Result; - } - catch - { - Console.WriteLine("WARNING: Unable to initialize the midi sound system. Background music will not play."); - } + try + { + var access = MidiAccessManager.Default; + _output = access.OpenOutputAsync(access.Outputs.Last().Id).Result; } - - public void PlayBackgroundMusic(int id, MusicControl musicControl, bool isJukebox = false) + catch { - if (!_configurationProvider.MusicEnabled) - return; + Console.WriteLine("WARNING: Unable to initialize the midi sound system. Background music will not play."); + } + } - if ((!isJukebox && (id < 1 || id > _mfxFiles.Length)) || - (isJukebox && (id < 1 || id > _jboxFiles.Length))) - throw new ArgumentException("ID should be 1-based index", nameof(id)); + public void PlayBackgroundMusic(int id, MusicControl musicControl, bool isJukebox = false) + { + if (!_configurationProvider.MusicEnabled) + return; - var interrupt = false; - var repeat = false; + if ((!isJukebox && (id < 1 || id > _mfxFiles.Length)) || + (isJukebox && (id < 1 || id > _jboxFiles.Length))) + throw new ArgumentException("ID should be 1-based index", nameof(id)); - switch (musicControl) - { - case MusicControl.InterruptIfDifferentPlayOnce: - interrupt = id != _activeId; - break; - case MusicControl.InterruptPlayOnce: - interrupt = true; - break; - case MusicControl.FinishPlayOnce: - break; - case MusicControl.InterruptIfDifferentPlayRepeat: - interrupt = id != _activeId; - repeat = true; - break; - case MusicControl.InterruptPlayRepeat: - interrupt = repeat = true; - break; - case MusicControl.FinishPlayRepeat: - repeat = true; - break; - case MusicControl.TurnOff: - StopBackgroundMusic(); - return; - } + var interrupt = false; + var repeat = false; - if (_activePlayer != null) - { - if (interrupt || _activePlayer.State == PlayerState.Stopped) - { - StopBackgroundMusic(); - StartPlaying(); - } - } - else - { - StartPlaying(); - } + switch (musicControl) + { + case MusicControl.InterruptIfDifferentPlayOnce: + interrupt = id != _activeId; + break; + case MusicControl.InterruptPlayOnce: + interrupt = true; + break; + case MusicControl.FinishPlayOnce: + break; + case MusicControl.InterruptIfDifferentPlayRepeat: + interrupt = id != _activeId; + repeat = true; + break; + case MusicControl.InterruptPlayRepeat: + interrupt = repeat = true; + break; + case MusicControl.FinishPlayRepeat: + repeat = true; + break; + case MusicControl.TurnOff: + StopBackgroundMusic(); + return; + } - _activePlayer.PlaybackCompletedToEnd -= PlaybackCompleteAction; - if (repeat) + if (_activePlayer != null) + { + if (interrupt || _activePlayer.State == PlayerState.Stopped) { - _activePlayer.PlaybackCompletedToEnd += PlaybackCompleteAction; + StopBackgroundMusic(); + StartPlaying(); } + } + else + { + StartPlaying(); + } - void StartPlaying() - { - if (_output != null) - { - var music = MidiMusic.Read(File.OpenRead(isJukebox ? _jboxFiles[id - 1] : _mfxFiles[id - 1])); - _activePlayer = new MidiPlayer(music, _output); - _activePlayer.Play(); - } - - _activeId = id; - } + _activePlayer.PlaybackCompletedToEnd -= PlaybackCompleteAction; + if (repeat) + { + _activePlayer.PlaybackCompletedToEnd += PlaybackCompleteAction; + } - void PlaybackCompleteAction() + void StartPlaying() + { + if (_output != null) { - PlayBackgroundMusic(id, musicControl); + var music = MidiMusic.Read(File.OpenRead(isJukebox ? _jboxFiles[id - 1] : _mfxFiles[id - 1])); + _activePlayer = new MidiPlayer(music, _output); + _activePlayer.Play(); } - } - public void StopBackgroundMusic() - { - _activePlayer?.Stop(); - _activePlayer?.Dispose(); - _activePlayer = null; + _activeId = id; } - public void Dispose() + void PlaybackCompleteAction() { - StopBackgroundMusic(); - _output?.Dispose(); + PlayBackgroundMusic(id, musicControl); } } - public interface IMfxPlayer : IDisposable + public void StopBackgroundMusic() { - void PlayBackgroundMusic(int id, MusicControl musicControl, bool isJukebox = false); + _activePlayer?.Stop(); + _activePlayer?.Dispose(); + _activePlayer = null; + } - void StopBackgroundMusic(); + public void Dispose() + { + StopBackgroundMusic(); + _output?.Dispose(); } +} + +public interface IMfxPlayer : IDisposable +{ + void PlayBackgroundMusic(int id, MusicControl musicControl, bool isJukebox = false); + + void StopBackgroundMusic(); } \ No newline at end of file diff --git a/EndlessClient/Audio/SfxPlayer.cs b/EndlessClient/Audio/SfxPlayer.cs index 4ae6db01d..b36458f3d 100644 --- a/EndlessClient/Audio/SfxPlayer.cs +++ b/EndlessClient/Audio/SfxPlayer.cs @@ -4,93 +4,92 @@ using Microsoft.Xna.Framework.Audio; using System; -namespace EndlessClient.Audio +namespace EndlessClient.Audio; + +[AutoMappedType(IsSingleton = true)] +public sealed class SfxPlayer : ISfxPlayer { - [AutoMappedType(IsSingleton = true)] - public sealed class SfxPlayer : ISfxPlayer + private readonly IContentProvider _contentProvider; + private readonly IConfigurationProvider _configurationProvider; + + private SoundEffectInstance _loopingSfx; + + public SfxPlayer(IContentProvider contentProvider, + IConfigurationProvider configurationProvider) { - private readonly IContentProvider _contentProvider; - private readonly IConfigurationProvider _configurationProvider; - - private SoundEffectInstance _loopingSfx; - - public SfxPlayer(IContentProvider contentProvider, - IConfigurationProvider configurationProvider) - { - _contentProvider = contentProvider; - _configurationProvider = configurationProvider; - } - - public void PlaySfx(SoundEffectID id) - { - if (!_configurationProvider.SoundEnabled) - return; - - _contentProvider.SFX[id - 1].Play(); - } - - public void PlayHarpNote(int index) - { - if (!_configurationProvider.SoundEnabled || index < 0 || index >= _contentProvider.HarpNotes.Count) - return; - - _contentProvider.HarpNotes[index].Play(); - } - - public void PlayGuitarNote(int index) - { - if (!_configurationProvider.SoundEnabled || index < 0 || index >= _contentProvider.GuitarNotes.Count) - return; - - _contentProvider.GuitarNotes[index].Play(); - } - - public void PlayLoopingSfx(SoundEffectID id) - { - if (!_configurationProvider.SoundEnabled || (_loopingSfx != null && _loopingSfx.State != SoundState.Stopped)) - return; - - StopLoopingSfx(); - - _loopingSfx = _contentProvider.SFX[id - 1].CreateInstance(); - _loopingSfx.IsLooped = true; - _loopingSfx.Volume = 0.5f; - _loopingSfx.Play(); - } - - public void SetLoopingSfxVolume(float volume) - { - if (volume < 0 || volume > 1) - throw new ArgumentException($"Volume {volume} must be between 0 and 1", nameof(volume)); - - if (_loopingSfx != null) - _loopingSfx.Volume = volume; - } - - public void StopLoopingSfx() - { - _loopingSfx?.Stop(); - _loopingSfx?.Dispose(); - } - - public void Dispose() - { - StopLoopingSfx(); - } + _contentProvider = contentProvider; + _configurationProvider = configurationProvider; } - public interface ISfxPlayer : IDisposable + public void PlaySfx(SoundEffectID id) { - void PlaySfx(SoundEffectID id); + if (!_configurationProvider.SoundEnabled) + return; - void PlayHarpNote(int index); + _contentProvider.SFX[id - 1].Play(); + } - void PlayGuitarNote(int index); + public void PlayHarpNote(int index) + { + if (!_configurationProvider.SoundEnabled || index < 0 || index >= _contentProvider.HarpNotes.Count) + return; - void PlayLoopingSfx(SoundEffectID id); + _contentProvider.HarpNotes[index].Play(); + } - void SetLoopingSfxVolume(float volume); + public void PlayGuitarNote(int index) + { + if (!_configurationProvider.SoundEnabled || index < 0 || index >= _contentProvider.GuitarNotes.Count) + return; - void StopLoopingSfx(); + _contentProvider.GuitarNotes[index].Play(); } + + public void PlayLoopingSfx(SoundEffectID id) + { + if (!_configurationProvider.SoundEnabled || (_loopingSfx != null && _loopingSfx.State != SoundState.Stopped)) + return; + + StopLoopingSfx(); + + _loopingSfx = _contentProvider.SFX[id - 1].CreateInstance(); + _loopingSfx.IsLooped = true; + _loopingSfx.Volume = 0.5f; + _loopingSfx.Play(); + } + + public void SetLoopingSfxVolume(float volume) + { + if (volume < 0 || volume > 1) + throw new ArgumentException($"Volume {volume} must be between 0 and 1", nameof(volume)); + + if (_loopingSfx != null) + _loopingSfx.Volume = volume; + } + + public void StopLoopingSfx() + { + _loopingSfx?.Stop(); + _loopingSfx?.Dispose(); + } + + public void Dispose() + { + StopLoopingSfx(); + } +} + +public interface ISfxPlayer : IDisposable +{ + void PlaySfx(SoundEffectID id); + + void PlayHarpNote(int index); + + void PlayGuitarNote(int index); + + void PlayLoopingSfx(SoundEffectID id); + + void SetLoopingSfxVolume(float volume); + + void StopLoopingSfx(); } \ No newline at end of file diff --git a/EndlessClient/Audio/SoundEffectID.cs b/EndlessClient/Audio/SoundEffectID.cs index 16ad15708..24a56bbcd 100644 --- a/EndlessClient/Audio/SoundEffectID.cs +++ b/EndlessClient/Audio/SoundEffectID.cs @@ -1,104 +1,103 @@ -namespace EndlessClient.Audio +namespace EndlessClient.Audio; + +// These are 0 based indexes even though the files start at sfx001 +// sfx001 will be id 0 +// sfx060 will be id 59 +public enum SoundEffectID { - // These are 0 based indexes even though the files start at sfx001 - // sfx001 will be id 0 - // sfx060 will be id 59 - public enum SoundEffectID - { - NONE, - LayeredTechIntro = 1, - ButtonClick, - DialogButtonClick, - TextBoxFocus = 4, - ChestOpen = TextBoxFocus, - SpellActivate = TextBoxFocus, - ServerCommand = TextBoxFocus, - TradeItemOfferChanged = TextBoxFocus, - Login, - ServerMessage = Login, - DeleteCharacter, - MapMutation = DeleteCharacter, - Banned, - Reboot = Banned, - ScreenCapture = 8, - PrivateMessageReceived, - PunchAttack, - UnknownWarpSound, - UnknownPingSound = 12, - HudStatusBarClick, - AdminAnnounceReceived, - MeleeWeaponAttack, - MemberLeftParty = 16, - TradeAccepted, - JoinParty = TradeAccepted, - GroupChatReceived, - PrivateMessageSent, - InventoryPickup = 20, - InventoryPlace, - Earthquake, - DoorClose, - DoorOpen = 24, - DoorOrChestLocked, - BuySell, - Craft, - UnknownBuzzSound = 28, - AdminChatReceived, - AlternateMeleeAttack, - PotionOfFlamesEffect, - AdminWarp = 32, - NoWallWalk, - GhostPlayer = NoWallWalk, - ScrollTeleport = NoWallWalk, - PotionOfEvilTerrorEffect, - PotionOfFireworksEffect, - PotionOfSparklesEffect = 36, - LearnNewSpell, - PotionOfLoveEffect = LearnNewSpell, - InnSignUp = LearnNewSpell, - AttackBow, - LevelUp, - Dead = 40, - JumpStone, - Water, - Heal, - Harp1 = 44, - Harp2, - Harp3, - Guitar1, - Guitar2 = 48, - Guitar3, - Thunder, - MapEvacTimer, - ArenaTickSound = MapEvacTimer, - ArenaWin = 52, - Gun, - UltimaBlastSpell, - ShieldSpell, - RingOfFireSpell = 56, - IceBlastSpell1, - EnergyBallSpell, - WhirlSpell, - BouldersSpell = 60, - AuraSpell, - HeavenSpell, - IceBlastSpell2, - MapAmbientNoiseWater = 64, - MapAmbientNoiseDrone1, - AdminHide, - MapAmbientNoiseLavaBubbles1, - AdminRequestSent = 68, - MapAmbientNoiseFactory, - MapEffectHPDrain, - MapEffectTPDrain, - Spikes = 72, - NoArrows, - EnterPkMap, - UnknownMapAmbientNoise5, - DarkHandSpell = 76, - TentaclesSpell, - MagicWhirlSpell, - PowerWindSpell, - FireBlastSpell = 80, - MapAmbientNoiseLavaBubbles2, - } + NONE, + LayeredTechIntro = 1, + ButtonClick, + DialogButtonClick, + TextBoxFocus = 4, + ChestOpen = TextBoxFocus, + SpellActivate = TextBoxFocus, + ServerCommand = TextBoxFocus, + TradeItemOfferChanged = TextBoxFocus, + Login, + ServerMessage = Login, + DeleteCharacter, + MapMutation = DeleteCharacter, + Banned, + Reboot = Banned, + ScreenCapture = 8, + PrivateMessageReceived, + PunchAttack, + UnknownWarpSound, + UnknownPingSound = 12, + HudStatusBarClick, + AdminAnnounceReceived, + MeleeWeaponAttack, + MemberLeftParty = 16, + TradeAccepted, + JoinParty = TradeAccepted, + GroupChatReceived, + PrivateMessageSent, + InventoryPickup = 20, + InventoryPlace, + Earthquake, + DoorClose, + DoorOpen = 24, + DoorOrChestLocked, + BuySell, + Craft, + UnknownBuzzSound = 28, + AdminChatReceived, + AlternateMeleeAttack, + PotionOfFlamesEffect, + AdminWarp = 32, + NoWallWalk, + GhostPlayer = NoWallWalk, + ScrollTeleport = NoWallWalk, + PotionOfEvilTerrorEffect, + PotionOfFireworksEffect, + PotionOfSparklesEffect = 36, + LearnNewSpell, + PotionOfLoveEffect = LearnNewSpell, + InnSignUp = LearnNewSpell, + AttackBow, + LevelUp, + Dead = 40, + JumpStone, + Water, + Heal, + Harp1 = 44, + Harp2, + Harp3, + Guitar1, + Guitar2 = 48, + Guitar3, + Thunder, + MapEvacTimer, + ArenaTickSound = MapEvacTimer, + ArenaWin = 52, + Gun, + UltimaBlastSpell, + ShieldSpell, + RingOfFireSpell = 56, + IceBlastSpell1, + EnergyBallSpell, + WhirlSpell, + BouldersSpell = 60, + AuraSpell, + HeavenSpell, + IceBlastSpell2, + MapAmbientNoiseWater = 64, + MapAmbientNoiseDrone1, + AdminHide, + MapAmbientNoiseLavaBubbles1, + AdminRequestSent = 68, + MapAmbientNoiseFactory, + MapEffectHPDrain, + MapEffectTPDrain, + Spikes = 72, + NoArrows, + EnterPkMap, + UnknownMapAmbientNoise5, + DarkHandSpell = 76, + TentaclesSpell, + MagicWhirlSpell, + PowerWindSpell, + FireBlastSpell = 80, + MapAmbientNoiseLavaBubbles2, } \ No newline at end of file diff --git a/EndlessClient/Audio/WAVFileValidator.cs b/EndlessClient/Audio/WAVFileValidator.cs index 23a3ad59a..08bd492be 100644 --- a/EndlessClient/Audio/WAVFileValidator.cs +++ b/EndlessClient/Audio/WAVFileValidator.cs @@ -2,32 +2,31 @@ using System.IO; using System.Text; -namespace EndlessClient.Audio +namespace EndlessClient.Audio; + +public static class WAVFileValidator { - public static class WAVFileValidator + //some of the original SFX files will fail to load because the file length is stored incorrectly in the WAV header. + //this helper method returns a stream around the corrected raw bytes of the file. + public static Stream GetStreamWithCorrectLengthHeader(string filename) { - //some of the original SFX files will fail to load because the file length is stored incorrectly in the WAV header. - //this helper method returns a stream around the corrected raw bytes of the file. - public static Stream GetStreamWithCorrectLengthHeader(string filename) - { - var wavBuffer = File.ReadAllBytes(filename); - - var riff = Encoding.ASCII.GetString(wavBuffer[..4]); - if (riff != "RIFF" || wavBuffer.Length < 8) //check for RIFF tag and length - throw new ArgumentException("Invalid WAV file", nameof(filename)); + var wavBuffer = File.ReadAllBytes(filename); - var reportedLength = wavBuffer[4] + wavBuffer[5] * 256 + wavBuffer[6] * 65536 + wavBuffer[7] * 16777216; - var actualLength = wavBuffer.Length - 8; + var riff = Encoding.ASCII.GetString(wavBuffer[..4]); + if (riff != "RIFF" || wavBuffer.Length < 8) //check for RIFF tag and length + throw new ArgumentException("Invalid WAV file", nameof(filename)); - if (reportedLength != actualLength) - { - wavBuffer[4] = (byte)(actualLength & 0xFF); - wavBuffer[5] = (byte)((actualLength >> 8) & 0xFF); - wavBuffer[6] = (byte)((actualLength >> 16) & 0xFF); - wavBuffer[7] = (byte)((actualLength >> 24) & 0xFF); - } + var reportedLength = wavBuffer[4] + wavBuffer[5] * 256 + wavBuffer[6] * 65536 + wavBuffer[7] * 16777216; + var actualLength = wavBuffer.Length - 8; - return new MemoryStream(wavBuffer); + if (reportedLength != actualLength) + { + wavBuffer[4] = (byte)(actualLength & 0xFF); + wavBuffer[5] = (byte)((actualLength >> 8) & 0xFF); + wavBuffer[6] = (byte)((actualLength >> 16) & 0xFF); + wavBuffer[7] = (byte)((actualLength >> 24) & 0xFF); } + + return new MemoryStream(wavBuffer); } } \ No newline at end of file diff --git a/EndlessClient/Content/ContentProvider.cs b/EndlessClient/Content/ContentProvider.cs index a7aacd0e4..3cb5f44cd 100644 --- a/EndlessClient/Content/ContentProvider.cs +++ b/EndlessClient/Content/ContentProvider.cs @@ -9,159 +9,158 @@ using System.IO; using System.Linq; -namespace EndlessClient.Content +namespace EndlessClient.Content; + +public interface IContentProvider { - public interface IContentProvider - { - IReadOnlyDictionary Textures { get; } + IReadOnlyDictionary Textures { get; } - IReadOnlyDictionary Fonts { get; } + IReadOnlyDictionary Fonts { get; } - IReadOnlyDictionary SFX { get; } + IReadOnlyDictionary SFX { get; } - IReadOnlyList HarpNotes { get; } + IReadOnlyList HarpNotes { get; } - IReadOnlyList GuitarNotes { get; } + IReadOnlyList GuitarNotes { get; } - void SetContentManager(ContentManager content); + void SetContentManager(ContentManager content); - void Load(); - } + void Load(); +} - [AutoMappedType(IsSingleton = true)] - public class ContentProvider : IContentProvider - { - private readonly Dictionary _textures; - private readonly Dictionary _fonts; - private readonly Dictionary _sfx; - private readonly List _harpNotes; - private readonly List _guitarNotes; +[AutoMappedType(IsSingleton = true)] +public class ContentProvider : IContentProvider +{ + private readonly Dictionary _textures; + private readonly Dictionary _fonts; + private readonly Dictionary _sfx; + private readonly List _harpNotes; + private readonly List _guitarNotes; - private ContentManager _content; + private ContentManager _content; - public const string Cursor = "cursor"; + public const string Cursor = "cursor"; - public const string TBBack = "tbBack"; - public const string TBLeft = "tbLeft"; - public const string TBRight = "tbRight"; + public const string TBBack = "tbBack"; + public const string TBLeft = "tbLeft"; + public const string TBRight = "tbRight"; - public const string ChatTL = @"ChatBubble\TL"; - public const string ChatTM = @"ChatBubble\TM"; - public const string ChatTR = @"ChatBubble\TR"; - public const string ChatML = @"ChatBubble\ML"; - public const string ChatMM = @"ChatBubble\MM"; - public const string ChatMR = @"ChatBubble\MR"; - public const string ChatRL = @"ChatBubble\RL"; - public const string ChatRM = @"ChatBubble\RM"; - public const string ChatRR = @"ChatBubble\RR"; - public const string ChatNUB = @"ChatBubble\NUB"; + public const string ChatTL = @"ChatBubble\TL"; + public const string ChatTM = @"ChatBubble\TM"; + public const string ChatTR = @"ChatBubble\TR"; + public const string ChatML = @"ChatBubble\ML"; + public const string ChatMM = @"ChatBubble\MM"; + public const string ChatMR = @"ChatBubble\MR"; + public const string ChatRL = @"ChatBubble\RL"; + public const string ChatRM = @"ChatBubble\RM"; + public const string ChatRR = @"ChatBubble\RR"; + public const string ChatNUB = @"ChatBubble\NUB"; - public const string HPOutline = @"Party\hp-outline"; - public const string HPRed = @"Party\hp-red"; - public const string HPYellow = @"Party\hp-yellow"; - public const string HPGreen = @"Party\hp-green"; + public const string HPOutline = @"Party\hp-outline"; + public const string HPRed = @"Party\hp-red"; + public const string HPYellow = @"Party\hp-yellow"; + public const string HPGreen = @"Party\hp-green"; - public IReadOnlyDictionary Textures => _textures; + public IReadOnlyDictionary Textures => _textures; - public IReadOnlyDictionary Fonts => _fonts; + public IReadOnlyDictionary Fonts => _fonts; - public IReadOnlyDictionary SFX => _sfx; + public IReadOnlyDictionary SFX => _sfx; - public IReadOnlyList HarpNotes => _harpNotes; + public IReadOnlyList HarpNotes => _harpNotes; - public IReadOnlyList GuitarNotes => _guitarNotes; + public IReadOnlyList GuitarNotes => _guitarNotes; - public ContentProvider() - { - _textures = new Dictionary(); - _fonts = new Dictionary(); - _sfx = new Dictionary(); - _harpNotes = new List(); - _guitarNotes = new List(); - } + public ContentProvider() + { + _textures = new Dictionary(); + _fonts = new Dictionary(); + _sfx = new Dictionary(); + _harpNotes = new List(); + _guitarNotes = new List(); + } - public void SetContentManager(ContentManager content) - { - _content = content; - } + public void SetContentManager(ContentManager content) + { + _content = content; + } - public void Load() - { - RefreshTextures(); - RefreshFonts(); - LoadSFX(); - LoadHarp(); - LoadGuitar(); - } + public void Load() + { + RefreshTextures(); + RefreshFonts(); + LoadSFX(); + LoadHarp(); + LoadGuitar(); + } - private void RefreshTextures() - { - if (_content == null) - return; - - _textures[Cursor] = _content.Load(Cursor); - - _textures[TBBack] = _content.Load(TBBack); - _textures[TBLeft] = _content.Load(TBLeft); - _textures[TBRight] = _content.Load(TBRight); - - _textures[ChatTL] = _content.Load(ChatTL); - _textures[ChatTM] = _content.Load(ChatTM); - _textures[ChatTR] = _content.Load(ChatTR); - _textures[ChatML] = _content.Load(ChatML); - _textures[ChatMM] = _content.Load(ChatMM); - _textures[ChatMR] = _content.Load(ChatMR); - _textures[ChatRL] = _content.Load(ChatRL); - _textures[ChatRM] = _content.Load(ChatRM); - _textures[ChatRR] = _content.Load(ChatRR); - _textures[ChatNUB] = _content.Load(ChatNUB); - - _textures[HPOutline] = _content.Load(HPOutline); - _textures[HPRed] = _content.Load(HPRed); - _textures[HPYellow] = _content.Load(HPYellow); - _textures[HPGreen] = _content.Load(HPGreen); - } + private void RefreshTextures() + { + if (_content == null) + return; + + _textures[Cursor] = _content.Load(Cursor); + + _textures[TBBack] = _content.Load(TBBack); + _textures[TBLeft] = _content.Load(TBLeft); + _textures[TBRight] = _content.Load(TBRight); + + _textures[ChatTL] = _content.Load(ChatTL); + _textures[ChatTM] = _content.Load(ChatTM); + _textures[ChatTR] = _content.Load(ChatTR); + _textures[ChatML] = _content.Load(ChatML); + _textures[ChatMM] = _content.Load(ChatMM); + _textures[ChatMR] = _content.Load(ChatMR); + _textures[ChatRL] = _content.Load(ChatRL); + _textures[ChatRM] = _content.Load(ChatRM); + _textures[ChatRR] = _content.Load(ChatRR); + _textures[ChatNUB] = _content.Load(ChatNUB); + + _textures[HPOutline] = _content.Load(HPOutline); + _textures[HPRed] = _content.Load(HPRed); + _textures[HPYellow] = _content.Load(HPYellow); + _textures[HPGreen] = _content.Load(HPGreen); + } - private void RefreshFonts() - { - _fonts[Constants.FontSize08] = _content.Load(Constants.FontSize08); - _fonts[Constants.FontSize08pt5] = _content.Load(Constants.FontSize08pt5); - _fonts[Constants.FontSize09] = _content.Load(Constants.FontSize09); - } + private void RefreshFonts() + { + _fonts[Constants.FontSize08] = _content.Load(Constants.FontSize08); + _fonts[Constants.FontSize08pt5] = _content.Load(Constants.FontSize08pt5); + _fonts[Constants.FontSize09] = _content.Load(Constants.FontSize09); + } - private void LoadSFX() - { - var id = (SoundEffectID)0; - foreach (var sfxFile in GetSoundEffects("sfx*.wav")) - _sfx[id++] = sfxFile; - if (_sfx.Count < 81) - throw new FileNotFoundException("Unexpected number of SFX"); - } + private void LoadSFX() + { + var id = (SoundEffectID)0; + foreach (var sfxFile in GetSoundEffects("sfx*.wav")) + _sfx[id++] = sfxFile; + if (_sfx.Count < 81) + throw new FileNotFoundException("Unexpected number of SFX"); + } - private void LoadHarp() - { - _harpNotes.AddRange(GetSoundEffects("har*.wav")); - if (_harpNotes.Count != 36) - throw new FileNotFoundException("Unexpected number of harp SFX"); - } + private void LoadHarp() + { + _harpNotes.AddRange(GetSoundEffects("har*.wav")); + if (_harpNotes.Count != 36) + throw new FileNotFoundException("Unexpected number of harp SFX"); + } - private void LoadGuitar() - { - _guitarNotes.AddRange(GetSoundEffects("gui*.wav")); - if (_guitarNotes.Count != 36) - throw new FileNotFoundException("Unexpected number of guitar SFX"); - } + private void LoadGuitar() + { + _guitarNotes.AddRange(GetSoundEffects("gui*.wav")); + if (_guitarNotes.Count != 36) + throw new FileNotFoundException("Unexpected number of guitar SFX"); + } + + private static IEnumerable GetSoundEffects(string filter) + { + var sfxFiles = Directory.GetFiles(Constants.SfxDirectory, filter).ToList(); + sfxFiles.Sort(); - private static IEnumerable GetSoundEffects(string filter) + foreach (var file in sfxFiles) { - var sfxFiles = Directory.GetFiles(Constants.SfxDirectory, filter).ToList(); - sfxFiles.Sort(); - - foreach (var file in sfxFiles) - { - using var wavStream = WAVFileValidator.GetStreamWithCorrectLengthHeader(file); - yield return SoundEffect.FromStream(wavStream); - } + using var wavStream = WAVFileValidator.GetStreamWithCorrectLengthHeader(file); + yield return SoundEffect.FromStream(wavStream); } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/BackButtonControlSet.cs b/EndlessClient/ControlSets/BackButtonControlSet.cs index c4ad0cd9f..515265653 100644 --- a/EndlessClient/ControlSets/BackButtonControlSet.cs +++ b/EndlessClient/ControlSets/BackButtonControlSet.cs @@ -7,62 +7,61 @@ using System; using XNAControls; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public abstract class BackButtonControlSet : BaseControlSet { - public abstract class BackButtonControlSet : BaseControlSet - { - protected readonly IMainButtonController _mainButtonController; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private Texture2D _backButtonTexture; + protected readonly IMainButtonController _mainButtonController; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private Texture2D _backButtonTexture; - private XNAButton _backButton; + private XNAButton _backButton; - protected BackButtonControlSet(IMainButtonController mainButtonController, - IClientWindowSizeRepository clientWindowSizeRepository) - { - _mainButtonController = mainButtonController; - _clientWindowSizeRepository = clientWindowSizeRepository; - } + protected BackButtonControlSet(IMainButtonController mainButtonController, + IClientWindowSizeRepository clientWindowSizeRepository) + { + _mainButtonController = mainButtonController; + _clientWindowSizeRepository = clientWindowSizeRepository; + } - public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - base.InitializeResources(gfxManager, contentProvider); + public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + base.InitializeResources(gfxManager, contentProvider); - _backButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 24, true); - } + _backButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 24, true); + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - _backButton = GetControl(currentControlSet, GameControlIdentifier.BackButton, GetBackButton); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + _backButton = GetControl(currentControlSet, GameControlIdentifier.BackButton, GetBackButton); - _allComponents.Add(_backButton); - } + _allComponents.Add(_backButton); + } - private XNAButton GetBackButton() + private XNAButton GetBackButton() + { + var button = new XNAButton( + _backButtonTexture, + new Vector2(_clientWindowSizeRepository.Width - _backButtonTexture.Width, 0), + new Rectangle(0, 0, _backButtonTexture.Width, _backButtonTexture.Height / 2), + new Rectangle(0, _backButtonTexture.Height / 2, _backButtonTexture.Width, _backButtonTexture.Height / 2)) { - var button = new XNAButton( - _backButtonTexture, - new Vector2(_clientWindowSizeRepository.Width - _backButtonTexture.Width, 0), - new Rectangle(0, 0, _backButtonTexture.Width, _backButtonTexture.Height / 2), - new Rectangle(0, _backButtonTexture.Height / 2, _backButtonTexture.Width, _backButtonTexture.Height / 2)) - { - UpdateOrder = -1, - DrawOrder = 100, - ClickArea = new Rectangle(4, 16, 16, 16) - }; - button.OnClick += DoBackButtonClick; + UpdateOrder = -1, + DrawOrder = 100, + ClickArea = new Rectangle(4, 16, 16, 16) + }; + button.OnClick += DoBackButtonClick; - _clientWindowSizeRepository.GameWindowSizeChanged += (o, e) => - { - button.DrawPosition = new Vector2(_clientWindowSizeRepository.Width - _backButtonTexture.Width, 0); - }; + _clientWindowSizeRepository.GameWindowSizeChanged += (o, e) => + { + button.DrawPosition = new Vector2(_clientWindowSizeRepository.Width - _backButtonTexture.Width, 0); + }; - return button; - } + return button; + } - protected virtual void DoBackButtonClick(object sender, EventArgs e) - { - _mainButtonController.GoToInitialState(); - } + protected virtual void DoBackButtonClick(object sender, EventArgs e) + { + _mainButtonController.GoToInitialState(); } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/BaseControlSet.cs b/EndlessClient/ControlSets/BaseControlSet.cs index c0e9e109e..6676537fd 100644 --- a/EndlessClient/ControlSets/BaseControlSet.cs +++ b/EndlessClient/ControlSets/BaseControlSet.cs @@ -8,120 +8,119 @@ using System.Linq; using XNAControls; -namespace EndlessClient.ControlSets -{ - public abstract class BaseControlSet : IControlSet - { - #region IGameStateControlSet implementation +namespace EndlessClient.ControlSets; - protected readonly List _allComponents; +public abstract class BaseControlSet : IControlSet +{ + #region IGameStateControlSet implementation - public IReadOnlyList AllComponents => _allComponents; + protected readonly List _allComponents; - public IReadOnlyList XNAControlComponents => _allComponents.OfType().ToList(); + public IReadOnlyList AllComponents => _allComponents; - public abstract GameStates GameState { get; } + public IReadOnlyList XNAControlComponents => _allComponents.OfType().ToList(); - #endregion + public abstract GameStates GameState { get; } - protected Texture2D _mainButtonTexture; - protected Texture2D _secondaryButtonTexture; - protected Texture2D _smallButtonSheet; - protected Texture2D _textBoxCursor; - protected Texture2D _textBoxRight; - protected Texture2D _textBoxLeft; - protected Texture2D _textBoxBackground; + #endregion - private Texture2D[] _backgroundImages; - private IXNAPictureBox _backgroundImage; + protected Texture2D _mainButtonTexture; + protected Texture2D _secondaryButtonTexture; + protected Texture2D _smallButtonSheet; + protected Texture2D _textBoxCursor; + protected Texture2D _textBoxRight; + protected Texture2D _textBoxLeft; + protected Texture2D _textBoxBackground; - private bool _resourcesInitialized, _controlsInitialized; + private Texture2D[] _backgroundImages; + private IXNAPictureBox _backgroundImage; - protected BaseControlSet() - { - _allComponents = new List(16); - } + private bool _resourcesInitialized, _controlsInitialized; - public virtual void InitializeResources(INativeGraphicsManager gfxManager, - IContentProvider contentProvider) - { - if (_resourcesInitialized) - throw new InvalidOperationException("Error initializing resources: resources have already been initialized"); + protected BaseControlSet() + { + _allComponents = new List(16); + } - _mainButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 13, true); - _secondaryButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 14, true); - _smallButtonSheet = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 15, true); + public virtual void InitializeResources(INativeGraphicsManager gfxManager, + IContentProvider contentProvider) + { + if (_resourcesInitialized) + throw new InvalidOperationException("Error initializing resources: resources have already been initialized"); - _textBoxBackground = contentProvider.Textures[ContentProvider.TBBack]; - _textBoxLeft = contentProvider.Textures[ContentProvider.TBLeft]; - _textBoxRight = contentProvider.Textures[ContentProvider.TBRight]; - _textBoxCursor = contentProvider.Textures[ContentProvider.Cursor]; + _mainButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 13, true); + _secondaryButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 14, true); + _smallButtonSheet = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 15, true); - _backgroundImages = new Texture2D[7]; - for (int i = 0; i < _backgroundImages.Length; ++i) - _backgroundImages[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 30 + i); + _textBoxBackground = contentProvider.Textures[ContentProvider.TBBack]; + _textBoxLeft = contentProvider.Textures[ContentProvider.TBLeft]; + _textBoxRight = contentProvider.Textures[ContentProvider.TBRight]; + _textBoxCursor = contentProvider.Textures[ContentProvider.Cursor]; - _resourcesInitialized = true; - } + _backgroundImages = new Texture2D[7]; + for (int i = 0; i < _backgroundImages.Length; ++i) + _backgroundImages[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 30 + i); - public void InitializeControls(IControlSet currentControlSet) - { - if (!_resourcesInitialized) - throw new InvalidOperationException("Error initializing controls: resources have not yet been initialized"); - if (_controlsInitialized) - throw new InvalidOperationException("Error initializing controls: controls have already been initialized"); + _resourcesInitialized = true; + } - if (GameState != GameStates.PlayingTheGame) - { - _backgroundImage = GetControl(currentControlSet, GameControlIdentifier.BackgroundImage, GetBackgroundImage); - _allComponents.Add(_backgroundImage); - } + public void InitializeControls(IControlSet currentControlSet) + { + if (!_resourcesInitialized) + throw new InvalidOperationException("Error initializing controls: resources have not yet been initialized"); + if (_controlsInitialized) + throw new InvalidOperationException("Error initializing controls: controls have already been initialized"); - InitializeControlsHelper(currentControlSet); + if (GameState != GameStates.PlayingTheGame) + { + _backgroundImage = GetControl(currentControlSet, GameControlIdentifier.BackgroundImage, GetBackgroundImage); + _allComponents.Add(_backgroundImage); + } - foreach (var control in XNAControlComponents) - control.AddControlToDefaultGame(); + InitializeControlsHelper(currentControlSet); - _controlsInitialized = true; - } + foreach (var control in XNAControlComponents) + control.AddControlToDefaultGame(); - protected abstract void InitializeControlsHelper(IControlSet currentControlSet); + _controlsInitialized = true; + } - protected static T GetControl(IControlSet currentControlSet, - GameControlIdentifier whichControl, - Func componentFactory) - where T : class, IGameComponent - { - return (T)currentControlSet.FindComponentByControlIdentifier(whichControl) ?? componentFactory(); - } + protected abstract void InitializeControlsHelper(IControlSet currentControlSet); - public virtual IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) - { - return control == GameControlIdentifier.BackgroundImage ? _backgroundImage : null; - } + protected static T GetControl(IControlSet currentControlSet, + GameControlIdentifier whichControl, + Func componentFactory) + where T : class, IGameComponent + { + return (T)currentControlSet.FindComponentByControlIdentifier(whichControl) ?? componentFactory(); + } - private IXNAPictureBox GetBackgroundImage() - { - var rnd = new Random(); - var texture = _backgroundImages[rnd.Next(7)]; - return new XNAPictureBox - { - Texture = texture, - DrawArea = new Rectangle(0, 0, texture.Width, texture.Height), - DrawOrder = 0 - }; - } + public virtual IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + return control == GameControlIdentifier.BackgroundImage ? _backgroundImage : null; + } - public void Dispose() + private IXNAPictureBox GetBackgroundImage() + { + var rnd = new Random(); + var texture = _backgroundImages[rnd.Next(7)]; + return new XNAPictureBox { - Dispose(true); - } + Texture = texture, + DrawArea = new Rectangle(0, 0, texture.Width, texture.Height), + DrawOrder = 0 + }; + } - ~BaseControlSet() - { - Dispose(false); - } + public void Dispose() + { + Dispose(true); + } - protected virtual void Dispose(bool disposing) { } + ~BaseControlSet() + { + Dispose(false); } + + protected virtual void Dispose(bool disposing) { } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/ControlSetFactory.cs b/EndlessClient/ControlSets/ControlSetFactory.cs index ea25b2924..b542fc96e 100644 --- a/EndlessClient/ControlSets/ControlSetFactory.cs +++ b/EndlessClient/ControlSets/ControlSetFactory.cs @@ -13,100 +13,99 @@ using EOLib.Graphics; using System; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +[MappedType(BaseType = typeof(IControlSetFactory), IsSingleton = true)] +public class ControlSetFactory : IControlSetFactory { - [MappedType(BaseType = typeof(IControlSetFactory), IsSingleton = true)] - public class ControlSetFactory : IControlSetFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IHudControlsFactory _hudControlsFactory; - private readonly IContentProvider _contentProvider; - private readonly IConfigurationProvider _configProvider; - private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; - private readonly ICharacterSelectorProvider _characterSelectorProvider; - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IUserInputRepository _userInputRepository; - private readonly IActiveDialogRepository _activeDialogRepository; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IHudControlsFactory _hudControlsFactory; + private readonly IContentProvider _contentProvider; + private readonly IConfigurationProvider _configProvider; + private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; + private readonly ICharacterSelectorProvider _characterSelectorProvider; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IUserInputRepository _userInputRepository; + private readonly IActiveDialogRepository _activeDialogRepository; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private IMainButtonController _mainButtonController; - private IAccountController _accountController; - private ILoginController _loginController; - private ICharacterManagementController _characterManagementController; + private IMainButtonController _mainButtonController; + private IAccountController _accountController; + private ILoginController _loginController; + private ICharacterManagementController _characterManagementController; - public ControlSetFactory(INativeGraphicsManager nativeGraphicsManager, - IEOMessageBoxFactory messageBoxFactory, - IHudControlsFactory hudControlsFactory, - IContentProvider contentProvider, - IConfigurationProvider configProvider, - ICharacterInfoPanelFactory characterInfoPanelFactory, - ICharacterSelectorProvider characterSelectorProvider, - IEndlessGameProvider endlessGameProvider, - IUserInputRepository userInputRepository, - IActiveDialogRepository activeDialogRepository, - IClientWindowSizeRepository clientWindowSizeRepository) - { - _nativeGraphicsManager = nativeGraphicsManager; - _messageBoxFactory = messageBoxFactory; - _hudControlsFactory = hudControlsFactory; - _contentProvider = contentProvider; - _configProvider = configProvider; - _characterInfoPanelFactory = characterInfoPanelFactory; - _characterSelectorProvider = characterSelectorProvider; - _endlessGameProvider = endlessGameProvider; - _userInputRepository = userInputRepository; - _activeDialogRepository = activeDialogRepository; - _clientWindowSizeRepository = clientWindowSizeRepository; - } + public ControlSetFactory(INativeGraphicsManager nativeGraphicsManager, + IEOMessageBoxFactory messageBoxFactory, + IHudControlsFactory hudControlsFactory, + IContentProvider contentProvider, + IConfigurationProvider configProvider, + ICharacterInfoPanelFactory characterInfoPanelFactory, + ICharacterSelectorProvider characterSelectorProvider, + IEndlessGameProvider endlessGameProvider, + IUserInputRepository userInputRepository, + IActiveDialogRepository activeDialogRepository, + IClientWindowSizeRepository clientWindowSizeRepository) + { + _nativeGraphicsManager = nativeGraphicsManager; + _messageBoxFactory = messageBoxFactory; + _hudControlsFactory = hudControlsFactory; + _contentProvider = contentProvider; + _configProvider = configProvider; + _characterInfoPanelFactory = characterInfoPanelFactory; + _characterSelectorProvider = characterSelectorProvider; + _endlessGameProvider = endlessGameProvider; + _userInputRepository = userInputRepository; + _activeDialogRepository = activeDialogRepository; + _clientWindowSizeRepository = clientWindowSizeRepository; + } - public IControlSet CreateControlsForState(GameStates newState, IControlSet currentControlSet) - { - if (_mainButtonController == null || _accountController == null || - _loginController == null || _characterManagementController == null) - throw new InvalidOperationException("Missing controllers - the Unity container was initialized incorrectly"); + public IControlSet CreateControlsForState(GameStates newState, IControlSet currentControlSet) + { + if (_mainButtonController == null || _accountController == null || + _loginController == null || _characterManagementController == null) + throw new InvalidOperationException("Missing controllers - the Unity container was initialized incorrectly"); - var controlSet = GetSetBasedOnState(newState); - controlSet.InitializeResources(_nativeGraphicsManager, _contentProvider); - controlSet.InitializeControls(currentControlSet); - return controlSet; - } + var controlSet = GetSetBasedOnState(newState); + controlSet.InitializeResources(_nativeGraphicsManager, _contentProvider); + controlSet.InitializeControls(currentControlSet); + return controlSet; + } - public void InjectControllers(IMainButtonController mainButtonController, - IAccountController accountController, - ILoginController loginController, - ICharacterManagementController characterManagementController) - { - _mainButtonController = mainButtonController; - _accountController = accountController; - _loginController = loginController; - _characterManagementController = characterManagementController; - } + public void InjectControllers(IMainButtonController mainButtonController, + IAccountController accountController, + ILoginController loginController, + ICharacterManagementController characterManagementController) + { + _mainButtonController = mainButtonController; + _accountController = accountController; + _loginController = loginController; + _characterManagementController = characterManagementController; + } - private IControlSet GetSetBasedOnState(GameStates newState) + private IControlSet GetSetBasedOnState(GameStates newState) + { + switch (newState) { - switch (newState) - { - case GameStates.Initial: return new InitialControlSet(_configProvider, _mainButtonController); - case GameStates.CreateAccount: - return new CreateAccountControlSet(_mainButtonController, _accountController, _clientWindowSizeRepository); - case GameStates.Login: - return new LoginPromptControlSet(_configProvider, _mainButtonController, _loginController); - case GameStates.ViewCredits: return new ViewCreditsControlSet(_configProvider, _mainButtonController); - case GameStates.LoggedIn: - return new LoggedInControlSet( - _mainButtonController, - _characterInfoPanelFactory, - _characterSelectorProvider, - _characterManagementController, - _accountController, - _endlessGameProvider, - _userInputRepository, - _clientWindowSizeRepository); - case GameStates.PlayingTheGame: - return new InGameControlSet(_mainButtonController, _messageBoxFactory, _hudControlsFactory, _activeDialogRepository, _clientWindowSizeRepository); - default: throw new ArgumentOutOfRangeException(nameof(newState), newState, null); - } + case GameStates.Initial: return new InitialControlSet(_configProvider, _mainButtonController); + case GameStates.CreateAccount: + return new CreateAccountControlSet(_mainButtonController, _accountController, _clientWindowSizeRepository); + case GameStates.Login: + return new LoginPromptControlSet(_configProvider, _mainButtonController, _loginController); + case GameStates.ViewCredits: return new ViewCreditsControlSet(_configProvider, _mainButtonController); + case GameStates.LoggedIn: + return new LoggedInControlSet( + _mainButtonController, + _characterInfoPanelFactory, + _characterSelectorProvider, + _characterManagementController, + _accountController, + _endlessGameProvider, + _userInputRepository, + _clientWindowSizeRepository); + case GameStates.PlayingTheGame: + return new InGameControlSet(_mainButtonController, _messageBoxFactory, _hudControlsFactory, _activeDialogRepository, _clientWindowSizeRepository); + default: throw new ArgumentOutOfRangeException(nameof(newState), newState, null); } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/CreateAccountControlSet.cs b/EndlessClient/ControlSets/CreateAccountControlSet.cs index 51bda50cc..a8799ecff 100644 --- a/EndlessClient/ControlSets/CreateAccountControlSet.cs +++ b/EndlessClient/ControlSets/CreateAccountControlSet.cs @@ -13,202 +13,201 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public class CreateAccountControlSet : IntermediateControlSet { - public class CreateAccountControlSet : IntermediateControlSet - { - private readonly IAccountController _accountController; + private readonly IAccountController _accountController; - private Texture2D _labelsTexture; + private Texture2D _labelsTexture; - private IXNATextBox _tbAccountName, - _tbPassword, - _tbConfirm, - _tbRealName, - _tbLocation, - _tbEmail; - private IXNAButton _btnCancel; - private IXNAPanel _labels; + private IXNATextBox _tbAccountName, + _tbPassword, + _tbConfirm, + _tbRealName, + _tbLocation, + _tbEmail; + private IXNAButton _btnCancel; + private IXNAPanel _labels; - private Task _createAccountTask; + private Task _createAccountTask; - public override GameStates GameState => GameStates.CreateAccount; + public override GameStates GameState => GameStates.CreateAccount; - public CreateAccountControlSet(IMainButtonController mainButtonController, - IAccountController accountController, - IClientWindowSizeRepository clientWindowSizeRepository) - : base(mainButtonController, clientWindowSizeRepository) - { - _accountController = accountController; - } + public CreateAccountControlSet(IMainButtonController mainButtonController, + IAccountController accountController, + IClientWindowSizeRepository clientWindowSizeRepository) + : base(mainButtonController, clientWindowSizeRepository) + { + _accountController = accountController; + } - public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - base.InitializeResources(gfxManager, contentProvider); + public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + base.InitializeResources(gfxManager, contentProvider); - _labelsTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 12, true); - } + _labelsTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 12, true); + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - _tbAccountName = GetControl(currentControlSet, GameControlIdentifier.CreateAccountName, GetCreateAccountNameTextBox); - _tbPassword = GetControl(currentControlSet, GameControlIdentifier.CreateAccountPassword, GetCreateAccountPasswordTextBox); - _tbConfirm = GetControl(currentControlSet, GameControlIdentifier.CreateAccountPasswordConfirm, GetCreateAccountConfirmTextBox); - _tbRealName = GetControl(currentControlSet, GameControlIdentifier.CreateAccountRealName, GetCreateAccountRealNameTextBox); - _tbLocation = GetControl(currentControlSet, GameControlIdentifier.CreateAccountLocation, GetCreateAccountLocationTextBox); - _tbEmail = GetControl(currentControlSet, GameControlIdentifier.CreateAccountEmail, GetCreateAccountEmailTextBox); - _btnCancel = GetControl(currentControlSet, GameControlIdentifier.CreateAccountCancelButton, GetCreateAccountCancelButton); - _labels = GetControl(currentControlSet, GameControlIdentifier.CreateAccountLabels, GetCreateAccountLabels); - - _allComponents.Add(_tbAccountName); - _allComponents.Add(_tbPassword); - _allComponents.Add(_tbConfirm); - _allComponents.Add(_tbRealName); - _allComponents.Add(_tbLocation); - _allComponents.Add(_tbEmail); - _allComponents.Add(_btnCancel); - _allComponents.Add(_labels); - - var textBoxes = _allComponents.OfType().ToArray(); - - _tbAccountName.Selected = true; - - base.InitializeControlsHelper(currentControlSet); - } + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + _tbAccountName = GetControl(currentControlSet, GameControlIdentifier.CreateAccountName, GetCreateAccountNameTextBox); + _tbPassword = GetControl(currentControlSet, GameControlIdentifier.CreateAccountPassword, GetCreateAccountPasswordTextBox); + _tbConfirm = GetControl(currentControlSet, GameControlIdentifier.CreateAccountPasswordConfirm, GetCreateAccountConfirmTextBox); + _tbRealName = GetControl(currentControlSet, GameControlIdentifier.CreateAccountRealName, GetCreateAccountRealNameTextBox); + _tbLocation = GetControl(currentControlSet, GameControlIdentifier.CreateAccountLocation, GetCreateAccountLocationTextBox); + _tbEmail = GetControl(currentControlSet, GameControlIdentifier.CreateAccountEmail, GetCreateAccountEmailTextBox); + _btnCancel = GetControl(currentControlSet, GameControlIdentifier.CreateAccountCancelButton, GetCreateAccountCancelButton); + _labels = GetControl(currentControlSet, GameControlIdentifier.CreateAccountLabels, GetCreateAccountLabels); + + _allComponents.Add(_tbAccountName); + _allComponents.Add(_tbPassword); + _allComponents.Add(_tbConfirm); + _allComponents.Add(_tbRealName); + _allComponents.Add(_tbLocation); + _allComponents.Add(_tbEmail); + _allComponents.Add(_btnCancel); + _allComponents.Add(_labels); + + var textBoxes = _allComponents.OfType().ToArray(); + + _tbAccountName.Selected = true; + + base.InitializeControlsHelper(currentControlSet); + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + switch (control) { - switch (control) - { - case GameControlIdentifier.CreateAccountLabels: return _labels; - case GameControlIdentifier.CreateAccountName: return _tbAccountName; - case GameControlIdentifier.CreateAccountPassword: return _tbPassword; - case GameControlIdentifier.CreateAccountPasswordConfirm: return _tbConfirm; - case GameControlIdentifier.CreateAccountRealName: return _tbRealName; - case GameControlIdentifier.CreateAccountLocation: return _tbLocation; - case GameControlIdentifier.CreateAccountEmail: return _tbEmail; - case GameControlIdentifier.CreateAccountCancelButton: return _btnCancel; - default: return base.FindComponentByControlIdentifier(control); - } + case GameControlIdentifier.CreateAccountLabels: return _labels; + case GameControlIdentifier.CreateAccountName: return _tbAccountName; + case GameControlIdentifier.CreateAccountPassword: return _tbPassword; + case GameControlIdentifier.CreateAccountPasswordConfirm: return _tbConfirm; + case GameControlIdentifier.CreateAccountRealName: return _tbRealName; + case GameControlIdentifier.CreateAccountLocation: return _tbLocation; + case GameControlIdentifier.CreateAccountEmail: return _tbEmail; + case GameControlIdentifier.CreateAccountCancelButton: return _btnCancel; + default: return base.FindComponentByControlIdentifier(control); } + } - private IXNATextBox GetCreateAccountNameTextBox() - { - var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountName); - tb.MaxChars = 16; - return tb; - } + private IXNATextBox GetCreateAccountNameTextBox() + { + var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountName); + tb.MaxChars = 16; + return tb; + } - private IXNATextBox GetCreateAccountPasswordTextBox() - { - var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountPassword); - tb.PasswordBox = true; - tb.MaxChars = 12; - return tb; - } + private IXNATextBox GetCreateAccountPasswordTextBox() + { + var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountPassword); + tb.PasswordBox = true; + tb.MaxChars = 12; + return tb; + } - private IXNATextBox GetCreateAccountConfirmTextBox() - { - var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountPasswordConfirm); - tb.PasswordBox = true; - tb.MaxChars = 12; - return tb; - } + private IXNATextBox GetCreateAccountConfirmTextBox() + { + var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountPasswordConfirm); + tb.PasswordBox = true; + tb.MaxChars = 12; + return tb; + } - private IXNATextBox GetCreateAccountRealNameTextBox() - { - return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountRealName); - } + private IXNATextBox GetCreateAccountRealNameTextBox() + { + return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountRealName); + } - private IXNATextBox GetCreateAccountLocationTextBox() - { - return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountLocation); - } + private IXNATextBox GetCreateAccountLocationTextBox() + { + return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountLocation); + } - private IXNATextBox GetCreateAccountEmailTextBox() - { - return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountEmail); - } + private IXNATextBox GetCreateAccountEmailTextBox() + { + return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountEmail); + } - private IXNATextBox AccountInputTextBoxCreationHelper(GameControlIdentifier whichControl) + private IXNATextBox AccountInputTextBoxCreationHelper(GameControlIdentifier whichControl) + { + int i; + switch (whichControl) { - int i; - switch (whichControl) - { - case GameControlIdentifier.CreateAccountName: i = 0; break; - case GameControlIdentifier.CreateAccountPassword: i = 1; break; - case GameControlIdentifier.CreateAccountPasswordConfirm: i = 2; break; - case GameControlIdentifier.CreateAccountRealName: i = 3; break; - case GameControlIdentifier.CreateAccountLocation: i = 4; break; - case GameControlIdentifier.CreateAccountEmail: i = 5; break; - default: throw new ArgumentException("Invalid control specified for helper", nameof(whichControl)); - } - - //set the first 3 Y coord to start at 69 and move up by 51 each time - //set the second 3 Y coord to start at 260 and move up by 51 each time - var txtYCoord = (i < 3 ? 69 : 260) + i % 3 * 51; - var drawArea = new Rectangle(358, txtYCoord, 240, _textBoxBackground.Height); - return new XNATextBox(drawArea, - Constants.FontSize08, - _textBoxBackground, - _textBoxLeft, - _textBoxRight, - _textBoxCursor) - { - LeftPadding = 4, - MaxChars = 35, - Text = "", - DefaultText = " ", - TabOrder = whichControl - GameControlIdentifier.CreateAccountName - }; + case GameControlIdentifier.CreateAccountName: i = 0; break; + case GameControlIdentifier.CreateAccountPassword: i = 1; break; + case GameControlIdentifier.CreateAccountPasswordConfirm: i = 2; break; + case GameControlIdentifier.CreateAccountRealName: i = 3; break; + case GameControlIdentifier.CreateAccountLocation: i = 4; break; + case GameControlIdentifier.CreateAccountEmail: i = 5; break; + default: throw new ArgumentException("Invalid control specified for helper", nameof(whichControl)); } - private IXNAButton GetCreateAccountCancelButton() + //set the first 3 Y coord to start at 69 and move up by 51 each time + //set the second 3 Y coord to start at 260 and move up by 51 each time + var txtYCoord = (i < 3 ? 69 : 260) + i % 3 * 51; + var drawArea = new Rectangle(358, txtYCoord, 240, _textBoxBackground.Height); + return new XNATextBox(drawArea, + Constants.FontSize08, + _textBoxBackground, + _textBoxLeft, + _textBoxRight, + _textBoxCursor) { - var button = new XNAButton(_secondaryButtonTexture, - new Vector2(481, 417), - new Rectangle(0, 40, 120, 40), - new Rectangle(120, 40, 120, 40)); - button.OnClick += (o, e) => _mainButtonController.GoToInitialState(); - return button; - } + LeftPadding = 4, + MaxChars = 35, + Text = "", + DefaultText = " ", + TabOrder = whichControl - GameControlIdentifier.CreateAccountName + }; + } - private IXNAPanel GetCreateAccountLabels() + private IXNAButton GetCreateAccountCancelButton() + { + var button = new XNAButton(_secondaryButtonTexture, + new Vector2(481, 417), + new Rectangle(0, 40, 120, 40), + new Rectangle(120, 40, 120, 40)); + button.OnClick += (o, e) => _mainButtonController.GoToInitialState(); + return button; + } + + private IXNAPanel GetCreateAccountLabels() + { + var labelsPanel = new XNAPanel(); + for (int srcYIndex = 0; srcYIndex < 6; ++srcYIndex) { - var labelsPanel = new XNAPanel(); - for (int srcYIndex = 0; srcYIndex < 6; ++srcYIndex) + var texturePictureBox = new XNAPictureBox { - var texturePictureBox = new XNAPictureBox - { - Texture = _labelsTexture, - SourceRectangle = new Rectangle(0, srcYIndex * (srcYIndex < 2 ? 14 : 15), 149, 15), - DrawPosition = new Vector2(430, (srcYIndex < 3 ? 50 : 241) + 10 + srcYIndex % 3 * 51) - }; - texturePictureBox.SetParentControl(labelsPanel); - } - return labelsPanel; + Texture = _labelsTexture, + SourceRectangle = new Rectangle(0, srcYIndex * (srcYIndex < 2 ? 14 : 15), 149, 15), + DrawPosition = new Vector2(430, (srcYIndex < 3 ? 50 : 241) + 10 + srcYIndex % 3 * 51) + }; + texturePictureBox.SetParentControl(labelsPanel); } + return labelsPanel; + } - protected override IXNAButton GetCreateButton() - { - var button = base.GetCreateButton(); - button.OnClick += DoCreateAccount; - return button; - } + protected override IXNAButton GetCreateButton() + { + var button = base.GetCreateButton(); + button.OnClick += DoCreateAccount; + return button; + } - private void DoCreateAccount(object sender, EventArgs e) + private void DoCreateAccount(object sender, EventArgs e) + { + if (_createAccountTask == null) { - if (_createAccountTask == null) - { - _createAccountTask = _accountController.CreateAccount( - new CreateAccountParameters(_tbAccountName.Text, - _tbPassword.Text, - _tbConfirm.Text, - _tbRealName.Text, - _tbLocation.Text, - _tbEmail.Text)); - _createAccountTask.ContinueWith(_ => _createAccountTask = null); - } + _createAccountTask = _accountController.CreateAccount( + new CreateAccountParameters(_tbAccountName.Text, + _tbPassword.Text, + _tbConfirm.Text, + _tbRealName.Text, + _tbLocation.Text, + _tbEmail.Text)); + _createAccountTask.ContinueWith(_ => _createAccountTask = null); } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/EmptyControlSet.cs b/EndlessClient/ControlSets/EmptyControlSet.cs index 1fe96ebbe..33f7a76be 100644 --- a/EndlessClient/ControlSets/EmptyControlSet.cs +++ b/EndlessClient/ControlSets/EmptyControlSet.cs @@ -6,34 +6,33 @@ using System.Linq; using XNAControls; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +/// +/// An empty control set that represents the initial state of the game with no controls +/// +public class EmptyControlSet : IControlSet { - /// - /// An empty control set that represents the initial state of the game with no controls - /// - public class EmptyControlSet : IControlSet - { - public GameStates GameState => GameStates.None; + public GameStates GameState => GameStates.None; - public IReadOnlyList AllComponents => Enumerable.Empty().ToList(); + public IReadOnlyList AllComponents => Enumerable.Empty().ToList(); - public IReadOnlyList XNAControlComponents => AllComponents.OfType().ToList(); + public IReadOnlyList XNAControlComponents => AllComponents.OfType().ToList(); - public void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - } + public void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + } - public void InitializeControls(IControlSet currentControlSet) - { - } + public void InitializeControls(IControlSet currentControlSet) + { + } - public IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) - { - return null; - } + public IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + return null; + } - public void Dispose() - { - } + public void Dispose() + { } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/GameControlIdentifier.cs b/EndlessClient/ControlSets/GameControlIdentifier.cs index 19f429449..15259325f 100644 --- a/EndlessClient/ControlSets/GameControlIdentifier.cs +++ b/EndlessClient/ControlSets/GameControlIdentifier.cs @@ -1,41 +1,40 @@ -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public enum GameControlIdentifier { - public enum GameControlIdentifier - { - InitialCreateAccount, - InitialLogin, - InitialViewCredits, - InitialExitGame, - InitialVersionLabel, + InitialCreateAccount, + InitialLogin, + InitialViewCredits, + InitialExitGame, + InitialVersionLabel, - CreateAccountLabels, - CreateAccountName, - CreateAccountPassword, - CreateAccountPasswordConfirm, - CreateAccountRealName, - CreateAccountLocation, - CreateAccountEmail, - CreateAccountButton, - CreateAccountCancelButton, + CreateAccountLabels, + CreateAccountName, + CreateAccountPassword, + CreateAccountPasswordConfirm, + CreateAccountRealName, + CreateAccountLocation, + CreateAccountEmail, + CreateAccountButton, + CreateAccountCancelButton, - LoginPanelBackground, - LoginAccountName, - LoginPassword, - LoginButton, - LoginCancel, + LoginPanelBackground, + LoginAccountName, + LoginPassword, + LoginButton, + LoginCancel, - CreditsLabel, + CreditsLabel, - BackButton, - PersonDisplay1, - PersonDisplay2, - BackgroundImage, + BackButton, + PersonDisplay1, + PersonDisplay2, + BackgroundImage, - CreateCharacterButton, - ChangePasswordButton, + CreateCharacterButton, + ChangePasswordButton, - Character1Panel, - Character2Panel, - Character3Panel - } + Character1Panel, + Character2Panel, + Character3Panel } \ No newline at end of file diff --git a/EndlessClient/ControlSets/IControlSet.cs b/EndlessClient/ControlSets/IControlSet.cs index c77c536a4..d2ce1acbd 100644 --- a/EndlessClient/ControlSets/IControlSet.cs +++ b/EndlessClient/ControlSets/IControlSet.cs @@ -6,43 +6,42 @@ using System.Collections.Generic; using XNAControls; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public interface IControlSet : IDisposable { - public interface IControlSet : IDisposable - { - /// - /// The game state that this control set represents - /// - GameStates GameState { get; } + /// + /// The game state that this control set represents + /// + GameStates GameState { get; } - /// - /// All components in this control set - /// - IReadOnlyList AllComponents { get; } + /// + /// All components in this control set + /// + IReadOnlyList AllComponents { get; } - /// - /// Components in this control set that are XNAControls - /// - IReadOnlyList XNAControlComponents { get; } + /// + /// Components in this control set that are XNAControls + /// + IReadOnlyList XNAControlComponents { get; } - /// - /// Initialize the required resources for the control set from the resource dependencies. Should be called before InitializeControls() - /// - /// An initialized native graphics manager - /// The ContentProvider for the game - void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider); + /// + /// Initialize the required resources for the control set from the resource dependencies. Should be called before InitializeControls() + /// + /// An initialized native graphics manager + /// The ContentProvider for the game + void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider); - /// - /// Create the controls for this IControlSet based on an existing set of controls - /// - /// The current active set of controls - void InitializeControls(IControlSet currentControlSet); + /// + /// Create the controls for this IControlSet based on an existing set of controls + /// + /// The current active set of controls + void InitializeControls(IControlSet currentControlSet); - /// - /// Find an existing component from this game control set - /// - /// The control specification - /// The matching control - IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control); - } + /// + /// Find an existing component from this game control set + /// + /// The control specification + /// The matching control + IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control); } \ No newline at end of file diff --git a/EndlessClient/ControlSets/IControlSetFactory.cs b/EndlessClient/ControlSets/IControlSetFactory.cs index 7117fc67f..e8759d5d3 100644 --- a/EndlessClient/ControlSets/IControlSetFactory.cs +++ b/EndlessClient/ControlSets/IControlSetFactory.cs @@ -1,15 +1,14 @@ using EndlessClient.Controllers; using EndlessClient.GameExecution; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public interface IControlSetFactory { - public interface IControlSetFactory - { - IControlSet CreateControlsForState(GameStates newState, IControlSet currentControlSet); + IControlSet CreateControlsForState(GameStates newState, IControlSet currentControlSet); - void InjectControllers(IMainButtonController mainButtonController, - IAccountController accountController, - ILoginController loginController, - ICharacterManagementController characterManagementController); - } + void InjectControllers(IMainButtonController mainButtonController, + IAccountController accountController, + ILoginController loginController, + ICharacterManagementController characterManagementController); } \ No newline at end of file diff --git a/EndlessClient/ControlSets/IControlSetRepository.cs b/EndlessClient/ControlSets/IControlSetRepository.cs index efddacb41..cc76e581d 100644 --- a/EndlessClient/ControlSets/IControlSetRepository.cs +++ b/EndlessClient/ControlSets/IControlSetRepository.cs @@ -1,26 +1,25 @@ using AutomaticTypeMapper; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public interface IControlSetRepository { - public interface IControlSetRepository - { - IControlSet CurrentControlSet { get; set; } - } + IControlSet CurrentControlSet { get; set; } +} - public interface IControlSetProvider - { - IControlSet CurrentControlSet { get; } - } +public interface IControlSetProvider +{ + IControlSet CurrentControlSet { get; } +} - [MappedType(BaseType = typeof(IControlSetRepository), IsSingleton = true)] - [MappedType(BaseType = typeof(IControlSetProvider), IsSingleton = true)] - public class ControlSetRepository : IControlSetRepository, IControlSetProvider - { - public IControlSet CurrentControlSet { get; set; } +[MappedType(BaseType = typeof(IControlSetRepository), IsSingleton = true)] +[MappedType(BaseType = typeof(IControlSetProvider), IsSingleton = true)] +public class ControlSetRepository : IControlSetRepository, IControlSetProvider +{ + public IControlSet CurrentControlSet { get; set; } - public ControlSetRepository() - { - CurrentControlSet = new EmptyControlSet(); - } + public ControlSetRepository() + { + CurrentControlSet = new EmptyControlSet(); } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/IHudControlProvider.cs b/EndlessClient/ControlSets/IHudControlProvider.cs index c6693c135..ff7160750 100644 --- a/EndlessClient/ControlSets/IHudControlProvider.cs +++ b/EndlessClient/ControlSets/IHudControlProvider.cs @@ -6,65 +6,64 @@ using System; using System.Collections.Generic; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public interface IHudControlProvider { - public interface IHudControlProvider - { - bool IsInGame { get; } + bool IsInGame { get; } - InGameControlSet ControlSet { get; } + InGameControlSet ControlSet { get; } - IReadOnlyList HudPanels { get; } + IReadOnlyList HudPanels { get; } - T GetComponent(HudControlIdentifier identifier) where T : IGameComponent; - } + T GetComponent(HudControlIdentifier identifier) where T : IGameComponent; +} - [MappedType(BaseType = typeof(IHudControlProvider), IsSingleton = true)] - public class HudControlProvider : IHudControlProvider - { - private readonly IGameStateProvider _gameStateProvider; - private readonly IControlSetProvider _controlSetProvider; +[MappedType(BaseType = typeof(IHudControlProvider), IsSingleton = true)] +public class HudControlProvider : IHudControlProvider +{ + private readonly IGameStateProvider _gameStateProvider; + private readonly IControlSetProvider _controlSetProvider; - public bool IsInGame => _gameStateProvider.CurrentState == GameStates.PlayingTheGame && - _controlSetProvider.CurrentControlSet.GameState == GameStates.PlayingTheGame && - _controlSetProvider.CurrentControlSet is InGameControlSet; + public bool IsInGame => _gameStateProvider.CurrentState == GameStates.PlayingTheGame && + _controlSetProvider.CurrentControlSet.GameState == GameStates.PlayingTheGame && + _controlSetProvider.CurrentControlSet is InGameControlSet; - public InGameControlSet ControlSet + public InGameControlSet ControlSet + { + get { - get - { - if (!IsInGame) - throw new InvalidOperationException("Not currently in game, in game control set does not exist"); + if (!IsInGame) + throw new InvalidOperationException("Not currently in game, in game control set does not exist"); - return (InGameControlSet)_controlSetProvider.CurrentControlSet; - } + return (InGameControlSet)_controlSetProvider.CurrentControlSet; } + } - public IReadOnlyList HudPanels => new[] - { - GetComponent(HudControlIdentifier.NewsPanel), - GetComponent(HudControlIdentifier.InventoryPanel), - GetComponent(HudControlIdentifier.ActiveSpellsPanel), - GetComponent(HudControlIdentifier.PassiveSpellsPanel), - GetComponent(HudControlIdentifier.ChatPanel), - GetComponent(HudControlIdentifier.StatsPanel), - GetComponent(HudControlIdentifier.OnlineListPanel), - GetComponent(HudControlIdentifier.PartyPanel), - //macro panel - GetComponent(HudControlIdentifier.SettingsPanel), - GetComponent(HudControlIdentifier.HelpPanel) - }; + public IReadOnlyList HudPanels => new[] + { + GetComponent(HudControlIdentifier.NewsPanel), + GetComponent(HudControlIdentifier.InventoryPanel), + GetComponent(HudControlIdentifier.ActiveSpellsPanel), + GetComponent(HudControlIdentifier.PassiveSpellsPanel), + GetComponent(HudControlIdentifier.ChatPanel), + GetComponent(HudControlIdentifier.StatsPanel), + GetComponent(HudControlIdentifier.OnlineListPanel), + GetComponent(HudControlIdentifier.PartyPanel), + //macro panel + GetComponent(HudControlIdentifier.SettingsPanel), + GetComponent(HudControlIdentifier.HelpPanel) + }; - public HudControlProvider(IGameStateProvider gameStateProvider, - IControlSetProvider controlSetProvider) - { - _gameStateProvider = gameStateProvider; - _controlSetProvider = controlSetProvider; - } + public HudControlProvider(IGameStateProvider gameStateProvider, + IControlSetProvider controlSetProvider) + { + _gameStateProvider = gameStateProvider; + _controlSetProvider = controlSetProvider; + } - public T GetComponent(HudControlIdentifier identifier) where T : IGameComponent - { - return ControlSet.GetHudComponent(identifier); - } + public T GetComponent(HudControlIdentifier identifier) where T : IGameComponent + { + return ControlSet.GetHudComponent(identifier); } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/InGameControlSet.cs b/EndlessClient/ControlSets/InGameControlSet.cs index 12bb0dfd6..0a4bcf56e 100644 --- a/EndlessClient/ControlSets/InGameControlSet.cs +++ b/EndlessClient/ControlSets/InGameControlSet.cs @@ -11,63 +11,62 @@ using System.Linq; using XNAControls; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public class InGameControlSet : BackButtonControlSet { - public class InGameControlSet : BackButtonControlSet - { - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IHudControlsFactory _hudControlsFactory; - private readonly IActiveDialogRepository _activeDialogRepository; - private IReadOnlyDictionary _controls; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IHudControlsFactory _hudControlsFactory; + private readonly IActiveDialogRepository _activeDialogRepository; + private IReadOnlyDictionary _controls; - public override GameStates GameState => GameStates.PlayingTheGame; + public override GameStates GameState => GameStates.PlayingTheGame; - public InGameControlSet(IMainButtonController mainButtonController, - IEOMessageBoxFactory messageBoxFactory, - IHudControlsFactory hudControlsFactory, - IActiveDialogRepository activeDialogRepository, - IClientWindowSizeRepository clientWindowSizeRepository) - : base(mainButtonController, clientWindowSizeRepository) - { - _messageBoxFactory = messageBoxFactory; - _hudControlsFactory = hudControlsFactory; - _activeDialogRepository = activeDialogRepository; - _controls = new Dictionary(); - } + public InGameControlSet(IMainButtonController mainButtonController, + IEOMessageBoxFactory messageBoxFactory, + IHudControlsFactory hudControlsFactory, + IActiveDialogRepository activeDialogRepository, + IClientWindowSizeRepository clientWindowSizeRepository) + : base(mainButtonController, clientWindowSizeRepository) + { + _messageBoxFactory = messageBoxFactory; + _hudControlsFactory = hudControlsFactory; + _activeDialogRepository = activeDialogRepository; + _controls = new Dictionary(); + } - public T GetHudComponent(HudControlIdentifier whichControl) - where T : IGameComponent - { - return (T)_controls[whichControl]; - } + public T GetHudComponent(HudControlIdentifier whichControl) + where T : IGameComponent + { + return (T)_controls[whichControl]; + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - _controls = _hudControlsFactory.CreateHud(); - _allComponents.AddRange(_controls.Select(x => x.Value)); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + _controls = _hudControlsFactory.CreateHud(); + _allComponents.AddRange(_controls.Select(x => x.Value)); - base.InitializeControlsHelper(currentControlSet); - } + base.InitializeControlsHelper(currentControlSet); + } - protected override async void DoBackButtonClick(object sender, EventArgs e) - { - var messageBox = _messageBoxFactory.CreateMessageBox( - DialogResourceID.EXIT_GAME_ARE_YOU_SURE, - EODialogButtons.OkCancel); + protected override async void DoBackButtonClick(object sender, EventArgs e) + { + var messageBox = _messageBoxFactory.CreateMessageBox( + DialogResourceID.EXIT_GAME_ARE_YOU_SURE, + EODialogButtons.OkCancel); - var result = await messageBox.ShowDialogAsync(); - if (result == XNADialogResult.OK) - _mainButtonController.GoToInitialStateAndDisconnect(); - } + var result = await messageBox.ShowDialogAsync(); + if (result == XNADialogResult.OK) + _mainButtonController.GoToInitialStateAndDisconnect(); + } - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - _activeDialogRepository.Dispose(); - } - - base.Dispose(disposing); + _activeDialogRepository.Dispose(); } + + base.Dispose(disposing); } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/InitialControlSet.cs b/EndlessClient/ControlSets/InitialControlSet.cs index 11c4d8a31..92aff0895 100644 --- a/EndlessClient/ControlSets/InitialControlSet.cs +++ b/EndlessClient/ControlSets/InitialControlSet.cs @@ -10,166 +10,165 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public class InitialControlSet : BaseControlSet { - public class InitialControlSet : BaseControlSet - { - private readonly IConfigurationProvider _configProvider; - private readonly IMainButtonController _mainButtonController; + private readonly IConfigurationProvider _configProvider; + private readonly IMainButtonController _mainButtonController; - private IXNAButton _createAccount, - _login, - _viewCredits, - _exitGame; - private IXNALabel _versionInfo; + private IXNAButton _createAccount, + _login, + _viewCredits, + _exitGame; + private IXNALabel _versionInfo; - protected IXNAPictureBox _personPicture; + protected IXNAPictureBox _personPicture; - private readonly Texture2D[] _personSet1; - private readonly Random _randomGen; + private readonly Texture2D[] _personSet1; + private readonly Random _randomGen; - private Task _mainButtonClickTask; + private Task _mainButtonClickTask; - public override GameStates GameState => GameStates.Initial; + public override GameStates GameState => GameStates.Initial; - public InitialControlSet(IConfigurationProvider configProvider, - IMainButtonController mainButtonController) - { - _configProvider = configProvider; - _mainButtonController = mainButtonController; - _personSet1 = new Texture2D[4]; - _randomGen = new Random(); - } + public InitialControlSet(IConfigurationProvider configProvider, + IMainButtonController mainButtonController) + { + _configProvider = configProvider; + _mainButtonController = mainButtonController; + _personSet1 = new Texture2D[4]; + _randomGen = new Random(); + } - public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - base.InitializeResources(gfxManager, contentProvider); + public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + base.InitializeResources(gfxManager, contentProvider); - for (int i = 0; i < _personSet1.Length; ++i) - _personSet1[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 41 + i, true); - } + for (int i = 0; i < _personSet1.Length; ++i) + _personSet1[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 41 + i, true); + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - _createAccount = GetControl(currentControlSet, GameControlIdentifier.InitialCreateAccount, GetMainCreateAccountButton); - _login = GetControl(currentControlSet, GameControlIdentifier.InitialLogin, GetMainLoginButton); - _viewCredits = GetControl(currentControlSet, GameControlIdentifier.InitialViewCredits, GetViewCreditsButton); - _exitGame = GetControl(currentControlSet, GameControlIdentifier.InitialExitGame, GetExitButton); - _versionInfo = GetControl(currentControlSet, GameControlIdentifier.InitialVersionLabel, GetVersionInfoLabel); - _personPicture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay1, GetPersonPicture1); - - _allComponents.Add(_createAccount); - _allComponents.Add(_login); - _allComponents.Add(_viewCredits); - _allComponents.Add(_exitGame); - _allComponents.Add(_versionInfo); - _allComponents.Add(_personPicture); - } + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + _createAccount = GetControl(currentControlSet, GameControlIdentifier.InitialCreateAccount, GetMainCreateAccountButton); + _login = GetControl(currentControlSet, GameControlIdentifier.InitialLogin, GetMainLoginButton); + _viewCredits = GetControl(currentControlSet, GameControlIdentifier.InitialViewCredits, GetViewCreditsButton); + _exitGame = GetControl(currentControlSet, GameControlIdentifier.InitialExitGame, GetExitButton); + _versionInfo = GetControl(currentControlSet, GameControlIdentifier.InitialVersionLabel, GetVersionInfoLabel); + _personPicture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay1, GetPersonPicture1); + + _allComponents.Add(_createAccount); + _allComponents.Add(_login); + _allComponents.Add(_viewCredits); + _allComponents.Add(_exitGame); + _allComponents.Add(_versionInfo); + _allComponents.Add(_personPicture); + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + switch (control) { - switch (control) - { - case GameControlIdentifier.InitialCreateAccount: return _createAccount; - case GameControlIdentifier.InitialLogin: return _login; - case GameControlIdentifier.InitialViewCredits: return _viewCredits; - case GameControlIdentifier.InitialExitGame: return _exitGame; - case GameControlIdentifier.InitialVersionLabel: return _versionInfo; - case GameControlIdentifier.PersonDisplay1: return _personPicture; - default: return base.FindComponentByControlIdentifier(control); - } + case GameControlIdentifier.InitialCreateAccount: return _createAccount; + case GameControlIdentifier.InitialLogin: return _login; + case GameControlIdentifier.InitialViewCredits: return _viewCredits; + case GameControlIdentifier.InitialExitGame: return _exitGame; + case GameControlIdentifier.InitialVersionLabel: return _versionInfo; + case GameControlIdentifier.PersonDisplay1: return _personPicture; + default: return base.FindComponentByControlIdentifier(control); } + } - private IXNAButton GetMainCreateAccountButton() - { - var button = MainButtonCreationHelper(GameControlIdentifier.InitialCreateAccount); - button.OnClick += (o, e) => AsyncMainButtonClick(_mainButtonController.ClickCreateAccount); - return button; - } + private IXNAButton GetMainCreateAccountButton() + { + var button = MainButtonCreationHelper(GameControlIdentifier.InitialCreateAccount); + button.OnClick += (o, e) => AsyncMainButtonClick(_mainButtonController.ClickCreateAccount); + return button; + } - private IXNAButton GetMainLoginButton() - { - var button = MainButtonCreationHelper(GameControlIdentifier.InitialLogin); - button.OnClick += (o, e) => AsyncMainButtonClick(_mainButtonController.ClickLogin); - return button; - } + private IXNAButton GetMainLoginButton() + { + var button = MainButtonCreationHelper(GameControlIdentifier.InitialLogin); + button.OnClick += (o, e) => AsyncMainButtonClick(_mainButtonController.ClickLogin); + return button; + } - private IXNAButton GetViewCreditsButton() - { - var button = MainButtonCreationHelper(GameControlIdentifier.InitialViewCredits); - button.OnClick += (o, e) => _mainButtonController.ClickViewCredits(); - return button; - } + private IXNAButton GetViewCreditsButton() + { + var button = MainButtonCreationHelper(GameControlIdentifier.InitialViewCredits); + button.OnClick += (o, e) => _mainButtonController.ClickViewCredits(); + return button; + } - private IXNAButton GetExitButton() - { - var button = MainButtonCreationHelper(GameControlIdentifier.InitialExitGame); - button.OnClick += (o, e) => _mainButtonController.ClickExit(); - return button; - } + private IXNAButton GetExitButton() + { + var button = MainButtonCreationHelper(GameControlIdentifier.InitialExitGame); + button.OnClick += (o, e) => _mainButtonController.ClickExit(); + return button; + } - private void AsyncMainButtonClick(Func clickHandler) + private void AsyncMainButtonClick(Func clickHandler) + { + if (_mainButtonClickTask == null) { - if (_mainButtonClickTask == null) - { - _mainButtonClickTask = clickHandler(); - _mainButtonClickTask.ContinueWith(_ => _mainButtonClickTask = null); - } + _mainButtonClickTask = clickHandler(); + _mainButtonClickTask.ContinueWith(_ => _mainButtonClickTask = null); } + } - private IXNAButton MainButtonCreationHelper(GameControlIdentifier whichControl) + private IXNAButton MainButtonCreationHelper(GameControlIdentifier whichControl) + { + int i; + switch (whichControl) { - int i; - switch (whichControl) - { - case GameControlIdentifier.InitialCreateAccount: i = 0; break; - case GameControlIdentifier.InitialLogin: i = 1; break; - case GameControlIdentifier.InitialViewCredits: i = 2; break; - case GameControlIdentifier.InitialExitGame: i = 3; break; - default: throw new ArgumentException("Invalid control specified for helper", nameof(whichControl)); - } - - var widthFactor = _mainButtonTexture.Width / 2; - var heightFactor = _mainButtonTexture.Height / 4; - var outSource = new Rectangle(0, i * heightFactor, widthFactor, heightFactor); - var overSource = new Rectangle(widthFactor, i * heightFactor, widthFactor, heightFactor); - - return new XNAButton(_mainButtonTexture, new Vector2(25, 280 + i * 40), outSource, overSource) - { - //DrawOrder = i + 1 - }; + case GameControlIdentifier.InitialCreateAccount: i = 0; break; + case GameControlIdentifier.InitialLogin: i = 1; break; + case GameControlIdentifier.InitialViewCredits: i = 2; break; + case GameControlIdentifier.InitialExitGame: i = 3; break; + default: throw new ArgumentException("Invalid control specified for helper", nameof(whichControl)); } - private IXNALabel GetVersionInfoLabel() + var widthFactor = _mainButtonTexture.Width / 2; + var heightFactor = _mainButtonTexture.Height / 4; + var outSource = new Rectangle(0, i * heightFactor, widthFactor, heightFactor); + var overSource = new Rectangle(widthFactor, i * heightFactor, widthFactor, heightFactor); + + return new XNAButton(_mainButtonTexture, new Vector2(25, 280 + i * 40), outSource, overSource) { - return new XNALabel(Constants.FontSize07) - { - AutoSize = true, - Text = string.Format(Constants.VersionInfoFormat, - _configProvider.VersionMajor, - _configProvider.VersionMinor, - _configProvider.VersionBuild, - _configProvider.Host, - _configProvider.Port), - ForeColor = Color.FromNonPremultiplied(190, 170, 150, 255), - DrawArea = new Rectangle(28, 457, 1, 1) - }; - } + //DrawOrder = i + 1 + }; + } - private IXNAPictureBox GetPersonPicture1() + private IXNALabel GetVersionInfoLabel() + { + return new XNALabel(Constants.FontSize07) { - var texture = _personSet1[_randomGen.Next(4)]; - return new XNAPictureBox - { - Texture = texture, - DrawArea = new Rectangle(229, 70, texture.Width, texture.Height) - }; - } + AutoSize = true, + Text = string.Format(Constants.VersionInfoFormat, + _configProvider.VersionMajor, + _configProvider.VersionMinor, + _configProvider.VersionBuild, + _configProvider.Host, + _configProvider.Port), + ForeColor = Color.FromNonPremultiplied(190, 170, 150, 255), + DrawArea = new Rectangle(28, 457, 1, 1) + }; + } - protected void ExcludePersonPicture1() + private IXNAPictureBox GetPersonPicture1() + { + var texture = _personSet1[_randomGen.Next(4)]; + return new XNAPictureBox { - _personPicture.Dispose(); - _allComponents.Remove(_personPicture); - } + Texture = texture, + DrawArea = new Rectangle(229, 70, texture.Width, texture.Height) + }; + } + + protected void ExcludePersonPicture1() + { + _personPicture.Dispose(); + _allComponents.Remove(_personPicture); } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/IntermediateControlSet.cs b/EndlessClient/ControlSets/IntermediateControlSet.cs index 63ebe9f95..6d581fd9a 100644 --- a/EndlessClient/ControlSets/IntermediateControlSet.cs +++ b/EndlessClient/ControlSets/IntermediateControlSet.cs @@ -8,76 +8,75 @@ using System; using XNAControls; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public abstract class IntermediateControlSet : BackButtonControlSet { - public abstract class IntermediateControlSet : BackButtonControlSet - { - private readonly Texture2D[] _personSet2; - private readonly Random _randomGen; + private readonly Texture2D[] _personSet2; + private readonly Random _randomGen; - private IXNAButton _btnCreate; - private IXNAPictureBox _person2Picture; + private IXNAButton _btnCreate; + private IXNAPictureBox _person2Picture; - protected IntermediateControlSet(IMainButtonController mainButtonController, - IClientWindowSizeRepository clientWindowSizeRepository) - : base(mainButtonController, clientWindowSizeRepository) - { - _personSet2 = new Texture2D[8]; - _randomGen = new Random(); - } + protected IntermediateControlSet(IMainButtonController mainButtonController, + IClientWindowSizeRepository clientWindowSizeRepository) + : base(mainButtonController, clientWindowSizeRepository) + { + _personSet2 = new Texture2D[8]; + _randomGen = new Random(); + } - public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - base.InitializeResources(gfxManager, contentProvider); + public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + base.InitializeResources(gfxManager, contentProvider); - for (int i = 0; i < _personSet2.Length; ++i) - _personSet2[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 61 + i, true); - } + for (int i = 0; i < _personSet2.Length; ++i) + _personSet2[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 61 + i, true); + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - _btnCreate = GetControl(currentControlSet, - GameState == GameStates.LoggedIn ? GameControlIdentifier.CreateCharacterButton : GameControlIdentifier.CreateAccountButton, - GetCreateButton); - _person2Picture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay2, GetPerson2Picture); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + _btnCreate = GetControl(currentControlSet, + GameState == GameStates.LoggedIn ? GameControlIdentifier.CreateCharacterButton : GameControlIdentifier.CreateAccountButton, + GetCreateButton); + _person2Picture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay2, GetPerson2Picture); - _allComponents.Add(_btnCreate); - _allComponents.Add(_person2Picture); + _allComponents.Add(_btnCreate); + _allComponents.Add(_person2Picture); - base.InitializeControlsHelper(currentControlSet); - } + base.InitializeControlsHelper(currentControlSet); + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + switch (control) { - switch (control) - { - case GameControlIdentifier.CreateAccountButton: - return GameState == GameStates.CreateAccount ? _btnCreate : null; - case GameControlIdentifier.CreateCharacterButton: - return GameState == GameStates.LoggedIn ? _btnCreate : null; - case GameControlIdentifier.PersonDisplay2: return _person2Picture; - default: return base.FindComponentByControlIdentifier(control); - } + case GameControlIdentifier.CreateAccountButton: + return GameState == GameStates.CreateAccount ? _btnCreate : null; + case GameControlIdentifier.CreateCharacterButton: + return GameState == GameStates.LoggedIn ? _btnCreate : null; + case GameControlIdentifier.PersonDisplay2: return _person2Picture; + default: return base.FindComponentByControlIdentifier(control); } + } - protected virtual IXNAButton GetCreateButton() - { - var isCreateCharacterButton = GameState == GameStates.LoggedIn; - var button = new XNAButton(_secondaryButtonTexture, - new Vector2(isCreateCharacterButton ? 334 : 359, 417), - new Rectangle(0, 0, 120, 40), - new Rectangle(120, 0, 120, 40)); - return button; - } + protected virtual IXNAButton GetCreateButton() + { + var isCreateCharacterButton = GameState == GameStates.LoggedIn; + var button = new XNAButton(_secondaryButtonTexture, + new Vector2(isCreateCharacterButton ? 334 : 359, 417), + new Rectangle(0, 0, 120, 40), + new Rectangle(120, 0, 120, 40)); + return button; + } - private IXNAPictureBox GetPerson2Picture() + private IXNAPictureBox GetPerson2Picture() + { + var texture = _personSet2[_randomGen.Next(8)]; + return new XNAPictureBox { - var texture = _personSet2[_randomGen.Next(8)]; - return new XNAPictureBox - { - Texture = texture, - DrawArea = new Rectangle(43, 140, texture.Width, texture.Height) - }; - } + Texture = texture, + DrawArea = new Rectangle(43, 140, texture.Width, texture.Height) + }; } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/LoggedInControlSet.cs b/EndlessClient/ControlSets/LoggedInControlSet.cs index 325b4895b..f37a12550 100644 --- a/EndlessClient/ControlSets/LoggedInControlSet.cs +++ b/EndlessClient/ControlSets/LoggedInControlSet.cs @@ -10,97 +10,96 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public class LoggedInControlSet : IntermediateControlSet { - public class LoggedInControlSet : IntermediateControlSet - { - private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; - private readonly ICharacterSelectorProvider _characterSelectorProvider; - private readonly ICharacterManagementController _characterManagementController; - private readonly IAccountController _accountController; - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IUserInputRepository _userInputRepository; - private readonly List _characterInfoPanels; + private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; + private readonly ICharacterSelectorProvider _characterSelectorProvider; + private readonly ICharacterManagementController _characterManagementController; + private readonly IAccountController _accountController; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IUserInputRepository _userInputRepository; + private readonly List _characterInfoPanels; - private IXNAButton _changePasswordButton; + private IXNAButton _changePasswordButton; - private Task _loggedInActionTask; + private Task _loggedInActionTask; - public override GameStates GameState => GameStates.LoggedIn; + public override GameStates GameState => GameStates.LoggedIn; - public LoggedInControlSet(IMainButtonController mainButtonController, - ICharacterInfoPanelFactory characterInfoPanelFactory, - ICharacterSelectorProvider characterSelectorProvider, - ICharacterManagementController characterManagementController, - IAccountController accountController, - IEndlessGameProvider endlessGameProvider, - IUserInputRepository userInputRepository, - IClientWindowSizeRepository clientWindowSizeRepository) - : base(mainButtonController, clientWindowSizeRepository) - { - _characterInfoPanelFactory = characterInfoPanelFactory; - _characterSelectorProvider = characterSelectorProvider; - _characterManagementController = characterManagementController; - _accountController = accountController; - _endlessGameProvider = endlessGameProvider; - _userInputRepository = userInputRepository; - _characterInfoPanels = new List(); - } + public LoggedInControlSet(IMainButtonController mainButtonController, + ICharacterInfoPanelFactory characterInfoPanelFactory, + ICharacterSelectorProvider characterSelectorProvider, + ICharacterManagementController characterManagementController, + IAccountController accountController, + IEndlessGameProvider endlessGameProvider, + IUserInputRepository userInputRepository, + IClientWindowSizeRepository clientWindowSizeRepository) + : base(mainButtonController, clientWindowSizeRepository) + { + _characterInfoPanelFactory = characterInfoPanelFactory; + _characterSelectorProvider = characterSelectorProvider; + _characterManagementController = characterManagementController; + _accountController = accountController; + _endlessGameProvider = endlessGameProvider; + _userInputRepository = userInputRepository; + _characterInfoPanels = new List(); + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - base.InitializeControlsHelper(currentControlSet); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + base.InitializeControlsHelper(currentControlSet); - _changePasswordButton = GetControl(currentControlSet, GameControlIdentifier.ChangePasswordButton, GetPasswordButton); - _characterInfoPanels.AddRange(_characterInfoPanelFactory.CreatePanels(_characterSelectorProvider.Characters)); + _changePasswordButton = GetControl(currentControlSet, GameControlIdentifier.ChangePasswordButton, GetPasswordButton); + _characterInfoPanels.AddRange(_characterInfoPanelFactory.CreatePanels(_characterSelectorProvider.Characters)); - _allComponents.Add(new CurrentUserInputTracker(_endlessGameProvider, _userInputRepository)); - _allComponents.Add(new PreviousUserInputTracker(_endlessGameProvider, _userInputRepository)); - _allComponents.Add(_changePasswordButton); - _allComponents.AddRange(_characterInfoPanels); - } + _allComponents.Add(new CurrentUserInputTracker(_endlessGameProvider, _userInputRepository)); + _allComponents.Add(new PreviousUserInputTracker(_endlessGameProvider, _userInputRepository)); + _allComponents.Add(_changePasswordButton); + _allComponents.AddRange(_characterInfoPanels); + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + switch (control) { - switch (control) - { - case GameControlIdentifier.Character1Panel: return _characterInfoPanels[0]; - case GameControlIdentifier.Character2Panel: return _characterInfoPanels[1]; - case GameControlIdentifier.Character3Panel: return _characterInfoPanels[2]; - case GameControlIdentifier.ChangePasswordButton: return _changePasswordButton; - default: return base.FindComponentByControlIdentifier(control); - } + case GameControlIdentifier.Character1Panel: return _characterInfoPanels[0]; + case GameControlIdentifier.Character2Panel: return _characterInfoPanels[1]; + case GameControlIdentifier.Character3Panel: return _characterInfoPanels[2]; + case GameControlIdentifier.ChangePasswordButton: return _changePasswordButton; + default: return base.FindComponentByControlIdentifier(control); } + } - private IXNAButton GetPasswordButton() - { - var button = new XNAButton(_secondaryButtonTexture, - new Vector2(454, 417), - new Rectangle(0, 120, 120, 40), - new Rectangle(120, 120, 120, 40)); - button.OnClick += (o, e) => AsyncButtonAction(_accountController.ChangePassword); - return button; - } + private IXNAButton GetPasswordButton() + { + var button = new XNAButton(_secondaryButtonTexture, + new Vector2(454, 417), + new Rectangle(0, 120, 120, 40), + new Rectangle(120, 120, 120, 40)); + button.OnClick += (o, e) => AsyncButtonAction(_accountController.ChangePassword); + return button; + } - protected override IXNAButton GetCreateButton() - { - var button = base.GetCreateButton(); - button.OnClick += (o, e) => AsyncButtonAction(_characterManagementController.CreateCharacter); - return button; - } + protected override IXNAButton GetCreateButton() + { + var button = base.GetCreateButton(); + button.OnClick += (o, e) => AsyncButtonAction(_characterManagementController.CreateCharacter); + return button; + } - protected override void DoBackButtonClick(object sender, EventArgs e) - { - _mainButtonController.GoToInitialStateAndDisconnect(); - } + protected override void DoBackButtonClick(object sender, EventArgs e) + { + _mainButtonController.GoToInitialStateAndDisconnect(); + } - private void AsyncButtonAction(Func clickHandler) + private void AsyncButtonAction(Func clickHandler) + { + if (_loggedInActionTask == null) { - if (_loggedInActionTask == null) - { - _loggedInActionTask = clickHandler(); - _loggedInActionTask.ContinueWith(_ => _loggedInActionTask = null); - } + _loggedInActionTask = clickHandler(); + _loggedInActionTask.ContinueWith(_ => _loggedInActionTask = null); } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/LoginPromptControlSet.cs b/EndlessClient/ControlSets/LoginPromptControlSet.cs index 2da2d5452..bb46138ce 100644 --- a/EndlessClient/ControlSets/LoginPromptControlSet.cs +++ b/EndlessClient/ControlSets/LoginPromptControlSet.cs @@ -13,154 +13,153 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public class LoginPromptControlSet : InitialControlSet { - public class LoginPromptControlSet : InitialControlSet - { - private readonly IMainButtonController _mainButtonController; - private readonly ILoginController _loginController; + private readonly IMainButtonController _mainButtonController; + private readonly ILoginController _loginController; - private IXNATextBox _tbUsername, _tbPassword; - private XNAButton _btnLogin, _btnCancel; - private IXNAPictureBox _loginPanelBackground; + private IXNATextBox _tbUsername, _tbPassword; + private XNAButton _btnLogin, _btnCancel; + private IXNAPictureBox _loginPanelBackground; - private Texture2D _loginBackgroundTexture; + private Texture2D _loginBackgroundTexture; - private Task _loginTask; + private Task _loginTask; - public override GameStates GameState => GameStates.Login; + public override GameStates GameState => GameStates.Login; - public LoginPromptControlSet(IConfigurationProvider configProvider, - IMainButtonController mainButtonController, - ILoginController loginController) - : base(configProvider, mainButtonController) - { - _mainButtonController = mainButtonController; - _loginController = loginController; - } + public LoginPromptControlSet(IConfigurationProvider configProvider, + IMainButtonController mainButtonController, + ILoginController loginController) + : base(configProvider, mainButtonController) + { + _mainButtonController = mainButtonController; + _loginController = loginController; + } - public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - base.InitializeResources(gfxManager, contentProvider); + public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + base.InitializeResources(gfxManager, contentProvider); - _loginBackgroundTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 2); - } + _loginBackgroundTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 2); + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - base.InitializeControlsHelper(currentControlSet); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + base.InitializeControlsHelper(currentControlSet); - _loginPanelBackground = GetControl(currentControlSet, GameControlIdentifier.LoginPanelBackground, GetLoginPanelBackground); - _tbUsername = GetControl(currentControlSet, GameControlIdentifier.LoginAccountName, GetLoginUserNameTextBox); - _tbPassword = GetControl(currentControlSet, GameControlIdentifier.LoginPassword, GetLoginPasswordTextBox); - _btnLogin = GetControl(currentControlSet, GameControlIdentifier.LoginButton, GetLoginAccountButton); - _btnCancel = GetControl(currentControlSet, GameControlIdentifier.LoginCancel, GetLoginCancelButton); + _loginPanelBackground = GetControl(currentControlSet, GameControlIdentifier.LoginPanelBackground, GetLoginPanelBackground); + _tbUsername = GetControl(currentControlSet, GameControlIdentifier.LoginAccountName, GetLoginUserNameTextBox); + _tbPassword = GetControl(currentControlSet, GameControlIdentifier.LoginPassword, GetLoginPasswordTextBox); + _btnLogin = GetControl(currentControlSet, GameControlIdentifier.LoginButton, GetLoginAccountButton); + _btnCancel = GetControl(currentControlSet, GameControlIdentifier.LoginCancel, GetLoginCancelButton); - _allComponents.Add(_loginPanelBackground); - _allComponents.Add(_tbUsername); - _allComponents.Add(_tbPassword); - _allComponents.Add(_btnLogin); - _allComponents.Add(_btnCancel); + _allComponents.Add(_loginPanelBackground); + _allComponents.Add(_tbUsername); + _allComponents.Add(_tbPassword); + _allComponents.Add(_btnLogin); + _allComponents.Add(_btnCancel); - _tbUsername.Selected = true; - } + _tbUsername.Selected = true; + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + switch (control) { - switch (control) - { - case GameControlIdentifier.LoginPanelBackground: return _loginPanelBackground; - case GameControlIdentifier.LoginAccountName: return _tbUsername; - case GameControlIdentifier.LoginPassword: return _tbPassword; - case GameControlIdentifier.LoginButton: return _btnLogin; - case GameControlIdentifier.LoginCancel: return _btnCancel; - default: return base.FindComponentByControlIdentifier(control); - } + case GameControlIdentifier.LoginPanelBackground: return _loginPanelBackground; + case GameControlIdentifier.LoginAccountName: return _tbUsername; + case GameControlIdentifier.LoginPassword: return _tbPassword; + case GameControlIdentifier.LoginButton: return _btnLogin; + case GameControlIdentifier.LoginCancel: return _btnCancel; + default: return base.FindComponentByControlIdentifier(control); } + } - private IXNAPictureBox GetLoginPanelBackground() + private IXNAPictureBox GetLoginPanelBackground() + { + return new XNAPictureBox { - return new XNAPictureBox - { - Texture = _loginBackgroundTexture, - DrawArea = new Rectangle(266, 291, _loginBackgroundTexture.Width, _loginBackgroundTexture.Height), - DrawOrder = _personPicture.DrawOrder + 1 - }; - } + Texture = _loginBackgroundTexture, + DrawArea = new Rectangle(266, 291, _loginBackgroundTexture.Width, _loginBackgroundTexture.Height), + DrawOrder = _personPicture.DrawOrder + 1 + }; + } - private IXNATextBox GetLoginUserNameTextBox() + private IXNATextBox GetLoginUserNameTextBox() + { + var textBox = new XNATextBox( + new Rectangle(402, 322, 140, _textBoxBackground.Height), + Constants.FontSize08, + _textBoxBackground, + _textBoxLeft, + _textBoxRight, + _textBoxCursor) { - var textBox = new XNATextBox( - new Rectangle(402, 322, 140, _textBoxBackground.Height), - Constants.FontSize08, - _textBoxBackground, - _textBoxLeft, - _textBoxRight, - _textBoxCursor) - { - MaxChars = 16, - DefaultText = "", - LeftPadding = 4, - DrawOrder = _personPicture.DrawOrder + 2, - DefaultTextColor = Color.FromNonPremultiplied(80, 80, 80, 0xff), - TextColor = Color.Black, - TabOrder = 1, - }; - textBox.OnEnterPressed += DoLogin; - return textBox; - } + MaxChars = 16, + DefaultText = "", + LeftPadding = 4, + DrawOrder = _personPicture.DrawOrder + 2, + DefaultTextColor = Color.FromNonPremultiplied(80, 80, 80, 0xff), + TextColor = Color.Black, + TabOrder = 1, + }; + textBox.OnEnterPressed += DoLogin; + return textBox; + } - private IXNATextBox GetLoginPasswordTextBox() + private IXNATextBox GetLoginPasswordTextBox() + { + var textBox = new XNATextBox( + new Rectangle(402, 358, 140, _textBoxBackground.Height), + Constants.FontSize08, + _textBoxBackground, + _textBoxLeft, + _textBoxRight, + _textBoxCursor) { - var textBox = new XNATextBox( - new Rectangle(402, 358, 140, _textBoxBackground.Height), - Constants.FontSize08, - _textBoxBackground, - _textBoxLeft, - _textBoxRight, - _textBoxCursor) - { - MaxChars = 12, - PasswordBox = true, - LeftPadding = 4, - DefaultText = "", - DrawOrder = _personPicture.DrawOrder + 2, - DefaultTextColor = Color.FromNonPremultiplied(80, 80, 80, 0xff), - TextColor = Color.Black, - TabOrder = 2, - }; - textBox.OnEnterPressed += DoLogin; - return textBox; - } + MaxChars = 12, + PasswordBox = true, + LeftPadding = 4, + DefaultText = "", + DrawOrder = _personPicture.DrawOrder + 2, + DefaultTextColor = Color.FromNonPremultiplied(80, 80, 80, 0xff), + TextColor = Color.Black, + TabOrder = 2, + }; + textBox.OnEnterPressed += DoLogin; + return textBox; + } - private XNAButton GetLoginAccountButton() + private XNAButton GetLoginAccountButton() + { + var button = new XNAButton(_smallButtonSheet, new Vector2(361, 389), new Rectangle(0, 0, 91, 29), new Rectangle(91, 0, 91, 29)) { - var button = new XNAButton(_smallButtonSheet, new Vector2(361, 389), new Rectangle(0, 0, 91, 29), new Rectangle(91, 0, 91, 29)) - { - DrawOrder = _personPicture.DrawOrder + 2 - }; - button.OnClick += DoLogin; - return button; - } + DrawOrder = _personPicture.DrawOrder + 2 + }; + button.OnClick += DoLogin; + return button; + } - private void DoLogin(object sender, EventArgs e) + private void DoLogin(object sender, EventArgs e) + { + if (_loginTask == null) { - if (_loginTask == null) - { - var loginParameters = new LoginParameters(_tbUsername.Text, _tbPassword.Text); - _loginTask = _loginController.LoginToAccount(loginParameters); - _loginTask.ContinueWith(_ => _loginTask = null); - } + var loginParameters = new LoginParameters(_tbUsername.Text, _tbPassword.Text); + _loginTask = _loginController.LoginToAccount(loginParameters); + _loginTask.ContinueWith(_ => _loginTask = null); } + } - private XNAButton GetLoginCancelButton() + private XNAButton GetLoginCancelButton() + { + var button = new XNAButton(_smallButtonSheet, new Vector2(453, 389), new Rectangle(0, 29, 91, 29), new Rectangle(91, 29, 91, 29)) { - var button = new XNAButton(_smallButtonSheet, new Vector2(453, 389), new Rectangle(0, 29, 91, 29), new Rectangle(91, 29, 91, 29)) - { - DrawOrder = _personPicture.DrawOrder + 2 - }; - button.OnClick += (o, e) => _mainButtonController.GoToInitialState(); - return button; - } + DrawOrder = _personPicture.DrawOrder + 2 + }; + button.OnClick += (o, e) => _mainButtonController.GoToInitialState(); + return button; } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/ViewCreditsControlSet.cs b/EndlessClient/ControlSets/ViewCreditsControlSet.cs index e6b37e55a..7e74e8463 100644 --- a/EndlessClient/ControlSets/ViewCreditsControlSet.cs +++ b/EndlessClient/ControlSets/ViewCreditsControlSet.cs @@ -5,44 +5,43 @@ using Microsoft.Xna.Framework; using XNAControls; -namespace EndlessClient.ControlSets +namespace EndlessClient.ControlSets; + +public class ViewCreditsControlSet : InitialControlSet { - public class ViewCreditsControlSet : InitialControlSet - { - private IXNALabel _creditsLabel; + private IXNALabel _creditsLabel; - public override GameStates GameState => GameStates.ViewCredits; + public override GameStates GameState => GameStates.ViewCredits; - public ViewCreditsControlSet(IConfigurationProvider configProvider, - IMainButtonController mainButtonController) - : base(configProvider, mainButtonController) { } + public ViewCreditsControlSet(IConfigurationProvider configProvider, + IMainButtonController mainButtonController) + : base(configProvider, mainButtonController) { } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - base.InitializeControlsHelper(currentControlSet); - ExcludePersonPicture1(); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + base.InitializeControlsHelper(currentControlSet); + ExcludePersonPicture1(); - _creditsLabel = GetControl(currentControlSet, GameControlIdentifier.CreditsLabel, GetCreditsLabel); - _allComponents.Add(_creditsLabel); - } + _creditsLabel = GetControl(currentControlSet, GameControlIdentifier.CreditsLabel, GetCreditsLabel); + _allComponents.Add(_creditsLabel); + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + switch (control) { - switch (control) - { - case GameControlIdentifier.CreditsLabel: return _creditsLabel; - default: return base.FindComponentByControlIdentifier(control); - } + case GameControlIdentifier.CreditsLabel: return _creditsLabel; + default: return base.FindComponentByControlIdentifier(control); } + } - private XNALabel GetCreditsLabel() + private XNALabel GetCreditsLabel() + { + return new XNALabel(Constants.FontSize10) { - return new XNALabel(Constants.FontSize10) - { - AutoSize = true, - Text = Constants.CreditsText, - DrawPosition = new Vector2(300, 200) - }; - } + AutoSize = true, + Text = Constants.CreditsText, + DrawPosition = new Vector2(300, 200) + }; } } \ No newline at end of file diff --git a/EndlessClient/Controllers/AccountController.cs b/EndlessClient/Controllers/AccountController.cs index 79394a599..80d587adf 100644 --- a/EndlessClient/Controllers/AccountController.cs +++ b/EndlessClient/Controllers/AccountController.cs @@ -8,114 +8,113 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[MappedType(BaseType = typeof(IAccountController))] +public class AccountController : IAccountController { - [MappedType(BaseType = typeof(IAccountController))] - public class AccountController : IAccountController + private readonly IAccountDialogDisplayActions _accountDialogDisplayActions; + private readonly IErrorDialogDisplayAction _errorDisplayAction; + private readonly IAccountActions _accountActions; + private readonly IGameStateActions _gameStateActions; + private readonly ISafeNetworkOperationFactory _networkOperationFactory; + + public AccountController(IAccountDialogDisplayActions accountDialogDisplayActions, + IErrorDialogDisplayAction errorDisplayAction, + IAccountActions accountActions, + IGameStateActions gameStateActions, + ISafeNetworkOperationFactory networkOperationFactory) + { + _accountDialogDisplayActions = accountDialogDisplayActions; + _errorDisplayAction = errorDisplayAction; + _accountActions = accountActions; + _gameStateActions = gameStateActions; + _networkOperationFactory = networkOperationFactory; + } + + public async Task CreateAccount(ICreateAccountParameters createAccountParameters) { - private readonly IAccountDialogDisplayActions _accountDialogDisplayActions; - private readonly IErrorDialogDisplayAction _errorDisplayAction; - private readonly IAccountActions _accountActions; - private readonly IGameStateActions _gameStateActions; - private readonly ISafeNetworkOperationFactory _networkOperationFactory; - - public AccountController(IAccountDialogDisplayActions accountDialogDisplayActions, - IErrorDialogDisplayAction errorDisplayAction, - IAccountActions accountActions, - IGameStateActions gameStateActions, - ISafeNetworkOperationFactory networkOperationFactory) + var paramsValidationResult = _accountActions.CheckAccountCreateParameters(createAccountParameters); + if (paramsValidationResult.FaultingParameter != WhichParameter.None) { - _accountDialogDisplayActions = accountDialogDisplayActions; - _errorDisplayAction = errorDisplayAction; - _accountActions = accountActions; - _gameStateActions = gameStateActions; - _networkOperationFactory = networkOperationFactory; + _accountDialogDisplayActions.ShowCreateParameterValidationError(paramsValidationResult); + return; } - public async Task CreateAccount(ICreateAccountParameters createAccountParameters) - { - var paramsValidationResult = _accountActions.CheckAccountCreateParameters(createAccountParameters); - if (paramsValidationResult.FaultingParameter != WhichParameter.None) - { - _accountDialogDisplayActions.ShowCreateParameterValidationError(paramsValidationResult); - return; - } - - var checkNameOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _accountActions.CheckAccountNameWithServer(createAccountParameters.AccountName), - SetInitialStateAndShowError, - SetInitialStateAndShowError); - if (!await checkNameOperation.Invoke().ConfigureAwait(false)) - return; - - var nameResult = checkNameOperation.Result; - if (nameResult < (AccountReply)10) - { - _accountDialogDisplayActions.ShowCreateAccountServerError(nameResult); - return; - } - - var result = await _accountDialogDisplayActions.ShowCreatePendingDialog().ConfigureAwait(false); - if (result == XNADialogResult.Cancel) - return; - - var createAccountOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _accountActions.CreateAccount(createAccountParameters, (int)nameResult), - SetInitialStateAndShowError, - SetInitialStateAndShowError); - if (!await createAccountOperation.Invoke().ConfigureAwait(false)) - return; - - var accountResult = createAccountOperation.Result; - if (accountResult != AccountReply.Created) - { - _accountDialogDisplayActions.ShowCreateAccountServerError(accountResult); - return; - } + var checkNameOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _accountActions.CheckAccountNameWithServer(createAccountParameters.AccountName), + SetInitialStateAndShowError, + SetInitialStateAndShowError); + if (!await checkNameOperation.Invoke().ConfigureAwait(false)) + return; - _gameStateActions.ChangeToState(GameStates.Initial); - _accountDialogDisplayActions.ShowSuccessMessage(); + var nameResult = checkNameOperation.Result; + if (nameResult < (AccountReply)10) + { + _accountDialogDisplayActions.ShowCreateAccountServerError(nameResult); + return; } - public async Task ChangePassword() - { - var changePasswordResult = await _accountDialogDisplayActions.ShowChangePasswordDialog().ConfigureAwait(false); - changePasswordResult.MatchSome(changePasswordParameters => - { - var changePasswordOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _accountActions.ChangePassword(changePasswordParameters), - SetInitialStateAndShowError, - SetInitialStateAndShowError); + var result = await _accountDialogDisplayActions.ShowCreatePendingDialog().ConfigureAwait(false); + if (result == XNADialogResult.Cancel) + return; - var opTask = changePasswordOperation.Invoke(); - opTask.ContinueWith(t => - { - if (t.Result) - { - var result = changePasswordOperation.Result; - _accountDialogDisplayActions.ShowCreateAccountServerError(result); - } - }); - }); - } + var createAccountOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _accountActions.CreateAccount(createAccountParameters, (int)nameResult), + SetInitialStateAndShowError, + SetInitialStateAndShowError); + if (!await createAccountOperation.Invoke().ConfigureAwait(false)) + return; - private void SetInitialStateAndShowError(NoDataSentException ex) + var accountResult = createAccountOperation.Result; + if (accountResult != AccountReply.Created) { - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDisplayAction.ShowException(ex); + _accountDialogDisplayActions.ShowCreateAccountServerError(accountResult); + return; } - private void SetInitialStateAndShowError(EmptyPacketReceivedException ex) - { - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDisplayAction.ShowException(ex); - } + _gameStateActions.ChangeToState(GameStates.Initial); + _accountDialogDisplayActions.ShowSuccessMessage(); } - public interface IAccountController + public async Task ChangePassword() { - Task CreateAccount(ICreateAccountParameters createAccountParameters); + var changePasswordResult = await _accountDialogDisplayActions.ShowChangePasswordDialog().ConfigureAwait(false); + changePasswordResult.MatchSome(changePasswordParameters => + { + var changePasswordOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _accountActions.ChangePassword(changePasswordParameters), + SetInitialStateAndShowError, + SetInitialStateAndShowError); - Task ChangePassword(); + var opTask = changePasswordOperation.Invoke(); + opTask.ContinueWith(t => + { + if (t.Result) + { + var result = changePasswordOperation.Result; + _accountDialogDisplayActions.ShowCreateAccountServerError(result); + } + }); + }); } + + private void SetInitialStateAndShowError(NoDataSentException ex) + { + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDisplayAction.ShowException(ex); + } + + private void SetInitialStateAndShowError(EmptyPacketReceivedException ex) + { + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDisplayAction.ShowException(ex); + } +} + +public interface IAccountController +{ + Task CreateAccount(ICreateAccountParameters createAccountParameters); + + Task ChangePassword(); } \ No newline at end of file diff --git a/EndlessClient/Controllers/ArrowKeyController.cs b/EndlessClient/Controllers/ArrowKeyController.cs index d42bd8ac6..0db96e81b 100644 --- a/EndlessClient/Controllers/ArrowKeyController.cs +++ b/EndlessClient/Controllers/ArrowKeyController.cs @@ -10,143 +10,142 @@ using EOLib.Localization; using Optional; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[AutoMappedType] +public class ArrowKeyController : IArrowKeyController { - [AutoMappedType] - public class ArrowKeyController : IArrowKeyController + private readonly IWalkValidationActions _walkValidationActions; + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly ICharacterProvider _characterProvider; + private readonly IUnwalkableTileActions _unwalkableTileActions; + private readonly IUnwalkableTileActionsHandler _unwalkableTileActionsHandler; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IGhostingRepository _ghostingRepository; + private readonly ISfxPlayer _sfxPlayer; + + public ArrowKeyController(IWalkValidationActions walkValidationActions, + ICharacterAnimationActions characterAnimationActions, + ICharacterProvider characterProvider, + IUnwalkableTileActions walkErrorHandler, + IUnwalkableTileActionsHandler unwalkableTileActionsHandler, + IStatusLabelSetter statusLabelSetter, + IGhostingRepository ghostingRepository, + ISfxPlayer sfxPlayer) { - private readonly IWalkValidationActions _walkValidationActions; - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly ICharacterProvider _characterProvider; - private readonly IUnwalkableTileActions _unwalkableTileActions; - private readonly IUnwalkableTileActionsHandler _unwalkableTileActionsHandler; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IGhostingRepository _ghostingRepository; - private readonly ISfxPlayer _sfxPlayer; - - public ArrowKeyController(IWalkValidationActions walkValidationActions, - ICharacterAnimationActions characterAnimationActions, - ICharacterProvider characterProvider, - IUnwalkableTileActions walkErrorHandler, - IUnwalkableTileActionsHandler unwalkableTileActionsHandler, - IStatusLabelSetter statusLabelSetter, - IGhostingRepository ghostingRepository, - ISfxPlayer sfxPlayer) - { - _walkValidationActions = walkValidationActions; - _characterAnimationActions = characterAnimationActions; - _characterProvider = characterProvider; - _unwalkableTileActions = walkErrorHandler; - _unwalkableTileActionsHandler = unwalkableTileActionsHandler; - _statusLabelSetter = statusLabelSetter; - _ghostingRepository = ghostingRepository; - _sfxPlayer = sfxPlayer; - } + _walkValidationActions = walkValidationActions; + _characterAnimationActions = characterAnimationActions; + _characterProvider = characterProvider; + _unwalkableTileActions = walkErrorHandler; + _unwalkableTileActionsHandler = unwalkableTileActionsHandler; + _statusLabelSetter = statusLabelSetter; + _ghostingRepository = ghostingRepository; + _sfxPlayer = sfxPlayer; + } - public bool MoveLeft() - { - if (!CanWalkAgain()) - return false; + public bool MoveLeft() + { + if (!CanWalkAgain()) + return false; - FaceOrAttemptWalk(EODirection.Left); + FaceOrAttemptWalk(EODirection.Left); - return true; - } + return true; + } - public bool MoveRight() - { - if (!CanWalkAgain()) - return false; + public bool MoveRight() + { + if (!CanWalkAgain()) + return false; - FaceOrAttemptWalk(EODirection.Right); + FaceOrAttemptWalk(EODirection.Right); - return true; - } + return true; + } - public bool MoveUp() - { - if (!CanWalkAgain()) - return false; + public bool MoveUp() + { + if (!CanWalkAgain()) + return false; - FaceOrAttemptWalk(EODirection.Up); + FaceOrAttemptWalk(EODirection.Up); - return true; - } + return true; + } - public bool MoveDown() - { - if (!CanWalkAgain()) - return false; + public bool MoveDown() + { + if (!CanWalkAgain()) + return false; - FaceOrAttemptWalk(EODirection.Down); + FaceOrAttemptWalk(EODirection.Down); - return true; - } + return true; + } - public void KeysUp() - { - _ghostingRepository.ResetState(); - } + public void KeysUp() + { + _ghostingRepository.ResetState(); + } - private bool CanWalkAgain() - { - return _characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing) || - _characterProvider.MainCharacter.RenderProperties.ActualWalkFrame == CharacterRenderProperties.MAX_NUMBER_OF_WALK_FRAMES - 1; - } + private bool CanWalkAgain() + { + return _characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing) || + _characterProvider.MainCharacter.RenderProperties.ActualWalkFrame == CharacterRenderProperties.MAX_NUMBER_OF_WALK_FRAMES - 1; + } - private bool CurrentDirectionIs(EODirection direction) + private bool CurrentDirectionIs(EODirection direction) + { + return _characterProvider.MainCharacter.RenderProperties.IsFacing(direction); + } + + private void FaceOrAttemptWalk(EODirection direction) + { + if (!CurrentDirectionIs(direction) && _characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing)) { - return _characterProvider.MainCharacter.RenderProperties.IsFacing(direction); + _characterAnimationActions.Face(direction); } - - private void FaceOrAttemptWalk(EODirection direction) + else { - if (!CurrentDirectionIs(direction) && _characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing)) - { - _characterAnimationActions.Face(direction); - } - else - { - _characterAnimationActions.Face(direction); - AttemptToStartWalking(); - } + _characterAnimationActions.Face(direction); + AttemptToStartWalking(); } + } - private void AttemptToStartWalking() + private void AttemptToStartWalking() + { + var walkValidationResult = _walkValidationActions.CanMoveToDestinationCoordinates(); + if (walkValidationResult == WalkValidationResult.GhostComplete) + _sfxPlayer.PlaySfx(SoundEffectID.GhostPlayer); + + switch (walkValidationResult) { - var walkValidationResult = _walkValidationActions.CanMoveToDestinationCoordinates(); - if (walkValidationResult == WalkValidationResult.GhostComplete) - _sfxPlayer.PlaySfx(SoundEffectID.GhostPlayer); - - switch (walkValidationResult) - { - case WalkValidationResult.BlockedByCharacter: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_KEEP_MOVING_THROUGH_PLAYER); - break; - case WalkValidationResult.NotWalkable: - var (unwalkableActions, cellState) = _unwalkableTileActions.GetUnwalkableTileActions(); - _unwalkableTileActionsHandler.HandleUnwalkableTileActions(unwalkableActions, cellState); - break; - case WalkValidationResult.GhostComplete: - _characterAnimationActions.StartWalking(Option.None(), ghosted: true); - break; - case WalkValidationResult.Walkable: - _characterAnimationActions.StartWalking(Option.None()); - break; - } + case WalkValidationResult.BlockedByCharacter: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_KEEP_MOVING_THROUGH_PLAYER); + break; + case WalkValidationResult.NotWalkable: + var (unwalkableActions, cellState) = _unwalkableTileActions.GetUnwalkableTileActions(); + _unwalkableTileActionsHandler.HandleUnwalkableTileActions(unwalkableActions, cellState); + break; + case WalkValidationResult.GhostComplete: + _characterAnimationActions.StartWalking(Option.None(), ghosted: true); + break; + case WalkValidationResult.Walkable: + _characterAnimationActions.StartWalking(Option.None()); + break; } } +} - public interface IArrowKeyController - { - bool MoveLeft(); +public interface IArrowKeyController +{ + bool MoveLeft(); - bool MoveRight(); + bool MoveRight(); - bool MoveUp(); + bool MoveUp(); - bool MoveDown(); + bool MoveDown(); - void KeysUp(); - } + void KeysUp(); } \ No newline at end of file diff --git a/EndlessClient/Controllers/BardController.cs b/EndlessClient/Controllers/BardController.cs index 6cf4c2e8e..86936799b 100644 --- a/EndlessClient/Controllers/BardController.cs +++ b/EndlessClient/Controllers/BardController.cs @@ -4,40 +4,39 @@ using EOLib.Domain.Extensions; using EOLib.Domain.Interact.Jukebox; -namespace EndlessClient.Controllers -{ - [AutoMappedType] - public class BardController : IBardController - { - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly IJukeboxActions _jukeboxActions; - private readonly ICharacterProvider _characterProvider; +namespace EndlessClient.Controllers; - public BardController(ICharacterAnimationActions characterAnimationActions, - IJukeboxActions jukeboxActions, - ICharacterProvider characterProvider) - { - _characterAnimationActions = characterAnimationActions; - _jukeboxActions = jukeboxActions; - _characterProvider = characterProvider; - } +[AutoMappedType] +public class BardController : IBardController +{ + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly IJukeboxActions _jukeboxActions; + private readonly ICharacterProvider _characterProvider; - public void PlayInstrumentNote(int noteIndex) - { - _characterAnimationActions.StartAttacking(noteIndex); - _jukeboxActions.PlayNote(noteIndex); - } + public BardController(ICharacterAnimationActions characterAnimationActions, + IJukeboxActions jukeboxActions, + ICharacterProvider characterProvider) + { + _characterAnimationActions = characterAnimationActions; + _jukeboxActions = jukeboxActions; + _characterProvider = characterProvider; + } - private bool CanAttackAgain() - { - var rp = _characterProvider.MainCharacter.RenderProperties; - return rp.IsActing(CharacterActionState.Standing) || - rp.RenderAttackFrame == CharacterRenderProperties.MAX_NUMBER_OF_ATTACK_FRAMES; - } + public void PlayInstrumentNote(int noteIndex) + { + _characterAnimationActions.StartAttacking(noteIndex); + _jukeboxActions.PlayNote(noteIndex); } - public interface IBardController + private bool CanAttackAgain() { - void PlayInstrumentNote(int noteIndex); + var rp = _characterProvider.MainCharacter.RenderProperties; + return rp.IsActing(CharacterActionState.Standing) || + rp.RenderAttackFrame == CharacterRenderProperties.MAX_NUMBER_OF_ATTACK_FRAMES; } +} + +public interface IBardController +{ + void PlayInstrumentNote(int noteIndex); } \ No newline at end of file diff --git a/EndlessClient/Controllers/CharacterManagementController.cs b/EndlessClient/Controllers/CharacterManagementController.cs index 90eb67e2a..ddc076cf1 100644 --- a/EndlessClient/Controllers/CharacterManagementController.cs +++ b/EndlessClient/Controllers/CharacterManagementController.cs @@ -12,151 +12,150 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[MappedType(BaseType = typeof(ICharacterManagementController))] +public class CharacterManagementController : ICharacterManagementController { - [MappedType(BaseType = typeof(ICharacterManagementController))] - public class CharacterManagementController : ICharacterManagementController + private readonly ISafeNetworkOperationFactory _safeNetworkOperationFactory; + private readonly ICharacterManagementActions _characterManagementActions; + private readonly IErrorDialogDisplayAction _errorDialogDisplayAction; + private readonly ICharacterDialogActions _characterDialogActions; + private readonly IBackgroundReceiveActions _backgroundReceiveActions; + private readonly INetworkConnectionActions _networkConnectionActions; + private readonly IGameStateActions _gameStateActions; + private readonly ICharacterSelectorRepository _characterSelectorRepository; + private readonly ISfxPlayer _sfxPlayer; + + public CharacterManagementController(ISafeNetworkOperationFactory safeNetworkOperationFactory, + ICharacterManagementActions characterManagementActions, + IErrorDialogDisplayAction errorDialogDisplayAction, + ICharacterDialogActions characterDialogActions, + IBackgroundReceiveActions backgroundReceiveActions, + INetworkConnectionActions networkConnectionActions, + IGameStateActions gameStateActions, + ICharacterSelectorRepository characterSelectorRepository, + ISfxPlayer sfxPlayer) { - private readonly ISafeNetworkOperationFactory _safeNetworkOperationFactory; - private readonly ICharacterManagementActions _characterManagementActions; - private readonly IErrorDialogDisplayAction _errorDialogDisplayAction; - private readonly ICharacterDialogActions _characterDialogActions; - private readonly IBackgroundReceiveActions _backgroundReceiveActions; - private readonly INetworkConnectionActions _networkConnectionActions; - private readonly IGameStateActions _gameStateActions; - private readonly ICharacterSelectorRepository _characterSelectorRepository; - private readonly ISfxPlayer _sfxPlayer; - - public CharacterManagementController(ISafeNetworkOperationFactory safeNetworkOperationFactory, - ICharacterManagementActions characterManagementActions, - IErrorDialogDisplayAction errorDialogDisplayAction, - ICharacterDialogActions characterDialogActions, - IBackgroundReceiveActions backgroundReceiveActions, - INetworkConnectionActions networkConnectionActions, - IGameStateActions gameStateActions, - ICharacterSelectorRepository characterSelectorRepository, - ISfxPlayer sfxPlayer) - { - _safeNetworkOperationFactory = safeNetworkOperationFactory; - _characterManagementActions = characterManagementActions; - _errorDialogDisplayAction = errorDialogDisplayAction; - _characterDialogActions = characterDialogActions; - _backgroundReceiveActions = backgroundReceiveActions; - _networkConnectionActions = networkConnectionActions; - _gameStateActions = gameStateActions; - _characterSelectorRepository = characterSelectorRepository; - _sfxPlayer = sfxPlayer; - } + _safeNetworkOperationFactory = safeNetworkOperationFactory; + _characterManagementActions = characterManagementActions; + _errorDialogDisplayAction = errorDialogDisplayAction; + _characterDialogActions = characterDialogActions; + _backgroundReceiveActions = backgroundReceiveActions; + _networkConnectionActions = networkConnectionActions; + _gameStateActions = gameStateActions; + _characterSelectorRepository = characterSelectorRepository; + _sfxPlayer = sfxPlayer; + } - public async Task CreateCharacter() - { - var requestCreateOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(_characterManagementActions.RequestCharacterCreation, SendError, RecvError); - if (!await requestCreateOp.Invoke().ConfigureAwait(false)) - return; + public async Task CreateCharacter() + { + var requestCreateOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(_characterManagementActions.RequestCharacterCreation, SendError, RecvError); + if (!await requestCreateOp.Invoke().ConfigureAwait(false)) + return; - var createID = requestCreateOp.Result; + var createID = requestCreateOp.Result; - //todo: make not approved character names cancel the dialog close - var showResult = await _characterDialogActions.ShowCreateCharacterDialog().ConfigureAwait(false); - showResult.MatchSome(parameters => + //todo: make not approved character names cancel the dialog close + var showResult = await _characterDialogActions.ShowCreateCharacterDialog().ConfigureAwait(false); + showResult.MatchSome(parameters => + { + var createOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation( + () => _characterManagementActions.CreateCharacter(parameters, createID), SendError, RecvError); + var opTask = createOp.Invoke(); + opTask.ContinueWith(t => { - var createOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation( - () => _characterManagementActions.CreateCharacter(parameters, createID), SendError, RecvError); - var opTask = createOp.Invoke(); - opTask.ContinueWith(t => + if (t.Result) { - if (t.Result) - { - _gameStateActions.RefreshCurrentState(); - _characterDialogActions.ShowCharacterReplyDialog(createOp.Result); - } - }); + _gameStateActions.RefreshCurrentState(); + _characterDialogActions.ShowCharacterReplyDialog(createOp.Result); + } }); - } + }); + } - public async Task DeleteCharacter(Character characterToDelete) + public async Task DeleteCharacter(Character characterToDelete) + { + void ShowCharacterDeleteWarning(Character c) { - void ShowCharacterDeleteWarning(Character c) - { - _characterDialogActions.ShowCharacterDeleteWarning(c.Name); - _characterSelectorRepository.CharacterForDelete = Option.Some(c); - } + _characterDialogActions.ShowCharacterDeleteWarning(c.Name); + _characterSelectorRepository.CharacterForDelete = Option.Some(c); + } - var warningShown = _characterSelectorRepository.CharacterForDelete.Match( - some: c => - { - if (c != characterToDelete) - { - ShowCharacterDeleteWarning(characterToDelete); - return true; - } - - return false; - }, - none: () => + var warningShown = _characterSelectorRepository.CharacterForDelete.Match( + some: c => + { + if (c != characterToDelete) { ShowCharacterDeleteWarning(characterToDelete); return true; - }); + } - if (warningShown) - return; - - var requestDeleteOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(_characterManagementActions.RequestCharacterDelete, SendError, RecvError); - if (!await requestDeleteOp.Invoke().ConfigureAwait(false)) - return; + return false; + }, + none: () => + { + ShowCharacterDeleteWarning(characterToDelete); + return true; + }); - var takeID = requestDeleteOp.Result; + if (warningShown) + return; - var dialogResult = await _characterDialogActions.ShowConfirmDeleteWarning(characterToDelete.Name).ConfigureAwait(false); - if (dialogResult != XNADialogResult.OK) - return; + var requestDeleteOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(_characterManagementActions.RequestCharacterDelete, SendError, RecvError); + if (!await requestDeleteOp.Invoke().ConfigureAwait(false)) + return; - var deleteOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(() => _characterManagementActions.DeleteCharacter(takeID), SendError, RecvError); - if (!await deleteOp.Invoke().ConfigureAwait(false)) - return; + var takeID = requestDeleteOp.Result; - _characterSelectorRepository.CharacterForDelete = Option.None(); - if (deleteOp.Result != CharacterReply.Deleted) - { - SetInitialStateAndShowError(); - DisconnectAndStopReceiving(); - return; - } + var dialogResult = await _characterDialogActions.ShowConfirmDeleteWarning(characterToDelete.Name).ConfigureAwait(false); + if (dialogResult != XNADialogResult.OK) + return; - _sfxPlayer.PlaySfx(SoundEffectID.DeleteCharacter); - _gameStateActions.RefreshCurrentState(); - } + var deleteOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(() => _characterManagementActions.DeleteCharacter(takeID), SendError, RecvError); + if (!await deleteOp.Invoke().ConfigureAwait(false)) + return; - private void SendError(NoDataSentException ndes) + _characterSelectorRepository.CharacterForDelete = Option.None(); + if (deleteOp.Result != CharacterReply.Deleted) { SetInitialStateAndShowError(); DisconnectAndStopReceiving(); + return; } - private void RecvError(EmptyPacketReceivedException epre) - { - SetInitialStateAndShowError(); - DisconnectAndStopReceiving(); - } + _sfxPlayer.PlaySfx(SoundEffectID.DeleteCharacter); + _gameStateActions.RefreshCurrentState(); + } - private void SetInitialStateAndShowError() - { - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDialogDisplayAction.ShowError(ConnectResult.SocketError); - } + private void SendError(NoDataSentException ndes) + { + SetInitialStateAndShowError(); + DisconnectAndStopReceiving(); + } - private void DisconnectAndStopReceiving() - { - _backgroundReceiveActions.CancelBackgroundReceiveLoop(); - _networkConnectionActions.DisconnectFromServer(); - } + private void RecvError(EmptyPacketReceivedException epre) + { + SetInitialStateAndShowError(); + DisconnectAndStopReceiving(); } - public interface ICharacterManagementController + private void SetInitialStateAndShowError() { - Task CreateCharacter(); + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDialogDisplayAction.ShowError(ConnectResult.SocketError); + } - Task DeleteCharacter(Character characterToDelete); + private void DisconnectAndStopReceiving() + { + _backgroundReceiveActions.CancelBackgroundReceiveLoop(); + _networkConnectionActions.DisconnectFromServer(); } +} + +public interface ICharacterManagementController +{ + Task CreateCharacter(); + + Task DeleteCharacter(Character characterToDelete); } \ No newline at end of file diff --git a/EndlessClient/Controllers/ChatController.cs b/EndlessClient/Controllers/ChatController.cs index 4e84953b2..f181bd56c 100644 --- a/EndlessClient/Controllers/ChatController.cs +++ b/EndlessClient/Controllers/ChatController.cs @@ -11,102 +11,101 @@ using EOLib.Localization; using System; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[AutoMappedType] +public class ChatController : IChatController { - [AutoMappedType] - public class ChatController : IChatController + private readonly IChatTextBoxActions _chatTextBoxActions; + private readonly IChatActions _chatActions; + private readonly IPrivateMessageActions _privateMessageActions; + private readonly IChatBubbleActions _chatBubbleActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IHudControlProvider _hudControlProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IChatTypeCalculator _chatTypeCalculator; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + + public ChatController(IChatTextBoxActions chatTextBoxActions, + IChatActions chatActions, + IPrivateMessageActions privateMessageActions, + IChatBubbleActions chatBubbleActions, + IStatusLabelSetter statusLabelSetter, + IHudControlProvider hudControlProvider, + ISfxPlayer sfxPlayer, + IChatTypeCalculator chatTypeCalculator, + ICurrentMapStateProvider currentMapStateProvider) { - private readonly IChatTextBoxActions _chatTextBoxActions; - private readonly IChatActions _chatActions; - private readonly IPrivateMessageActions _privateMessageActions; - private readonly IChatBubbleActions _chatBubbleActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IHudControlProvider _hudControlProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IChatTypeCalculator _chatTypeCalculator; - private readonly ICurrentMapStateProvider _currentMapStateProvider; + _chatTextBoxActions = chatTextBoxActions; + _chatActions = chatActions; + _privateMessageActions = privateMessageActions; + _chatBubbleActions = chatBubbleActions; + _statusLabelSetter = statusLabelSetter; + _hudControlProvider = hudControlProvider; + _sfxPlayer = sfxPlayer; + _chatTypeCalculator = chatTypeCalculator; + _currentMapStateProvider = currentMapStateProvider; + } - public ChatController(IChatTextBoxActions chatTextBoxActions, - IChatActions chatActions, - IPrivateMessageActions privateMessageActions, - IChatBubbleActions chatBubbleActions, - IStatusLabelSetter statusLabelSetter, - IHudControlProvider hudControlProvider, - ISfxPlayer sfxPlayer, - IChatTypeCalculator chatTypeCalculator, - ICurrentMapStateProvider currentMapStateProvider) - { - _chatTextBoxActions = chatTextBoxActions; - _chatActions = chatActions; - _privateMessageActions = privateMessageActions; - _chatBubbleActions = chatBubbleActions; - _statusLabelSetter = statusLabelSetter; - _hudControlProvider = hudControlProvider; - _sfxPlayer = sfxPlayer; - _chatTypeCalculator = chatTypeCalculator; - _currentMapStateProvider = currentMapStateProvider; - } + public void SendChatAndClearTextBox() + { + var localTypedText = ChatTextBox.Text; + var (pmCheckOk, targetCharacter) = _privateMessageActions.GetTargetCharacter(localTypedText); - public void SendChatAndClearTextBox() + if (pmCheckOk) { - var localTypedText = ChatTextBox.Text; - var (pmCheckOk, targetCharacter) = _privateMessageActions.GetTargetCharacter(localTypedText); - - if (pmCheckOk) + if (!string.IsNullOrEmpty(targetCharacter)) { - if (!string.IsNullOrEmpty(targetCharacter)) - { - _sfxPlayer.PlaySfx(SoundEffectID.PrivateMessageSent); - } + _sfxPlayer.PlaySfx(SoundEffectID.PrivateMessageSent); + } - var chatType = _chatTypeCalculator.CalculateChatType(localTypedText); - var (result, updatedChat) = _chatActions.SendChatToServer(localTypedText, targetCharacter, chatType); - switch (result) - { - case ChatResult.Ok: _chatBubbleActions.ShowChatBubbleForMainCharacter(updatedChat, chatType == ChatType.Party); break; - case ChatResult.YourMindPrevents: _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.YOUR_MIND_PREVENTS_YOU_TO_SAY); break; - case ChatResult.Command: + var chatType = _chatTypeCalculator.CalculateChatType(localTypedText); + var (result, updatedChat) = _chatActions.SendChatToServer(localTypedText, targetCharacter, chatType); + switch (result) + { + case ChatResult.Ok: _chatBubbleActions.ShowChatBubbleForMainCharacter(updatedChat, chatType == ChatType.Party); break; + case ChatResult.YourMindPrevents: _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.YOUR_MIND_PREVENTS_YOU_TO_SAY); break; + case ChatResult.Command: + { + var commandText = updatedChat[1..].Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)[0]; + _sfxPlayer.PlaySfx(commandText switch { - var commandText = updatedChat[1..].Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)[0]; - _sfxPlayer.PlaySfx(commandText switch - { - NoWallCommand.Text or PingCommand.Text => SoundEffectID.ServerCommand, - _ => SoundEffectID.ServerMessage, - }); - } - break; - case ChatResult.JailProtection: _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_USE_GLOBAL); break; - case ChatResult.AdminAnnounce: _sfxPlayer.PlaySfx(SoundEffectID.AdminAnnounceReceived); goto case ChatResult.Ok; - case ChatResult.HideSpeechBubble: break; // no-op - case ChatResult.HideAll: break; // no-op - } + NoWallCommand.Text or PingCommand.Text => SoundEffectID.ServerCommand, + _ => SoundEffectID.ServerMessage, + }); + } + break; + case ChatResult.JailProtection: _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_USE_GLOBAL); break; + case ChatResult.AdminAnnounce: _sfxPlayer.PlaySfx(SoundEffectID.AdminAnnounceReceived); goto case ChatResult.Ok; + case ChatResult.HideSpeechBubble: break; // no-op + case ChatResult.HideAll: break; // no-op } - - _chatTextBoxActions.ClearChatText(); } - public void SelectChatTextBox() - { - _chatTextBoxActions.FocusChatTextBox(); - } + _chatTextBoxActions.ClearChatText(); + } - public void ClearAndWarnIfJailAndGlobal() - { - if (!_currentMapStateProvider.IsJail || _chatTypeCalculator.CalculateChatType(ChatTextBox.Text) != ChatType.Global) return; + public void SelectChatTextBox() + { + _chatTextBoxActions.FocusChatTextBox(); + } - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_USE_GLOBAL); - _chatTextBoxActions.ClearChatText(); - } + public void ClearAndWarnIfJailAndGlobal() + { + if (!_currentMapStateProvider.IsJail || _chatTypeCalculator.CalculateChatType(ChatTextBox.Text) != ChatType.Global) return; - private ChatTextBox ChatTextBox => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_USE_GLOBAL); + _chatTextBoxActions.ClearChatText(); } - public interface IChatController - { - void SendChatAndClearTextBox(); + private ChatTextBox ChatTextBox => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); +} - void SelectChatTextBox(); +public interface IChatController +{ + void SendChatAndClearTextBox(); - void ClearAndWarnIfJailAndGlobal(); - } + void SelectChatTextBox(); + + void ClearAndWarnIfJailAndGlobal(); } \ No newline at end of file diff --git a/EndlessClient/Controllers/ControlKeyController.cs b/EndlessClient/Controllers/ControlKeyController.cs index 6b8c06ff8..9f1ff9bd9 100644 --- a/EndlessClient/Controllers/ControlKeyController.cs +++ b/EndlessClient/Controllers/ControlKeyController.cs @@ -6,92 +6,91 @@ using EOLib.Domain.Extensions; using EOLib.Localization; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[MappedType(BaseType = typeof(IControlKeyController))] +public class ControlKeyController : IControlKeyController { - [MappedType(BaseType = typeof(IControlKeyController))] - public class ControlKeyController : IControlKeyController - { - private readonly ICharacterProvider _characterProvider; - private readonly IAttackValidationActions _attackValidationActions; - private readonly ICharacterActions _characterActions; - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ISfxPlayer _sfxPlayer; + private readonly ICharacterProvider _characterProvider; + private readonly IAttackValidationActions _attackValidationActions; + private readonly ICharacterActions _characterActions; + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ISfxPlayer _sfxPlayer; - public ControlKeyController(ICharacterProvider characterProvider, - IAttackValidationActions attackValidationActions, - ICharacterActions characterActions, - ICharacterAnimationActions characterAnimationActions, - IStatusLabelSetter statusLabelSetter, - ISfxPlayer sfxPlayer) - { - _characterProvider = characterProvider; - _attackValidationActions = attackValidationActions; - _characterActions = characterActions; - _characterAnimationActions = characterAnimationActions; - _statusLabelSetter = statusLabelSetter; - _sfxPlayer = sfxPlayer; - } + public ControlKeyController(ICharacterProvider characterProvider, + IAttackValidationActions attackValidationActions, + ICharacterActions characterActions, + ICharacterAnimationActions characterAnimationActions, + IStatusLabelSetter statusLabelSetter, + ISfxPlayer sfxPlayer) + { + _characterProvider = characterProvider; + _attackValidationActions = attackValidationActions; + _characterActions = characterActions; + _characterAnimationActions = characterAnimationActions; + _statusLabelSetter = statusLabelSetter; + _sfxPlayer = sfxPlayer; + } - public bool Attack() - { - _characterAnimationActions.CancelClickToWalk(); + public bool Attack() + { + _characterAnimationActions.CancelClickToWalk(); - if (!CanAttackAgain()) - return false; + if (!CanAttackAgain()) + return false; - AttemptAttack(); + AttemptAttack(); - return true; - } + return true; + } - private bool CanAttackAgain() - { - var rp = _characterProvider.MainCharacter.RenderProperties; - return rp.IsActing(CharacterActionState.Standing) || - rp.RenderAttackFrame == CharacterRenderProperties.MAX_NUMBER_OF_ATTACK_FRAMES; - } + private bool CanAttackAgain() + { + var rp = _characterProvider.MainCharacter.RenderProperties; + return rp.IsActing(CharacterActionState.Standing) || + rp.RenderAttackFrame == CharacterRenderProperties.MAX_NUMBER_OF_ATTACK_FRAMES; + } - private void AttemptAttack() + private void AttemptAttack() + { + var showAnimationAnyway = false; + var validationResult = _attackValidationActions.ValidateCharacterStateBeforeAttacking(); + if (validationResult != AttackValidationError.OK) { - var showAnimationAnyway = false; - var validationResult = _attackValidationActions.ValidateCharacterStateBeforeAttacking(); - if (validationResult != AttackValidationError.OK) + if (validationResult == AttackValidationError.Overweight) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.STATUS_LABEL_CANNOT_ATTACK_OVERWEIGHT); + else if (validationResult == AttackValidationError.Exhausted) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); + else if (validationResult == AttackValidationError.NotYourBattle) { - if (validationResult == AttackValidationError.Overweight) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.STATUS_LABEL_CANNOT_ATTACK_OVERWEIGHT); - else if (validationResult == AttackValidationError.Exhausted) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); - else if (validationResult == AttackValidationError.NotYourBattle) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, - EOResourceID.STATUS_LABEL_UNABLE_TO_ATTACK); - showAnimationAnyway = true; - } - else if (validationResult == AttackValidationError.MissingArrows) - { - _sfxPlayer.PlaySfx(SoundEffectID.NoArrows); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.STATUS_LABEL_YOU_HAVE_NO_ARROWS); - - _sfxPlayer.PlaySfx(SoundEffectID.NoArrows); - } - } - else + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, + EOResourceID.STATUS_LABEL_UNABLE_TO_ATTACK); showAnimationAnyway = true; - - if (showAnimationAnyway) + } + else if (validationResult == AttackValidationError.MissingArrows) { - _characterActions.Attack(); - _characterAnimationActions.StartAttacking(); + _sfxPlayer.PlaySfx(SoundEffectID.NoArrows); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.STATUS_LABEL_YOU_HAVE_NO_ARROWS); + + _sfxPlayer.PlaySfx(SoundEffectID.NoArrows); } } - } + else + showAnimationAnyway = true; - public interface IControlKeyController - { - bool Attack(); + if (showAnimationAnyway) + { + _characterActions.Attack(); + _characterAnimationActions.StartAttacking(); + } } +} + +public interface IControlKeyController +{ + bool Attack(); } \ No newline at end of file diff --git a/EndlessClient/Controllers/FunctionKeyController.cs b/EndlessClient/Controllers/FunctionKeyController.cs index ffc5ed050..d605efbef 100644 --- a/EndlessClient/Controllers/FunctionKeyController.cs +++ b/EndlessClient/Controllers/FunctionKeyController.cs @@ -17,111 +17,110 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[AutoMappedType] +public class FunctionKeyController : IFunctionKeyController { - [AutoMappedType] - public class FunctionKeyController : IFunctionKeyController + private readonly IMapActions _mapActions; + private readonly ICharacterActions _characterActions; + private readonly ISpellSelectActions _spellSelectActions; + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly ISpellCastValidationActions _spellCastValidationActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ICharacterProvider _characterProvider; + private readonly IESFFileProvider _esfFileProvider; + private readonly ISpellSlotDataProvider _spellSlotDataProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly ISfxPlayer _sfxPlayer; + + public FunctionKeyController(IMapActions mapActions, + ICharacterActions characterActions, + ISpellSelectActions spellSelectActions, + ICharacterAnimationActions characterAnimationActions, + ISpellCastValidationActions spellCastValidationActions, + IInGameDialogActions inGameDialogActions, + IStatusLabelSetter statusLabelSetter, + ICharacterProvider characterProvider, + IESFFileProvider esfFileProvider, + ISpellSlotDataProvider spellSlotDataProvider, + IHudControlProvider hudControlProvider, + ISfxPlayer sfxPlayer) { - private readonly IMapActions _mapActions; - private readonly ICharacterActions _characterActions; - private readonly ISpellSelectActions _spellSelectActions; - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly ISpellCastValidationActions _spellCastValidationActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ICharacterProvider _characterProvider; - private readonly IESFFileProvider _esfFileProvider; - private readonly ISpellSlotDataProvider _spellSlotDataProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly ISfxPlayer _sfxPlayer; + _mapActions = mapActions; + _characterActions = characterActions; + _spellSelectActions = spellSelectActions; + _characterAnimationActions = characterAnimationActions; + _spellCastValidationActions = spellCastValidationActions; + _inGameDialogActions = inGameDialogActions; + _statusLabelSetter = statusLabelSetter; + _characterProvider = characterProvider; + _esfFileProvider = esfFileProvider; + _spellSlotDataProvider = spellSlotDataProvider; + _hudControlProvider = hudControlProvider; + _sfxPlayer = sfxPlayer; + } - public FunctionKeyController(IMapActions mapActions, - ICharacterActions characterActions, - ISpellSelectActions spellSelectActions, - ICharacterAnimationActions characterAnimationActions, - ISpellCastValidationActions spellCastValidationActions, - IInGameDialogActions inGameDialogActions, - IStatusLabelSetter statusLabelSetter, - ICharacterProvider characterProvider, - IESFFileProvider esfFileProvider, - ISpellSlotDataProvider spellSlotDataProvider, - IHudControlProvider hudControlProvider, - ISfxPlayer sfxPlayer) + public bool SelectSpell(int index, bool isAlternate) + { + if (_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing)) { - _mapActions = mapActions; - _characterActions = characterActions; - _spellSelectActions = spellSelectActions; - _characterAnimationActions = characterAnimationActions; - _spellCastValidationActions = spellCastValidationActions; - _inGameDialogActions = inGameDialogActions; - _statusLabelSetter = statusLabelSetter; - _characterProvider = characterProvider; - _esfFileProvider = esfFileProvider; - _spellSlotDataProvider = spellSlotDataProvider; - _hudControlProvider = hudControlProvider; - _sfxPlayer = sfxPlayer; - } + _spellSelectActions.SelectSpellBySlot(index + (isAlternate ? ActiveSpellsPanel.SpellRowLength : 0)); - public bool SelectSpell(int index, bool isAlternate) - { - if (_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing)) + _spellSlotDataProvider.SelectedSpellInfo.MatchSome(x => { - _spellSelectActions.SelectSpellBySlot(index + (isAlternate ? ActiveSpellsPanel.SpellRowLength : 0)); - - _spellSlotDataProvider.SelectedSpellInfo.MatchSome(x => + var spellData = _esfFileProvider.ESFFile[x.ID]; + if (spellData.Type == SpellType.Bard && _spellCastValidationActions.ValidateBard()) { - var spellData = _esfFileProvider.ESFFile[x.ID]; - if (spellData.Type == SpellType.Bard && _spellCastValidationActions.ValidateBard()) - { - _inGameDialogActions.ShowBardDialog(); - } - else if (spellData.Target == SpellTarget.Self || spellData.Target == SpellTarget.Group) - { - var castResult = _spellCastValidationActions.ValidateSpellCast(x.ID); - - if (castResult == SpellCastValidationResult.ExhaustedNoTp) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_TP); - else if (castResult == SpellCastValidationResult.ExhaustedNoSp) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); - else if (_characterAnimationActions.PrepareMainCharacterSpell(x.ID, _characterProvider.MainCharacter)) - _characterActions.PrepareCastSpell(x.ID); - } - else - { - _sfxPlayer.PlaySfx(SoundEffectID.SpellActivate); - } - }); + _inGameDialogActions.ShowBardDialog(); + } + else if (spellData.Target == SpellTarget.Self || spellData.Target == SpellTarget.Group) + { + var castResult = _spellCastValidationActions.ValidateSpellCast(x.ID); - return true; - } + if (castResult == SpellCastValidationResult.ExhaustedNoTp) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_TP); + else if (castResult == SpellCastValidationResult.ExhaustedNoSp) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); + else if (_characterAnimationActions.PrepareMainCharacterSpell(x.ID, _characterProvider.MainCharacter)) + _characterActions.PrepareCastSpell(x.ID); + } + else + { + _sfxPlayer.PlaySfx(SoundEffectID.SpellActivate); + } + }); - return false; + return true; } - public bool Sit() - { - if (_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Walking, CharacterActionState.Attacking, CharacterActionState.SpellCast)) - return false; + return false; + } - var cursorRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - _characterActions.Sit(cursorRenderer.GridCoordinates); + public bool Sit() + { + if (_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Walking, CharacterActionState.Attacking, CharacterActionState.SpellCast)) + return false; - return true; - } + var cursorRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + _characterActions.Sit(cursorRenderer.GridCoordinates); - public bool RefreshMapState() - { - _mapActions.RequestRefresh(); - return true; - } + return true; } - public interface IFunctionKeyController + public bool RefreshMapState() { - bool SelectSpell(int index, bool isAlternate); + _mapActions.RequestRefresh(); + return true; + } +} - bool Sit(); +public interface IFunctionKeyController +{ + bool SelectSpell(int index, bool isAlternate); - bool RefreshMapState(); - } + bool Sit(); + + bool RefreshMapState(); } \ No newline at end of file diff --git a/EndlessClient/Controllers/InventoryController.cs b/EndlessClient/Controllers/InventoryController.cs index 34ccb0ba6..1e88a5efa 100644 --- a/EndlessClient/Controllers/InventoryController.cs +++ b/EndlessClient/Controllers/InventoryController.cs @@ -24,397 +24,396 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[AutoMappedType(IsSingleton = true)] +public class InventoryController : IInventoryController { - [AutoMappedType(IsSingleton = true)] - public class InventoryController : IInventoryController + private readonly IItemActions _itemActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IPaperdollActions _paperdollActions; + private readonly IChestActions _chestActions; + private readonly ILockerActions _lockerActions; + private readonly IBankActions _bankActions; + private readonly ITradeActions _tradeActions; + private readonly IItemEquipValidator _itemEquipValidator; + private readonly IItemDropValidator _itemDropValidator; + private readonly ICharacterProvider _characterProvider; + private readonly IPaperdollProvider _paperdollProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly ITradeProvider _tradeProvider; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IItemTransferDialogFactory _itemTransferDialogFactory; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ISfxPlayer _sfxPlayer; + + private bool _goldWarningShown = false; + + public InventoryController(IItemActions itemActions, + IInGameDialogActions inGameDialogActions, + IPaperdollActions paperdollActions, + IChestActions chestActions, + ILockerActions lockerActions, + IBankActions bankActions, + ITradeActions tradeActions, + IItemEquipValidator itemEquipValidator, + IItemDropValidator itemDropValidator, + ICharacterProvider characterProvider, + IPaperdollProvider paperdollProvider, + IHudControlProvider hudControlProvider, + ICurrentMapProvider currentMapProvider, + IEIFFileProvider eifFileProvider, + IActiveDialogProvider activeDialogProvider, + ITradeProvider tradeProvider, + IStatusLabelSetter statusLabelSetter, + IItemTransferDialogFactory itemTransferDialogFactory, + IEOMessageBoxFactory eoMessageBoxFactory, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + ISfxPlayer sfxPlayer) { - private readonly IItemActions _itemActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IPaperdollActions _paperdollActions; - private readonly IChestActions _chestActions; - private readonly ILockerActions _lockerActions; - private readonly IBankActions _bankActions; - private readonly ITradeActions _tradeActions; - private readonly IItemEquipValidator _itemEquipValidator; - private readonly IItemDropValidator _itemDropValidator; - private readonly ICharacterProvider _characterProvider; - private readonly IPaperdollProvider _paperdollProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly ITradeProvider _tradeProvider; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IItemTransferDialogFactory _itemTransferDialogFactory; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ISfxPlayer _sfxPlayer; - - private bool _goldWarningShown = false; - - public InventoryController(IItemActions itemActions, - IInGameDialogActions inGameDialogActions, - IPaperdollActions paperdollActions, - IChestActions chestActions, - ILockerActions lockerActions, - IBankActions bankActions, - ITradeActions tradeActions, - IItemEquipValidator itemEquipValidator, - IItemDropValidator itemDropValidator, - ICharacterProvider characterProvider, - IPaperdollProvider paperdollProvider, - IHudControlProvider hudControlProvider, - ICurrentMapProvider currentMapProvider, - IEIFFileProvider eifFileProvider, - IActiveDialogProvider activeDialogProvider, - ITradeProvider tradeProvider, - IStatusLabelSetter statusLabelSetter, - IItemTransferDialogFactory itemTransferDialogFactory, - IEOMessageBoxFactory eoMessageBoxFactory, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - ISfxPlayer sfxPlayer) - { - _itemActions = itemActions; - _inGameDialogActions = inGameDialogActions; - _paperdollActions = paperdollActions; - _chestActions = chestActions; - _lockerActions = lockerActions; - _bankActions = bankActions; - _tradeActions = tradeActions; - _itemEquipValidator = itemEquipValidator; - _itemDropValidator = itemDropValidator; - _characterProvider = characterProvider; - _paperdollProvider = paperdollProvider; - _hudControlProvider = hudControlProvider; - _currentMapProvider = currentMapProvider; - _eifFileProvider = eifFileProvider; - _activeDialogProvider = activeDialogProvider; - _tradeProvider = tradeProvider; - _statusLabelSetter = statusLabelSetter; - _itemTransferDialogFactory = itemTransferDialogFactory; - _eoMessageBoxFactory = eoMessageBoxFactory; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _sfxPlayer = sfxPlayer; - } - - public void ShowPaperdollDialog() - { - // when called from inventory controller, paperdoll is for the main character - _paperdollActions.RequestPaperdoll(_characterProvider.MainCharacter.ID); - _inGameDialogActions.ShowPaperdollDialog(_characterProvider.MainCharacter, isMainCharacter: true); - } - - public void UseItem(EIFRecord record) - { - var useItem = false; - - var character = _characterProvider.MainCharacter; + _itemActions = itemActions; + _inGameDialogActions = inGameDialogActions; + _paperdollActions = paperdollActions; + _chestActions = chestActions; + _lockerActions = lockerActions; + _bankActions = bankActions; + _tradeActions = tradeActions; + _itemEquipValidator = itemEquipValidator; + _itemDropValidator = itemDropValidator; + _characterProvider = characterProvider; + _paperdollProvider = paperdollProvider; + _hudControlProvider = hudControlProvider; + _currentMapProvider = currentMapProvider; + _eifFileProvider = eifFileProvider; + _activeDialogProvider = activeDialogProvider; + _tradeProvider = tradeProvider; + _statusLabelSetter = statusLabelSetter; + _itemTransferDialogFactory = itemTransferDialogFactory; + _eoMessageBoxFactory = eoMessageBoxFactory; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _sfxPlayer = sfxPlayer; + } - switch (record.Type) - { - //usable items - case ItemType.Teleport: - if (!_currentMapProvider.CurrentMap.Properties.CanScroll) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_NOTHING_HAPPENED); - break; - } + public void ShowPaperdollDialog() + { + // when called from inventory controller, paperdoll is for the main character + _paperdollActions.RequestPaperdoll(_characterProvider.MainCharacter.ID); + _inGameDialogActions.ShowPaperdollDialog(_characterProvider.MainCharacter, isMainCharacter: true); + } - if (record.ScrollMap == character.MapID && record.ScrollX == character.RenderProperties.MapX && record.ScrollY == character.RenderProperties.MapY) - break; + public void UseItem(EIFRecord record) + { + var useItem = false; - useItem = true; - break; + var character = _characterProvider.MainCharacter; - case ItemType.CureCurse: - var paperdollItems = _paperdollProvider.VisibleCharacterPaperdolls[_characterProvider.MainCharacter.ID].Paperdoll.Values; - if (paperdollItems.Where(id => id > 0).Select(id => _eifFileProvider.EIFFile[id].Special).Any(s => s == ItemSpecial.Cursed)) - { - var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_CURSE_REMOVE_PROMPT, EODialogButtons.OkCancel, EOMessageBoxStyle.SmallDialogSmallHeader); - msgBox.DialogClosing += (o, e) => - { - if (e.Result == XNADialogResult.OK) - { - _itemActions.UseItem(record.ID); - } - }; - msgBox.ShowDialog(); - } - break; - - case ItemType.Heal: - case ItemType.HairDye: - case ItemType.Beer: - case ItemType.EffectPotion: - case ItemType.EXPReward: - useItem = true; + switch (record.Type) + { + //usable items + case ItemType.Teleport: + if (!_currentMapProvider.CurrentMap.Properties.CanScroll) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_NOTHING_HAPPENED); break; + } - // Not implemented server - side - case ItemType.SkillReward: - case ItemType.StatReward: + if (record.ScrollMap == character.MapID && record.ScrollX == character.RenderProperties.MapX && record.ScrollY == character.RenderProperties.MapY) break; - } - if (useItem) - { - _itemActions.UseItem(record.ID); + useItem = true; + break; - if (record.Type == ItemType.Beer) + case ItemType.CureCurse: + var paperdollItems = _paperdollProvider.VisibleCharacterPaperdolls[_characterProvider.MainCharacter.ID].Paperdoll.Values; + if (paperdollItems.Where(id => id > 0).Select(id => _eifFileProvider.EIFFile[id].Special).Any(s => s == ItemSpecial.Cursed)) { - // The server does not send back the potency, it is all client-side - _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler) - .SetDrunkTimeout(record.BeerPotency); + var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_CURSE_REMOVE_PROMPT, EODialogButtons.OkCancel, EOMessageBoxStyle.SmallDialogSmallHeader); + msgBox.DialogClosing += (o, e) => + { + if (e.Result == XNADialogResult.OK) + { + _itemActions.UseItem(record.ID); + } + }; + msgBox.ShowDialog(); } - } + break; + + case ItemType.Heal: + case ItemType.HairDye: + case ItemType.Beer: + case ItemType.EffectPotion: + case ItemType.EXPReward: + useItem = true; + break; + + // Not implemented server - side + case ItemType.SkillReward: + case ItemType.StatReward: + break; } - public void EquipItem(EIFRecord itemData) + if (useItem) { - var c = _characterProvider.MainCharacter; - var (validationResult, detail, isAlternateEquipLocation) = _itemEquipValidator.ValidateItemEquip(c, itemData); + _itemActions.UseItem(record.ID); - switch (validationResult) + if (record.Type == ItemType.Beer) { - case ItemEquipResult.NotEquippable: - throw new ArgumentException("Item is not equippable", nameof(itemData)); - case ItemEquipResult.AlreadyEquipped: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_TYPE_ALREADY_EQUIPPED); - break; - case ItemEquipResult.WrongGender: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_DOES_NOT_FIT_GENDER); - break; - case ItemEquipResult.StatRequirementNotMet: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, - EOResourceID.STATUS_LABEL_ITEM_EQUIP_THIS_ITEM_REQUIRES, detail); - break; - case ItemEquipResult.ClassRequirementNotMet: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, - EOResourceID.STATUS_LABEL_ITEM_EQUIP_CAN_ONLY_BE_USED_BY, detail); - break; - case ItemEquipResult.Ok: - _itemActions.EquipItem(itemData.ID, isAlternateEquipLocation); - break; + // The server does not send back the potency, it is all client-side + _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler) + .SetDrunkTimeout(record.BeerPotency); } } + } - public void UnequipItem(EquipLocation equipLocation) + public void EquipItem(EIFRecord itemData) + { + var c = _characterProvider.MainCharacter; + var (validationResult, detail, isAlternateEquipLocation) = _itemEquipValidator.ValidateItemEquip(c, itemData); + + switch (validationResult) { - var locName = Enum.GetName(typeof(EquipLocation), equipLocation); - var equipId = _paperdollProvider.VisibleCharacterPaperdolls[_characterProvider.MainCharacter.ID].Paperdoll[equipLocation]; - _itemActions.UnequipItem(equipId, alternateLocation: locName.Contains('2')); + case ItemEquipResult.NotEquippable: + throw new ArgumentException("Item is not equippable", nameof(itemData)); + case ItemEquipResult.AlreadyEquipped: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_TYPE_ALREADY_EQUIPPED); + break; + case ItemEquipResult.WrongGender: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_DOES_NOT_FIT_GENDER); + break; + case ItemEquipResult.StatRequirementNotMet: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, + EOResourceID.STATUS_LABEL_ITEM_EQUIP_THIS_ITEM_REQUIRES, detail); + break; + case ItemEquipResult.ClassRequirementNotMet: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, + EOResourceID.STATUS_LABEL_ITEM_EQUIP_CAN_ONLY_BE_USED_BY, detail); + break; + case ItemEquipResult.Ok: + _itemActions.EquipItem(itemData.ID, isAlternateEquipLocation); + break; } + } - public void DropItem(EIFRecord itemData, InventoryItem inventoryItem, MapCoordinate coords) - { - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue) && mapRenderer.MouseOver) - return; + public void UnequipItem(EquipLocation equipLocation) + { + var locName = Enum.GetName(typeof(EquipLocation), equipLocation); + var equipId = _paperdollProvider.VisibleCharacterPaperdolls[_characterProvider.MainCharacter.ID].Paperdoll[equipLocation]; + _itemActions.UnequipItem(equipId, alternateLocation: locName.Contains('2')); + } - var rp = _characterProvider.MainCharacter.RenderProperties; - var validationResult = _itemDropValidator.ValidateItemDrop(_characterProvider.MainCharacter, inventoryItem, coords); + public void DropItem(EIFRecord itemData, InventoryItem inventoryItem, MapCoordinate coords) + { + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue) && mapRenderer.MouseOver) + return; - if (validationResult == ItemDropResult.Lore) - { - var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM, EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); - msgBox.ShowDialog(); - } - else if (validationResult == ItemDropResult.Jail) - { - var msgBox = _eoMessageBoxFactory.CreateMessageBox( - EOResourceID.JAIL_WARNING_CANNOT_DROP_ITEMS, - EOResourceID.STATUS_LABEL_TYPE_WARNING, - EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); - msgBox.ShowDialog(); - } - else if (validationResult == ItemDropResult.Ok) - { - DoItemDrop(itemData, inventoryItem, a => _itemActions.DropItem(inventoryItem.ItemID, a, coords)); - } - else if (validationResult == ItemDropResult.TooFar) - { - var localizedMessage = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_DROP_OUT_OF_RANGE); - var chatData = new ChatData(ChatTab.System, "System", localizedMessage, ChatIcon.DotDotDotDot); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_DROP_OUT_OF_RANGE); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } - } + var rp = _characterProvider.MainCharacter.RenderProperties; + var validationResult = _itemDropValidator.ValidateItemDrop(_characterProvider.MainCharacter, inventoryItem, coords); - public void DropItemInChest(EIFRecord itemData, InventoryItem inventoryItem) + if (validationResult == ItemDropResult.Lore) + { + var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM, EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); + msgBox.ShowDialog(); + } + else if (validationResult == ItemDropResult.Jail) + { + var msgBox = _eoMessageBoxFactory.CreateMessageBox( + EOResourceID.JAIL_WARNING_CANNOT_DROP_ITEMS, + EOResourceID.STATUS_LABEL_TYPE_WARNING, + EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); + msgBox.ShowDialog(); + } + else if (validationResult == ItemDropResult.Ok) + { + DoItemDrop(itemData, inventoryItem, a => _itemActions.DropItem(inventoryItem.ItemID, a, coords)); + } + else if (validationResult == ItemDropResult.TooFar) { - var validationResult = _itemDropValidator.ValidateItemDrop(_characterProvider.MainCharacter, inventoryItem); + var localizedMessage = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_DROP_OUT_OF_RANGE); + var chatData = new ChatData(ChatTab.System, "System", localizedMessage, ChatIcon.DotDotDotDot); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_DROP_OUT_OF_RANGE); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } + } - if (validationResult == ItemDropResult.Lore) - { - var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM); - msgBox.ShowDialog(); - } - else - { - DoItemDrop(itemData, inventoryItem, a => _chestActions.AddItemToChest(inventoryItem.WithAmount(a))); - } + public void DropItemInChest(EIFRecord itemData, InventoryItem inventoryItem) + { + var validationResult = _itemDropValidator.ValidateItemDrop(_characterProvider.MainCharacter, inventoryItem); + + if (validationResult == ItemDropResult.Lore) + { + var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM); + msgBox.ShowDialog(); + } + else + { + DoItemDrop(itemData, inventoryItem, a => _chestActions.AddItemToChest(inventoryItem.WithAmount(a))); } + } - public void DropItemInLocker(EIFRecord itemData, InventoryItem inventoryItem) + public void DropItemInLocker(EIFRecord itemData, InventoryItem inventoryItem) + { + if (inventoryItem.ItemID == 1) { - if (inventoryItem.ItemID == 1) - { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_DEPOSIT_GOLD_ERROR); - dlg.ShowDialog(); - } - else + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_DEPOSIT_GOLD_ERROR); + dlg.ShowDialog(); + } + else + { + DoItemDrop(itemData, inventoryItem, a => { - DoItemDrop(itemData, inventoryItem, a => + if (_lockerActions.GetNewItemAmount(inventoryItem.ItemID, a) > Constants.LockerMaxSingleItemAmount) { - if (_lockerActions.GetNewItemAmount(inventoryItem.ItemID, a) > Constants.LockerMaxSingleItemAmount) - { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_FULL_SINGLE_ITEM_MAX); - dlg.ShowDialog(); - } - else - { - _lockerActions.AddItemToLocker(inventoryItem.WithAmount(a)); - } - }, - ItemTransferDialog.TransferType.ShopTransfer, - EOResourceID.DIALOG_TRANSFER_TRANSFER); - } + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_FULL_SINGLE_ITEM_MAX); + dlg.ShowDialog(); + } + else + { + _lockerActions.AddItemToLocker(inventoryItem.WithAmount(a)); + } + }, + ItemTransferDialog.TransferType.ShopTransfer, + EOResourceID.DIALOG_TRANSFER_TRANSFER); } + } - public void DropItemInBank(EIFRecord itemData, InventoryItem inventoryItem) + public void DropItemInBank(EIFRecord itemData, InventoryItem inventoryItem) + { + if (inventoryItem.Amount == 0) { - if (inventoryItem.Amount == 0) - { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); - dlg.ShowDialog(); - } - else - { - DoItemDrop(itemData, - inventoryItem, - a => _bankActions.Deposit(a), - ItemTransferDialog.TransferType.BankTransfer, - EOResourceID.DIALOG_TRANSFER_DEPOSIT); - } + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); + dlg.ShowDialog(); + } + else + { + DoItemDrop(itemData, + inventoryItem, + a => _bankActions.Deposit(a), + ItemTransferDialog.TransferType.BankTransfer, + EOResourceID.DIALOG_TRANSFER_DEPOSIT); } + } - public void JunkItem(EIFRecord itemData, InventoryItem inventoryItem) + public void JunkItem(EIFRecord itemData, InventoryItem inventoryItem) + { + if (inventoryItem.Amount > 1) { - if (inventoryItem.Amount > 1) + var transferDialog = _itemTransferDialogFactory.CreateItemTransferDialog( + itemData.Name, + ItemTransferDialog.TransferType.JunkItems, + inventoryItem.Amount, + EOResourceID.DIALOG_TRANSFER_JUNK); + transferDialog.DialogClosing += (sender, e) => { - var transferDialog = _itemTransferDialogFactory.CreateItemTransferDialog( - itemData.Name, - ItemTransferDialog.TransferType.JunkItems, - inventoryItem.Amount, - EOResourceID.DIALOG_TRANSFER_JUNK); - transferDialog.DialogClosing += (sender, e) => + if (e.Result == XNADialogResult.OK) { - if (e.Result == XNADialogResult.OK) - { - _itemActions.JunkItem(inventoryItem.ItemID, transferDialog.SelectedAmount); - } - }; - transferDialog.ShowDialog(); - } - else - { - _itemActions.JunkItem(inventoryItem.ItemID, 1); - } + _itemActions.JunkItem(inventoryItem.ItemID, transferDialog.SelectedAmount); + } + }; + transferDialog.ShowDialog(); } - - public void TradeItem(EIFRecord itemData, InventoryItem inventoryItem) + else { - var mainPlayerAgrees = _characterProvider.MainCharacter.ID == _tradeProvider.PlayerOneOffer.PlayerID - ? _tradeProvider.PlayerOneOffer.Agrees - : _tradeProvider.PlayerTwoOffer.Agrees; + _itemActions.JunkItem(inventoryItem.ItemID, 1); + } + } - if (mainPlayerAgrees) - return; + public void TradeItem(EIFRecord itemData, InventoryItem inventoryItem) + { + var mainPlayerAgrees = _characterProvider.MainCharacter.ID == _tradeProvider.PlayerOneOffer.PlayerID + ? _tradeProvider.PlayerOneOffer.Agrees + : _tradeProvider.PlayerTwoOffer.Agrees; - if (itemData.Special == ItemSpecial.Lore) - { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM); - dlg.ShowDialog(); - } - else - { - DoItemDrop(itemData, inventoryItem, - a => _tradeActions.AddItemToOffer(inventoryItem.ItemID, a), - ItemTransferDialog.TransferType.TradeItems, - EOResourceID.DIALOG_TRANSFER_OFFER); - } + if (mainPlayerAgrees) + return; + + if (itemData.Special == ItemSpecial.Lore) + { + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM); + dlg.ShowDialog(); } + else + { + DoItemDrop(itemData, inventoryItem, + a => _tradeActions.AddItemToOffer(inventoryItem.ItemID, a), + ItemTransferDialog.TransferType.TradeItems, + EOResourceID.DIALOG_TRANSFER_OFFER); + } + } - private void DoItemDrop(EIFRecord itemData, InventoryItem inventoryItem, Action dropAction, - ItemTransferDialog.TransferType transferType = ItemTransferDialog.TransferType.DropItems, - EOResourceID message = EOResourceID.DIALOG_TRANSFER_DROP) + private void DoItemDrop(EIFRecord itemData, InventoryItem inventoryItem, Action dropAction, + ItemTransferDialog.TransferType transferType = ItemTransferDialog.TransferType.DropItems, + EOResourceID message = EOResourceID.DIALOG_TRANSFER_DROP) + { + if (inventoryItem.Amount > 1) { - if (inventoryItem.Amount > 1) - { - var transferDialog = _itemTransferDialogFactory.CreateItemTransferDialog( - itemData.Name, - transferType, - inventoryItem.Amount, - message); + var transferDialog = _itemTransferDialogFactory.CreateItemTransferDialog( + itemData.Name, + transferType, + inventoryItem.Amount, + message); - transferDialog.DialogClosing += (sender, e) => + transferDialog.DialogClosing += (sender, e) => + { + if (e.Result == XNADialogResult.OK) { - if (e.Result == XNADialogResult.OK) - { - var isLargeGoldItemDrop = inventoryItem.ItemID == 1 && inventoryItem.Amount > 10000 && transferType == ItemTransferDialog.TransferType.DropItems; + var isLargeGoldItemDrop = inventoryItem.ItemID == 1 && inventoryItem.Amount > 10000 && transferType == ItemTransferDialog.TransferType.DropItems; - if (isLargeGoldItemDrop && !_goldWarningShown) + if (isLargeGoldItemDrop && !_goldWarningShown) + { + var warningMsg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.DROP_MANY_GOLD_ON_GROUND, EODialogButtons.OkCancel); + _sfxPlayer.PlaySfx(SoundEffectID.Login); + warningMsg.DialogClosing += (_, warningArgs) => { - var warningMsg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.DROP_MANY_GOLD_ON_GROUND, EODialogButtons.OkCancel); - _sfxPlayer.PlaySfx(SoundEffectID.Login); - warningMsg.DialogClosing += (_, warningArgs) => + if (warningArgs.Result == XNADialogResult.OK) { - if (warningArgs.Result == XNADialogResult.OK) - { - _goldWarningShown = true; - } - }; - warningMsg.ShowDialog(); - } - else - { - dropAction(transferDialog.SelectedAmount); - } + _goldWarningShown = true; + } + }; + warningMsg.ShowDialog(); } - }; - transferDialog.ShowDialog(); - } - else - { - dropAction(1); - } + else + { + dropAction(transferDialog.SelectedAmount); + } + } + }; + transferDialog.ShowDialog(); + } + else + { + dropAction(1); } } +} - public interface IInventoryController - { - void ShowPaperdollDialog(); +public interface IInventoryController +{ + void ShowPaperdollDialog(); - void UseItem(EIFRecord record); + void UseItem(EIFRecord record); - void EquipItem(EIFRecord itemData); + void EquipItem(EIFRecord itemData); - void UnequipItem(EquipLocation equipLocation); + void UnequipItem(EquipLocation equipLocation); - void DropItem(EIFRecord itemData, InventoryItem inventoryItem, MapCoordinate coords); + void DropItem(EIFRecord itemData, InventoryItem inventoryItem, MapCoordinate coords); - void DropItemInChest(EIFRecord itemData, InventoryItem inventoryItem); + void DropItemInChest(EIFRecord itemData, InventoryItem inventoryItem); - void DropItemInLocker(EIFRecord itemData, InventoryItem inventoryItem); + void DropItemInLocker(EIFRecord itemData, InventoryItem inventoryItem); - void DropItemInBank(EIFRecord itemData, InventoryItem inventoryItem); + void DropItemInBank(EIFRecord itemData, InventoryItem inventoryItem); - void JunkItem(EIFRecord itemData, InventoryItem inventoryItem); + void JunkItem(EIFRecord itemData, InventoryItem inventoryItem); - void TradeItem(EIFRecord itemData, InventoryItem inventoryItem); - } + void TradeItem(EIFRecord itemData, InventoryItem inventoryItem); } \ No newline at end of file diff --git a/EndlessClient/Controllers/LoginController.cs b/EndlessClient/Controllers/LoginController.cs index b8fc7b40f..f68a749d2 100644 --- a/EndlessClient/Controllers/LoginController.cs +++ b/EndlessClient/Controllers/LoginController.cs @@ -25,296 +25,295 @@ using System.IO; using System.Threading.Tasks; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[AutoMappedType] +public class LoginController : ILoginController { - [AutoMappedType] - public class LoginController : ILoginController + private readonly ILoginActions _loginActions; + private readonly IMapFileLoadActions _mapFileLoadActions; + private readonly IFileRequestActions _fileRequestActions; + private readonly IGameStateActions _gameStateActions; + private readonly IChatTextBoxActions _chatTextBoxActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IChatRepository _chatRepository; + private readonly INewsProvider _newsProvider; + private readonly IUserInputTimeRepository _userInputTimeRepository; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IConfigurationProvider _configurationProvider; + private readonly IPlayerInfoRepository _playerInfoRepository; + private readonly IErrorDialogDisplayAction _errorDisplayAction; + private readonly ISafeNetworkOperationFactory _networkOperationFactory; + private readonly IGameLoadingDialogFactory _gameLoadingDialogFactory; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IFirstTimePlayerActions _firstTimePlayerActions; + private readonly IMapChangedActions _mapChangedActions; + + public LoginController(ILoginActions loginActions, + IMapFileLoadActions mapFileLoadActions, + IFileRequestActions fileRequestActions, + IGameStateActions gameStateActions, + IChatTextBoxActions chatTextBoxActions, + IErrorDialogDisplayAction errorDisplayAction, + IFirstTimePlayerActions firstTimePlayerActions, + IMapChangedActions mapChangedActions, + ISafeNetworkOperationFactory networkOperationFactory, + IGameLoadingDialogFactory gameLoadingDialogFactory, + ICurrentMapStateProvider currentMapStateProvider, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + IChatRepository chatRepository, + INewsProvider newsProvider, + IUserInputTimeRepository userInputTimeRepository, + IClientWindowSizeRepository clientWindowSizeRepository, + IConfigurationProvider configurationProvider, + IPlayerInfoRepository playerInfoRepository) { - private readonly ILoginActions _loginActions; - private readonly IMapFileLoadActions _mapFileLoadActions; - private readonly IFileRequestActions _fileRequestActions; - private readonly IGameStateActions _gameStateActions; - private readonly IChatTextBoxActions _chatTextBoxActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IChatRepository _chatRepository; - private readonly INewsProvider _newsProvider; - private readonly IUserInputTimeRepository _userInputTimeRepository; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private readonly IConfigurationProvider _configurationProvider; - private readonly IPlayerInfoRepository _playerInfoRepository; - private readonly IErrorDialogDisplayAction _errorDisplayAction; - private readonly ISafeNetworkOperationFactory _networkOperationFactory; - private readonly IGameLoadingDialogFactory _gameLoadingDialogFactory; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IFirstTimePlayerActions _firstTimePlayerActions; - private readonly IMapChangedActions _mapChangedActions; - - public LoginController(ILoginActions loginActions, - IMapFileLoadActions mapFileLoadActions, - IFileRequestActions fileRequestActions, - IGameStateActions gameStateActions, - IChatTextBoxActions chatTextBoxActions, - IErrorDialogDisplayAction errorDisplayAction, - IFirstTimePlayerActions firstTimePlayerActions, - IMapChangedActions mapChangedActions, - ISafeNetworkOperationFactory networkOperationFactory, - IGameLoadingDialogFactory gameLoadingDialogFactory, - ICurrentMapStateProvider currentMapStateProvider, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - IChatRepository chatRepository, - INewsProvider newsProvider, - IUserInputTimeRepository userInputTimeRepository, - IClientWindowSizeRepository clientWindowSizeRepository, - IConfigurationProvider configurationProvider, - IPlayerInfoRepository playerInfoRepository) - { - _loginActions = loginActions; - _mapFileLoadActions = mapFileLoadActions; - _fileRequestActions = fileRequestActions; - _gameStateActions = gameStateActions; - _chatTextBoxActions = chatTextBoxActions; - _errorDisplayAction = errorDisplayAction; - _firstTimePlayerActions = firstTimePlayerActions; - _mapChangedActions = mapChangedActions; - _networkOperationFactory = networkOperationFactory; - _gameLoadingDialogFactory = gameLoadingDialogFactory; - _currentMapStateProvider = currentMapStateProvider; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _chatRepository = chatRepository; - _newsProvider = newsProvider; - _userInputTimeRepository = userInputTimeRepository; - _clientWindowSizeRepository = clientWindowSizeRepository; - _configurationProvider = configurationProvider; - _playerInfoRepository = playerInfoRepository; - } + _loginActions = loginActions; + _mapFileLoadActions = mapFileLoadActions; + _fileRequestActions = fileRequestActions; + _gameStateActions = gameStateActions; + _chatTextBoxActions = chatTextBoxActions; + _errorDisplayAction = errorDisplayAction; + _firstTimePlayerActions = firstTimePlayerActions; + _mapChangedActions = mapChangedActions; + _networkOperationFactory = networkOperationFactory; + _gameLoadingDialogFactory = gameLoadingDialogFactory; + _currentMapStateProvider = currentMapStateProvider; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _chatRepository = chatRepository; + _newsProvider = newsProvider; + _userInputTimeRepository = userInputTimeRepository; + _clientWindowSizeRepository = clientWindowSizeRepository; + _configurationProvider = configurationProvider; + _playerInfoRepository = playerInfoRepository; + } - public async Task LoginToAccount(ILoginParameters loginParameters) - { - if (!_loginActions.LoginParametersAreValid(loginParameters)) - return; + public async Task LoginToAccount(ILoginParameters loginParameters) + { + if (!_loginActions.LoginParametersAreValid(loginParameters)) + return; - var loginToServerOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _loginActions.LoginToServer(loginParameters), - SetInitialStateAndShowError, SetInitialStateAndShowError); + var loginToServerOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _loginActions.LoginToServer(loginParameters), + SetInitialStateAndShowError, SetInitialStateAndShowError); - if (!await loginToServerOperation.Invoke().ConfigureAwait(false)) - return; - var reply = loginToServerOperation.Result; + if (!await loginToServerOperation.Invoke().ConfigureAwait(false)) + return; + var reply = loginToServerOperation.Result; - if (reply == LoginReply.Ok) - { - await DispatcherGameComponent.Invoke(() => _gameStateActions.ChangeToState(GameStates.LoggedIn)); - } + if (reply == LoginReply.Ok) + { + await DispatcherGameComponent.Invoke(() => _gameStateActions.ChangeToState(GameStates.LoggedIn)); + } + else + { + if (reply == LoginReply.WrongUser || reply == LoginReply.WrongUserPassword) + _playerInfoRepository.LoginAttempts++; else + _playerInfoRepository.LoginAttempts = 3; + + _errorDisplayAction.ShowLoginError(reply); + + if (_playerInfoRepository.LoginAttempts >= 3) { - if (reply == LoginReply.WrongUser || reply == LoginReply.WrongUserPassword) - _playerInfoRepository.LoginAttempts++; - else - _playerInfoRepository.LoginAttempts = 3; - - _errorDisplayAction.ShowLoginError(reply); - - if (_playerInfoRepository.LoginAttempts >= 3) - { - _gameStateActions.ChangeToState(GameStates.Initial); - _playerInfoRepository.LoginAttempts = 0; - } + _gameStateActions.ChangeToState(GameStates.Initial); + _playerInfoRepository.LoginAttempts = 0; } } + } - public async Task LoginToCharacter(Character character) + public async Task LoginToCharacter(Character character) + { + var requestCharacterLoginOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _loginActions.RequestCharacterLogin(character), + SetInitialStateAndShowError, SetInitialStateAndShowError); + if (!await requestCharacterLoginOperation.Invoke().ConfigureAwait(false)) + return; + + var sessionID = requestCharacterLoginOperation.Result; + + var unableToLoadMap = false; + try { - var requestCharacterLoginOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _loginActions.RequestCharacterLogin(character), - SetInitialStateAndShowError, SetInitialStateAndShowError); - if (!await requestCharacterLoginOperation.Invoke().ConfigureAwait(false)) - return; + _mapFileLoadActions.LoadMapFileByID(_currentMapStateProvider.CurrentMapID); + } + catch (IOException) + { + // Try to load the map now that we know what Map ID we need + // non-fatal exception + unableToLoadMap = true; + } + + GameLoadingDialog gameLoadingDialog = null; + try + { + gameLoadingDialog = _gameLoadingDialogFactory.CreateGameLoadingDialog(); + gameLoadingDialog.ShowDialog(); - var sessionID = requestCharacterLoginOperation.Result; + await InitialDelayInReleaseMode().ConfigureAwait(false); - var unableToLoadMap = false; - try + if (unableToLoadMap || _fileRequestActions.NeedsFileForLogin(FileType.Emf, _currentMapStateProvider.CurrentMapID)) { - _mapFileLoadActions.LoadMapFileByID(_currentMapStateProvider.CurrentMapID); + gameLoadingDialog.SetState(GameLoadingDialogState.Map); + if (!await SafeGetFile(() => _fileRequestActions.GetMapFromServer(_currentMapStateProvider.CurrentMapID, sessionID)).ConfigureAwait(false)) + return; + await Task.Delay(1000).ConfigureAwait(false); } - catch (IOException) + + if (_fileRequestActions.NeedsFileForLogin(FileType.Eif)) { - // Try to load the map now that we know what Map ID we need - // non-fatal exception - unableToLoadMap = true; + gameLoadingDialog.SetState(GameLoadingDialogState.Item); + if (!await SafeGetFile(() => _fileRequestActions.GetItemFileFromServer(sessionID)).ConfigureAwait(false)) + return; + await Task.Delay(1000).ConfigureAwait(false); } - GameLoadingDialog gameLoadingDialog = null; - try + if (_fileRequestActions.NeedsFileForLogin(FileType.Enf)) { - gameLoadingDialog = _gameLoadingDialogFactory.CreateGameLoadingDialog(); - gameLoadingDialog.ShowDialog(); - - await InitialDelayInReleaseMode().ConfigureAwait(false); - - if (unableToLoadMap || _fileRequestActions.NeedsFileForLogin(FileType.Emf, _currentMapStateProvider.CurrentMapID)) - { - gameLoadingDialog.SetState(GameLoadingDialogState.Map); - if (!await SafeGetFile(() => _fileRequestActions.GetMapFromServer(_currentMapStateProvider.CurrentMapID, sessionID)).ConfigureAwait(false)) - return; - await Task.Delay(1000).ConfigureAwait(false); - } - - if (_fileRequestActions.NeedsFileForLogin(FileType.Eif)) - { - gameLoadingDialog.SetState(GameLoadingDialogState.Item); - if (!await SafeGetFile(() => _fileRequestActions.GetItemFileFromServer(sessionID)).ConfigureAwait(false)) - return; - await Task.Delay(1000).ConfigureAwait(false); - } - - if (_fileRequestActions.NeedsFileForLogin(FileType.Enf)) - { - gameLoadingDialog.SetState(GameLoadingDialogState.NPC); - if (!await SafeGetFile(() => _fileRequestActions.GetNPCFileFromServer(sessionID)).ConfigureAwait(false)) - return; - await Task.Delay(1000).ConfigureAwait(false); - } - - if (_fileRequestActions.NeedsFileForLogin(FileType.Esf)) - { - gameLoadingDialog.SetState(GameLoadingDialogState.Spell); - if (!await SafeGetFile(() => _fileRequestActions.GetSpellFileFromServer(sessionID)).ConfigureAwait(false)) - return; - await Task.Delay(1000).ConfigureAwait(false); - } - - if (_fileRequestActions.NeedsFileForLogin(FileType.Ecf)) - { - gameLoadingDialog.SetState(GameLoadingDialogState.Class); - if (!await SafeGetFile(() => _fileRequestActions.GetClassFileFromServer(sessionID)).ConfigureAwait(false)) - return; - await Task.Delay(1000).ConfigureAwait(false); - } - - gameLoadingDialog.SetState(GameLoadingDialogState.LoadingGame); - - var completeCharacterLoginOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _loginActions.CompleteCharacterLogin(sessionID), - SetInitialStateAndShowError, - SetInitialStateAndShowError); - if (!await completeCharacterLoginOperation.Invoke().ConfigureAwait(false)) + gameLoadingDialog.SetState(GameLoadingDialogState.NPC); + if (!await SafeGetFile(() => _fileRequestActions.GetNPCFileFromServer(sessionID)).ConfigureAwait(false)) return; + await Task.Delay(1000).ConfigureAwait(false); + } - if (completeCharacterLoginOperation.Result == WelcomeCode.ServerBusy) - { - // https://discord.com/channels/723989119503696013/787685796055482368/946634672295784509 - // Sausage: 'I have WELCOME_REPLY 3 as returning a "server is busy" message if you send it and then disconnect the client' - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDisplayAction.ShowLoginError(LoginReply.Busy); + if (_fileRequestActions.NeedsFileForLogin(FileType.Esf)) + { + gameLoadingDialog.SetState(GameLoadingDialogState.Spell); + if (!await SafeGetFile(() => _fileRequestActions.GetSpellFileFromServer(sessionID)).ConfigureAwait(false)) return; - } - - // TODO: This is a temporary workaround until the bug in AutomaticTypeMapper/Unity is resolved - // https://github.com/ethanmoffat/EndlessClient/issues/151#issuecomment-1079738889 - ClearChat(); - AddDefaultTextToChat(); - - _userInputTimeRepository.LastInputTime = DateTime.Now; - - await Task.Delay(1000).ConfigureAwait(false); //always wait 1 second + await Task.Delay(1000).ConfigureAwait(false); } - finally + + if (_fileRequestActions.NeedsFileForLogin(FileType.Ecf)) { - gameLoadingDialog?.CloseDialog(); + gameLoadingDialog.SetState(GameLoadingDialogState.Class); + if (!await SafeGetFile(() => _fileRequestActions.GetClassFileFromServer(sessionID)).ConfigureAwait(false)) + return; + await Task.Delay(1000).ConfigureAwait(false); } - if (_configurationProvider.InGameWidth != 0 && _configurationProvider.InGameHeight != 0) + gameLoadingDialog.SetState(GameLoadingDialogState.LoadingGame); + + var completeCharacterLoginOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _loginActions.CompleteCharacterLogin(sessionID), + SetInitialStateAndShowError, + SetInitialStateAndShowError); + if (!await completeCharacterLoginOperation.Invoke().ConfigureAwait(false)) + return; + + if (completeCharacterLoginOperation.Result == WelcomeCode.ServerBusy) { - var layoutConfig = new IniReader(Constants.PanelLayoutFile); - - int width = _configurationProvider.InGameWidth; - int height = _configurationProvider.InGameHeight; - var loaded = layoutConfig.Load() && layoutConfig.GetValue("DISPLAY", "Width", out width) && layoutConfig.GetValue("DISPLAY", "Height", out height); - - await DispatcherGameComponent.Invoke(() => - { - _clientWindowSizeRepository.Width = loaded ? width : _configurationProvider.InGameWidth; - _clientWindowSizeRepository.Height = loaded ? height : _configurationProvider.InGameHeight; - }); - _clientWindowSizeRepository.Resizable = true; + // https://discord.com/channels/723989119503696013/787685796055482368/946634672295784509 + // Sausage: 'I have WELCOME_REPLY 3 as returning a "server is busy" message if you send it and then disconnect the client' + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDisplayAction.ShowLoginError(LoginReply.Busy); + return; } - await DispatcherGameComponent.Invoke(() => - { - _gameStateActions.ChangeToState(GameStates.PlayingTheGame); - _chatTextBoxActions.FocusChatTextBox(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.LOADING_GAME_HINT_FIRST); - _firstTimePlayerActions.WarnFirstTimePlayers(); - _mapChangedActions.ActiveCharacterEnterMapForLogin(); - }); - } + // TODO: This is a temporary workaround until the bug in AutomaticTypeMapper/Unity is resolved + // https://github.com/ethanmoffat/EndlessClient/issues/151#issuecomment-1079738889 + ClearChat(); + AddDefaultTextToChat(); - private void SetInitialStateAndShowError(NoDataSentException ex) + _userInputTimeRepository.LastInputTime = DateTime.Now; + + await Task.Delay(1000).ConfigureAwait(false); //always wait 1 second + } + finally { - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDisplayAction.ShowException(ex); + gameLoadingDialog?.CloseDialog(); } - private void SetInitialStateAndShowError(EmptyPacketReceivedException ex) + if (_configurationProvider.InGameWidth != 0 && _configurationProvider.InGameHeight != 0) { - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDisplayAction.ShowException(ex); + var layoutConfig = new IniReader(Constants.PanelLayoutFile); + + int width = _configurationProvider.InGameWidth; + int height = _configurationProvider.InGameHeight; + var loaded = layoutConfig.Load() && layoutConfig.GetValue("DISPLAY", "Width", out width) && layoutConfig.GetValue("DISPLAY", "Height", out height); + + await DispatcherGameComponent.Invoke(() => + { + _clientWindowSizeRepository.Width = loaded ? width : _configurationProvider.InGameWidth; + _clientWindowSizeRepository.Height = loaded ? height : _configurationProvider.InGameHeight; + }); + _clientWindowSizeRepository.Resizable = true; } - private static Task InitialDelayInReleaseMode() + await DispatcherGameComponent.Invoke(() => { + _gameStateActions.ChangeToState(GameStates.PlayingTheGame); + _chatTextBoxActions.FocusChatTextBox(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.LOADING_GAME_HINT_FIRST); + _firstTimePlayerActions.WarnFirstTimePlayers(); + _mapChangedActions.ActiveCharacterEnterMapForLogin(); + }); + } + + private void SetInitialStateAndShowError(NoDataSentException ex) + { + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDisplayAction.ShowException(ex); + } + + private void SetInitialStateAndShowError(EmptyPacketReceivedException ex) + { + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDisplayAction.ShowException(ex); + } + + private static Task InitialDelayInReleaseMode() + { #if DEBUG - return Task.Delay(1000); + return Task.Delay(1000); #else - return Task.Delay(5000); + return Task.Delay(5000); #endif - } + } - private async Task SafeGetFile(Func operation) - { - var op = _networkOperationFactory.CreateSafeBlockingOperation( - operation, - SetInitialStateAndShowError, - SetInitialStateAndShowError); - return await op.Invoke().ConfigureAwait(false); - } + private async Task SafeGetFile(Func operation) + { + var op = _networkOperationFactory.CreateSafeBlockingOperation( + operation, + SetInitialStateAndShowError, + SetInitialStateAndShowError); + return await op.Invoke().ConfigureAwait(false); + } - private void ClearChat() + private void ClearChat() + { + foreach (var chat in _chatRepository.AllChat.Values) { - foreach (var chat in _chatRepository.AllChat.Values) - { - chat.Clear(); - } + chat.Clear(); } + } - private void AddDefaultTextToChat() - { - var server = _localizedStringFinder.GetString(EOResourceID.STRING_SERVER); - var serverMessage1 = _localizedStringFinder.GetString(EOResourceID.GLOBAL_CHAT_SERVER_MESSAGE_1); - var serverMessage2 = _localizedStringFinder.GetString(EOResourceID.GLOBAL_CHAT_SERVER_MESSAGE_2); - - if (!string.IsNullOrWhiteSpace(_newsProvider.NewsHeader)) - { - _chatRepository.AllChat[ChatTab.Local].Add( - new ChatData(ChatTab.Local, server, _newsProvider.NewsHeader, ChatIcon.Note, ChatColor.Server, log: false)); - } + private void AddDefaultTextToChat() + { + var server = _localizedStringFinder.GetString(EOResourceID.STRING_SERVER); + var serverMessage1 = _localizedStringFinder.GetString(EOResourceID.GLOBAL_CHAT_SERVER_MESSAGE_1); + var serverMessage2 = _localizedStringFinder.GetString(EOResourceID.GLOBAL_CHAT_SERVER_MESSAGE_2); - _chatRepository.AllChat[ChatTab.Global].Add( - new ChatData(ChatTab.Global, server, serverMessage1, ChatIcon.Note, ChatColor.Server, log: false)); - _chatRepository.AllChat[ChatTab.Global].Add( - new ChatData(ChatTab.Global, server, serverMessage2, ChatIcon.Note, ChatColor.Server, log: false)); + if (!string.IsNullOrWhiteSpace(_newsProvider.NewsHeader)) + { + _chatRepository.AllChat[ChatTab.Local].Add( + new ChatData(ChatTab.Local, server, _newsProvider.NewsHeader, ChatIcon.Note, ChatColor.Server, log: false)); } + + _chatRepository.AllChat[ChatTab.Global].Add( + new ChatData(ChatTab.Global, server, serverMessage1, ChatIcon.Note, ChatColor.Server, log: false)); + _chatRepository.AllChat[ChatTab.Global].Add( + new ChatData(ChatTab.Global, server, serverMessage2, ChatIcon.Note, ChatColor.Server, log: false)); } +} - public interface ILoginController - { - Task LoginToAccount(ILoginParameters loginParameters); +public interface ILoginController +{ + Task LoginToAccount(ILoginParameters loginParameters); - Task LoginToCharacter(Character character); - } + Task LoginToCharacter(Character character); } \ No newline at end of file diff --git a/EndlessClient/Controllers/MainButtonController.cs b/EndlessClient/Controllers/MainButtonController.cs index 4f68aa7ff..cc4f040d8 100644 --- a/EndlessClient/Controllers/MainButtonController.cs +++ b/EndlessClient/Controllers/MainButtonController.cs @@ -13,168 +13,167 @@ using System.Threading; using System.Threading.Tasks; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[AutoMappedType(IsSingleton = true)] +public class MainButtonController : IMainButtonController { - [AutoMappedType(IsSingleton = true)] - public class MainButtonController : IMainButtonController + private readonly INetworkConnectionActions _networkConnectionActions; + private readonly IErrorDialogDisplayAction _errorDialogDisplayAction; + private readonly IPacketProcessActions _packetProcessActions; + private readonly IBackgroundReceiveActions _backgroundReceiveActions; + private readonly IGameStateActions _gameStateActions; + private readonly IAccountDialogDisplayActions _accountDialogDisplayActions; + private readonly IResetStateAction _resetStateAction; + private readonly ISafeNetworkOperationFactory _networkOperationFactory; + + private readonly Random _random; + + private int _numberOfConnectionRequests; + + public MainButtonController(INetworkConnectionActions networkConnectionActions, + IErrorDialogDisplayAction errorDialogDisplayAction, + IPacketProcessActions packetProcessActions, + IBackgroundReceiveActions backgroundReceiveActions, + IGameStateActions gameStateActions, + IAccountDialogDisplayActions accountDialogDisplayActions, + IResetStateAction resetStateAction, + ISafeNetworkOperationFactory networkOperationFactory) { - private readonly INetworkConnectionActions _networkConnectionActions; - private readonly IErrorDialogDisplayAction _errorDialogDisplayAction; - private readonly IPacketProcessActions _packetProcessActions; - private readonly IBackgroundReceiveActions _backgroundReceiveActions; - private readonly IGameStateActions _gameStateActions; - private readonly IAccountDialogDisplayActions _accountDialogDisplayActions; - private readonly IResetStateAction _resetStateAction; - private readonly ISafeNetworkOperationFactory _networkOperationFactory; - - private readonly Random _random; - - private int _numberOfConnectionRequests; - - public MainButtonController(INetworkConnectionActions networkConnectionActions, - IErrorDialogDisplayAction errorDialogDisplayAction, - IPacketProcessActions packetProcessActions, - IBackgroundReceiveActions backgroundReceiveActions, - IGameStateActions gameStateActions, - IAccountDialogDisplayActions accountDialogDisplayActions, - IResetStateAction resetStateAction, - ISafeNetworkOperationFactory networkOperationFactory) - { - _networkConnectionActions = networkConnectionActions; - _errorDialogDisplayAction = errorDialogDisplayAction; - _packetProcessActions = packetProcessActions; - _backgroundReceiveActions = backgroundReceiveActions; - _gameStateActions = gameStateActions; - _accountDialogDisplayActions = accountDialogDisplayActions; - _resetStateAction = resetStateAction; - _networkOperationFactory = networkOperationFactory; - - _random = new Random(); - } - - public void GoToInitialState() - { - _gameStateActions.ChangeToState(GameStates.Initial); - } + _networkConnectionActions = networkConnectionActions; + _errorDialogDisplayAction = errorDialogDisplayAction; + _packetProcessActions = packetProcessActions; + _backgroundReceiveActions = backgroundReceiveActions; + _gameStateActions = gameStateActions; + _accountDialogDisplayActions = accountDialogDisplayActions; + _resetStateAction = resetStateAction; + _networkOperationFactory = networkOperationFactory; + + _random = new Random(); + } - public void GoToInitialStateAndDisconnect(bool showLostConnection = false) - { - GoToInitialState(); - StopReceivingAndDisconnect(); + public void GoToInitialState() + { + _gameStateActions.ChangeToState(GameStates.Initial); + } - _resetStateAction.ResetState(); + public void GoToInitialStateAndDisconnect(bool showLostConnection = false) + { + GoToInitialState(); + StopReceivingAndDisconnect(); - if (showLostConnection) - _errorDialogDisplayAction.ShowConnectionLost(false); - } + _resetStateAction.ResetState(); - public async Task ClickCreateAccount() - { - var result = await StartNetworkConnection().ConfigureAwait(false); + if (showLostConnection) + _errorDialogDisplayAction.ShowConnectionLost(false); + } - if (result) - { - await DispatcherGameComponent.Invoke(() => - { - _gameStateActions.ChangeToState(GameStates.CreateAccount); - _accountDialogDisplayActions.ShowInitialCreateWarningDialog(); - }); - } - } + public async Task ClickCreateAccount() + { + var result = await StartNetworkConnection().ConfigureAwait(false); - public async Task ClickLogin() + if (result) { - var result = await StartNetworkConnection().ConfigureAwait(false); - - if (result) + await DispatcherGameComponent.Invoke(() => { - await DispatcherGameComponent.Invoke(() => _gameStateActions.ChangeToState(GameStates.Login)); - } + _gameStateActions.ChangeToState(GameStates.CreateAccount); + _accountDialogDisplayActions.ShowInitialCreateWarningDialog(); + }); } + } - public void ClickViewCredits() - { - _gameStateActions.ChangeToState(GameStates.ViewCredits); - } + public async Task ClickLogin() + { + var result = await StartNetworkConnection().ConfigureAwait(false); - public void ClickExit() + if (result) { - StopReceivingAndDisconnect(); - _gameStateActions.ExitGame(); + await DispatcherGameComponent.Invoke(() => _gameStateActions.ChangeToState(GameStates.Login)); } + } - private async Task StartNetworkConnection() + public void ClickViewCredits() + { + _gameStateActions.ChangeToState(GameStates.ViewCredits); + } + + public void ClickExit() + { + StopReceivingAndDisconnect(); + _gameStateActions.ExitGame(); + } + + private async Task StartNetworkConnection() + { + if (Interlocked.Increment(ref _numberOfConnectionRequests) != 1) + return false; + + try { - if (Interlocked.Increment(ref _numberOfConnectionRequests) != 1) + var connectResult = await _networkConnectionActions.ConnectToServer().ConfigureAwait(false); + if (connectResult == ConnectResult.AlreadyConnected) + return true; + + if (connectResult != ConnectResult.Success) + { + _errorDialogDisplayAction.ShowError(connectResult); return false; + } + + _backgroundReceiveActions.RunBackgroundReceiveLoop(); + + var beginHandshakeOperation = _networkOperationFactory.CreateSafeBlockingOperation( + async () => await _networkConnectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)), + ex => _errorDialogDisplayAction.ShowException(ex), + ex => _errorDialogDisplayAction.ShowException(ex)); - try + if (!await beginHandshakeOperation.Invoke().ConfigureAwait(false)) { - var connectResult = await _networkConnectionActions.ConnectToServer().ConfigureAwait(false); - if (connectResult == ConnectResult.AlreadyConnected) - return true; - - if (connectResult != ConnectResult.Success) - { - _errorDialogDisplayAction.ShowError(connectResult); - return false; - } - - _backgroundReceiveActions.RunBackgroundReceiveLoop(); - - var beginHandshakeOperation = _networkOperationFactory.CreateSafeBlockingOperation( - async () => await _networkConnectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)), - ex => _errorDialogDisplayAction.ShowException(ex), - ex => _errorDialogDisplayAction.ShowException(ex)); - - if (!await beginHandshakeOperation.Invoke().ConfigureAwait(false)) - { - StopReceivingAndDisconnect(); - return false; - } - - var serverPacket = beginHandshakeOperation.Result; - - if (serverPacket.ReplyCode != InitReply.Ok) - { - _errorDialogDisplayAction.ShowError(serverPacket.ReplyCode, serverPacket.ReplyCodeData); - StopReceivingAndDisconnect(); - return false; - } - - var okData = (InitInitServerPacket.ReplyCodeDataOk)serverPacket.ReplyCodeData; - var sequenceStart = InitSequenceStart.FromInitValues(okData.Seq1, okData.Seq2); - _packetProcessActions.SetSequenceStart(sequenceStart); - _packetProcessActions.SetEncodeMultiples(okData.ServerEncryptionMultiple, okData.ClientEncryptionMultiple); - - _networkConnectionActions.CompleteHandshake(serverPacket); - return true; + StopReceivingAndDisconnect(); + return false; } - finally + + var serverPacket = beginHandshakeOperation.Result; + + if (serverPacket.ReplyCode != InitReply.Ok) { - Interlocked.Exchange(ref _numberOfConnectionRequests, 0); + _errorDialogDisplayAction.ShowError(serverPacket.ReplyCode, serverPacket.ReplyCodeData); + StopReceivingAndDisconnect(); + return false; } - } - private void StopReceivingAndDisconnect() + var okData = (InitInitServerPacket.ReplyCodeDataOk)serverPacket.ReplyCodeData; + var sequenceStart = InitSequenceStart.FromInitValues(okData.Seq1, okData.Seq2); + _packetProcessActions.SetSequenceStart(sequenceStart); + _packetProcessActions.SetEncodeMultiples(okData.ServerEncryptionMultiple, okData.ClientEncryptionMultiple); + + _networkConnectionActions.CompleteHandshake(serverPacket); + return true; + } + finally { - _backgroundReceiveActions.CancelBackgroundReceiveLoop(); - _networkConnectionActions.DisconnectFromServer(); + Interlocked.Exchange(ref _numberOfConnectionRequests, 0); } } - public interface IMainButtonController + private void StopReceivingAndDisconnect() { - void GoToInitialState(); + _backgroundReceiveActions.CancelBackgroundReceiveLoop(); + _networkConnectionActions.DisconnectFromServer(); + } +} - void GoToInitialStateAndDisconnect(bool showLostConnection = false); +public interface IMainButtonController +{ + void GoToInitialState(); - Task ClickCreateAccount(); + void GoToInitialStateAndDisconnect(bool showLostConnection = false); - Task ClickLogin(); + Task ClickCreateAccount(); - void ClickViewCredits(); + Task ClickLogin(); - void ClickExit(); - } + void ClickViewCredits(); + + void ClickExit(); } \ No newline at end of file diff --git a/EndlessClient/Controllers/MapInteractionController.cs b/EndlessClient/Controllers/MapInteractionController.cs index b64509482..82c7ae55d 100644 --- a/EndlessClient/Controllers/MapInteractionController.cs +++ b/EndlessClient/Controllers/MapInteractionController.cs @@ -28,291 +28,290 @@ using System; using System.Linq; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[AutoMappedType] +public class MapInteractionController : IMapInteractionController { - [AutoMappedType] - public class MapInteractionController : IMapInteractionController + private readonly IMapActions _mapActions; + private readonly ICharacterActions _characterActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IPaperdollActions _paperdollActions; + private readonly IWalkValidationActions _walkValidationActions; + private readonly IUnwalkableTileActions _unwalkableTileActions; + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly ISpellCastValidationActions _spellCastValidationActions; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IHudControlProvider _hudControlProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly IContextMenuRepository _contextMenuRepository; + private readonly IUserInputTimeRepository _userInputTimeRepository; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IContextMenuRendererFactory _contextMenuRendererFactory; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ISfxPlayer _sfxPlayer; + + public MapInteractionController(IMapActions mapActions, + ICharacterActions characterActions, + IInGameDialogActions inGameDialogActions, + IPaperdollActions paperdollActions, + IWalkValidationActions walkValidationActions, + IUnwalkableTileActions unwalkableTileActions, + ICharacterAnimationActions characterAnimationActions, + ISpellCastValidationActions spellCastValidationActions, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterProvider characterProvider, + IStatusLabelSetter statusLabelSetter, + IInventorySpaceValidator inventorySpaceValidator, + IHudControlProvider hudControlProvider, + ICharacterRendererProvider characterRendererProvider, + IContextMenuRepository contextMenuRepository, + IUserInputTimeRepository userInputTimeRepository, + IEOMessageBoxFactory messageBoxFactory, + IContextMenuRendererFactory contextMenuRendererFactory, + IActiveDialogProvider activeDialogProvider, + ISpellSlotDataRepository spellSlotDataRepository, + ICurrentMapProvider currentMapProvider, + ISfxPlayer sfxPlayer) + { + _mapActions = mapActions; + _characterActions = characterActions; + _inGameDialogActions = inGameDialogActions; + _paperdollActions = paperdollActions; + _walkValidationActions = walkValidationActions; + _unwalkableTileActions = unwalkableTileActions; + _characterAnimationActions = characterAnimationActions; + _spellCastValidationActions = spellCastValidationActions; + _currentMapStateProvider = currentMapStateProvider; + _characterProvider = characterProvider; + _statusLabelSetter = statusLabelSetter; + _inventorySpaceValidator = inventorySpaceValidator; + _hudControlProvider = hudControlProvider; + _characterRendererProvider = characterRendererProvider; + _contextMenuRepository = contextMenuRepository; + _userInputTimeRepository = userInputTimeRepository; + _messageBoxFactory = messageBoxFactory; + _contextMenuRendererFactory = contextMenuRendererFactory; + _activeDialogProvider = activeDialogProvider; + _spellSlotDataRepository = spellSlotDataRepository; + _currentMapProvider = currentMapProvider; + _sfxPlayer = sfxPlayer; + } + + public void LeftClick(IMapCellState cellState) { - private readonly IMapActions _mapActions; - private readonly ICharacterActions _characterActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IPaperdollActions _paperdollActions; - private readonly IWalkValidationActions _walkValidationActions; - private readonly IUnwalkableTileActions _unwalkableTileActions; - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly ISpellCastValidationActions _spellCastValidationActions; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IHudControlProvider _hudControlProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly IContextMenuRepository _contextMenuRepository; - private readonly IUserInputTimeRepository _userInputTimeRepository; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IContextMenuRendererFactory _contextMenuRendererFactory; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ISfxPlayer _sfxPlayer; + if (!InventoryPanel.NoItemsDragging() || _activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) + return; - public MapInteractionController(IMapActions mapActions, - ICharacterActions characterActions, - IInGameDialogActions inGameDialogActions, - IPaperdollActions paperdollActions, - IWalkValidationActions walkValidationActions, - IUnwalkableTileActions unwalkableTileActions, - ICharacterAnimationActions characterAnimationActions, - ISpellCastValidationActions spellCastValidationActions, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterProvider characterProvider, - IStatusLabelSetter statusLabelSetter, - IInventorySpaceValidator inventorySpaceValidator, - IHudControlProvider hudControlProvider, - ICharacterRendererProvider characterRendererProvider, - IContextMenuRepository contextMenuRepository, - IUserInputTimeRepository userInputTimeRepository, - IEOMessageBoxFactory messageBoxFactory, - IContextMenuRendererFactory contextMenuRendererFactory, - IActiveDialogProvider activeDialogProvider, - ISpellSlotDataRepository spellSlotDataRepository, - ICurrentMapProvider currentMapProvider, - ISfxPlayer sfxPlayer) + var optionalItem = cellState.Items.FirstOrNone(); + if (optionalItem.HasValue) { - _mapActions = mapActions; - _characterActions = characterActions; - _inGameDialogActions = inGameDialogActions; - _paperdollActions = paperdollActions; - _walkValidationActions = walkValidationActions; - _unwalkableTileActions = unwalkableTileActions; - _characterAnimationActions = characterAnimationActions; - _spellCastValidationActions = spellCastValidationActions; - _currentMapStateProvider = currentMapStateProvider; - _characterProvider = characterProvider; - _statusLabelSetter = statusLabelSetter; - _inventorySpaceValidator = inventorySpaceValidator; - _hudControlProvider = hudControlProvider; - _characterRendererProvider = characterRendererProvider; - _contextMenuRepository = contextMenuRepository; - _userInputTimeRepository = userInputTimeRepository; - _messageBoxFactory = messageBoxFactory; - _contextMenuRendererFactory = contextMenuRendererFactory; - _activeDialogProvider = activeDialogProvider; - _spellSlotDataRepository = spellSlotDataRepository; - _currentMapProvider = currentMapProvider; - _sfxPlayer = sfxPlayer; + var item = optionalItem.ValueOr(MapItem.None); + if (!_inventorySpaceValidator.ItemFits(item)) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); + else + HandlePickupResult(_mapActions.PickUpItem(item), item); } - - public void LeftClick(IMapCellState cellState) + else if (cellState.Sign.HasValue) + { + var sign = cellState.Sign.ValueOr(Sign.None); + var messageBox = _messageBoxFactory.CreateMessageBox(sign.Message, sign.Title); + messageBox.ShowDialog(); + _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); + } + // vanilla client prioritizes standing first, then board interaction + else if (_characterProvider.MainCharacter.RenderProperties.SitState != SitState.Standing) + { + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + _characterActions.Sit(mapRenderer.GridCoordinates); + } + else if (InteractableTileSpec(cellState.TileSpec) && (cellState.TileSpec.IsBoard() || cellState.TileSpec == TileSpec.Jukebox || CharacterIsCloseEnough(cellState.Coordinate))) { - if (!InventoryPanel.NoItemsDragging() || _activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) - return; + var unwalkableActions = _unwalkableTileActions.GetUnwalkableTileActions(cellState); - var optionalItem = cellState.Items.FirstOrNone(); - if (optionalItem.HasValue) + foreach (var unwalkableAction in unwalkableActions) { - var item = optionalItem.ValueOr(MapItem.None); - if (!_inventorySpaceValidator.ItemFits(item)) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); + if (cellState.TileSpec.IsBoard()) + { + _mapActions.OpenBoard(cellState.TileSpec); + _inGameDialogActions.ShowBoardDialog(); + } + else if (cellState.TileSpec.IsChair()) + { + _characterActions.Sit(cellState.Coordinate, isChair: true); + } else - HandlePickupResult(_mapActions.PickUpItem(item), item); - } - else if (cellState.Sign.HasValue) - { - var sign = cellState.Sign.ValueOr(Sign.None); - var messageBox = _messageBoxFactory.CreateMessageBox(sign.Message, sign.Title); - messageBox.ShowDialog(); - _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); - } - // vanilla client prioritizes standing first, then board interaction - else if (_characterProvider.MainCharacter.RenderProperties.SitState != SitState.Standing) - { - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - _characterActions.Sit(mapRenderer.GridCoordinates); - } - else if (InteractableTileSpec(cellState.TileSpec) && (cellState.TileSpec.IsBoard() || cellState.TileSpec == TileSpec.Jukebox || CharacterIsCloseEnough(cellState.Coordinate))) - { - var unwalkableActions = _unwalkableTileActions.GetUnwalkableTileActions(cellState); - - foreach (var unwalkableAction in unwalkableActions) { - if (cellState.TileSpec.IsBoard()) - { - _mapActions.OpenBoard(cellState.TileSpec); - _inGameDialogActions.ShowBoardDialog(); - } - else if (cellState.TileSpec.IsChair()) - { - _characterActions.Sit(cellState.Coordinate, isChair: true); - } - else + switch (cellState.TileSpec) { - switch (cellState.TileSpec) - { - case TileSpec.Chest: - if (unwalkableAction == UnwalkableTileAction.Chest) - { - _mapActions.OpenChest(cellState.Coordinate); - _inGameDialogActions.ShowChestDialog(); - } - break; - case TileSpec.BankVault: - if (unwalkableAction == UnwalkableTileAction.Locker) - { - _mapActions.OpenLocker(cellState.Coordinate); - _inGameDialogActions.ShowLockerDialog(); - } - break; - case TileSpec.Jukebox: - if (unwalkableAction == UnwalkableTileAction.Jukebox) - { - _mapActions.OpenJukebox(cellState.Coordinate); - _inGameDialogActions.ShowJukeboxDialog(); - } - break; - } + case TileSpec.Chest: + if (unwalkableAction == UnwalkableTileAction.Chest) + { + _mapActions.OpenChest(cellState.Coordinate); + _inGameDialogActions.ShowChestDialog(); + } + break; + case TileSpec.BankVault: + if (unwalkableAction == UnwalkableTileAction.Locker) + { + _mapActions.OpenLocker(cellState.Coordinate); + _inGameDialogActions.ShowLockerDialog(); + } + break; + case TileSpec.Jukebox: + if (unwalkableAction == UnwalkableTileAction.Jukebox) + { + _mapActions.OpenJukebox(cellState.Coordinate); + _inGameDialogActions.ShowJukeboxDialog(); + } + break; } } } - else if (cellState.InBounds && !cellState.Character.HasValue && !cellState.NPC.HasValue - && _walkValidationActions.IsCellStateWalkable(cellState) == WalkValidationResult.Walkable - && !_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Attacking) - && !_spellSlotDataRepository.SelectedSpellSlot.HasValue) - { - _characterAnimationActions.StartWalking(Option.Some(cellState.Coordinate)); - _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer) - .AnimateMouseClick(); - } + } + else if (cellState.InBounds && !cellState.Character.HasValue && !cellState.NPC.HasValue + && _walkValidationActions.IsCellStateWalkable(cellState) == WalkValidationResult.Walkable + && !_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Attacking) + && !_spellSlotDataRepository.SelectedSpellSlot.HasValue) + { + _characterAnimationActions.StartWalking(Option.Some(cellState.Coordinate)); + _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer) + .AnimateMouseClick(); + } - cellState.Warp.MatchSome(w => - { - w.SomeWhen(d => d.DoorType != DoorSpec.NoDoor) - .MatchSome(d => + cellState.Warp.MatchSome(w => + { + w.SomeWhen(d => d.DoorType != DoorSpec.NoDoor) + .MatchSome(d => + { + if (_unwalkableTileActions.GetUnwalkableTileActions(cellState).Any(x => x == UnwalkableTileAction.Door)) { - if (_unwalkableTileActions.GetUnwalkableTileActions(cellState).Any(x => x == UnwalkableTileAction.Door)) - { - _mapActions.OpenDoor(d); - } - }); - }); + _mapActions.OpenDoor(d); + } + }); + }); - _spellSlotDataRepository.SelectedSpellSlot = Option.None(); + _spellSlotDataRepository.SelectedSpellSlot = Option.None(); - _userInputTimeRepository.LastInputTime = DateTime.Now; - } + _userInputTimeRepository.LastInputTime = DateTime.Now; + } - public bool LeftClick(ISpellTargetable target) - { - _userInputTimeRepository.LastInputTime = DateTime.Now; + public bool LeftClick(ISpellTargetable target) + { + _userInputTimeRepository.LastInputTime = DateTime.Now; - if (!_spellSlotDataRepository.SpellIsPrepared) - return false; + if (!_spellSlotDataRepository.SpellIsPrepared) + return false; - _spellSlotDataRepository.SelectedSpellInfo.MatchSome(si => - { - var result = _spellCastValidationActions.ValidateSpellCast(si.ID, target); - if (result == SpellCastValidationResult.Ok && _characterAnimationActions.PrepareMainCharacterSpell(si.ID, target)) - _characterActions.PrepareCastSpell(si.ID); - else if (result == SpellCastValidationResult.CannotAttackNPC) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.YOU_CANNOT_ATTACK_THIS_NPC); - else if (result == SpellCastValidationResult.ExhaustedNoTp) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_TP); - else if (result == SpellCastValidationResult.ExhaustedNoSp) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); - }); + _spellSlotDataRepository.SelectedSpellInfo.MatchSome(si => + { + var result = _spellCastValidationActions.ValidateSpellCast(si.ID, target); + if (result == SpellCastValidationResult.Ok && _characterAnimationActions.PrepareMainCharacterSpell(si.ID, target)) + _characterActions.PrepareCastSpell(si.ID); + else if (result == SpellCastValidationResult.CannotAttackNPC) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.YOU_CANNOT_ATTACK_THIS_NPC); + else if (result == SpellCastValidationResult.ExhaustedNoTp) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_TP); + else if (result == SpellCastValidationResult.ExhaustedNoSp) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); + }); - _spellSlotDataRepository.SpellIsPrepared = false; - _spellSlotDataRepository.SelectedSpellSlot = Option.None(); + _spellSlotDataRepository.SpellIsPrepared = false; + _spellSlotDataRepository.SelectedSpellSlot = Option.None(); - return true; - } + return true; + } - public void RightClick(ISpellTargetable target) - { - if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) - return; + public void RightClick(ISpellTargetable target) + { + if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) + return; - if (target == _characterProvider.MainCharacter) - { - _paperdollActions.RequestPaperdoll(_characterProvider.MainCharacter.ID); - _inGameDialogActions.ShowPaperdollDialog(_characterProvider.MainCharacter, isMainCharacter: true); - _userInputTimeRepository.LastInputTime = DateTime.Now; - } - else if (target is Character character && _characterRendererProvider.CharacterRenderers.ContainsKey(character.ID)) - { - _contextMenuRepository.ContextMenu = _contextMenuRepository.ContextMenu.Match( - some: cmr => - { - cmr.Dispose(); - return Option.Some(_contextMenuRendererFactory.CreateContextMenuRenderer(_characterRendererProvider.CharacterRenderers[character.ID])); - }, - none: () => Option.Some(_contextMenuRendererFactory.CreateContextMenuRenderer(_characterRendererProvider.CharacterRenderers[character.ID]))); - _contextMenuRepository.ContextMenu.MatchSome(r => r.Initialize()); - } + if (target == _characterProvider.MainCharacter) + { + _paperdollActions.RequestPaperdoll(_characterProvider.MainCharacter.ID); + _inGameDialogActions.ShowPaperdollDialog(_characterProvider.MainCharacter, isMainCharacter: true); + _userInputTimeRepository.LastInputTime = DateTime.Now; } - - private bool IsSteppingStone(CharacterRenderProperties renderProps) + else if (target is Character character && _characterRendererProvider.CharacterRenderers.ContainsKey(character.ID)) { - return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump - || _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump; + _contextMenuRepository.ContextMenu = _contextMenuRepository.ContextMenu.Match( + some: cmr => + { + cmr.Dispose(); + return Option.Some(_contextMenuRendererFactory.CreateContextMenuRenderer(_characterRendererProvider.CharacterRenderers[character.ID])); + }, + none: () => Option.Some(_contextMenuRendererFactory.CreateContextMenuRenderer(_characterRendererProvider.CharacterRenderers[character.ID]))); + _contextMenuRepository.ContextMenu.MatchSome(r => r.Initialize()); } + } - private void HandlePickupResult(ItemPickupResult pickupResult, MapItem item) + private bool IsSteppingStone(CharacterRenderProperties renderProps) + { + return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump + || _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump; + } + + private void HandlePickupResult(ItemPickupResult pickupResult, MapItem item) + { + switch (pickupResult) { - switch (pickupResult) - { - case ItemPickupResult.DropProtection: - var message = EOResourceID.STATUS_LABEL_ITEM_PICKUP_PROTECTED; - var extra = string.Empty; + case ItemPickupResult.DropProtection: + var message = EOResourceID.STATUS_LABEL_ITEM_PICKUP_PROTECTED; + var extra = string.Empty; - item.OwningPlayerID.MatchSome(playerId => + item.OwningPlayerID.MatchSome(playerId => + { + message = EOResourceID.STATUS_LABEL_ITEM_PICKUP_PROTECTED_BY; + if (_currentMapStateProvider.Characters.TryGetValue(playerId, out var character)) { - message = EOResourceID.STATUS_LABEL_ITEM_PICKUP_PROTECTED_BY; - if (_currentMapStateProvider.Characters.TryGetValue(playerId, out var character)) - { - extra = $" {character.Name}"; - } - }); + extra = $" {character.Name}"; + } + }); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, message, extra); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, message, extra); - break; - case ItemPickupResult.TooHeavy: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT); - break; - case ItemPickupResult.TooFar: - case ItemPickupResult.Ok: break; - default: throw new ArgumentOutOfRangeException(nameof(pickupResult), pickupResult, null); - } + break; + case ItemPickupResult.TooHeavy: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT); + break; + case ItemPickupResult.TooFar: + case ItemPickupResult.Ok: break; + default: throw new ArgumentOutOfRangeException(nameof(pickupResult), pickupResult, null); } + } - private InventoryPanel InventoryPanel => _hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); + private InventoryPanel InventoryPanel => _hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); - private static bool InteractableTileSpec(TileSpec tileSpec) - { - return tileSpec.IsBoard() || tileSpec.IsChair() - || tileSpec == TileSpec.Chest - || tileSpec == TileSpec.BankVault - || tileSpec == TileSpec.Jukebox; - } + private static bool InteractableTileSpec(TileSpec tileSpec) + { + return tileSpec.IsBoard() || tileSpec.IsChair() + || tileSpec == TileSpec.Chest + || tileSpec == TileSpec.BankVault + || tileSpec == TileSpec.Jukebox; + } - private bool CharacterIsCloseEnough(MapCoordinate coordinate) - { - var x = _characterProvider.MainCharacter.RenderProperties.MapX; - var y = _characterProvider.MainCharacter.RenderProperties.MapY; + private bool CharacterIsCloseEnough(MapCoordinate coordinate) + { + var x = _characterProvider.MainCharacter.RenderProperties.MapX; + var y = _characterProvider.MainCharacter.RenderProperties.MapY; - var withinOneUnit = Math.Max(Math.Abs(x - coordinate.X), Math.Abs(y - coordinate.Y)) <= 1; - var sameXOrY = x == coordinate.X || y == coordinate.Y; - return withinOneUnit && sameXOrY; - } + var withinOneUnit = Math.Max(Math.Abs(x - coordinate.X), Math.Abs(y - coordinate.Y)) <= 1; + var sameXOrY = x == coordinate.X || y == coordinate.Y; + return withinOneUnit && sameXOrY; } +} - public interface IMapInteractionController - { - void LeftClick(IMapCellState cellState); +public interface IMapInteractionController +{ + void LeftClick(IMapCellState cellState); - bool LeftClick(ISpellTargetable target); + bool LeftClick(ISpellTargetable target); - void RightClick(ISpellTargetable target); - } + void RightClick(ISpellTargetable target); } \ No newline at end of file diff --git a/EndlessClient/Controllers/NPCInteractionController.cs b/EndlessClient/Controllers/NPCInteractionController.cs index f031b3596..4760bb05a 100644 --- a/EndlessClient/Controllers/NPCInteractionController.cs +++ b/EndlessClient/Controllers/NPCInteractionController.cs @@ -9,76 +9,75 @@ using EOLib.Localization; using System.Linq; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[AutoMappedType] +public class NPCInteractionController : INPCInteractionController { - [AutoMappedType] - public class NPCInteractionController : INPCInteractionController - { - private readonly IMapNPCActions _mapNpcActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IENFFileProvider _enfFileProvider; - private readonly IActiveDialogProvider _activeDialogProvider; + private readonly IMapNPCActions _mapNpcActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IENFFileProvider _enfFileProvider; + private readonly IActiveDialogProvider _activeDialogProvider; - public NPCInteractionController(IMapNPCActions mapNpcActions, - IInGameDialogActions inGameDialogActions, - IStatusLabelSetter statusLabelSetter, - IENFFileProvider enfFileProvider, - IActiveDialogProvider activeDialogProvider) - { - _mapNpcActions = mapNpcActions; - _inGameDialogActions = inGameDialogActions; - _statusLabelSetter = statusLabelSetter; - _enfFileProvider = enfFileProvider; - _activeDialogProvider = activeDialogProvider; - } + public NPCInteractionController(IMapNPCActions mapNpcActions, + IInGameDialogActions inGameDialogActions, + IStatusLabelSetter statusLabelSetter, + IENFFileProvider enfFileProvider, + IActiveDialogProvider activeDialogProvider) + { + _mapNpcActions = mapNpcActions; + _inGameDialogActions = inGameDialogActions; + _statusLabelSetter = statusLabelSetter; + _enfFileProvider = enfFileProvider; + _activeDialogProvider = activeDialogProvider; + } - public void ShowNPCDialog(NPC npc) - { - if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) - return; + public void ShowNPCDialog(NPC npc) + { + if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) + return; - var data = _enfFileProvider.ENFFile[npc.ID]; + var data = _enfFileProvider.ENFFile[npc.ID]; - // there is no "NPC" text in the localized files - _statusLabelSetter.SetStatusLabel($"[ NPC ] {data.Name}"); + // there is no "NPC" text in the localized files + _statusLabelSetter.SetStatusLabel($"[ NPC ] {data.Name}"); - switch (data.Type) - { - case EOLib.IO.NPCType.Shop: - _mapNpcActions.RequestShop(npc); - break; - case EOLib.IO.NPCType.Quest: - _mapNpcActions.RequestQuest(npc); - break; - case EOLib.IO.NPCType.Bank: - _mapNpcActions.RequestBank(npc); - // note: the npc action types rely on a server response to show the dialog because they are driven - // by config data on the server. Bank account dialog does not have this restriction; - // interaction with the NPC should *always* show the dialog - _inGameDialogActions.ShowBankAccountDialog(); - break; - case EOLib.IO.NPCType.Skills: - _mapNpcActions.RequestSkillmaster(npc); - break; - case EOLib.IO.NPCType.Inn: - _mapNpcActions.RequestInnkeeper(npc); - break; - case EOLib.IO.NPCType.Law: - _mapNpcActions.RequestLaw(npc); - break; - case EOLib.IO.NPCType.Priest: - _mapNpcActions.RequestPriest(npc); - break; - case EOLib.IO.NPCType.Barber: - _mapNpcActions.RequestBarber(npc); - break; - } + switch (data.Type) + { + case EOLib.IO.NPCType.Shop: + _mapNpcActions.RequestShop(npc); + break; + case EOLib.IO.NPCType.Quest: + _mapNpcActions.RequestQuest(npc); + break; + case EOLib.IO.NPCType.Bank: + _mapNpcActions.RequestBank(npc); + // note: the npc action types rely on a server response to show the dialog because they are driven + // by config data on the server. Bank account dialog does not have this restriction; + // interaction with the NPC should *always* show the dialog + _inGameDialogActions.ShowBankAccountDialog(); + break; + case EOLib.IO.NPCType.Skills: + _mapNpcActions.RequestSkillmaster(npc); + break; + case EOLib.IO.NPCType.Inn: + _mapNpcActions.RequestInnkeeper(npc); + break; + case EOLib.IO.NPCType.Law: + _mapNpcActions.RequestLaw(npc); + break; + case EOLib.IO.NPCType.Priest: + _mapNpcActions.RequestPriest(npc); + break; + case EOLib.IO.NPCType.Barber: + _mapNpcActions.RequestBarber(npc); + break; } } +} - public interface INPCInteractionController - { - void ShowNPCDialog(NPC npc); - } +public interface INPCInteractionController +{ + void ShowNPCDialog(NPC npc); } \ No newline at end of file diff --git a/EndlessClient/Controllers/NumPadController.cs b/EndlessClient/Controllers/NumPadController.cs index 5661d14a2..892f861d1 100644 --- a/EndlessClient/Controllers/NumPadController.cs +++ b/EndlessClient/Controllers/NumPadController.cs @@ -3,36 +3,35 @@ using EOLib.Domain.Character; using EOLib.Domain.Extensions; -namespace EndlessClient.Controllers -{ - [AutoMappedType] - public class NumPadController : INumPadController - { - private readonly ICharacterActions _characterActions; - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly ICharacterProvider _characterProvider; +namespace EndlessClient.Controllers; - public NumPadController(ICharacterActions characterActions, - ICharacterAnimationActions characterAnimationActions, - ICharacterProvider characterProvider) - { - _characterActions = characterActions; - _characterAnimationActions = characterAnimationActions; - _characterProvider = characterProvider; - } - - public void Emote(Emote whichEmote) - { - if (!_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing, CharacterActionState.Sitting)) - return; +[AutoMappedType] +public class NumPadController : INumPadController +{ + private readonly ICharacterActions _characterActions; + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly ICharacterProvider _characterProvider; - _characterActions.Emote(whichEmote); - _characterAnimationActions.Emote(whichEmote); - } + public NumPadController(ICharacterActions characterActions, + ICharacterAnimationActions characterAnimationActions, + ICharacterProvider characterProvider) + { + _characterActions = characterActions; + _characterAnimationActions = characterAnimationActions; + _characterProvider = characterProvider; } - public interface INumPadController + public void Emote(Emote whichEmote) { - void Emote(Emote whichEmote); + if (!_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing, CharacterActionState.Sitting)) + return; + + _characterActions.Emote(whichEmote); + _characterAnimationActions.Emote(whichEmote); } +} + +public interface INumPadController +{ + void Emote(Emote whichEmote); } \ No newline at end of file diff --git a/EndlessClient/Controllers/TrainingController.cs b/EndlessClient/Controllers/TrainingController.cs index 4968f9f29..22d460607 100644 --- a/EndlessClient/Controllers/TrainingController.cs +++ b/EndlessClient/Controllers/TrainingController.cs @@ -2,55 +2,54 @@ using EndlessClient.Audio; using EOLib.Domain.Character; -namespace EndlessClient.Controllers +namespace EndlessClient.Controllers; + +[MappedType(BaseType = typeof(ITrainingController))] +public class TrainingController : ITrainingController { - [MappedType(BaseType = typeof(ITrainingController))] - public class TrainingController : ITrainingController - { - private readonly ITrainingActions _trainingActions; - private readonly ISfxPlayer _sfxPlayer; + private readonly ITrainingActions _trainingActions; + private readonly ISfxPlayer _sfxPlayer; - public TrainingController(ITrainingActions trainingActions, - ISfxPlayer sfxPlayer) - { - _trainingActions = trainingActions; - _sfxPlayer = sfxPlayer; - } + public TrainingController(ITrainingActions trainingActions, + ISfxPlayer sfxPlayer) + { + _trainingActions = trainingActions; + _sfxPlayer = sfxPlayer; + } - public void AddStatPoint(CharacterStat whichStat) - { - if (InvalidStat(whichStat)) - return; + public void AddStatPoint(CharacterStat whichStat) + { + if (InvalidStat(whichStat)) + return; - _trainingActions.LevelUpStat(whichStat); - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - } + _trainingActions.LevelUpStat(whichStat); + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + } - public void AddSkillPoint(int spellId) - { - _trainingActions.LevelUpSkill(spellId); - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - } + public void AddSkillPoint(int spellId) + { + _trainingActions.LevelUpSkill(spellId); + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + } - private static bool InvalidStat(CharacterStat whichStat) + private static bool InvalidStat(CharacterStat whichStat) + { + switch (whichStat) { - switch (whichStat) - { - case CharacterStat.Strength: - case CharacterStat.Intelligence: - case CharacterStat.Wisdom: - case CharacterStat.Agility: - case CharacterStat.Constitution: - case CharacterStat.Charisma: return false; - default: return true; - } + case CharacterStat.Strength: + case CharacterStat.Intelligence: + case CharacterStat.Wisdom: + case CharacterStat.Agility: + case CharacterStat.Constitution: + case CharacterStat.Charisma: return false; + default: return true; } } +} - public interface ITrainingController - { - void AddStatPoint(CharacterStat whichStat); +public interface ITrainingController +{ + void AddStatPoint(CharacterStat whichStat); - void AddSkillPoint(int spellId); - } + void AddSkillPoint(int spellId); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs b/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs index 6a7fa651b..013ed696f 100644 --- a/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs +++ b/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs @@ -8,85 +8,84 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +[AutoMappedType] +public class AccountDialogDisplayActions : IAccountDialogDisplayActions { - [AutoMappedType] - public class AccountDialogDisplayActions : IAccountDialogDisplayActions + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ICreateAccountWarningDialogFactory _createAccountWarningDialogFactory; + private readonly ICreateAccountProgressDialogFactory _createAccountProgressDialogFactory; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IChangePasswordDialogFactory _changePasswordDialogFactory; + + public AccountDialogDisplayActions(ILocalizedStringFinder localizedStringFinder, + ICreateAccountWarningDialogFactory createAccountWarningDialogFactory, + ICreateAccountProgressDialogFactory createAccountProgressDialogFactory, + IEOMessageBoxFactory eoMessageBoxFactory, + IChangePasswordDialogFactory changePasswordDialogFactory) { - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ICreateAccountWarningDialogFactory _createAccountWarningDialogFactory; - private readonly ICreateAccountProgressDialogFactory _createAccountProgressDialogFactory; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IChangePasswordDialogFactory _changePasswordDialogFactory; + _localizedStringFinder = localizedStringFinder; + _createAccountWarningDialogFactory = createAccountWarningDialogFactory; + _createAccountProgressDialogFactory = createAccountProgressDialogFactory; + _eoMessageBoxFactory = eoMessageBoxFactory; + _changePasswordDialogFactory = changePasswordDialogFactory; + } - public AccountDialogDisplayActions(ILocalizedStringFinder localizedStringFinder, - ICreateAccountWarningDialogFactory createAccountWarningDialogFactory, - ICreateAccountProgressDialogFactory createAccountProgressDialogFactory, - IEOMessageBoxFactory eoMessageBoxFactory, - IChangePasswordDialogFactory changePasswordDialogFactory) - { - _localizedStringFinder = localizedStringFinder; - _createAccountWarningDialogFactory = createAccountWarningDialogFactory; - _createAccountProgressDialogFactory = createAccountProgressDialogFactory; - _eoMessageBoxFactory = eoMessageBoxFactory; - _changePasswordDialogFactory = changePasswordDialogFactory; - } + public void ShowInitialCreateWarningDialog() + { + var message = + $"{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_1)}\n\n{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_2)}\n\n{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_3)}"; - public void ShowInitialCreateWarningDialog() - { - var message = - $"{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_1)}\n\n{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_2)}\n\n{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_3)}"; + var dialog = _createAccountWarningDialogFactory.ShowCreateAccountWarningDialog(message); + dialog.ShowDialog(); + } - var dialog = _createAccountWarningDialogFactory.ShowCreateAccountWarningDialog(message); - dialog.ShowDialog(); - } + public Task ShowCreatePendingDialog() + { + var progress = _createAccountProgressDialogFactory.BuildCreateAccountProgressDialog(); + return progress.ShowDialogAsync(); + } - public Task ShowCreatePendingDialog() - { - var progress = _createAccountProgressDialogFactory.BuildCreateAccountProgressDialog(); - return progress.ShowDialogAsync(); - } + public Task> ShowChangePasswordDialog() + { + var changePassword = _changePasswordDialogFactory.BuildChangePasswordDialog(); + return changePassword.ShowDialogAsync() + .ContinueWith(showDialogTask => showDialogTask.Result.SomeWhen(x => x == XNADialogResult.OK).Map(x => changePassword.Result)); + } - public Task> ShowChangePasswordDialog() - { - var changePassword = _changePasswordDialogFactory.BuildChangePasswordDialog(); - return changePassword.ShowDialogAsync() - .ContinueWith(showDialogTask => showDialogTask.Result.SomeWhen(x => x == XNADialogResult.OK).Map(x => changePassword.Result)); - } + public void ShowCreateParameterValidationError(CreateAccountParameterResult validationResult) + { + var messageBox = _eoMessageBoxFactory.CreateMessageBox( + validationResult.ErrorString, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - public void ShowCreateParameterValidationError(CreateAccountParameterResult validationResult) + public void ShowCreateAccountServerError(AccountReply serverError) + { + DialogResourceID message; + switch (serverError) { - var messageBox = _eoMessageBoxFactory.CreateMessageBox( - validationResult.ErrorString, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); + case AccountReply.Exists: message = DialogResourceID.ACCOUNT_CREATE_NAME_EXISTS; break; + case AccountReply.NotApproved: message = DialogResourceID.ACCOUNT_CREATE_NAME_NOT_APPROVED; break; + case AccountReply.Created: message = DialogResourceID.ACCOUNT_CREATE_SUCCESS_WELCOME; break; + case AccountReply.ChangeFailed: message = DialogResourceID.CHANGE_PASSWORD_MISMATCH; break; + case AccountReply.Changed: message = DialogResourceID.CHANGE_PASSWORD_SUCCESS; break; + case AccountReply.RequestDenied: message = DialogResourceID.LOGIN_SERVER_COULD_NOT_PROCESS; break; + default: throw new ArgumentOutOfRangeException(nameof(serverError), serverError, null); } - public void ShowCreateAccountServerError(AccountReply serverError) - { - DialogResourceID message; - switch (serverError) - { - case AccountReply.Exists: message = DialogResourceID.ACCOUNT_CREATE_NAME_EXISTS; break; - case AccountReply.NotApproved: message = DialogResourceID.ACCOUNT_CREATE_NAME_NOT_APPROVED; break; - case AccountReply.Created: message = DialogResourceID.ACCOUNT_CREATE_SUCCESS_WELCOME; break; - case AccountReply.ChangeFailed: message = DialogResourceID.CHANGE_PASSWORD_MISMATCH; break; - case AccountReply.Changed: message = DialogResourceID.CHANGE_PASSWORD_SUCCESS; break; - case AccountReply.RequestDenied: message = DialogResourceID.LOGIN_SERVER_COULD_NOT_PROCESS; break; - default: throw new ArgumentOutOfRangeException(nameof(serverError), serverError, null); - } - - var messageBox = _eoMessageBoxFactory.CreateMessageBox( - message, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + var messageBox = _eoMessageBoxFactory.CreateMessageBox( + message, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - public void ShowSuccessMessage() - { - ShowCreateAccountServerError(AccountReply.Created); - } + public void ShowSuccessMessage() + { + ShowCreateAccountServerError(AccountReply.Created); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs b/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs index ee99390e4..b7af0fd41 100644 --- a/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs @@ -8,75 +8,74 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +[AutoMappedType] +public class CharacterDialogActions : ICharacterDialogActions { - [AutoMappedType] - public class CharacterDialogActions : ICharacterDialogActions + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ICreateCharacterDialogFactory _createCharacterDialogFactory; + + public CharacterDialogActions(IEOMessageBoxFactory messageBoxFactory, + ICreateCharacterDialogFactory createCharacterDialogFactory) { - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ICreateCharacterDialogFactory _createCharacterDialogFactory; + _messageBoxFactory = messageBoxFactory; + _createCharacterDialogFactory = createCharacterDialogFactory; + } - public CharacterDialogActions(IEOMessageBoxFactory messageBoxFactory, - ICreateCharacterDialogFactory createCharacterDialogFactory) - { - _messageBoxFactory = messageBoxFactory; - _createCharacterDialogFactory = createCharacterDialogFactory; - } + public Task> ShowCreateCharacterDialog() + { + var dialog = _createCharacterDialogFactory.BuildCreateCharacterDialog(); + return dialog.ShowDialogAsync() + .ContinueWith(dialogTask => + dialogTask.Result.SomeWhen(x => x == XNADialogResult.OK) + .Map(x => new CharacterCreateParameters(dialog.Name, dialog.Gender, dialog.HairStyle, dialog.HairColor, dialog.Race))); + } - public Task> ShowCreateCharacterDialog() + public void ShowCharacterReplyDialog(CharacterReply response) + { + DialogResourceID message; + switch (response) { - var dialog = _createCharacterDialogFactory.BuildCreateCharacterDialog(); - return dialog.ShowDialogAsync() - .ContinueWith(dialogTask => - dialogTask.Result.SomeWhen(x => x == XNADialogResult.OK) - .Map(x => new CharacterCreateParameters(dialog.Name, dialog.Gender, dialog.HairStyle, dialog.HairColor, dialog.Race))); + case CharacterReply.Exists: message = DialogResourceID.CHARACTER_CREATE_NAME_EXISTS; break; + case CharacterReply.Full: message = DialogResourceID.CHARACTER_CREATE_TOO_MANY_CHARS; break; + case CharacterReply.NotApproved: message = DialogResourceID.CHARACTER_CREATE_NAME_NOT_APPROVED; break; + case CharacterReply.Ok: message = DialogResourceID.CHARACTER_CREATE_SUCCESS; break; + default: throw new ArgumentOutOfRangeException(nameof(response), response, null); } - public void ShowCharacterReplyDialog(CharacterReply response) - { - DialogResourceID message; - switch (response) - { - case CharacterReply.Exists: message = DialogResourceID.CHARACTER_CREATE_NAME_EXISTS; break; - case CharacterReply.Full: message = DialogResourceID.CHARACTER_CREATE_TOO_MANY_CHARS; break; - case CharacterReply.NotApproved: message = DialogResourceID.CHARACTER_CREATE_NAME_NOT_APPROVED; break; - case CharacterReply.Ok: message = DialogResourceID.CHARACTER_CREATE_SUCCESS; break; - default: throw new ArgumentOutOfRangeException(nameof(response), response, null); - } - - var messageBox = _messageBoxFactory.CreateMessageBox(message, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + var messageBox = _messageBoxFactory.CreateMessageBox(message, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - public void ShowCharacterDeleteWarning(string characterName) - { - var messageBox = _messageBoxFactory.CreateMessageBox( - $"Character \'{characterName}\' ", - DialogResourceID.CHARACTER_DELETE_FIRST_CHECK); - messageBox.ShowDialog(); - } + public void ShowCharacterDeleteWarning(string characterName) + { + var messageBox = _messageBoxFactory.CreateMessageBox( + $"Character \'{characterName}\' ", + DialogResourceID.CHARACTER_DELETE_FIRST_CHECK); + messageBox.ShowDialog(); + } - public Task ShowConfirmDeleteWarning(string characterName) - { - var messageBox = _messageBoxFactory.CreateMessageBox( - $"Character \'{characterName}\' ", - DialogResourceID.CHARACTER_DELETE_CONFIRM, - EODialogButtons.OkCancel, - EOMessageBoxStyle.SmallDialogLargeHeader); + public Task ShowConfirmDeleteWarning(string characterName) + { + var messageBox = _messageBoxFactory.CreateMessageBox( + $"Character \'{characterName}\' ", + DialogResourceID.CHARACTER_DELETE_CONFIRM, + EODialogButtons.OkCancel, + EOMessageBoxStyle.SmallDialogLargeHeader); - return messageBox.ShowDialogAsync(); - } + return messageBox.ShowDialogAsync(); + } - public void ShowCharacterDeleteError() - { - var messageBox = _messageBoxFactory.CreateMessageBox( - "The server did not respond properly for deleting the character. Try again.", - "Server error", - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + public void ShowCharacterDeleteError() + { + var messageBox = _messageBoxFactory.CreateMessageBox( + "The server did not respond properly for deleting the character. Try again.", + "Server error", + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs b/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs index 430d84281..734900dd2 100644 --- a/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs +++ b/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs @@ -9,166 +9,165 @@ using System.Net.Sockets; using System.Runtime.InteropServices; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +[AutoMappedType] +public class ErrorDialogDisplayAction : IErrorDialogDisplayAction { - [AutoMappedType] - public class ErrorDialogDisplayAction : IErrorDialogDisplayAction + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ISfxPlayer _sfxPlayer; + + public ErrorDialogDisplayAction(IEOMessageBoxFactory messageBoxFactory, + ISfxPlayer sfxPlayer) { - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ISfxPlayer _sfxPlayer; + _messageBoxFactory = messageBoxFactory; + _sfxPlayer = sfxPlayer; + } - public ErrorDialogDisplayAction(IEOMessageBoxFactory messageBoxFactory, - ISfxPlayer sfxPlayer) + public void ShowError(ConnectResult connectResult) + { + switch (connectResult) { - _messageBoxFactory = messageBoxFactory; - _sfxPlayer = sfxPlayer; - } + case ConnectResult.Timeout: + case ConnectResult.InvalidEndpoint: + case ConnectResult.InvalidSocket: + case ConnectResult.SocketError: + { + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } + break; + default: + { + var errorCode = (int)connectResult; + var ex = new SocketException(errorCode); - public void ShowError(ConnectResult connectResult) - { - switch (connectResult) - { - case ConnectResult.Timeout: - case ConnectResult.InvalidEndpoint: - case ConnectResult.InvalidSocket: - case ConnectResult.SocketError: - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } - break; - default: + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - var errorCode = (int)connectResult; - var ex = new SocketException(errorCode); - - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + if (Enum.TryParse(errorCode.ToString(), out var socketError)) { - if (Enum.TryParse(errorCode.ToString(), out var socketError)) + switch (socketError) { - switch (socketError) - { - case SocketError.HostUnreachable: - case SocketError.HostNotFound: - case SocketError.HostDown: - var hostDownMessageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - hostDownMessageBox.ShowDialog(); - return; + case SocketError.HostUnreachable: + case SocketError.HostNotFound: + case SocketError.HostDown: + var hostDownMessageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + hostDownMessageBox.ShowDialog(); + return; - // For some reason, this socket error code does not exist in the SocketError enum, but does occurr when the host is unreachable. - default: - if (errorCode == 10063) - goto case SocketError.HostDown; - break; - } + // For some reason, this socket error code does not exist in the SocketError enum, but does occurr when the host is unreachable. + default: + if (errorCode == 10063) + goto case SocketError.HostDown; + break; } } - - var messageBox = _messageBoxFactory.CreateMessageBox( - $"Error code from socket: {ex.SocketErrorCode}", - "Internal Error"); - messageBox.ShowDialog(); } - break; - } + + var messageBox = _messageBoxFactory.CreateMessageBox( + $"Error code from socket: {ex.SocketErrorCode}", + "Internal Error"); + messageBox.ShowDialog(); + } + break; } + } - public void ShowError(InitReply replyCode, InitInitServerPacket.IReplyCodeData initializationData) + public void ShowError(InitReply replyCode, InitInitServerPacket.IReplyCodeData initializationData) + { + switch (replyCode) { - switch (replyCode) - { - case InitReply.OutOfDate: + case InitReply.OutOfDate: + { + var data = (InitInitServerPacket.ReplyCodeDataOutOfDate)initializationData; + var extra = $" {data.Version.Major:D3}.{data.Version.Minor:D3}.{data.Version.Patch:D3}"; + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_CLIENT_OUT_OF_DATE, + extra, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } + break; + case InitReply.Banned: + { + var data = (InitInitServerPacket.ReplyCodeDataBanned)initializationData; + if (data.BanType == InitBanType.Permanent) { - var data = (InitInitServerPacket.ReplyCodeDataOutOfDate)initializationData; - var extra = $" {data.Version.Major:D3}.{data.Version.Minor:D3}.{data.Version.Patch:D3}"; - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_CLIENT_OUT_OF_DATE, - extra, + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_IP_BAN_PERM, EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogLargeHeader); messageBox.ShowDialog(); } - break; - case InitReply.Banned: + else if (data.BanType == InitBanType.Temporary || data.BanType == 0) { - var data = (InitInitServerPacket.ReplyCodeDataBanned)initializationData; - if (data.BanType == InitBanType.Permanent) - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_IP_BAN_PERM, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } - else if (data.BanType == InitBanType.Temporary || data.BanType == 0) - { - var banMinutesRemaining = data.BanTypeData is InitInitServerPacket.ReplyCodeDataBanned.BanTypeData0 dataZero - ? dataZero.MinutesRemaining - : data.BanTypeData is InitInitServerPacket.ReplyCodeDataBanned.BanTypeDataTemporary dataTemp - ? dataTemp.MinutesRemaining - : throw new ArgumentException(); - var extra = $" {banMinutesRemaining} minutes."; - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_IP_BAN_TEMP, - extra, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } - - _sfxPlayer.PlaySfx(SoundEffectID.Banned); + var banMinutesRemaining = data.BanTypeData is InitInitServerPacket.ReplyCodeDataBanned.BanTypeData0 dataZero + ? dataZero.MinutesRemaining + : data.BanTypeData is InitInitServerPacket.ReplyCodeDataBanned.BanTypeDataTemporary dataTemp + ? dataTemp.MinutesRemaining + : throw new ArgumentException(); + var extra = $" {banMinutesRemaining} minutes."; + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_IP_BAN_TEMP, + extra, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); } - break; - case 0: - ShowError(ConnectResult.SocketError); - break; - default: throw new ArgumentOutOfRangeException(); - } - } - public void ShowException(NoDataSentException ex) - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, - "\n\"" + ex.Message + "\"", - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); + _sfxPlayer.PlaySfx(SoundEffectID.Banned); + } + break; + case 0: + ShowError(ConnectResult.SocketError); + break; + default: throw new ArgumentOutOfRangeException(); } + } - public void ShowException(EmptyPacketReceivedException ex) - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, - "\n\"" + ex.Message + "\"", - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + public void ShowException(NoDataSentException ex) + { + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, + "\n\"" + ex.Message + "\"", + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - public void ShowLoginError(LoginReply loginError) - { - var message = loginError switch - { - LoginReply.WrongUser => DialogResourceID.LOGIN_ACCOUNT_NAME_NOT_FOUND, - LoginReply.WrongUserPassword => DialogResourceID.LOGIN_ACCOUNT_NAME_OR_PASSWORD_NOT_FOUND, - LoginReply.Banned => DialogResourceID.LOGIN_BANNED_FROM_SERVER, - LoginReply.LoggedIn => DialogResourceID.LOGIN_ACCOUNT_ALREADY_LOGGED_ON, - LoginReply.Busy => DialogResourceID.CONNECTION_SERVER_IS_FULL, - _ => DialogResourceID.LOGIN_SERVER_COULD_NOT_PROCESS, - }; - var messageBox = _messageBoxFactory.CreateMessageBox(message, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + public void ShowException(EmptyPacketReceivedException ex) + { + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, + "\n\"" + ex.Message + "\"", + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - public void ShowConnectionLost(bool isInGame) + public void ShowLoginError(LoginReply loginError) + { + var message = loginError switch { - var resource = isInGame ? DialogResourceID.CONNECTION_LOST_IN_GAME : DialogResourceID.CONNECTION_LOST_CONNECTION; - var style = isInGame ? EOMessageBoxStyle.SmallDialogSmallHeader : EOMessageBoxStyle.SmallDialogLargeHeader; + LoginReply.WrongUser => DialogResourceID.LOGIN_ACCOUNT_NAME_NOT_FOUND, + LoginReply.WrongUserPassword => DialogResourceID.LOGIN_ACCOUNT_NAME_OR_PASSWORD_NOT_FOUND, + LoginReply.Banned => DialogResourceID.LOGIN_BANNED_FROM_SERVER, + LoginReply.LoggedIn => DialogResourceID.LOGIN_ACCOUNT_ALREADY_LOGGED_ON, + LoginReply.Busy => DialogResourceID.CONNECTION_SERVER_IS_FULL, + _ => DialogResourceID.LOGIN_SERVER_COULD_NOT_PROCESS, + }; + var messageBox = _messageBoxFactory.CreateMessageBox(message, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - var messageBox = _messageBoxFactory.CreateMessageBox(resource, style: style); - messageBox.ShowDialog(); - } + public void ShowConnectionLost(bool isInGame) + { + var resource = isInGame ? DialogResourceID.CONNECTION_LOST_IN_GAME : DialogResourceID.CONNECTION_LOST_CONNECTION; + var style = isInGame ? EOMessageBoxStyle.SmallDialogSmallHeader : EOMessageBoxStyle.SmallDialogLargeHeader; + + var messageBox = _messageBoxFactory.CreateMessageBox(resource, style: style); + messageBox.ShowDialog(); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs b/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs index 162da9453..a04d491e8 100644 --- a/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs +++ b/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs @@ -3,33 +3,32 @@ using EOLib.Domain.Login; using EOLib.Localization; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +[MappedType(BaseType = typeof(IFirstTimePlayerActions))] +public class FirstTimePlayerActions : IFirstTimePlayerActions { - [MappedType(BaseType = typeof(IFirstTimePlayerActions))] - public class FirstTimePlayerActions : IFirstTimePlayerActions - { - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; - public FirstTimePlayerActions(IPlayerInfoProvider playerInfoProvider, - IEOMessageBoxFactory messageBoxFactory) - { - _playerInfoProvider = playerInfoProvider; - _messageBoxFactory = messageBoxFactory; - } + public FirstTimePlayerActions(IPlayerInfoProvider playerInfoProvider, + IEOMessageBoxFactory messageBoxFactory) + { + _playerInfoProvider = playerInfoProvider; + _messageBoxFactory = messageBoxFactory; + } - public void WarnFirstTimePlayers() + public void WarnFirstTimePlayers() + { + if (_playerInfoProvider.IsFirstTimePlayer) { - if (_playerInfoProvider.IsFirstTimePlayer) - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_FIRST_TIME_PLAYERS); - messageBox.ShowDialog(); - } + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_FIRST_TIME_PLAYERS); + messageBox.ShowDialog(); } } +} - public interface IFirstTimePlayerActions - { - void WarnFirstTimePlayers(); - } +public interface IFirstTimePlayerActions +{ + void WarnFirstTimePlayers(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/HelpActions.cs b/EndlessClient/Dialogs/Actions/HelpActions.cs index ee018a1d0..9e5ebe628 100644 --- a/EndlessClient/Dialogs/Actions/HelpActions.cs +++ b/EndlessClient/Dialogs/Actions/HelpActions.cs @@ -6,104 +6,103 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +[AutoMappedType] +public class HelpActions : IHelpActions { - [AutoMappedType] - public class HelpActions : IHelpActions + private readonly IReportActions _reportActions; + private readonly ITextMultiInputDialogFactory _textMultiInputDialogFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly ISfxPlayer _sfxPlayer; + + public HelpActions(IReportActions reportActions, + ITextMultiInputDialogFactory textMultiInputDialogFactory, + ITextInputDialogFactory textInputDialogFactory, + IEOMessageBoxFactory eoMessageBoxFactory, + ISfxPlayer sfxPlayer) { - private readonly IReportActions _reportActions; - private readonly ITextMultiInputDialogFactory _textMultiInputDialogFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly ISfxPlayer _sfxPlayer; - - public HelpActions(IReportActions reportActions, - ITextMultiInputDialogFactory textMultiInputDialogFactory, - ITextInputDialogFactory textInputDialogFactory, - IEOMessageBoxFactory eoMessageBoxFactory, - ISfxPlayer sfxPlayer) - { - _reportActions = reportActions; - _textMultiInputDialogFactory = textMultiInputDialogFactory; - _textInputDialogFactory = textInputDialogFactory; - _eoMessageBoxFactory = eoMessageBoxFactory; - _sfxPlayer = sfxPlayer; - } - - public void ResetPassword() - { - // no - } + _reportActions = reportActions; + _textMultiInputDialogFactory = textMultiInputDialogFactory; + _textInputDialogFactory = textInputDialogFactory; + _eoMessageBoxFactory = eoMessageBoxFactory; + _sfxPlayer = sfxPlayer; + } - public void ReportSomeone() - { - const string Title = "Report Player"; - const string Prompt = "Who do you want to report, and why?"; + public void ResetPassword() + { + // no + } + + public void ReportSomeone() + { + const string Title = "Report Player"; + const string Prompt = "Who do you want to report, and why?"; - var dlg = _textMultiInputDialogFactory.Create(Title, Prompt, TextMultiInputDialog.DialogSize.Two, - new TextMultiInputDialog.InputInfo { Label = "Name", MaxChars = 16 }, - new TextMultiInputDialog.InputInfo { Label = "Reason", MaxChars = 48 }); - dlg.DialogClosing += (_, e) => + var dlg = _textMultiInputDialogFactory.Create(Title, Prompt, TextMultiInputDialog.DialogSize.Two, + new TextMultiInputDialog.InputInfo { Label = "Name", MaxChars = 16 }, + new TextMultiInputDialog.InputInfo { Label = "Reason", MaxChars = 48 }); + dlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) { - if (e.Result == XNADialogResult.OK) + if (dlg.Responses[0].Length > 0 && dlg.Responses[1].Length > 0) { - if (dlg.Responses[0].Length > 0 && dlg.Responses[1].Length > 0) - { - _reportActions.ReportPlayer(dlg.Responses[0], dlg.Responses[1]); - _sfxPlayer.PlaySfx(SoundEffectID.AdminRequestSent); - } - - var dlg2 = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.HELP_REQUEST_RECEIVED); - dlg2.ShowDialog(); + _reportActions.ReportPlayer(dlg.Responses[0], dlg.Responses[1]); + _sfxPlayer.PlaySfx(SoundEffectID.AdminRequestSent); } - }; - UseDefaultDialogSounds(dlg); + var dlg2 = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.HELP_REQUEST_RECEIVED); + dlg2.ShowDialog(); + } + }; - dlg.ShowDialog(); - } + UseDefaultDialogSounds(dlg); - public void SpeakToAdmin() - { - const string Prompt = "Please enter your question, and we will try to get back to you."; + dlg.ShowDialog(); + } + + public void SpeakToAdmin() + { + const string Prompt = "Please enter your question, and we will try to get back to you."; - var dlg = _textInputDialogFactory.Create(Prompt, maxInputChars: 48); - dlg.DialogClosing += (_, e) => + var dlg = _textInputDialogFactory.Create(Prompt, maxInputChars: 48); + dlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) { - if (e.Result == XNADialogResult.OK) + if (dlg.ResponseText.Length > 0) { - if (dlg.ResponseText.Length > 0) - { - _reportActions.SpeakToAdmin(dlg.ResponseText); - _sfxPlayer.PlaySfx(SoundEffectID.AdminRequestSent); - } - - var dlg2 = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.HELP_REQUEST_RECEIVED); - dlg2.ShowDialog(); + _reportActions.SpeakToAdmin(dlg.ResponseText); + _sfxPlayer.PlaySfx(SoundEffectID.AdminRequestSent); } - }; - - UseDefaultDialogSounds(dlg); - dlg.ShowDialog(); - } + var dlg2 = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.HELP_REQUEST_RECEIVED); + dlg2.ShowDialog(); + } + }; - // copied from InGameDialogActions - private void UseDefaultDialogSounds(BaseEODialog dialog) - { - dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + UseDefaultDialogSounds(dlg); - foreach (var textbox in dialog.ChildControls.OfType()) - textbox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); - } + dlg.ShowDialog(); } - public interface IHelpActions + // copied from InGameDialogActions + private void UseDefaultDialogSounds(BaseEODialog dialog) { - void ResetPassword(); + dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - void ReportSomeone(); - - void SpeakToAdmin(); + foreach (var textbox in dialog.ChildControls.OfType()) + textbox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); } +} + +public interface IHelpActions +{ + void ResetPassword(); + + void ReportSomeone(); + + void SpeakToAdmin(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs b/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs index b394df971..7bd133ffa 100644 --- a/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs +++ b/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs @@ -4,20 +4,19 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +public interface IAccountDialogDisplayActions { - public interface IAccountDialogDisplayActions - { - void ShowInitialCreateWarningDialog(); + void ShowInitialCreateWarningDialog(); - Task ShowCreatePendingDialog(); + Task ShowCreatePendingDialog(); - Task> ShowChangePasswordDialog(); + Task> ShowChangePasswordDialog(); - void ShowCreateParameterValidationError(CreateAccountParameterResult validationResult); + void ShowCreateParameterValidationError(CreateAccountParameterResult validationResult); - void ShowCreateAccountServerError(AccountReply serverError); + void ShowCreateAccountServerError(AccountReply serverError); - void ShowSuccessMessage(); - } + void ShowSuccessMessage(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs b/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs index c681896cc..b24d3d932 100644 --- a/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs @@ -4,18 +4,17 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +public interface ICharacterDialogActions { - public interface ICharacterDialogActions - { - Task> ShowCreateCharacterDialog(); + Task> ShowCreateCharacterDialog(); - void ShowCharacterReplyDialog(CharacterReply response); + void ShowCharacterReplyDialog(CharacterReply response); - void ShowCharacterDeleteWarning(string characterName); + void ShowCharacterDeleteWarning(string characterName); - Task ShowConfirmDeleteWarning(string characterName); + Task ShowConfirmDeleteWarning(string characterName); - void ShowCharacterDeleteError(); - } + void ShowCharacterDeleteError(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs b/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs index 49707b8a1..6464954ce 100644 --- a/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs +++ b/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs @@ -2,20 +2,19 @@ using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +public interface IErrorDialogDisplayAction { - public interface IErrorDialogDisplayAction - { - void ShowError(ConnectResult connectResult); + void ShowError(ConnectResult connectResult); - void ShowError(InitReply replyCode, InitInitServerPacket.IReplyCodeData initializationData); + void ShowError(InitReply replyCode, InitInitServerPacket.IReplyCodeData initializationData); - void ShowException(NoDataSentException ex); + void ShowException(NoDataSentException ex); - void ShowException(EmptyPacketReceivedException ex); + void ShowException(EmptyPacketReceivedException ex); - void ShowLoginError(LoginReply loginError); + void ShowLoginError(LoginReply loginError); - void ShowConnectionLost(bool isIngame); - } + void ShowConnectionLost(bool isIngame); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/InGameDialogActions.cs b/EndlessClient/Dialogs/Actions/InGameDialogActions.cs index 58562eea9..ce85874f8 100644 --- a/EndlessClient/Dialogs/Actions/InGameDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/InGameDialogActions.cs @@ -13,535 +13,534 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +[AutoMappedType] +public class InGameDialogActions : IInGameDialogActions { - [AutoMappedType] - public class InGameDialogActions : IInGameDialogActions + private readonly IFriendIgnoreListDialogFactory _friendIgnoreListDialogFactory; + private readonly IPaperdollDialogFactory _paperdollDialogFactory; + private readonly IBookDialogFactory _bookDialogFactory; + private readonly ISessionExpDialogFactory _sessionExpDialogFactory; + private readonly IQuestStatusDialogFactory _questStatusDialogFactory; + private readonly IActiveDialogRepository _activeDialogRepository; + private readonly IShopDataRepository _shopDataRepository; + private readonly IQuestDataRepository _questDataRepository; + private readonly ISkillDataRepository _skillDataRepository; + private readonly IChestDialogFactory _chestDialogFactory; + private readonly ILockerDialogFactory _lockerDialogFactory; + private readonly IBankAccountDialogFactory _bankAccountDialogFactory; + private readonly ISkillmasterDialogFactory _skillmasterDialogFactory; + private readonly IBardDialogFactory _bardDialogFactory; + private readonly IScrollingListDialogFactory _scrollingListDialogFactory; + private readonly ITradeDialogFactory _tradeDialogFactory; + private readonly IBoardDialogFactory _boardDialogFactory; + private readonly IJukeboxDialogFactory _jukeboxDialogFactory; + private readonly IInnkeeperDialogFactory _innkeeperDialogFactory; + private readonly ILawDialogFactory _lawDialogFactory; + private readonly IHelpDialogFactory _helpDialogFactory; + private readonly ISfxPlayer _sfxPlayer; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IShopDialogFactory _shopDialogFactory; + private readonly IQuestDialogFactory _questDialogFactory; + private readonly IBarberDialogFactory _barberDialogFactory; + + public InGameDialogActions(IFriendIgnoreListDialogFactory friendIgnoreListDialogFactory, + IPaperdollDialogFactory paperdollDialogFactory, + IBookDialogFactory bookDialogFactory, + ISessionExpDialogFactory sessionExpDialogFactory, + IQuestStatusDialogFactory questStatusDialogFactory, + IShopDialogFactory shopDialogFactory, + IQuestDialogFactory questDialogFactory, + IActiveDialogRepository activeDialogRepository, + IShopDataRepository shopDataRepository, + IQuestDataRepository questDataRepository, + ISkillDataRepository skillDataRepository, + IChestDialogFactory chestDialogFactory, + ILockerDialogFactory lockerDialogFactory, + IBankAccountDialogFactory bankAccountDialogFactory, + ISkillmasterDialogFactory skillmasterDialogFactory, + IBardDialogFactory bardDialogFactory, + IScrollingListDialogFactory scrollingListDialogFactory, + ITradeDialogFactory tradeDialogFactory, + IBoardDialogFactory boardDialogFactory, + IJukeboxDialogFactory jukeboxDialogFactory, + IInnkeeperDialogFactory innkeeperDialogFactory, + ILawDialogFactory lawDialogFactory, + IHelpDialogFactory helpDialogFactory, + ISfxPlayer sfxPlayer, + IStatusLabelSetter statusLabelSetter, + IBarberDialogFactory barberDialogFactory) { - private readonly IFriendIgnoreListDialogFactory _friendIgnoreListDialogFactory; - private readonly IPaperdollDialogFactory _paperdollDialogFactory; - private readonly IBookDialogFactory _bookDialogFactory; - private readonly ISessionExpDialogFactory _sessionExpDialogFactory; - private readonly IQuestStatusDialogFactory _questStatusDialogFactory; - private readonly IActiveDialogRepository _activeDialogRepository; - private readonly IShopDataRepository _shopDataRepository; - private readonly IQuestDataRepository _questDataRepository; - private readonly ISkillDataRepository _skillDataRepository; - private readonly IChestDialogFactory _chestDialogFactory; - private readonly ILockerDialogFactory _lockerDialogFactory; - private readonly IBankAccountDialogFactory _bankAccountDialogFactory; - private readonly ISkillmasterDialogFactory _skillmasterDialogFactory; - private readonly IBardDialogFactory _bardDialogFactory; - private readonly IScrollingListDialogFactory _scrollingListDialogFactory; - private readonly ITradeDialogFactory _tradeDialogFactory; - private readonly IBoardDialogFactory _boardDialogFactory; - private readonly IJukeboxDialogFactory _jukeboxDialogFactory; - private readonly IInnkeeperDialogFactory _innkeeperDialogFactory; - private readonly ILawDialogFactory _lawDialogFactory; - private readonly IHelpDialogFactory _helpDialogFactory; - private readonly ISfxPlayer _sfxPlayer; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IShopDialogFactory _shopDialogFactory; - private readonly IQuestDialogFactory _questDialogFactory; - private readonly IBarberDialogFactory _barberDialogFactory; - - public InGameDialogActions(IFriendIgnoreListDialogFactory friendIgnoreListDialogFactory, - IPaperdollDialogFactory paperdollDialogFactory, - IBookDialogFactory bookDialogFactory, - ISessionExpDialogFactory sessionExpDialogFactory, - IQuestStatusDialogFactory questStatusDialogFactory, - IShopDialogFactory shopDialogFactory, - IQuestDialogFactory questDialogFactory, - IActiveDialogRepository activeDialogRepository, - IShopDataRepository shopDataRepository, - IQuestDataRepository questDataRepository, - ISkillDataRepository skillDataRepository, - IChestDialogFactory chestDialogFactory, - ILockerDialogFactory lockerDialogFactory, - IBankAccountDialogFactory bankAccountDialogFactory, - ISkillmasterDialogFactory skillmasterDialogFactory, - IBardDialogFactory bardDialogFactory, - IScrollingListDialogFactory scrollingListDialogFactory, - ITradeDialogFactory tradeDialogFactory, - IBoardDialogFactory boardDialogFactory, - IJukeboxDialogFactory jukeboxDialogFactory, - IInnkeeperDialogFactory innkeeperDialogFactory, - ILawDialogFactory lawDialogFactory, - IHelpDialogFactory helpDialogFactory, - ISfxPlayer sfxPlayer, - IStatusLabelSetter statusLabelSetter, - IBarberDialogFactory barberDialogFactory) + _friendIgnoreListDialogFactory = friendIgnoreListDialogFactory; + _paperdollDialogFactory = paperdollDialogFactory; + _bookDialogFactory = bookDialogFactory; + _sessionExpDialogFactory = sessionExpDialogFactory; + _questStatusDialogFactory = questStatusDialogFactory; + _activeDialogRepository = activeDialogRepository; + _shopDataRepository = shopDataRepository; + _questDataRepository = questDataRepository; + _skillDataRepository = skillDataRepository; + _chestDialogFactory = chestDialogFactory; + _lockerDialogFactory = lockerDialogFactory; + _bankAccountDialogFactory = bankAccountDialogFactory; + _skillmasterDialogFactory = skillmasterDialogFactory; + _bardDialogFactory = bardDialogFactory; + _scrollingListDialogFactory = scrollingListDialogFactory; + _tradeDialogFactory = tradeDialogFactory; + _boardDialogFactory = boardDialogFactory; + _jukeboxDialogFactory = jukeboxDialogFactory; + _innkeeperDialogFactory = innkeeperDialogFactory; + _lawDialogFactory = lawDialogFactory; + _helpDialogFactory = helpDialogFactory; + _sfxPlayer = sfxPlayer; + _statusLabelSetter = statusLabelSetter; + _shopDialogFactory = shopDialogFactory; + _questDialogFactory = questDialogFactory; + _barberDialogFactory = barberDialogFactory; + } + + public void ShowFriendListDialog() + { + _activeDialogRepository.FriendIgnoreDialog.MatchNone(() => { - _friendIgnoreListDialogFactory = friendIgnoreListDialogFactory; - _paperdollDialogFactory = paperdollDialogFactory; - _bookDialogFactory = bookDialogFactory; - _sessionExpDialogFactory = sessionExpDialogFactory; - _questStatusDialogFactory = questStatusDialogFactory; - _activeDialogRepository = activeDialogRepository; - _shopDataRepository = shopDataRepository; - _questDataRepository = questDataRepository; - _skillDataRepository = skillDataRepository; - _chestDialogFactory = chestDialogFactory; - _lockerDialogFactory = lockerDialogFactory; - _bankAccountDialogFactory = bankAccountDialogFactory; - _skillmasterDialogFactory = skillmasterDialogFactory; - _bardDialogFactory = bardDialogFactory; - _scrollingListDialogFactory = scrollingListDialogFactory; - _tradeDialogFactory = tradeDialogFactory; - _boardDialogFactory = boardDialogFactory; - _jukeboxDialogFactory = jukeboxDialogFactory; - _innkeeperDialogFactory = innkeeperDialogFactory; - _lawDialogFactory = lawDialogFactory; - _helpDialogFactory = helpDialogFactory; - _sfxPlayer = sfxPlayer; - _statusLabelSetter = statusLabelSetter; - _shopDialogFactory = shopDialogFactory; - _questDialogFactory = questDialogFactory; - _barberDialogFactory = barberDialogFactory; - } - - public void ShowFriendListDialog() + var dlg = _friendIgnoreListDialogFactory.Create(isFriendList: true); + dlg.DialogClosed += (_, _) => _activeDialogRepository.FriendIgnoreDialog = Option.None(); + _activeDialogRepository.FriendIgnoreDialog = Option.Some(dlg); + + UseDefaultDialogSounds(dlg); + + dlg.Show(); + }); + } + + public void ShowIgnoreListDialog() + { + _activeDialogRepository.FriendIgnoreDialog.MatchNone(() => { - _activeDialogRepository.FriendIgnoreDialog.MatchNone(() => - { - var dlg = _friendIgnoreListDialogFactory.Create(isFriendList: true); - dlg.DialogClosed += (_, _) => _activeDialogRepository.FriendIgnoreDialog = Option.None(); - _activeDialogRepository.FriendIgnoreDialog = Option.Some(dlg); + var dlg = _friendIgnoreListDialogFactory.Create(isFriendList: false); + dlg.DialogClosed += (_, _) => _activeDialogRepository.FriendIgnoreDialog = Option.None(); + _activeDialogRepository.FriendIgnoreDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowIgnoreListDialog() + public void ShowSessionExpDialog() + { + _activeDialogRepository.SessionExpDialog.MatchNone(() => { - _activeDialogRepository.FriendIgnoreDialog.MatchNone(() => - { - var dlg = _friendIgnoreListDialogFactory.Create(isFriendList: false); - dlg.DialogClosed += (_, _) => _activeDialogRepository.FriendIgnoreDialog = Option.None(); - _activeDialogRepository.FriendIgnoreDialog = Option.Some(dlg); + var dlg = _sessionExpDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.SessionExpDialog = Option.None(); + _activeDialogRepository.SessionExpDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowSessionExpDialog() + public void ShowQuestStatusDialog() + { + _activeDialogRepository.QuestStatusDialog.MatchNone(() => { - _activeDialogRepository.SessionExpDialog.MatchNone(() => - { - var dlg = _sessionExpDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.SessionExpDialog = Option.None(); - _activeDialogRepository.SessionExpDialog = Option.Some(dlg); + var dlg = _questStatusDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.QuestStatusDialog = Option.None(); + _activeDialogRepository.QuestStatusDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowQuestStatusDialog() + public void ShowPaperdollDialog(Character character, bool isMainCharacter) + { + _activeDialogRepository.PaperdollDialog.MatchNone(() => { - _activeDialogRepository.QuestStatusDialog.MatchNone(() => - { - var dlg = _questStatusDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.QuestStatusDialog = Option.None(); - _activeDialogRepository.QuestStatusDialog = Option.Some(dlg); + var dlg = _paperdollDialogFactory.Create(character, isMainCharacter); + dlg.DialogClosed += (_, _) => _activeDialogRepository.PaperdollDialog = Option.None(); + _activeDialogRepository.PaperdollDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowPaperdollDialog(Character character, bool isMainCharacter) + public void ShowBookDialog(Character character, bool isMainCharacter) + { + _activeDialogRepository.BookDialog.MatchNone(() => { - _activeDialogRepository.PaperdollDialog.MatchNone(() => - { - var dlg = _paperdollDialogFactory.Create(character, isMainCharacter); - dlg.DialogClosed += (_, _) => _activeDialogRepository.PaperdollDialog = Option.None(); - _activeDialogRepository.PaperdollDialog = Option.Some(dlg); + var dlg = _bookDialogFactory.Create(character, isMainCharacter); + dlg.DialogClosed += (_, _) => _activeDialogRepository.BookDialog = Option.None(); + _activeDialogRepository.BookDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowBookDialog(Character character, bool isMainCharacter) + public void ShowShopDialog() + { + _activeDialogRepository.ShopDialog.MatchNone(() => { - _activeDialogRepository.BookDialog.MatchNone(() => + var dlg = _shopDialogFactory.Create(); + dlg.DialogClosed += (_, _) => { - var dlg = _bookDialogFactory.Create(character, isMainCharacter); - dlg.DialogClosed += (_, _) => _activeDialogRepository.BookDialog = Option.None(); - _activeDialogRepository.BookDialog = Option.Some(dlg); + _activeDialogRepository.ShopDialog = Option.None(); + _shopDataRepository.ResetState(); + }; + _activeDialogRepository.ShopDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowShopDialog() + public void ShowQuestDialog() + { + _activeDialogRepository.QuestDialog.MatchNone(() => { - _activeDialogRepository.ShopDialog.MatchNone(() => + var dlg = _questDialogFactory.Create(); + dlg.DialogClosed += (_, _) => { - var dlg = _shopDialogFactory.Create(); - dlg.DialogClosed += (_, _) => - { - _activeDialogRepository.ShopDialog = Option.None(); - _shopDataRepository.ResetState(); - }; - _activeDialogRepository.ShopDialog = Option.Some(dlg); + _activeDialogRepository.QuestDialog = Option.None(); + _questDataRepository.ResetState(); + }; + _activeDialogRepository.QuestDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseQuestDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowQuestDialog() + public void ShowChestDialog() + { + _activeDialogRepository.ChestDialog.MatchNone(() => { - _activeDialogRepository.QuestDialog.MatchNone(() => - { - var dlg = _questDialogFactory.Create(); - dlg.DialogClosed += (_, _) => - { - _activeDialogRepository.QuestDialog = Option.None(); - _questDataRepository.ResetState(); - }; - _activeDialogRepository.QuestDialog = Option.Some(dlg); + var dlg = _chestDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.ChestDialog = Option.None(); + _activeDialogRepository.ChestDialog = Option.Some(dlg); - UseQuestDialogSounds(dlg); + UseDefaultDialogSounds(dlg); + _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowChestDialog() + public void ShowLockerDialog() + { + _activeDialogRepository.LockerDialog.MatchNone(() => { - _activeDialogRepository.ChestDialog.MatchNone(() => - { - var dlg = _chestDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.ChestDialog = Option.None(); - _activeDialogRepository.ChestDialog = Option.Some(dlg); + var dlg = _lockerDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.LockerDialog = Option.None(); + _activeDialogRepository.LockerDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); - _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); + UseDefaultDialogSounds(dlg); + _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowLockerDialog() + public void ShowBankAccountDialog() + { + _activeDialogRepository.BankAccountDialog.MatchNone(() => { - _activeDialogRepository.LockerDialog.MatchNone(() => - { - var dlg = _lockerDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.LockerDialog = Option.None(); - _activeDialogRepository.LockerDialog = Option.Some(dlg); + var dlg = _bankAccountDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.BankAccountDialog = Option.None(); + _activeDialogRepository.BankAccountDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); - _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowBankAccountDialog() + public void ShowSkillmasterDialog() + { + var dlg = _skillmasterDialogFactory.Create(); + dlg.DialogClosed += (_, _) => { - _activeDialogRepository.BankAccountDialog.MatchNone(() => - { - var dlg = _bankAccountDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.BankAccountDialog = Option.None(); - _activeDialogRepository.BankAccountDialog = Option.Some(dlg); + _activeDialogRepository.SkillmasterDialog = Option.None(); + _skillDataRepository.ResetState(); + }; + _activeDialogRepository.SkillmasterDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + } - public void ShowSkillmasterDialog() + public void ShowBardDialog() + { + _activeDialogRepository.BardDialog.MatchNone(() => { - var dlg = _skillmasterDialogFactory.Create(); + var dlg = _bardDialogFactory.Create(); dlg.DialogClosed += (_, _) => { - _activeDialogRepository.SkillmasterDialog = Option.None(); - _skillDataRepository.ResetState(); + _activeDialogRepository.BardDialog = Option.None(); }; - _activeDialogRepository.SkillmasterDialog = Option.Some(dlg); + _activeDialogRepository.BardDialog = Option.Some(dlg); UseDefaultDialogSounds(dlg); dlg.Show(); - } - - public void ShowBardDialog() - { - _activeDialogRepository.BardDialog.MatchNone(() => - { - var dlg = _bardDialogFactory.Create(); - dlg.DialogClosed += (_, _) => - { - _activeDialogRepository.BardDialog = Option.None(); - }; - _activeDialogRepository.BardDialog = Option.Some(dlg); - - UseDefaultDialogSounds(dlg); - - dlg.Show(); - }); - } + }); + } - public void ShowMessageDialog(string title, IReadOnlyList messages) + public void ShowMessageDialog(string title, IReadOnlyList messages) + { + _activeDialogRepository.MessageDialog.MatchNone(() => { - _activeDialogRepository.MessageDialog.MatchNone(() => - { - var dlg = _scrollingListDialogFactory.Create(DialogType.Message); - dlg.DialogClosed += (_, _) => _activeDialogRepository.MessageDialog = Option.None(); + var dlg = _scrollingListDialogFactory.Create(DialogType.Message); + dlg.DialogClosed += (_, _) => _activeDialogRepository.MessageDialog = Option.None(); - dlg.ListItemType = ListDialogItem.ListItemStyle.Small; - dlg.Buttons = ScrollingListDialogButtons.Cancel; - dlg.Title = title; + dlg.ListItemType = ListDialogItem.ListItemStyle.Small; + dlg.Buttons = ScrollingListDialogButtons.Cancel; + dlg.Title = title; - var _68spaces = new string(Enumerable.Repeat(' ', 68).ToArray()); - var items = messages - // BU hack - assume that 68 spaces or more indicates an extra line break - .Select(x => x.Replace(_68spaces, " \n")) - // BU hack - assume that 3 spaces or more indicates extra padding and should split the message into multiple lines - .SelectMany(x => x.Split(" ", StringSplitOptions.RemoveEmptyEntries)) - .Select(x => new ListDialogItem(dlg, ListDialogItem.ListItemStyle.Small) { PrimaryText = x == "\n" ? string.Empty : x.Trim() }).ToList(); + var _68spaces = new string(Enumerable.Repeat(' ', 68).ToArray()); + var items = messages + // BU hack - assume that 68 spaces or more indicates an extra line break + .Select(x => x.Replace(_68spaces, " \n")) + // BU hack - assume that 3 spaces or more indicates extra padding and should split the message into multiple lines + .SelectMany(x => x.Split(" ", StringSplitOptions.RemoveEmptyEntries)) + .Select(x => new ListDialogItem(dlg, ListDialogItem.ListItemStyle.Small) { PrimaryText = x == "\n" ? string.Empty : x.Trim() }).ToList(); - dlg.SetItemList(items); + dlg.SetItemList(items); - _activeDialogRepository.MessageDialog = Option.Some(dlg); + _activeDialogRepository.MessageDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowKeyValueMessageDialog(string title, IReadOnlyList<(string, string)> messages) + public void ShowKeyValueMessageDialog(string title, IReadOnlyList<(string, string)> messages) + { + _activeDialogRepository.MessageDialog.MatchNone(() => { - _activeDialogRepository.MessageDialog.MatchNone(() => - { - var dlg = _scrollingListDialogFactory.Create(DialogType.Message); - dlg.DialogClosed += (_, _) => _activeDialogRepository.MessageDialog = Option.None(); + var dlg = _scrollingListDialogFactory.Create(DialogType.Message); + dlg.DialogClosed += (_, _) => _activeDialogRepository.MessageDialog = Option.None(); - dlg.ListItemType = ListDialogItem.ListItemStyle.SmallKeyValue; - dlg.Buttons = ScrollingListDialogButtons.Cancel; - dlg.Title = title; + dlg.ListItemType = ListDialogItem.ListItemStyle.SmallKeyValue; + dlg.Buttons = ScrollingListDialogButtons.Cancel; + dlg.Title = title; - var _68spaces = new string(Enumerable.Repeat(' ', 68).ToArray()); - var items = messages - .Select(x => - new ListDialogItem(dlg, ListDialogItem.ListItemStyle.SmallKeyValue) - { - PrimaryText = x.Item1, - SubText = x.Item2, - }) - .ToList(); + var _68spaces = new string(Enumerable.Repeat(' ', 68).ToArray()); + var items = messages + .Select(x => + new ListDialogItem(dlg, ListDialogItem.ListItemStyle.SmallKeyValue) + { + PrimaryText = x.Item1, + SubText = x.Item2, + }) + .ToList(); - dlg.SetItemList(items); + dlg.SetItemList(items); - _activeDialogRepository.MessageDialog = Option.Some(dlg); + _activeDialogRepository.MessageDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowTradeDialog() + public void ShowTradeDialog() + { + _activeDialogRepository.TradeDialog.MatchNone(() => { - _activeDialogRepository.TradeDialog.MatchNone(() => - { - var dlg = _tradeDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.TradeDialog = Option.None(); - _activeDialogRepository.TradeDialog = Option.Some(dlg); + var dlg = _tradeDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.TradeDialog = Option.None(); + _activeDialogRepository.TradeDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void CloseTradeDialog() - { - _activeDialogRepository.TradeDialog.MatchSome(dlg => dlg.Close()); - } + public void CloseTradeDialog() + { + _activeDialogRepository.TradeDialog.MatchSome(dlg => dlg.Close()); + } - public void ShowBoardDialog() + public void ShowBoardDialog() + { + _activeDialogRepository.BoardDialog.MatchNone(() => { - _activeDialogRepository.BoardDialog.MatchNone(() => - { - var dlg = _boardDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.BoardDialog = Option.None(); - _activeDialogRepository.BoardDialog = Option.Some(dlg); + var dlg = _boardDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.BoardDialog = Option.None(); + _activeDialogRepository.BoardDialog = Option.Some(dlg); - dlg.Show(); + dlg.Show(); - UseDefaultDialogSounds(dlg); - }); + UseDefaultDialogSounds(dlg); + }); - // the vanilla client shows the status label any time the server sends the BOARD_OPEN packet - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.BOARD_TOWN_BOARD_NOW_VIEWED); - } + // the vanilla client shows the status label any time the server sends the BOARD_OPEN packet + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.BOARD_TOWN_BOARD_NOW_VIEWED); + } - public void ShowJukeboxDialog() + public void ShowJukeboxDialog() + { + _activeDialogRepository.JukeboxDialog.MatchNone(() => { - _activeDialogRepository.JukeboxDialog.MatchNone(() => - { - var dlg = _jukeboxDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.JukeboxDialog = Option.None(); - _activeDialogRepository.JukeboxDialog = Option.Some(dlg); + var dlg = _jukeboxDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.JukeboxDialog = Option.None(); + _activeDialogRepository.JukeboxDialog = Option.Some(dlg); - dlg.Show(); + dlg.Show(); - UseDefaultDialogSounds(dlg); - }); + UseDefaultDialogSounds(dlg); + }); - // the vanilla client shows the status label any time the server sends the BOARD_OPEN packet - // the vanilla client uses [Action] for Board and [Information] for Jukebox, for some reason - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.JUKEBOX_NOW_VIEWED); - } + // the vanilla client shows the status label any time the server sends the BOARD_OPEN packet + // the vanilla client uses [Action] for Board and [Information] for Jukebox, for some reason + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.JUKEBOX_NOW_VIEWED); + } - public void ShowInnkeeperDialog() + public void ShowInnkeeperDialog() + { + _activeDialogRepository.InnkeeperDialog.MatchNone(() => { - _activeDialogRepository.InnkeeperDialog.MatchNone(() => - { - var dlg = _innkeeperDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.InnkeeperDialog = Option.None(); - _activeDialogRepository.InnkeeperDialog = Option.Some(dlg); + var dlg = _innkeeperDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.InnkeeperDialog = Option.None(); + _activeDialogRepository.InnkeeperDialog = Option.Some(dlg); - dlg.Show(); + dlg.Show(); - UseDefaultDialogSounds(dlg); - }); - } + UseDefaultDialogSounds(dlg); + }); + } - public void ShowLawDialog() + public void ShowLawDialog() + { + _activeDialogRepository.LawDialog.MatchNone(() => { - _activeDialogRepository.LawDialog.MatchNone(() => - { - var dlg = _lawDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.LawDialog = Option.None(); - _activeDialogRepository.LawDialog = Option.Some(dlg); + var dlg = _lawDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.LawDialog = Option.None(); + _activeDialogRepository.LawDialog = Option.Some(dlg); - dlg.Show(); + dlg.Show(); - UseDefaultDialogSounds(dlg); - }); - } + UseDefaultDialogSounds(dlg); + }); + } - public void ShowHelpDialog() + public void ShowHelpDialog() + { + _activeDialogRepository.HelpDialog.MatchNone(() => { - _activeDialogRepository.HelpDialog.MatchNone(() => - { - var dlg = _helpDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.HelpDialog = Option.None(); - _activeDialogRepository.HelpDialog = Option.Some(dlg); + var dlg = _helpDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.HelpDialog = Option.None(); + _activeDialogRepository.HelpDialog = Option.Some(dlg); - dlg.Show(); + dlg.Show(); - UseDefaultDialogSounds(dlg); - }); - } + UseDefaultDialogSounds(dlg); + }); + } - public void ShowBarberDialog() + public void ShowBarberDialog() + { + _activeDialogRepository.BarberDialog.MatchNone(() => { - _activeDialogRepository.BarberDialog.MatchNone(() => + var dlg = _barberDialogFactory.Create(); + dlg.DialogClosed += (_, _) => { - var dlg = _barberDialogFactory.Create(); - dlg.DialogClosed += (_, _) => - { - _activeDialogRepository.BarberDialog = Option.None(); - }; - _activeDialogRepository.BarberDialog = Option.Some(dlg); - - UseDefaultDialogSounds(dlg); + _activeDialogRepository.BarberDialog = Option.None(); + }; + _activeDialogRepository.BarberDialog = Option.Some(dlg); - dlg.Show(); - }); - } + UseDefaultDialogSounds(dlg); - private void UseDefaultDialogSounds(ScrollingListDialog dialog) - { - UseDefaultDialogSounds((BaseEODialog)dialog); + dlg.Show(); + }); + } - foreach (var button in dialog.ChildControls.OfType()) - button.OnClick += Handler; + private void UseDefaultDialogSounds(ScrollingListDialog dialog) + { + UseDefaultDialogSounds((BaseEODialog)dialog); - void Handler(object sender, EventArgs e) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - } + foreach (var button in dialog.ChildControls.OfType()) + button.OnClick += Handler; - private void UseDefaultDialogSounds(BaseEODialog dialog) - { - dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + void Handler(object sender, EventArgs e) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + } - foreach (var textbox in dialog.ChildControls.OfType()) - textbox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); - } + private void UseDefaultDialogSounds(BaseEODialog dialog) + { + dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - private void UseQuestDialogSounds(QuestDialog dialog) - { - dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - dialog.BackAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); - dialog.NextAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); - dialog.LinkClickAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); - } + foreach (var textbox in dialog.ChildControls.OfType()) + textbox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); } - public interface IInGameDialogActions + private void UseQuestDialogSounds(QuestDialog dialog) { - void ShowFriendListDialog(); + dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + dialog.BackAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); + dialog.NextAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); + dialog.LinkClickAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + } +} + +public interface IInGameDialogActions +{ + void ShowFriendListDialog(); - void ShowIgnoreListDialog(); + void ShowIgnoreListDialog(); - void ShowSessionExpDialog(); + void ShowSessionExpDialog(); - void ShowQuestStatusDialog(); + void ShowQuestStatusDialog(); - void ShowPaperdollDialog(Character character, bool isMainCharacter); + void ShowPaperdollDialog(Character character, bool isMainCharacter); - void ShowBookDialog(Character character, bool isMainCharacter); + void ShowBookDialog(Character character, bool isMainCharacter); - void ShowShopDialog(); + void ShowShopDialog(); - void ShowQuestDialog(); + void ShowQuestDialog(); - void ShowChestDialog(); + void ShowChestDialog(); - void ShowLockerDialog(); + void ShowLockerDialog(); - void ShowBankAccountDialog(); + void ShowBankAccountDialog(); - void ShowSkillmasterDialog(); + void ShowSkillmasterDialog(); - void ShowBardDialog(); + void ShowBardDialog(); - void ShowMessageDialog(string title, IReadOnlyList messages); + void ShowMessageDialog(string title, IReadOnlyList messages); - void ShowKeyValueMessageDialog(string title, IReadOnlyList<(string, string)> messages); + void ShowKeyValueMessageDialog(string title, IReadOnlyList<(string, string)> messages); - void ShowTradeDialog(); + void ShowTradeDialog(); - void CloseTradeDialog(); + void CloseTradeDialog(); - void ShowBoardDialog(); + void ShowBoardDialog(); - void ShowJukeboxDialog(); + void ShowJukeboxDialog(); - void ShowInnkeeperDialog(); + void ShowInnkeeperDialog(); - void ShowLawDialog(); + void ShowLawDialog(); - void ShowHelpDialog(); + void ShowHelpDialog(); - void ShowBarberDialog(); - } + void ShowBarberDialog(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs b/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs index d6ebec130..ef34befce 100644 --- a/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs +++ b/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs @@ -13,221 +13,220 @@ using XNAControls; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +[AutoMappedType] +public class NPCInteractionActions : INPCInteractionNotifier { - [AutoMappedType] - public class NPCInteractionActions : INPCInteractionNotifier + private readonly IInGameDialogActions _inGameDialogActions; + private readonly ICitizenActions _citizenActions; + private readonly IPriestActions _priestActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IPubFileProvider _pubFileProvider; + private readonly ISfxPlayer _sfxPlayer; + + public NPCInteractionActions(IInGameDialogActions inGameDialogActions, + ICitizenActions citizenActions, + IPriestActions priestActions, + IEOMessageBoxFactory messageBoxFactory, + ITextInputDialogFactory textInputDialogFactory, + ILocalizedStringFinder localizedStringFinder, + IPubFileProvider pubFileProvider, + ISfxPlayer sfxPlayer) { - private readonly IInGameDialogActions _inGameDialogActions; - private readonly ICitizenActions _citizenActions; - private readonly IPriestActions _priestActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IPubFileProvider _pubFileProvider; - private readonly ISfxPlayer _sfxPlayer; - - public NPCInteractionActions(IInGameDialogActions inGameDialogActions, - ICitizenActions citizenActions, - IPriestActions priestActions, - IEOMessageBoxFactory messageBoxFactory, - ITextInputDialogFactory textInputDialogFactory, - ILocalizedStringFinder localizedStringFinder, - IPubFileProvider pubFileProvider, - ISfxPlayer sfxPlayer) - { - _inGameDialogActions = inGameDialogActions; - _citizenActions = citizenActions; - _priestActions = priestActions; - _messageBoxFactory = messageBoxFactory; - _textInputDialogFactory = textInputDialogFactory; - _localizedStringFinder = localizedStringFinder; - _pubFileProvider = pubFileProvider; - _sfxPlayer = sfxPlayer; - } + _inGameDialogActions = inGameDialogActions; + _citizenActions = citizenActions; + _priestActions = priestActions; + _messageBoxFactory = messageBoxFactory; + _textInputDialogFactory = textInputDialogFactory; + _localizedStringFinder = localizedStringFinder; + _pubFileProvider = pubFileProvider; + _sfxPlayer = sfxPlayer; + } - public void NotifyInteractionFromNPC(NPCType npcType) + public void NotifyInteractionFromNPC(NPCType npcType) + { + // originally, these methods were called directly from NPCInteractionController + // however, this resulted in empty responses (e.g. no shop or quest) showing an empty dialog + // instead, wait for the response packet to notify this class and then show the dialog + // once data has been received from the server + switch (npcType) { - // originally, these methods were called directly from NPCInteractionController - // however, this resulted in empty responses (e.g. no shop or quest) showing an empty dialog - // instead, wait for the response packet to notify this class and then show the dialog - // once data has been received from the server - switch (npcType) - { - case NPCType.Shop: _inGameDialogActions.ShowShopDialog(); break; - case NPCType.Quest: _inGameDialogActions.ShowQuestDialog(); break; - case NPCType.Skills: _inGameDialogActions.ShowSkillmasterDialog(); break; - case NPCType.Inn: _inGameDialogActions.ShowInnkeeperDialog(); break; - case NPCType.Law: _inGameDialogActions.ShowLawDialog(); break; - case NPCType.Barber: _inGameDialogActions.ShowBarberDialog(); break; - case NPCType.Priest: ShowPriestDialog(); break; - } + case NPCType.Shop: _inGameDialogActions.ShowShopDialog(); break; + case NPCType.Quest: _inGameDialogActions.ShowQuestDialog(); break; + case NPCType.Skills: _inGameDialogActions.ShowSkillmasterDialog(); break; + case NPCType.Inn: _inGameDialogActions.ShowInnkeeperDialog(); break; + case NPCType.Law: _inGameDialogActions.ShowLawDialog(); break; + case NPCType.Barber: _inGameDialogActions.ShowBarberDialog(); break; + case NPCType.Priest: ShowPriestDialog(); break; } + } - public void NotifySkillLearnSuccess(int spellId, int characterGold) - { - _sfxPlayer.PlaySfx(SoundEffectID.LearnNewSpell); - } + public void NotifySkillLearnSuccess(int spellId, int characterGold) + { + _sfxPlayer.PlaySfx(SoundEffectID.LearnNewSpell); + } - public void NotifySkillLearnFail(SkillmasterReply skillmasterReply, int classId) + public void NotifySkillLearnFail(SkillmasterReply skillmasterReply, int classId) + { + switch (skillmasterReply) { - switch (skillmasterReply) - { - //not sure if this will ever actually be sent because client validates data before trying to learn a skill - case SkillmasterReply.ErrorWrongClass: - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_WRONG_CLASS, $" {_pubFileProvider.ECFFile[classId].Name}!"); - dlg.ShowDialog(); - } - break; - case SkillmasterReply.ErrorRemoveItems: - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_CLEAR_PAPERDOLL); - dlg.ShowDialog(); - } - break; - } + //not sure if this will ever actually be sent because client validates data before trying to learn a skill + case SkillmasterReply.ErrorWrongClass: + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_WRONG_CLASS, $" {_pubFileProvider.ECFFile[classId].Name}!"); + dlg.ShowDialog(); + } + break; + case SkillmasterReply.ErrorRemoveItems: + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_CLEAR_PAPERDOLL); + dlg.ShowDialog(); + } + break; } + } - public void NotifySkillForget() - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_FORGET_SUCCESS); - dlg.ShowDialog(); - } + public void NotifySkillForget() + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_FORGET_SUCCESS); + dlg.ShowDialog(); + } - public void NotifyStatReset() - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_COMPLETE); - dlg.ShowDialog(); + public void NotifyStatReset() + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_COMPLETE); + dlg.ShowDialog(); - _sfxPlayer.PlaySfx(SoundEffectID.LearnNewSpell); - } + _sfxPlayer.PlaySfx(SoundEffectID.LearnNewSpell); + } - public void NotifyCitizenUnsubscribe(InnUnsubscribeReply reply) - { - var message = EOResourceID.INN_YOU_ARE_NOT_A_CITIZEN + (int)reply; - var dlg = _messageBoxFactory.CreateMessageBox(message, EOResourceID.INN_REGISTRATION_SERVICE); - dlg.ShowDialog(); - } + public void NotifyCitizenUnsubscribe(InnUnsubscribeReply reply) + { + var message = EOResourceID.INN_YOU_ARE_NOT_A_CITIZEN + (int)reply; + var dlg = _messageBoxFactory.CreateMessageBox(message, EOResourceID.INN_REGISTRATION_SERVICE); + dlg.ShowDialog(); + } - public void NotifyCitizenSignUp(int questionsWrong) + public void NotifyCitizenSignUp(int questionsWrong) + { + if (questionsWrong == 0) { - if (questionsWrong == 0) - { - _sfxPlayer.PlaySfx(SoundEffectID.InnSignUp); + _sfxPlayer.PlaySfx(SoundEffectID.InnSignUp); - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.INN_BECOME_CITIZEN_CONGRATULATIONS, EOResourceID.INN_REGISTRATION_SERVICE); - dlg.ShowDialog(); - } - else - { - var dlg = _messageBoxFactory.CreateMessageBox( - $"{questionsWrong} {_localizedStringFinder.GetString(EOResourceID.INN_YOUR_ANSWERS_WERE_INCORRECT)}", - _localizedStringFinder.GetString(EOResourceID.INN_REGISTRATION_SERVICE)); - dlg.ShowDialog(); - } + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.INN_BECOME_CITIZEN_CONGRATULATIONS, EOResourceID.INN_REGISTRATION_SERVICE); + dlg.ShowDialog(); } - - public void NotifyCitizenRequestSleep(int sleepCost) + else { - var message = $"{_localizedStringFinder.GetString(EOResourceID.INN_A_GOOD_NIGHT_REST_WILL_COST_YOU)} {sleepCost} Gold"; - - var dlg = _messageBoxFactory.CreateMessageBox(message, _localizedStringFinder.GetString(EOResourceID.INN_SLEEP), EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => - { - if (e.Result == XNADialogResult.OK) - { - _citizenActions.ConfirmSleep(); - } - }; - + var dlg = _messageBoxFactory.CreateMessageBox( + $"{questionsWrong} {_localizedStringFinder.GetString(EOResourceID.INN_YOUR_ANSWERS_WERE_INCORRECT)}", + _localizedStringFinder.GetString(EOResourceID.INN_REGISTRATION_SERVICE)); dlg.ShowDialog(); } + } - public void NotifyPriestReply(PriestReply reply) - { - var message = reply switch - { - PriestReply.NotDressed => DialogResourceID.WEDDING_NEED_PROPER_CLOTHES, - PriestReply.LowLevel => DialogResourceID.WEDDING_NEED_HIGHER_LEVEL, - PriestReply.PartnerNotPresent => DialogResourceID.WEDDING_PARTNER_IS_MISSING, - PriestReply.PartnerNotDressed => DialogResourceID.WEDDING_PARTNER_NEED_CLOTHES, - PriestReply.Busy => DialogResourceID.WEDDING_PRIEST_IS_BUSY, - PriestReply.DoYou => DialogResourceID.WEDDING_DO_YOU_ACCEPT, - PriestReply.PartnerAlreadyMarried => DialogResourceID.WEDDING_PARTNER_ALREADY_MARRIED, - PriestReply.NoPermission => DialogResourceID.WEDDING_NO_PERMISSION_TO_COMPLETE, - _ => throw new ArgumentOutOfRangeException(nameof(reply)) - }; + public void NotifyCitizenRequestSleep(int sleepCost) + { + var message = $"{_localizedStringFinder.GetString(EOResourceID.INN_A_GOOD_NIGHT_REST_WILL_COST_YOU)} {sleepCost} Gold"; - var dlg = _messageBoxFactory.CreateMessageBox(message, whichButtons: reply == PriestReply.DoYou ? EODialogButtons.OkCancel : EODialogButtons.Ok); - if (reply == PriestReply.DoYou) + var dlg = _messageBoxFactory.CreateMessageBox(message, _localizedStringFinder.GetString(EOResourceID.INN_SLEEP), EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) { - dlg.DialogClosing += (_, e) => - { - if (e.Result != XNADialogResult.OK) - return; - - _priestActions.ConfirmMarriage(); - }; + _citizenActions.ConfirmSleep(); } - dlg.ShowDialog(); - } + }; - public void NotifyPriestRequest(string partnerName) - { - // The dialog title "Ceremony Notice" is not paired with the message, which is in EOResourceID and not a proper dialog text (????) - var ceremonyNoticeCaption = _localizedStringFinder.GetString(DialogResourceID.WEDDING_NEED_PROPER_CLOTHES); - var ceremonyNoticeMessage = $"{char.ToUpper(partnerName[0]) + partnerName[1..]} {_localizedStringFinder.GetString(EOResourceID.WEDDING_IS_ASKING_YOU_TO_MARRY)}"; + dlg.ShowDialog(); + } - var dlg = _messageBoxFactory.CreateMessageBox(ceremonyNoticeMessage, ceremonyNoticeCaption, EODialogButtons.OkCancel); + public void NotifyPriestReply(PriestReply reply) + { + var message = reply switch + { + PriestReply.NotDressed => DialogResourceID.WEDDING_NEED_PROPER_CLOTHES, + PriestReply.LowLevel => DialogResourceID.WEDDING_NEED_HIGHER_LEVEL, + PriestReply.PartnerNotPresent => DialogResourceID.WEDDING_PARTNER_IS_MISSING, + PriestReply.PartnerNotDressed => DialogResourceID.WEDDING_PARTNER_NEED_CLOTHES, + PriestReply.Busy => DialogResourceID.WEDDING_PRIEST_IS_BUSY, + PriestReply.DoYou => DialogResourceID.WEDDING_DO_YOU_ACCEPT, + PriestReply.PartnerAlreadyMarried => DialogResourceID.WEDDING_PARTNER_ALREADY_MARRIED, + PriestReply.NoPermission => DialogResourceID.WEDDING_NO_PERMISSION_TO_COMPLETE, + _ => throw new ArgumentOutOfRangeException(nameof(reply)) + }; + + var dlg = _messageBoxFactory.CreateMessageBox(message, whichButtons: reply == PriestReply.DoYou ? EODialogButtons.OkCancel : EODialogButtons.Ok); + if (reply == PriestReply.DoYou) + { dlg.DialogClosing += (_, e) => { if (e.Result != XNADialogResult.OK) return; - _priestActions.AcceptRequest(); + _priestActions.ConfirmMarriage(); }; - dlg.ShowDialog(); } + dlg.ShowDialog(); + } + + public void NotifyPriestRequest(string partnerName) + { + // The dialog title "Ceremony Notice" is not paired with the message, which is in EOResourceID and not a proper dialog text (????) + var ceremonyNoticeCaption = _localizedStringFinder.GetString(DialogResourceID.WEDDING_NEED_PROPER_CLOTHES); + var ceremonyNoticeMessage = $"{char.ToUpper(partnerName[0]) + partnerName[1..]} {_localizedStringFinder.GetString(EOResourceID.WEDDING_IS_ASKING_YOU_TO_MARRY)}"; - public void NotifyMarriageReply(MarriageReply reply) + var dlg = _messageBoxFactory.CreateMessageBox(ceremonyNoticeMessage, ceremonyNoticeCaption, EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => { - var message = reply switch - { - MarriageReply.AlreadyMarried => DialogResourceID.WEDDING_YOU_ALREADY_MARRIED, - MarriageReply.NotMarried => DialogResourceID.WEDDING_CANNOT_DIVORCE_NO_PARTNER, - MarriageReply.Success => DialogResourceID.WEDDING_REGISTRATION_COMPLETE, - MarriageReply.NotEnoughGold => DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, - MarriageReply.WrongName => DialogResourceID.WEDDING_PARTNER_NOT_MATCH, - MarriageReply.ServiceBusy => DialogResourceID.WEDDING_REGISTRATION_TOO_BUSY, - MarriageReply.DivorceNotification => DialogResourceID.WEDDING_DIVORCE_NO_MORE_PARTNER, - _ => throw new ArgumentOutOfRangeException(nameof(reply)) - }; + if (e.Result != XNADialogResult.OK) + return; - var dlg = _messageBoxFactory.CreateMessageBox(message, reply == MarriageReply.NotEnoughGold ? $" {_pubFileProvider.EIFFile[1].Name}" : string.Empty); - dlg.ShowDialog(); - } + _priestActions.AcceptRequest(); + }; + dlg.ShowDialog(); + } - private void ShowPriestDialog() + public void NotifyMarriageReply(MarriageReply reply) + { + var message = reply switch { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WEDDING_PRIEST_CAN_PERFORM, EODialogButtons.OkCancel, EOMessageBoxStyle.LargeDialogSmallHeader); - dlg.DialogClosing += (_, e1) => - { - if (e1.Result != XNADialogResult.OK) - return; + MarriageReply.AlreadyMarried => DialogResourceID.WEDDING_YOU_ALREADY_MARRIED, + MarriageReply.NotMarried => DialogResourceID.WEDDING_CANNOT_DIVORCE_NO_PARTNER, + MarriageReply.Success => DialogResourceID.WEDDING_REGISTRATION_COMPLETE, + MarriageReply.NotEnoughGold => DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, + MarriageReply.WrongName => DialogResourceID.WEDDING_PARTNER_NOT_MATCH, + MarriageReply.ServiceBusy => DialogResourceID.WEDDING_REGISTRATION_TOO_BUSY, + MarriageReply.DivorceNotification => DialogResourceID.WEDDING_DIVORCE_NO_MORE_PARTNER, + _ => throw new ArgumentOutOfRangeException(nameof(reply)) + }; + + var dlg = _messageBoxFactory.CreateMessageBox(message, reply == MarriageReply.NotEnoughGold ? $" {_pubFileProvider.EIFFile[1].Name}" : string.Empty); + dlg.ShowDialog(); + } - var inputDlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PLEASE_ENTER_NAME)); - inputDlg.DialogClosing += (_, e2) => - { - if (e2.Result != XNADialogResult.OK) - return; + private void ShowPriestDialog() + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WEDDING_PRIEST_CAN_PERFORM, EODialogButtons.OkCancel, EOMessageBoxStyle.LargeDialogSmallHeader); + dlg.DialogClosing += (_, e1) => + { + if (e1.Result != XNADialogResult.OK) + return; - _priestActions.RequestMarriage(inputDlg.ResponseText); - }; + var inputDlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PLEASE_ENTER_NAME)); + inputDlg.DialogClosing += (_, e2) => + { + if (e2.Result != XNADialogResult.OK) + return; - inputDlg.ShowDialog(); + _priestActions.RequestMarriage(inputDlg.ResponseText); }; - dlg.ShowDialog(); - } + + inputDlg.ShowDialog(); + }; + dlg.ShowDialog(); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/PartyDialogActions.cs b/EndlessClient/Dialogs/Actions/PartyDialogActions.cs index 5c911ccf6..c752de038 100644 --- a/EndlessClient/Dialogs/Actions/PartyDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/PartyDialogActions.cs @@ -10,77 +10,76 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using XNAControls; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +[AutoMappedType] +public class PartyDialogActions : IPartyEventNotifier { - [AutoMappedType] - public class PartyDialogActions : IPartyEventNotifier + private readonly IPartyActions _partyActions; + private readonly ISfxPlayer _sfxPlayer; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IChatRepository _chatRepository; + private readonly IConfigurationProvider _configurationProvider; + + public PartyDialogActions(IPartyActions partyActions, + ISfxPlayer sfxPlayer, + IEOMessageBoxFactory messageBoxFactory, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + IChatRepository chatRepository, + IConfigurationProvider configurationProvider) { - private readonly IPartyActions _partyActions; - private readonly ISfxPlayer _sfxPlayer; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IChatRepository _chatRepository; - private readonly IConfigurationProvider _configurationProvider; + _partyActions = partyActions; + _sfxPlayer = sfxPlayer; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _chatRepository = chatRepository; + _configurationProvider = configurationProvider; + } - public PartyDialogActions(IPartyActions partyActions, - ISfxPlayer sfxPlayer, - IEOMessageBoxFactory messageBoxFactory, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - IChatRepository chatRepository, - IConfigurationProvider configurationProvider) - { - _partyActions = partyActions; - _sfxPlayer = sfxPlayer; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _chatRepository = chatRepository; - _configurationProvider = configurationProvider; - } + public void NotifyPartyRequest(PartyRequestType type, int playerId, string name) + { + if (!_configurationProvider.Interaction) + return; - public void NotifyPartyRequest(PartyRequestType type, int playerId, string name) + var dlg = _messageBoxFactory.CreateMessageBox( + $"{char.ToUpper(name[0])}{name[1..]} ", + type == PartyRequestType.Join + ? DialogResourceID.PARTY_GROUP_REQUEST_TO_JOIN + : DialogResourceID.PARTY_GROUP_SEND_INVITATION, + EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => { - if (!_configurationProvider.Interaction) - return; - - var dlg = _messageBoxFactory.CreateMessageBox( - $"{char.ToUpper(name[0])}{name[1..]} ", - type == PartyRequestType.Join - ? DialogResourceID.PARTY_GROUP_REQUEST_TO_JOIN - : DialogResourceID.PARTY_GROUP_SEND_INVITATION, - EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => + if (e.Result == XNADialogResult.OK) { - if (e.Result == XNADialogResult.OK) - { - _partyActions.AcceptParty(type, playerId); - } - }; - dlg.ShowDialog(); - } + _partyActions.AcceptParty(type, playerId); + } + }; + dlg.ShowDialog(); + } - public void NotifyPartyJoined() - { - _sfxPlayer.PlaySfx(SoundEffectID.JoinParty); + public void NotifyPartyJoined() + { + _sfxPlayer.PlaySfx(SoundEffectID.JoinParty); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_PARTY_YOU_JOINED); - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_YOU_JOINED), ChatIcon.PlayerParty, ChatColor.PM)); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_PARTY_YOU_JOINED); + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_YOU_JOINED), ChatIcon.PlayerParty, ChatColor.PM)); + } - public void NotifyPartyMemberAdd(string name) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, name, EOResourceID.STATUS_LABEL_PARTY_JOINED_YOUR); - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_JOINED_YOUR), ChatIcon.PlayerParty, ChatColor.PM)); - } + public void NotifyPartyMemberAdd(string name) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, name, EOResourceID.STATUS_LABEL_PARTY_JOINED_YOUR); + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_JOINED_YOUR), ChatIcon.PlayerParty, ChatColor.PM)); + } - public void NotifyPartyMemberRemove(string name) - { - _sfxPlayer.PlaySfx(SoundEffectID.MemberLeftParty); + public void NotifyPartyMemberRemove(string name) + { + _sfxPlayer.PlaySfx(SoundEffectID.MemberLeftParty); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, name, EOResourceID.STATUS_LABEL_PARTY_LEFT_YOUR); - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_LEFT_YOUR), ChatIcon.PlayerPartyDark, ChatColor.PM)); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, name, EOResourceID.STATUS_LABEL_PARTY_LEFT_YOUR); + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_LEFT_YOUR), ChatIcon.PlayerPartyDark, ChatColor.PM)); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/TradeDialogActions.cs b/EndlessClient/Dialogs/Actions/TradeDialogActions.cs index c1be94edf..b770f3eb4 100644 --- a/EndlessClient/Dialogs/Actions/TradeDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/TradeDialogActions.cs @@ -8,81 +8,80 @@ using EOLib.Localization; using XNAControls; -namespace EndlessClient.Dialogs.Actions +namespace EndlessClient.Dialogs.Actions; + +[AutoMappedType] +public class TradeDialogActions : ITradeEventNotifier { - [AutoMappedType] - public class TradeDialogActions : ITradeEventNotifier + private readonly ITradeActions _tradeActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ITradeProvider _tradeProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IConfigurationProvider _configurationProvider; + + public TradeDialogActions(ITradeActions tradeActions, + IInGameDialogActions inGameDialogActions, + IEOMessageBoxFactory messageBoxFactory, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + ITradeProvider tradeProvider, + ICharacterProvider characterProvider, + IConfigurationProvider configurationProvider) { - private readonly ITradeActions _tradeActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ITradeProvider _tradeProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IConfigurationProvider _configurationProvider; + _tradeActions = tradeActions; + _inGameDialogActions = inGameDialogActions; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _tradeProvider = tradeProvider; + _characterProvider = characterProvider; + _configurationProvider = configurationProvider; + } - public TradeDialogActions(ITradeActions tradeActions, - IInGameDialogActions inGameDialogActions, - IEOMessageBoxFactory messageBoxFactory, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - ITradeProvider tradeProvider, - ICharacterProvider characterProvider, - IConfigurationProvider configurationProvider) - { - _tradeActions = tradeActions; - _inGameDialogActions = inGameDialogActions; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _tradeProvider = tradeProvider; - _characterProvider = characterProvider; - _configurationProvider = configurationProvider; - } + public void NotifyTradeRequest(int playerId, string name) + { + if (!_configurationProvider.Interaction) + return; - public void NotifyTradeRequest(int playerId, string name) + var dlg = _messageBoxFactory.CreateMessageBox(char.ToUpper(name[0]) + name[1..] + " ", DialogResourceID.TRADE_REQUEST, EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => { - if (!_configurationProvider.Interaction) - return; - - var dlg = _messageBoxFactory.CreateMessageBox(char.ToUpper(name[0]) + name[1..] + " ", DialogResourceID.TRADE_REQUEST, EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => + if (e.Result == XNADialogResult.OK) { - if (e.Result == XNADialogResult.OK) - { - _tradeActions.AcceptTradeRequest(playerId); - } - }; + _tradeActions.AcceptTradeRequest(playerId); + } + }; - dlg.ShowDialog(); - } + dlg.ShowDialog(); + } - public void NotifyTradeAccepted() - { - _inGameDialogActions.ShowTradeDialog(); + public void NotifyTradeAccepted() + { + _inGameDialogActions.ShowTradeDialog(); - var otherName = _tradeProvider.PlayerOneOffer.PlayerID == _characterProvider.MainCharacter.ID - ? _tradeProvider.PlayerOneOffer.PlayerName - : _tradeProvider.PlayerTwoOffer.PlayerName; - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - EOResourceID.STATUS_LABEL_TRADE_YOU_ARE_TRADING_WITH, - $"{otherName} {_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_DRAG_AND_DROP_ITEMS)}"); - } + var otherName = _tradeProvider.PlayerOneOffer.PlayerID == _characterProvider.MainCharacter.ID + ? _tradeProvider.PlayerOneOffer.PlayerName + : _tradeProvider.PlayerTwoOffer.PlayerName; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + EOResourceID.STATUS_LABEL_TRADE_YOU_ARE_TRADING_WITH, + $"{otherName} {_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_DRAG_AND_DROP_ITEMS)}"); + } - public void NotifyTradeClose(bool cancel) - { - _inGameDialogActions.CloseTradeDialog(); + public void NotifyTradeClose(bool cancel) + { + _inGameDialogActions.CloseTradeDialog(); - if (cancel) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_TRADE_ABORTED); - } - else - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_SUCCESS); - dlg.ShowDialog(); - } + if (cancel) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_TRADE_ABORTED); + } + else + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_SUCCESS); + dlg.ShowDialog(); } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ActiveDialogRepository.cs b/EndlessClient/Dialogs/ActiveDialogRepository.cs index b8932eee4..34ec910fd 100644 --- a/EndlessClient/Dialogs/ActiveDialogRepository.cs +++ b/EndlessClient/Dialogs/ActiveDialogRepository.cs @@ -5,213 +5,212 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public interface IActiveDialogProvider : IDisposable { - public interface IActiveDialogProvider : IDisposable - { - Option FriendIgnoreDialog { get; } + Option FriendIgnoreDialog { get; } - Option SessionExpDialog { get; } + Option SessionExpDialog { get; } - Option QuestStatusDialog { get; } + Option QuestStatusDialog { get; } - Option PaperdollDialog { get; } + Option PaperdollDialog { get; } - Option BookDialog { get; } + Option BookDialog { get; } - Option ShopDialog { get; } + Option ShopDialog { get; } - Option QuestDialog { get; } + Option QuestDialog { get; } - Option ChestDialog { get; } + Option ChestDialog { get; } - Option LockerDialog { get; } + Option LockerDialog { get; } - Option BankAccountDialog { get; } + Option BankAccountDialog { get; } - Option SkillmasterDialog { get; } + Option SkillmasterDialog { get; } - Option BardDialog { get; } + Option BardDialog { get; } - Option MessageDialog { get; } + Option MessageDialog { get; } - Option TradeDialog { get; } + Option TradeDialog { get; } - Option MessageBox { get; } + Option MessageBox { get; } - Option BoardDialog { get; } + Option BoardDialog { get; } - Option JukeboxDialog { get; } + Option JukeboxDialog { get; } - Option InnkeeperDialog { get; } + Option InnkeeperDialog { get; } - Option LawDialog { get; } + Option LawDialog { get; } - Option BarberDialog { get; } + Option BarberDialog { get; } - Option HelpDialog { get; } + Option HelpDialog { get; } - IReadOnlyList> ActiveDialogs { get; } - } + IReadOnlyList> ActiveDialogs { get; } +} - public interface IActiveDialogRepository : IDisposable - { - Option FriendIgnoreDialog { get; set; } +public interface IActiveDialogRepository : IDisposable +{ + Option FriendIgnoreDialog { get; set; } - Option SessionExpDialog { get; set; } + Option SessionExpDialog { get; set; } - Option QuestStatusDialog { get; set; } + Option QuestStatusDialog { get; set; } - Option PaperdollDialog { get; set; } + Option PaperdollDialog { get; set; } - Option BookDialog { get; set; } + Option BookDialog { get; set; } - Option ShopDialog { get; set; } + Option ShopDialog { get; set; } - Option QuestDialog { get; set; } + Option QuestDialog { get; set; } - Option ChestDialog { get; set; } + Option ChestDialog { get; set; } - Option LockerDialog { get; set; } + Option LockerDialog { get; set; } - Option BankAccountDialog { get; set; } + Option BankAccountDialog { get; set; } - Option SkillmasterDialog { get; set; } + Option SkillmasterDialog { get; set; } - Option BardDialog { get; set; } + Option BardDialog { get; set; } - Option MessageDialog { get; set; } + Option MessageDialog { get; set; } - Option TradeDialog { get; set; } + Option TradeDialog { get; set; } - Option MessageBox { get; set; } + Option MessageBox { get; set; } - Option BoardDialog { get; set; } + Option BoardDialog { get; set; } - Option JukeboxDialog { get; set; } + Option JukeboxDialog { get; set; } - Option InnkeeperDialog { get; set; } + Option InnkeeperDialog { get; set; } - Option LawDialog { get; set; } + Option LawDialog { get; set; } - Option BarberDialog { get; set; } + Option BarberDialog { get; set; } - Option HelpDialog { get; set; } + Option HelpDialog { get; set; } - IReadOnlyList> ActiveDialogs { get; } - } + IReadOnlyList> ActiveDialogs { get; } +} - [AutoMappedType(IsSingleton = true)] - public class ActiveDialogRepository : IActiveDialogRepository, IActiveDialogProvider - { - public Option FriendIgnoreDialog { get; set; } +[AutoMappedType(IsSingleton = true)] +public class ActiveDialogRepository : IActiveDialogRepository, IActiveDialogProvider +{ + public Option FriendIgnoreDialog { get; set; } - public Option SessionExpDialog { get; set; } + public Option SessionExpDialog { get; set; } - public Option QuestStatusDialog { get; set; } + public Option QuestStatusDialog { get; set; } - public Option PaperdollDialog { get; set; } + public Option PaperdollDialog { get; set; } - public Option BookDialog { get; set; } + public Option BookDialog { get; set; } - public Option ShopDialog { get; set; } + public Option ShopDialog { get; set; } - public Option QuestDialog { get; set; } + public Option QuestDialog { get; set; } - public Option ChestDialog { get; set; } + public Option ChestDialog { get; set; } - public Option LockerDialog { get; set; } + public Option LockerDialog { get; set; } - public Option BankAccountDialog { get; set; } + public Option BankAccountDialog { get; set; } - public Option SkillmasterDialog { get; set; } + public Option SkillmasterDialog { get; set; } - public Option BardDialog { get; set; } + public Option BardDialog { get; set; } - public Option MessageDialog { get; set; } + public Option MessageDialog { get; set; } - public Option TradeDialog { get; set; } + public Option TradeDialog { get; set; } - public Option MessageBox { get; set; } + public Option MessageBox { get; set; } - public Option BoardDialog { get; set; } + public Option BoardDialog { get; set; } - public Option JukeboxDialog { get; set; } + public Option JukeboxDialog { get; set; } - public Option InnkeeperDialog { get; set; } + public Option InnkeeperDialog { get; set; } - public Option LawDialog { get; set; } + public Option LawDialog { get; set; } - public Option BarberDialog { get; set; } + public Option BarberDialog { get; set; } - public Option HelpDialog { get; set; } + public Option HelpDialog { get; set; } - IReadOnlyList> ActiveDialogs + IReadOnlyList> ActiveDialogs + { + get { - get + return new Option[] { - return new Option[] - { - FriendIgnoreDialog.Map(Map), - SessionExpDialog.Map(Map), - QuestStatusDialog.Map(Map), - PaperdollDialog.Map(Map), - BookDialog.Map(Map), - ShopDialog.Map(Map), - QuestDialog.Map(Map), - ChestDialog.Map(Map), - LockerDialog.Map(Map), - BankAccountDialog.Map(Map), - SkillmasterDialog.Map(Map), - BardDialog.Map(Map), - MessageDialog.Map(Map), - TradeDialog.Map(Map), - MessageBox.Map(Map), - BoardDialog.Map(Map), - JukeboxDialog.Map(Map), - InnkeeperDialog.Map(Map), - LawDialog.Map(Map), - BarberDialog.Map(Map), - HelpDialog.Map(Map), - }.ToList(); - - static IXNADialog Map(object d) - { - return (IXNADialog)d; - } + FriendIgnoreDialog.Map(Map), + SessionExpDialog.Map(Map), + QuestStatusDialog.Map(Map), + PaperdollDialog.Map(Map), + BookDialog.Map(Map), + ShopDialog.Map(Map), + QuestDialog.Map(Map), + ChestDialog.Map(Map), + LockerDialog.Map(Map), + BankAccountDialog.Map(Map), + SkillmasterDialog.Map(Map), + BardDialog.Map(Map), + MessageDialog.Map(Map), + TradeDialog.Map(Map), + MessageBox.Map(Map), + BoardDialog.Map(Map), + JukeboxDialog.Map(Map), + InnkeeperDialog.Map(Map), + LawDialog.Map(Map), + BarberDialog.Map(Map), + HelpDialog.Map(Map), + }.ToList(); + + static IXNADialog Map(object d) + { + return (IXNADialog)d; } } + } - IReadOnlyList> IActiveDialogRepository.ActiveDialogs => ActiveDialogs; + IReadOnlyList> IActiveDialogRepository.ActiveDialogs => ActiveDialogs; - IReadOnlyList> IActiveDialogProvider.ActiveDialogs => ActiveDialogs; + IReadOnlyList> IActiveDialogProvider.ActiveDialogs => ActiveDialogs; - public void Dispose() - { - foreach (var dlg in ActiveDialogs) - dlg.MatchSome(d => d.Dispose()); - - FriendIgnoreDialog = Option.None(); - SessionExpDialog = Option.None(); - QuestStatusDialog = Option.None(); - PaperdollDialog = Option.None(); - BookDialog = Option.None(); - ShopDialog = Option.None(); - QuestDialog = Option.None(); - ChestDialog = Option.None(); - LockerDialog = Option.None(); - BankAccountDialog = Option.None(); - SkillmasterDialog = Option.None(); - BardDialog = Option.None(); - MessageDialog = Option.None(); - TradeDialog = Option.None(); - MessageBox = Option.None(); - BoardDialog = Option.None(); - JukeboxDialog = Option.None(); - InnkeeperDialog = Option.None(); - LawDialog = Option.None(); - BarberDialog = Option.None(); - HelpDialog = Option.None(); - } + public void Dispose() + { + foreach (var dlg in ActiveDialogs) + dlg.MatchSome(d => d.Dispose()); + + FriendIgnoreDialog = Option.None(); + SessionExpDialog = Option.None(); + QuestStatusDialog = Option.None(); + PaperdollDialog = Option.None(); + BookDialog = Option.None(); + ShopDialog = Option.None(); + QuestDialog = Option.None(); + ChestDialog = Option.None(); + LockerDialog = Option.None(); + BankAccountDialog = Option.None(); + SkillmasterDialog = Option.None(); + BardDialog = Option.None(); + MessageDialog = Option.None(); + TradeDialog = Option.None(); + MessageBox = Option.None(); + BoardDialog = Option.None(); + JukeboxDialog = Option.None(); + InnkeeperDialog = Option.None(); + LawDialog = Option.None(); + BarberDialog = Option.None(); + HelpDialog = Option.None(); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BankAccountDialog.cs b/EndlessClient/Dialogs/BankAccountDialog.cs index f6d9f22bc..5771830f5 100644 --- a/EndlessClient/Dialogs/BankAccountDialog.cs +++ b/EndlessClient/Dialogs/BankAccountDialog.cs @@ -16,235 +16,234 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class BankAccountDialog : ScrollingListDialog { - public class BankAccountDialog : ScrollingListDialog + private readonly IBankActions _bankActions; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IItemTransferDialogFactory _itemTransferDialogFactory; + private readonly IBankDataProvider _bankDataProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly InventoryPanel _inventoryPanel; + + private int _cachedValue; + private Option _cachedUpgrades; + + public BankAccountDialog(INativeGraphicsManager nativeGraphicsManager, + IBankActions bankActions, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + IItemTransferDialogFactory itemTransferDialogFactory, + IHudControlProvider hudControlProvider, + IBankDataProvider bankDataProvider, + ICharacterInventoryProvider characterInventoryProvider, + IEIFFileProvider eifFileProvider) + : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.BankAccountDialog) { - private readonly IBankActions _bankActions; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IItemTransferDialogFactory _itemTransferDialogFactory; - private readonly IBankDataProvider _bankDataProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly InventoryPanel _inventoryPanel; - - private int _cachedValue; - private Option _cachedUpgrades; - - public BankAccountDialog(INativeGraphicsManager nativeGraphicsManager, - IBankActions bankActions, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - IItemTransferDialogFactory itemTransferDialogFactory, - IHudControlProvider hudControlProvider, - IBankDataProvider bankDataProvider, - ICharacterInventoryProvider characterInventoryProvider, - IEIFFileProvider eifFileProvider) - : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.BankAccountDialog) + _bankActions = bankActions; + _localizedStringFinder = localizedStringFinder; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _itemTransferDialogFactory = itemTransferDialogFactory; + _bankDataProvider = bankDataProvider; + _characterInventoryProvider = characterInventoryProvider; + _eifFileProvider = eifFileProvider; + _inventoryPanel = hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); + + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.Cancel; + + _titleText.Text = "0"; + _titleText.TextAlign = LabelAlignment.MiddleRight; + _titleText.AutoSize = false; + + var currencyName = _eifFileProvider.EIFFile[1].Name; + + var depositItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) { - _bankActions = bankActions; - _localizedStringFinder = localizedStringFinder; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _itemTransferDialogFactory = itemTransferDialogFactory; - _bankDataProvider = bankDataProvider; - _characterInventoryProvider = characterInventoryProvider; - _eifFileProvider = eifFileProvider; - _inventoryPanel = hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); - - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.Cancel; - - _titleText.Text = "0"; - _titleText.TextAlign = LabelAlignment.MiddleRight; - _titleText.AutoSize = false; - - var currencyName = _eifFileProvider.EIFFile[1].Name; - - var depositItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_DEPOSIT), - SubText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TRANSFER)} {currencyName} {_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TO_ACCOUNT)}", - IconGraphic = dialogIconService.IconSheet, - IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankDeposit), - OffsetY = 55, - ShowIconBackGround = false, - }; - depositItem.LeftClick += Deposit; - depositItem.RightClick += Deposit; + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_DEPOSIT), + SubText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TRANSFER)} {currencyName} {_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TO_ACCOUNT)}", + IconGraphic = dialogIconService.IconSheet, + IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankDeposit), + OffsetY = 55, + ShowIconBackGround = false, + }; + depositItem.LeftClick += Deposit; + depositItem.RightClick += Deposit; + + var withdrawItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_WITHDRAW), + SubText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TRANSFER)} {currencyName} {_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_FROM_ACCOUNT)}", + IconGraphic = dialogIconService.IconSheet, + IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankWithdraw), + OffsetY = 55, + ShowIconBackGround = false, + }; + withdrawItem.LeftClick += Withdraw; + withdrawItem.RightClick += Withdraw; + + var upgradeItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_LOCKER_UPGRADE), + SubText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_MORE_SPACE), + IconGraphic = dialogIconService.IconSheet, + IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankLockerUpgrade), + OffsetY = 55, + ShowIconBackGround = false, + }; + upgradeItem.LeftClick += Upgrade; + upgradeItem.RightClick += Upgrade; + + AddItemToList(depositItem, sortList: false); + AddItemToList(withdrawItem, sortList: false); + AddItemToList(upgradeItem, sortList: false); + + DrawPosition += new Vector2(0, 50); + } - var withdrawItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_WITHDRAW), - SubText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TRANSFER)} {currencyName} {_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_FROM_ACCOUNT)}", - IconGraphic = dialogIconService.IconSheet, - IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankWithdraw), - OffsetY = 55, - ShowIconBackGround = false, - }; - withdrawItem.LeftClick += Withdraw; - withdrawItem.RightClick += Withdraw; + protected override void OnUpdateControl(GameTime gameTime) + { + if (_bankDataProvider.AccountValue != _cachedValue) + { + _cachedValue = _bankDataProvider.AccountValue; + Title = $"{_bankDataProvider.AccountValue}"; + } - var upgradeItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) + _cachedUpgrades.Match( + some: c => { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_LOCKER_UPGRADE), - SubText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_MORE_SPACE), - IconGraphic = dialogIconService.IconSheet, - IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankLockerUpgrade), - OffsetY = 55, - ShowIconBackGround = false, - }; - upgradeItem.LeftClick += Upgrade; - upgradeItem.RightClick += Upgrade; - - AddItemToList(depositItem, sortList: false); - AddItemToList(withdrawItem, sortList: false); - AddItemToList(upgradeItem, sortList: false); + _bankDataProvider.LockerUpgrades.MatchSome( + upgrades => + { + if (upgrades != c) + { + _cachedUpgrades = _bankDataProvider.LockerUpgrades; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_LOCKER_SPACE_INCREASED); + } + }); + }, + none: () => _cachedUpgrades = _bankDataProvider.LockerUpgrades); - DrawPosition += new Vector2(0, 50); - } + base.OnUpdateControl(gameTime); + } - protected override void OnUpdateControl(GameTime gameTime) - { - if (_bankDataProvider.AccountValue != _cachedValue) - { - _cachedValue = _bankDataProvider.AccountValue; - Title = $"{_bankDataProvider.AccountValue}"; - } + private void Deposit(object sender, EventArgs e) + { + if (!_inventoryPanel.NoItemsDragging()) + return; - _cachedUpgrades.Match( - some: c => + _characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1) + .Match( + some: characterGold => { - _bankDataProvider.LockerUpgrades.MatchSome( - upgrades => + if (characterGold.Amount == 0) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); + dlg.ShowDialog(); + + // todo: show the dialog message as a warning in the status label + } + else if (characterGold.Amount == 1) + { + _bankActions.Deposit(1); + } + else if (characterGold.Amount > 1) + { + var dlg = _itemTransferDialogFactory.CreateItemTransferDialog(_eifFileProvider.EIFFile[1].Name, ItemTransferDialog.TransferType.BankTransfer, characterGold.Amount, EOResourceID.DIALOG_TRANSFER_DEPOSIT); + dlg.DialogClosing += (_, e) => { - if (upgrades != c) - { - _cachedUpgrades = _bankDataProvider.LockerUpgrades; - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_LOCKER_SPACE_INCREASED); - } - }); + if (e.Result == XNADialogResult.OK) + _bankActions.Deposit(dlg.SelectedAmount); + }; + dlg.ShowDialog(); + } }, - none: () => _cachedUpgrades = _bankDataProvider.LockerUpgrades); + none: () => + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); + dlg.ShowDialog(); - base.OnUpdateControl(gameTime); + // todo: show the dialog message as a warning in the status label + }); + } + + private void Withdraw(object sender, EventArgs e) + { + if (!_inventoryPanel.NoItemsDragging()) + return; + + if (_bankDataProvider.AccountValue == 0) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_WITHDRAW); + dlg.ShowDialog(); + + // todo: show the dialog message as a warning in the status label + } + else if (_bankDataProvider.AccountValue == 1) + { + _bankActions.Withdraw(1); + } + else if (_bankDataProvider.AccountValue > 1) + { + var dlg = _itemTransferDialogFactory.CreateItemTransferDialog(_eifFileProvider.EIFFile[1].Name, ItemTransferDialog.TransferType.BankTransfer, _bankDataProvider.AccountValue, EOResourceID.DIALOG_TRANSFER_WITHDRAW); + dlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + _bankActions.Withdraw(dlg.SelectedAmount); + }; + dlg.ShowDialog(); } + } + + private void Upgrade(object sender, EventArgs e) + { + if (!_inventoryPanel.NoItemsDragging()) + return; - private void Deposit(object sender, EventArgs e) + _bankDataProvider.LockerUpgrades.MatchSome(lockerUpgrades => { - if (!_inventoryPanel.NoItemsDragging()) + if (lockerUpgrades == Constants.MaxLockerUpgrades) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_UPGRADE_IMPOSSIBLE); + dlg.ShowDialog(); return; + } + + int requiredGold = (lockerUpgrades + 1) * 1000; _characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1) .Match( - some: characterGold => + some: charaterGold => { - if (characterGold.Amount == 0) + if (charaterGold.Amount < requiredGold) { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); dlg.ShowDialog(); - - // todo: show the dialog message as a warning in the status label } - else if (characterGold.Amount == 1) + else { - _bankActions.Deposit(1); - } - else if (characterGold.Amount > 1) - { - var dlg = _itemTransferDialogFactory.CreateItemTransferDialog(_eifFileProvider.EIFFile[1].Name, ItemTransferDialog.TransferType.BankTransfer, characterGold.Amount, EOResourceID.DIALOG_TRANSFER_DEPOSIT); + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_UPGRADE_UNIT, $"{requiredGold} {_eifFileProvider.EIFFile[1].Name}?", EODialogButtons.OkCancel); dlg.DialogClosing += (_, e) => { if (e.Result == XNADialogResult.OK) - _bankActions.Deposit(dlg.SelectedAmount); + _bankActions.BuyStorageUpgrade(); }; dlg.ShowDialog(); } }, - none: () => + () => { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); dlg.ShowDialog(); - - // todo: show the dialog message as a warning in the status label }); - } - - private void Withdraw(object sender, EventArgs e) - { - if (!_inventoryPanel.NoItemsDragging()) - return; - - if (_bankDataProvider.AccountValue == 0) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_WITHDRAW); - dlg.ShowDialog(); - - // todo: show the dialog message as a warning in the status label - } - else if (_bankDataProvider.AccountValue == 1) - { - _bankActions.Withdraw(1); - } - else if (_bankDataProvider.AccountValue > 1) - { - var dlg = _itemTransferDialogFactory.CreateItemTransferDialog(_eifFileProvider.EIFFile[1].Name, ItemTransferDialog.TransferType.BankTransfer, _bankDataProvider.AccountValue, EOResourceID.DIALOG_TRANSFER_WITHDRAW); - dlg.DialogClosing += (_, e) => - { - if (e.Result == XNADialogResult.OK) - _bankActions.Withdraw(dlg.SelectedAmount); - }; - dlg.ShowDialog(); - } - } - - private void Upgrade(object sender, EventArgs e) - { - if (!_inventoryPanel.NoItemsDragging()) - return; - - _bankDataProvider.LockerUpgrades.MatchSome(lockerUpgrades => - { - if (lockerUpgrades == Constants.MaxLockerUpgrades) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_UPGRADE_IMPOSSIBLE); - dlg.ShowDialog(); - return; - } - - int requiredGold = (lockerUpgrades + 1) * 1000; - - _characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1) - .Match( - some: charaterGold => - { - if (charaterGold.Amount < requiredGold) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); - dlg.ShowDialog(); - } - else - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_UPGRADE_UNIT, $"{requiredGold} {_eifFileProvider.EIFFile[1].Name}?", EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => - { - if (e.Result == XNADialogResult.OK) - _bankActions.BuyStorageUpgrade(); - }; - dlg.ShowDialog(); - } - }, - () => - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); - dlg.ShowDialog(); - }); - }); - } + }); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BarberDialog.cs b/EndlessClient/Dialogs/BarberDialog.cs index f730de83f..b829e2078 100644 --- a/EndlessClient/Dialogs/BarberDialog.cs +++ b/EndlessClient/Dialogs/BarberDialog.cs @@ -13,185 +13,184 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class BarberDialog : BaseEODialog { - public class BarberDialog : BaseEODialog + private const int AdjustedWidth = 175; + private const int AdjustedHighlightXOffset = 3; + private readonly string[] _hairColorNames = { "brown", "green", "pink", "red", "blonde", "blue", "purple", "luna", "white", "black" }; + private readonly CreateCharacterControl _characterControl; + private readonly ICharacterRepository _characterRepository; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IBarberActions _barberActions; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ISfxPlayer _sfxPlayer; + + private CharacterRenderProperties RenderProperties => _characterControl.RenderProperties; + private ListDialogItem _changeHairItem, _changeHairColor, _changeBuyHairStyleOrColor; + + public BarberDialog(INativeGraphicsManager nativeGraphicsManager, + ICharacterRendererFactory rendererFactory, + IEODialogButtonService dialogButtonService, + ICharacterRepository characterLvRepository, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IBarberActions barberActions, + ICharacterInventoryProvider characterInventoryProvider, + IEOMessageBoxFactory messageBoxFactory, + IEIFFileProvider eifFileProvider, + ISfxPlayer sfxPlayer) + : base(nativeGraphicsManager, isInGame: true) { - private const int AdjustedWidth = 175; - private const int AdjustedHighlightXOffset = 3; - private readonly string[] _hairColorNames = { "brown", "green", "pink", "red", "blonde", "blue", "purple", "luna", "white", "black" }; - private readonly CreateCharacterControl _characterControl; - private readonly ICharacterRepository _characterRepository; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IBarberActions _barberActions; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ISfxPlayer _sfxPlayer; - - private CharacterRenderProperties RenderProperties => _characterControl.RenderProperties; - private ListDialogItem _changeHairItem, _changeHairColor, _changeBuyHairStyleOrColor; - - public BarberDialog(INativeGraphicsManager nativeGraphicsManager, - ICharacterRendererFactory rendererFactory, - IEODialogButtonService dialogButtonService, - ICharacterRepository characterLvRepository, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IBarberActions barberActions, - ICharacterInventoryProvider characterInventoryProvider, - IEOMessageBoxFactory messageBoxFactory, - IEIFFileProvider eifFileProvider, - ISfxPlayer sfxPlayer) - : base(nativeGraphicsManager, isInGame: true) + _characterRepository = characterLvRepository; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _barberActions = barberActions; + _characterInventoryProvider = characterInventoryProvider; + _messageBoxFactory = messageBoxFactory; + _eifFileProvider = eifFileProvider; + _sfxPlayer = sfxPlayer; + + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 56); + + var mainCharacterRenderProperties = _characterRepository.MainCharacter.RenderProperties; + _characterControl = new CreateCharacterControl(mainCharacterRenderProperties, rendererFactory) { - _characterRepository = characterLvRepository; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _barberActions = barberActions; - _characterInventoryProvider = characterInventoryProvider; - _messageBoxFactory = messageBoxFactory; - _eifFileProvider = eifFileProvider; - _sfxPlayer = sfxPlayer; - - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 56); - - var mainCharacterRenderProperties = _characterRepository.MainCharacter.RenderProperties; - _characterControl = new CreateCharacterControl(mainCharacterRenderProperties, rendererFactory) - { - DrawPosition = new Vector2(210, 19), - }; + DrawPosition = new Vector2(210, 19), + }; - InitializeCharacterControl(); - InitializeDialogItems(dialogButtonService); - CenterInGameView(); - } + InitializeCharacterControl(); + InitializeDialogItems(dialogButtonService); + CenterInGameView(); + } - private void InitializeCharacterControl() - { - _characterControl.SetParentControl(this); - } + private void InitializeCharacterControl() + { + _characterControl.SetParentControl(this); + } - private void InitializeDialogItems(IEODialogButtonService dialogButtonService) - { - var cancel = CreateButton(dialogButtonService, new Vector2(215, 151), SmallButton.Cancel); - cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); + private void InitializeDialogItems(IEODialogButtonService dialogButtonService) + { + var cancel = CreateButton(dialogButtonService, new Vector2(215, 151), SmallButton.Cancel); + cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); - _changeHairItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberHairModel), - ShowIconBackGround = false, - OffsetX = AdjustedHighlightXOffset, - }; - _changeHairItem.DrawArea = _changeHairItem.DrawArea.WithSize(AdjustedWidth, _changeHairItem.DrawArea.Size.Y); - _changeHairItem.LeftClick += ChangeHairStyle_Click; + _changeHairItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + { + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberHairModel), + ShowIconBackGround = false, + OffsetX = AdjustedHighlightXOffset, + }; + _changeHairItem.DrawArea = _changeHairItem.DrawArea.WithSize(AdjustedWidth, _changeHairItem.DrawArea.Size.Y); + _changeHairItem.LeftClick += ChangeHairStyle_Click; + + _changeHairColor = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberChangeHairColor), + ShowIconBackGround = false, + OffsetX = AdjustedHighlightXOffset, + }; + _changeHairColor.DrawArea = _changeHairColor.DrawArea.WithSize(AdjustedWidth, _changeHairColor.DrawArea.Size.Y); + _changeHairColor.LeftClick += ChangeHairColor_Click; + + _changeBuyHairStyleOrColor = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) + { + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberOk), + ShowIconBackGround = false, + OffsetX = AdjustedHighlightXOffset, + }; + _changeBuyHairStyleOrColor.DrawArea = _changeBuyHairStyleOrColor.DrawArea.WithSize(AdjustedWidth, _changeBuyHairStyleOrColor.DrawArea.Size.Y); + _changeBuyHairStyleOrColor.LeftClick += BuyHair_Click; + } - _changeHairColor = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberChangeHairColor), - ShowIconBackGround = false, - OffsetX = AdjustedHighlightXOffset, - }; - _changeHairColor.DrawArea = _changeHairColor.DrawArea.WithSize(AdjustedWidth, _changeHairColor.DrawArea.Size.Y); - _changeHairColor.LeftClick += ChangeHairColor_Click; + public override void Initialize() + { + base.Initialize(); + _characterControl.Initialize(); + UpdateListItems(_characterRepository.MainCharacter.RenderProperties); + } - _changeBuyHairStyleOrColor = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) - { - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberOk), - ShowIconBackGround = false, - OffsetX = AdjustedHighlightXOffset, - }; - _changeBuyHairStyleOrColor.DrawArea = _changeBuyHairStyleOrColor.DrawArea.WithSize(AdjustedWidth, _changeBuyHairStyleOrColor.DrawArea.Size.Y); - _changeBuyHairStyleOrColor.LeftClick += BuyHair_Click; - } + private void UpdateListItems(CharacterRenderProperties currentProperties) + { + _changeHairItem.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_CHANGE_MODAL); + _changeHairItem.SubText = GetCurrentHairStyleText(currentProperties.HairStyle); - public override void Initialize() - { - base.Initialize(); - _characterControl.Initialize(); - UpdateListItems(_characterRepository.MainCharacter.RenderProperties); - } + _changeHairColor.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_CHANGE_HAIR_COLOR); + _changeHairColor.SubText = GetCurrentHairColorText(currentProperties.HairColor); - private void UpdateListItems(CharacterRenderProperties currentProperties) - { - _changeHairItem.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_CHANGE_MODAL); - _changeHairItem.SubText = GetCurrentHairStyleText(currentProperties.HairStyle); + _changeBuyHairStyleOrColor.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_BUY_HAIRSTYLE); + _changeBuyHairStyleOrColor.SubText = GetCostText(); + } - _changeHairColor.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_CHANGE_HAIR_COLOR); - _changeHairColor.SubText = GetCurrentHairColorText(currentProperties.HairColor); + private string GetCurrentHairStyleText(int hairStyle) => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {hairStyle}"; + private string GetCurrentHairColorText(int hairColor) => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {_hairColorNames[hairColor % _hairColorNames.Length]}"; + private string GetCostText() => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {CalculateCost()} gold"; - _changeBuyHairStyleOrColor.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_BUY_HAIRSTYLE); - _changeBuyHairStyleOrColor.SubText = GetCostText(); - } + private int CalculateCost() + { + var level = (int)_characterRepository.MainCharacter.Stats[CharacterStat.Level]; + return 200 + Math.Max(level - 1, 0) * 200; + } - private string GetCurrentHairStyleText(int hairStyle) => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {hairStyle}"; - private string GetCurrentHairColorText(int hairColor) => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {_hairColorNames[hairColor % _hairColorNames.Length]}"; - private string GetCostText() => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {CalculateCost()} gold"; + private void ChangeHairStyle_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) + { + _characterControl.NextHairStyle(); + _changeHairItem.SubText = GetCurrentHairStyleText(_characterControl.RenderProperties.HairStyle); + } - private int CalculateCost() - { - var level = (int)_characterRepository.MainCharacter.Stats[CharacterStat.Level]; - return 200 + Math.Max(level - 1, 0) * 200; - } + private void ChangeHairColor_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) + { + _characterControl.NextHairColor(); + _changeHairColor.SubText = GetCurrentHairColorText(_characterControl.RenderProperties.HairColor); + } - private void ChangeHairStyle_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) - { - _characterControl.NextHairStyle(); - _changeHairItem.SubText = GetCurrentHairStyleText(_characterControl.RenderProperties.HairStyle); - } + private void BuyHair_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) + { + int hairStyle = _characterControl.RenderProperties.HairStyle; + int hairColor = _characterControl.RenderProperties.HairColor; - private void ChangeHairColor_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) - { - _characterControl.NextHairColor(); - _changeHairColor.SubText = GetCurrentHairColorText(_characterControl.RenderProperties.HairColor); - } + int totalCost = CalculateCost(); + int currentGold = _characterInventoryProvider.ItemInventory.SingleOrNone(i => i.ItemID == 1) + .Map(i => i.Amount) + .ValueOr(0); - private void BuyHair_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) + if (currentGold >= totalCost) { - int hairStyle = _characterControl.RenderProperties.HairStyle; - int hairColor = _characterControl.RenderProperties.HairColor; + var message = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_DO_YOU_WANT_TO_BUY_A_NEW_HAIRSTYLE)}, {totalCost} {_eifFileProvider.EIFFile[1].Name}"; + var title = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_BUY_HAIRSTYLE); + var msgBox = _messageBoxFactory.CreateMessageBox(message, title, EODialogButtons.OkCancel); - int totalCost = CalculateCost(); - int currentGold = _characterInventoryProvider.ItemInventory.SingleOrNone(i => i.ItemID == 1) - .Map(i => i.Amount) - .ValueOr(0); - - if (currentGold >= totalCost) + msgBox.DialogClosing += (_, e) => { - var message = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_DO_YOU_WANT_TO_BUY_A_NEW_HAIRSTYLE)}, {totalCost} {_eifFileProvider.EIFFile[1].Name}"; - var title = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_BUY_HAIRSTYLE); - var msgBox = _messageBoxFactory.CreateMessageBox(message, title, EODialogButtons.OkCancel); - - msgBox.DialogClosing += (_, e) => + if (e.Result == XNADialogResult.OK) { - if (e.Result == XNADialogResult.OK) - { - _barberActions.Purchase(hairStyle, hairColor); - _sfxPlayer.PlaySfx(SoundEffectID.BuySell); - } - }; - - msgBox.ShowDialog(); - } - else - { - var msgBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); - msgBox.ShowDialog(); - } - } + _barberActions.Purchase(hairStyle, hairColor); + _sfxPlayer.PlaySfx(SoundEffectID.BuySell); + } + }; - private XNAButton CreateButton(IEODialogButtonService dialogButtonService, Vector2 position, SmallButton buttonType) + msgBox.ShowDialog(); + } + else { - var button = new XNAButton(dialogButtonService.SmallButtonSheet, position, - dialogButtonService.GetSmallDialogButtonOutSource(buttonType), - dialogButtonService.GetSmallDialogButtonOverSource(buttonType)); - button.Initialize(); - button.SetParentControl(this); - return button; + var msgBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); + msgBox.ShowDialog(); } } + + private XNAButton CreateButton(IEODialogButtonService dialogButtonService, Vector2 position, SmallButton buttonType) + { + var button = new XNAButton(dialogButtonService.SmallButtonSheet, position, + dialogButtonService.GetSmallDialogButtonOutSource(buttonType), + dialogButtonService.GetSmallDialogButtonOverSource(buttonType)); + button.Initialize(); + button.SetParentControl(this); + return button; + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BardDialog.cs b/EndlessClient/Dialogs/BardDialog.cs index b2ba3498d..3382b6446 100644 --- a/EndlessClient/Dialogs/BardDialog.cs +++ b/EndlessClient/Dialogs/BardDialog.cs @@ -9,103 +9,102 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class BardDialog : BaseEODialog { - public class BardDialog : BaseEODialog - { - private readonly IBardController _bardController; - private readonly Texture2D _noteHighlight; - private readonly Rectangle _noteRectangleArea; + private readonly IBardController _bardController; + private readonly Texture2D _noteHighlight; + private readonly Rectangle _noteRectangleArea; - private Vector2 _highlightDrawPosition; - private Option _highlightSource; + private Vector2 _highlightDrawPosition; + private Option _highlightSource; - private ulong _currentTick; + private ulong _currentTick; - public BardDialog(INativeGraphicsManager nativeGraphicsManager, - IBardController bardController, - IEODialogButtonService dialogButtonService) - : base(nativeGraphicsManager, isInGame: true) - { - _bardController = bardController; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 65); - _noteHighlight = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 66); - _noteRectangleArea = new Rectangle(15, 15, 240, 60); + public BardDialog(INativeGraphicsManager nativeGraphicsManager, + IBardController bardController, + IEODialogButtonService dialogButtonService) + : base(nativeGraphicsManager, isInGame: true) + { + _bardController = bardController; + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 65); + _noteHighlight = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 66); + _noteRectangleArea = new Rectangle(15, 15, 240, 60); - var cancel = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(92, 83), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - cancel.Initialize(); - cancel.SetParentControl(this); - cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); + var cancel = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(92, 83), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + cancel.Initialize(); + cancel.SetParentControl(this); + cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); - CenterInGameView(); + CenterInGameView(); - OnMouseOver += HandleMouseOver; - } + OnMouseOver += HandleMouseOver; + } - protected override void OnUpdateControl(GameTime gameTime) - { - _currentTick++; + protected override void OnUpdateControl(GameTime gameTime) + { + _currentTick++; - base.OnUpdateControl(gameTime); - } + base.OnUpdateControl(gameTime); + } + + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - protected override void OnDrawControl(GameTime gameTime) + _highlightSource.MatchSome(src => { - base.OnDrawControl(gameTime); + _spriteBatch.Begin(); + _spriteBatch.Draw(_noteHighlight, _highlightDrawPosition, src, Color.White); + _spriteBatch.End(); + }); + } - _highlightSource.MatchSome(src => + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (eventArgs.Button == MouseButton.Left && _currentTick > 8) + { + _highlightSource.MatchSome(highlightSource => { - _spriteBatch.Begin(); - _spriteBatch.Draw(_noteHighlight, _highlightDrawPosition, src, Color.White); - _spriteBatch.End(); + var highlightDrawPosition = highlightSource.Location.ToVector2(); + var noteIndex = (int)Math.Floor(highlightDrawPosition.X / 20 + (12 * (highlightDrawPosition.Y / 20))); + _bardController.PlayInstrumentNote(noteIndex); + _currentTick = 0; }); } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + return true; + } + + private void HandleMouseOver(object sender, MouseStateExtended eventArgs) + { + var relativeMousePosition = eventArgs.Position - DrawAreaWithParentOffset.Location; + + if (_noteRectangleArea.Contains(relativeMousePosition)) { - if (eventArgs.Button == MouseButton.Left && _currentTick > 8) - { - _highlightSource.MatchSome(highlightSource => - { - var highlightDrawPosition = highlightSource.Location.ToVector2(); - var noteIndex = (int)Math.Floor(highlightDrawPosition.X / 20 + (12 * (highlightDrawPosition.Y / 20))); - _bardController.PlayInstrumentNote(noteIndex); - _currentTick = 0; - }); - } - - return true; + var relativePosition = relativeMousePosition - _noteRectangleArea.Location; + var highlightDrawPosition = new Vector2( + relativePosition.X - (relativePosition.X % 20), + relativePosition.Y - (relativePosition.Y % 20)); + _highlightDrawPosition = highlightDrawPosition + DrawPositionWithParentOffset + _noteRectangleArea.Location.ToVector2(); + _highlightSource = Option.Some(new Rectangle(highlightDrawPosition.ToPoint(), new Point(20, 20))); } - - private void HandleMouseOver(object sender, MouseStateExtended eventArgs) + else { - var relativeMousePosition = eventArgs.Position - DrawAreaWithParentOffset.Location; - - if (_noteRectangleArea.Contains(relativeMousePosition)) - { - var relativePosition = relativeMousePosition - _noteRectangleArea.Location; - var highlightDrawPosition = new Vector2( - relativePosition.X - (relativePosition.X % 20), - relativePosition.Y - (relativePosition.Y % 20)); - _highlightDrawPosition = highlightDrawPosition + DrawPositionWithParentOffset + _noteRectangleArea.Location.ToVector2(); - _highlightSource = Option.Some(new Rectangle(highlightDrawPosition.ToPoint(), new Point(20, 20))); - } - else - { - _highlightSource = Option.None(); - } + _highlightSource = Option.None(); } + } - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - OnMouseOver -= HandleMouseOver; - } - - base.Dispose(disposing); + OnMouseOver -= HandleMouseOver; } + + base.Dispose(disposing); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BaseEODialog.cs b/EndlessClient/Dialogs/BaseEODialog.cs index 52d39c3d8..50fa1fb71 100644 --- a/EndlessClient/Dialogs/BaseEODialog.cs +++ b/EndlessClient/Dialogs/BaseEODialog.cs @@ -4,38 +4,37 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public abstract class BaseEODialog : XNADialog { - public abstract class BaseEODialog : XNADialog + private readonly Func _isInGame; + + public INativeGraphicsManager GraphicsManager { get; } + + protected BaseEODialog(INativeGraphicsManager graphicsManager, + IGameStateProvider gameStateProvider) + { + GraphicsManager = graphicsManager; + _isInGame = () => gameStateProvider.CurrentState == GameStates.PlayingTheGame; + } + + protected BaseEODialog(INativeGraphicsManager graphicsManager, bool isInGame) + { + GraphicsManager = graphicsManager; + _isInGame = () => isInGame; + } + + public override void CenterInGameView() + { + base.CenterInGameView(); + + if (_isInGame() && !Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, (330 - DrawArea.Height) / 2f); + } + + public void Close() { - private readonly Func _isInGame; - - public INativeGraphicsManager GraphicsManager { get; } - - protected BaseEODialog(INativeGraphicsManager graphicsManager, - IGameStateProvider gameStateProvider) - { - GraphicsManager = graphicsManager; - _isInGame = () => gameStateProvider.CurrentState == GameStates.PlayingTheGame; - } - - protected BaseEODialog(INativeGraphicsManager graphicsManager, bool isInGame) - { - GraphicsManager = graphicsManager; - _isInGame = () => isInGame; - } - - public override void CenterInGameView() - { - base.CenterInGameView(); - - if (_isInGame() && !Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, (330 - DrawArea.Height) / 2f); - } - - public void Close() - { - Close(XNADialogResult.NO_BUTTON_PRESSED); - } + Close(XNADialogResult.NO_BUTTON_PRESSED); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BoardDialog.cs b/EndlessClient/Dialogs/BoardDialog.cs index e648db10b..f2a1f0c98 100644 --- a/EndlessClient/Dialogs/BoardDialog.cs +++ b/EndlessClient/Dialogs/BoardDialog.cs @@ -19,297 +19,296 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class BoardDialog : ScrollingListDialog { - public class BoardDialog : ScrollingListDialog + private enum BoardDialogState { - private enum BoardDialogState - { - ViewList, - ViewPost, - CreatePost, - } + ViewList, + ViewPost, + CreatePost, + } - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IBoardActions _boardActions; - private readonly IBoardRepository _boardRepository; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IHudControlProvider _hudControlProvider; - - private readonly XNATextBox _subject, _message; - - private BoardDialogState _state; - private HashSet _cachedPostInfo; - - public BoardDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IEOMessageBoxFactory eoMessageBoxFactory, - IBoardActions boardActions, - IBoardRepository boardRepository, - IPlayerInfoProvider playerInfoProvider, - ICharacterProvider characterProvider, - IContentProvider contentProvider, - IHudControlProvider hudControlProvider) - : base(nativeGraphicsManager, dialogButtonService, DialogType.Board) + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IBoardActions _boardActions; + private readonly IBoardRepository _boardRepository; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IHudControlProvider _hudControlProvider; + + private readonly XNATextBox _subject, _message; + + private BoardDialogState _state; + private HashSet _cachedPostInfo; + + public BoardDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IEOMessageBoxFactory eoMessageBoxFactory, + IBoardActions boardActions, + IBoardRepository boardRepository, + IPlayerInfoProvider playerInfoProvider, + ICharacterProvider characterProvider, + IContentProvider contentProvider, + IHudControlProvider hudControlProvider) + : base(nativeGraphicsManager, dialogButtonService, DialogType.Board) + { + _localizedStringFinder = localizedStringFinder; + _eoMessageBoxFactory = eoMessageBoxFactory; + _boardActions = boardActions; + _boardRepository = boardRepository; + _playerInfoProvider = playerInfoProvider; + _characterProvider = characterProvider; + _hudControlProvider = hudControlProvider; + ListItemType = ListDialogItem.ListItemStyle.Small; + Title = _localizedStringFinder.GetString(EOResourceID.BOARD_TOWN_BOARD); + _state = BoardDialogState.ViewList; + _cachedPostInfo = new HashSet(); + + _subject = new XNATextBox(new Rectangle(150, 44, 315, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) { - _localizedStringFinder = localizedStringFinder; - _eoMessageBoxFactory = eoMessageBoxFactory; - _boardActions = boardActions; - _boardRepository = boardRepository; - _playerInfoProvider = playerInfoProvider; - _characterProvider = characterProvider; - _hudControlProvider = hudControlProvider; - ListItemType = ListDialogItem.ListItemStyle.Small; - Title = _localizedStringFinder.GetString(EOResourceID.BOARD_TOWN_BOARD); - _state = BoardDialogState.ViewList; - _cachedPostInfo = new HashSet(); - - _subject = new XNATextBox(new Rectangle(150, 44, 315, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) - { - TextAlignment = LabelAlignment.MiddleLeft, - TextColor = ColorConstants.LightGrayText, - Visible = false, - MaxWidth = 310 - }; - _subject.SetScrollWheelHandler(_scrollBar); - _subject.SetParentControl(this); - - _message = new XNATextBox(new Rectangle(18, 80, 430, 168), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) - { - TextAlignment = LabelAlignment.TopLeft, - TextColor = ColorConstants.LightGrayText, - Visible = false, - MaxWidth = 412, - - Multiline = true, - ScrollHandler = _scrollBar, - RowSpacing = 16, - }; - _message.SetScrollWheelHandler(_scrollBar); - _message.SetParentControl(this); - - _add.OnClick += AddButton_Click; - _delete.OnClick += DeleteButton_Click; - } - - public override void Initialize() + TextAlignment = LabelAlignment.MiddleLeft, + TextColor = ColorConstants.LightGrayText, + Visible = false, + MaxWidth = 310 + }; + _subject.SetScrollWheelHandler(_scrollBar); + _subject.SetParentControl(this); + + _message = new XNATextBox(new Rectangle(18, 80, 430, 168), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) { - _subject.Initialize(); - _message.Initialize(); + TextAlignment = LabelAlignment.TopLeft, + TextColor = ColorConstants.LightGrayText, + Visible = false, + MaxWidth = 412, + + Multiline = true, + ScrollHandler = _scrollBar, + RowSpacing = 16, + }; + _message.SetScrollWheelHandler(_scrollBar); + _message.SetParentControl(this); + + _add.OnClick += AddButton_Click; + _delete.OnClick += DeleteButton_Click; + } - base.Initialize(); - } + public override void Initialize() + { + _subject.Initialize(); + _message.Initialize(); - protected override void OnUpdateControl(GameTime gameTime) + base.Initialize(); + } + + protected override void OnUpdateControl(GameTime gameTime) + { + switch (_state) { - switch (_state) - { - case BoardDialogState.ViewList: - if (!_cachedPostInfo.SetEquals(_boardRepository.Posts)) - { - ClearItemList(); + case BoardDialogState.ViewList: + if (!_cachedPostInfo.SetEquals(_boardRepository.Posts)) + { + ClearItemList(); - _cachedPostInfo = new HashSet(_boardRepository.Posts); + _cachedPostInfo = new HashSet(_boardRepository.Posts); - var index = 0; - foreach (var post in _cachedPostInfo) + var index = 0; + foreach (var post in _cachedPostInfo) + { + var childItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) { - var childItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) - { - PrimaryText = char.ToUpper(post.Author[0]) + post.Author[1..], - SubText = post.Subject, - Data = post.PostId, - Visible = true, - UnderlineLinks = false, - ShowSubtext = true, - OffsetX = 2, - OffsetY = 48, - }; - - childItem.DrawArea = new Rectangle(childItem.DrawArea.Location, new Point(427, 16)); - childItem.SetPrimaryClickAction(ChildItem_Click); - childItem.SetScrollWheelHandler(this); - - AddItemToList(childItem, sortList: false); - } - - _scrollBar.ScrollToTop(); + PrimaryText = char.ToUpper(post.Author[0]) + post.Author[1..], + SubText = post.Subject, + Data = post.PostId, + Visible = true, + UnderlineLinks = false, + ShowSubtext = true, + OffsetX = 2, + OffsetY = 48, + }; + + childItem.DrawArea = new Rectangle(childItem.DrawArea.Location, new Point(427, 16)); + childItem.SetPrimaryClickAction(ChildItem_Click); + childItem.SetScrollWheelHandler(this); + + AddItemToList(childItem, sortList: false); } - break; - case BoardDialogState.ViewPost: - if (_boardRepository.ActivePostMessage.Map(msg => msg != _message.Text).ValueOr(false)) - { - _boardRepository.ActivePostMessage.MatchSome(msg => _message.Text = msg); - _scrollBar.ScrollToTop(); - } - break; - } + _scrollBar.ScrollToTop(); + } - base.OnUpdateControl(gameTime); + break; + case BoardDialogState.ViewPost: + if (_boardRepository.ActivePostMessage.Map(msg => msg != _message.Text).ValueOr(false)) + { + _boardRepository.ActivePostMessage.MatchSome(msg => _message.Text = msg); + _scrollBar.ScrollToTop(); + } + break; } - private void SetState(BoardDialogState state, int postId = -1) - { - // todo: - // 1. backspace on scrolled newline is broken - // 2. need 10 rows per message for parity (increase space between rows) + base.OnUpdateControl(gameTime); + } - if (state == _state) - return; + private void SetState(BoardDialogState state, int postId = -1) + { + // todo: + // 1. backspace on scrolled newline is broken + // 2. need 10 rows per message for parity (increase space between rows) - _state = state; + if (state == _state) + return; - _titleText.DrawArea = _state == BoardDialogState.ViewList - ? GetTitleDrawArea(DialogType) - : GetTitleDrawArea(DialogType).WithPosition(new Vector2(150, _titleText.DrawArea.Y)); + _state = state; - BackgroundTextureSource = _state == BoardDialogState.ViewList - ? GetBackgroundSourceRectangle(BackgroundTexture, DialogType) - : GetBackgroundSourceRectangle(BackgroundTexture, DialogType).Value.WithPosition(new Vector2(0, BackgroundTexture.Height / 2)); + _titleText.DrawArea = _state == BoardDialogState.ViewList + ? GetTitleDrawArea(DialogType) + : GetTitleDrawArea(DialogType).WithPosition(new Vector2(150, _titleText.DrawArea.Y)); - _scrollBar.LinesToRender = _state == BoardDialogState.ViewList - ? 12 - : 10; + BackgroundTextureSource = _state == BoardDialogState.ViewList + ? GetBackgroundSourceRectangle(BackgroundTexture, DialogType) + : GetBackgroundSourceRectangle(BackgroundTexture, DialogType).Value.WithPosition(new Vector2(0, BackgroundTexture.Height / 2)); - switch (_state) - { - case BoardDialogState.ViewList: - _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Selected = true; + _scrollBar.LinesToRender = _state == BoardDialogState.ViewList + ? 12 + : 10; - Buttons = ScrollingListDialogButtons.AddCancel; - Title = _localizedStringFinder.GetString(EOResourceID.BOARD_TOWN_BOARD); - _subject.Visible = _message.Visible = false; - _subject.Selected = _message.Selected = false; + switch (_state) + { + case BoardDialogState.ViewList: + _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Selected = true; - _scrollBar.DrawArea = new Rectangle( - _scrollBar.DrawArea.X, 44, - _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType)); + Buttons = ScrollingListDialogButtons.AddCancel; + Title = _localizedStringFinder.GetString(EOResourceID.BOARD_TOWN_BOARD); + _subject.Visible = _message.Visible = false; + _subject.Selected = _message.Selected = false; - break; + _scrollBar.DrawArea = new Rectangle( + _scrollBar.DrawArea.X, 44, + _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType)); - case BoardDialogState.CreatePost: - Buttons = ScrollingListDialogButtons.OkCancel; - Title = _localizedStringFinder.GetString(EOResourceID.BOARD_POSTING_NEW_MESSAGE); + break; - _subject.Text = _message.Text = string.Empty; - _subject.Visible = _message.Visible = true; - _subject.Enabled = _message.Enabled = true; + case BoardDialogState.CreatePost: + Buttons = ScrollingListDialogButtons.OkCancel; + Title = _localizedStringFinder.GetString(EOResourceID.BOARD_POSTING_NEW_MESSAGE); - _subject.TabOrder = 0; - _message.TabOrder = 1; + _subject.Text = _message.Text = string.Empty; + _subject.Visible = _message.Visible = true; + _subject.Enabled = _message.Enabled = true; - _subject.Selected = true; + _subject.TabOrder = 0; + _message.TabOrder = 1; - _scrollBar.DrawArea = new Rectangle( - _scrollBar.DrawArea.X, 74, - _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType) - 30); + _subject.Selected = true; - ClearItemList(); - _cachedPostInfo.Clear(); - break; - - case BoardDialogState.ViewPost: - var author = _boardRepository.ActivePost.Map(x => x.Author).ValueOr(string.Empty); - var matchesAuthor = author.IndexOf(_characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase) >= 0; - if (_playerInfoProvider.PlayerHasAdminCharacter || matchesAuthor) - Buttons = ScrollingListDialogButtons.DeleteCancel; - else - Buttons = ScrollingListDialogButtons.OffsetCancel; - - _boardRepository.Posts.SingleOrNone(x => x.PostId == postId) - .MatchSome(post => - { - Title = post.Author; - _subject.Text = post.Subject; - }); + _scrollBar.DrawArea = new Rectangle( + _scrollBar.DrawArea.X, 74, + _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType) - 30); - _subject.Visible = true; - _message.Text = _localizedStringFinder.GetString(EOResourceID.BOARD_LOADING_MESSAGE); - _message.Visible = true; + ClearItemList(); + _cachedPostInfo.Clear(); + break; - _subject.Enabled = _message.Enabled = false; + case BoardDialogState.ViewPost: + var author = _boardRepository.ActivePost.Map(x => x.Author).ValueOr(string.Empty); + var matchesAuthor = author.IndexOf(_characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase) >= 0; + if (_playerInfoProvider.PlayerHasAdminCharacter || matchesAuthor) + Buttons = ScrollingListDialogButtons.DeleteCancel; + else + Buttons = ScrollingListDialogButtons.OffsetCancel; - _scrollBar.DrawArea = new Rectangle( - _scrollBar.DrawArea.X, 74, - _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType) - 30); + _boardRepository.Posts.SingleOrNone(x => x.PostId == postId) + .MatchSome(post => + { + Title = post.Author; + _subject.Text = post.Subject; + }); - ClearItemList(); - _cachedPostInfo.Clear(); - break; - } + _subject.Visible = true; + _message.Text = _localizedStringFinder.GetString(EOResourceID.BOARD_LOADING_MESSAGE); + _message.Visible = true; + + _subject.Enabled = _message.Enabled = false; + + _scrollBar.DrawArea = new Rectangle( + _scrollBar.DrawArea.X, 74, + _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType) - 30); + + ClearItemList(); + _cachedPostInfo.Clear(); + break; } + } - private void AddButton_Click(object sender, EventArgs e) + private void AddButton_Click(object sender, EventArgs e) + { + var numPostsByThisPlayer = _boardRepository.Posts.Count(x => string.Equals(x.Author, _characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase)); + if (numPostsByThisPlayer > 2) { - var numPostsByThisPlayer = _boardRepository.Posts.Count(x => string.Equals(x.Author, _characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase)); - if (numPostsByThisPlayer > 2) - { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_TOO_MANY_MESSAGES); - dlg.ShowDialog(); - } - else - { - SetState(BoardDialogState.CreatePost); - } + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_TOO_MANY_MESSAGES); + dlg.ShowDialog(); } - - private void DeleteButton_Click(object sender, MouseEventArgs e) + else { - _boardRepository.ActivePost.MatchSome(x => _boardActions.DeletePost(x.PostId)); - SetState(BoardDialogState.ViewList); + SetState(BoardDialogState.CreatePost); } + } + + private void DeleteButton_Click(object sender, MouseEventArgs e) + { + _boardRepository.ActivePost.MatchSome(x => _boardActions.DeletePost(x.PostId)); + SetState(BoardDialogState.ViewList); + } - protected override void CloseButton_Click(object sender, MouseEventArgs e) + protected override void CloseButton_Click(object sender, MouseEventArgs e) + { + if (sender == _cancel && _state == BoardDialogState.ViewList) { - if (sender == _cancel && _state == BoardDialogState.ViewList) - { - Close(XNADialogResult.Cancel); - } - else + Close(XNADialogResult.Cancel); + } + else + { + if (sender == _ok && _state == BoardDialogState.CreatePost) { - if (sender == _ok && _state == BoardDialogState.CreatePost) + if (string.IsNullOrEmpty(_message.Text)) { - if (string.IsNullOrEmpty(_message.Text)) - { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_NO_MESSAGE); - dlg.ShowDialog(); - return; - } - else if (string.IsNullOrEmpty(_subject.Text)) - { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_NO_SUBJECT); - dlg.ShowDialog(); - return; - } - - _boardActions.AddPost(_subject.Text, _message.Text); + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_NO_MESSAGE); + dlg.ShowDialog(); + return; + } + else if (string.IsNullOrEmpty(_subject.Text)) + { + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_NO_SUBJECT); + dlg.ShowDialog(); + return; } - _boardRepository.ActivePost = Option.None(); - - SetState(BoardDialogState.ViewList); + _boardActions.AddPost(_subject.Text, _message.Text); } + + _boardRepository.ActivePost = Option.None(); + + SetState(BoardDialogState.ViewList); } + } - private void ChildItem_Click(object sender, MouseEventArgs e) - { - var postId = sender is ListDialogItem itemSender - ? (int)itemSender.Data - : sender is IXNAHyperLink linkSender - ? (int)((ListDialogItem)linkSender.ImmediateParent).Data - : -1; + private void ChildItem_Click(object sender, MouseEventArgs e) + { + var postId = sender is ListDialogItem itemSender + ? (int)itemSender.Data + : sender is IXNAHyperLink linkSender + ? (int)((ListDialogItem)linkSender.ImmediateParent).Data + : -1; - if (postId >= 0) - { - _boardRepository.ActivePost = _boardRepository.Posts.SingleOrNone(x => x.PostId == postId); + if (postId >= 0) + { + _boardRepository.ActivePost = _boardRepository.Posts.SingleOrNone(x => x.PostId == postId); - SetState(BoardDialogState.ViewPost, postId); - _boardActions.ViewPost(postId); - } + SetState(BoardDialogState.ViewPost, postId); + _boardActions.ViewPost(postId); } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BookDialog.cs b/EndlessClient/Dialogs/BookDialog.cs index fef42d67f..cef4932c7 100644 --- a/EndlessClient/Dialogs/BookDialog.cs +++ b/EndlessClient/Dialogs/BookDialog.cs @@ -10,121 +10,120 @@ using XNAControls; using static EndlessClient.Dialogs.QuestStatusListDialogItem; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class BookDialog : PlayerInfoDialog { - public class BookDialog : PlayerInfoDialog - { - private readonly IPaperdollProvider _paperdollProvider; + private readonly IPaperdollProvider _paperdollProvider; - private readonly List _childItems; - private ScrollBar _scrollBar; + private readonly List _childItems; + private ScrollBar _scrollBar; - private int _lastScrollOffset; + private int _lastScrollOffset; - public BookDialog(INativeGraphicsManager graphicsManager, - IEODialogButtonService eoDialogButtonService, - IPubFileProvider pubFileProvider, - IPaperdollProvider paperdollProvider, - Character character, - bool isMainCharacter) - : base(graphicsManager, eoDialogButtonService, pubFileProvider, paperdollProvider, character, isMainCharacter) - { - _paperdollProvider = paperdollProvider; + public BookDialog(INativeGraphicsManager graphicsManager, + IEODialogButtonService eoDialogButtonService, + IPubFileProvider pubFileProvider, + IPaperdollProvider paperdollProvider, + Character character, + bool isMainCharacter) + : base(graphicsManager, eoDialogButtonService, pubFileProvider, paperdollProvider, character, isMainCharacter) + { + _paperdollProvider = paperdollProvider; - _childItems = new List(); + _childItems = new List(); - var backgroundTexture = graphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); - _scrollBar = new ScrollBar(new Vector2(188, 34), backgroundTexture, new Rectangle(303, 2, 20, 237), ScrollBarColors.DarkOnDark, graphicsManager) - { - LinesToRender = 14 - }; - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); + var backgroundTexture = graphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); + _scrollBar = new ScrollBar(new Vector2(188, 34), backgroundTexture, new Rectangle(303, 2, 20, 237), ScrollBarColors.DarkOnDark, graphicsManager) + { + LinesToRender = 14 + }; + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 69); + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 69); - CenterInGameView(); + CenterInGameView(); - if (!Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, 15); - } + if (!Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, 15); + } - public override void Initialize() - { - _scrollBar.Initialize(); + public override void Initialize() + { + _scrollBar.Initialize(); - base.Initialize(); - } + base.Initialize(); + } - protected override void OnUnconditionalUpdateControl(GameTime gameTime) + protected override void OnUnconditionalUpdateControl(GameTime gameTime) + { + if (_childItems.Count > _scrollBar.LinesToRender && _lastScrollOffset != _scrollBar.ScrollOffset) { - if (_childItems.Count > _scrollBar.LinesToRender && _lastScrollOffset != _scrollBar.ScrollOffset) - { - _lastScrollOffset = _scrollBar.ScrollOffset; + _lastScrollOffset = _scrollBar.ScrollOffset; - for (int i = 0; i < _childItems.Count; i++) - { - _childItems[i].DrawPosition = new Vector2(_childItems[i].DrawPosition.X, 42 + (i - _lastScrollOffset) * 16); - _childItems[i].Visible = (i - _lastScrollOffset) >= 0 && (i - _lastScrollOffset) < _scrollBar.LinesToRender; - } + for (int i = 0; i < _childItems.Count; i++) + { + _childItems[i].DrawPosition = new Vector2(_childItems[i].DrawPosition.X, 42 + (i - _lastScrollOffset) * 16); + _childItems[i].Visible = (i - _lastScrollOffset) >= 0 && (i - _lastScrollOffset) < _scrollBar.LinesToRender; } - - base.OnUnconditionalUpdateControl(gameTime); } - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + base.OnUnconditionalUpdateControl(gameTime); + } - var iconTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - _spriteBatch.Begin(); + var iconTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); - for (int i = 0; i < Math.Min(_childItems.Count, _scrollBar.LinesToRender); i++) - { - _spriteBatch.Draw(iconTexture, DrawPositionWithParentOffset + new Vector2(26, 41 + i * 16), GetIconSourceRectangle(QuestStatusIcon.None2), Color.White); - } + _spriteBatch.Begin(); - _spriteBatch.End(); + for (int i = 0; i < Math.Min(_childItems.Count, _scrollBar.LinesToRender); i++) + { + _spriteBatch.Draw(iconTexture, DrawPositionWithParentOffset + new Vector2(26, 41 + i * 16), GetIconSourceRectangle(QuestStatusIcon.None2), Color.White); } - protected override void UpdateDisplayedData(PaperdollData paperdollData) - { - base.UpdateDisplayedData(paperdollData); + _spriteBatch.End(); + } + + protected override void UpdateDisplayedData(PaperdollData paperdollData) + { + base.UpdateDisplayedData(paperdollData); - foreach (var item in _childItems) - item.Dispose(); + foreach (var item in _childItems) + item.Dispose(); - _childItems.Clear(); + _childItems.Clear(); - for (int i = 0; i < paperdollData.QuestNames.Count; i++) + for (int i = 0; i < paperdollData.QuestNames.Count; i++) + { + var quest = paperdollData.QuestNames[i]; + + var nextLabel = new XNALabel(Constants.FontSize08pt5) { - var quest = paperdollData.QuestNames[i]; - - var nextLabel = new XNALabel(Constants.FontSize08pt5) - { - Text = quest, - ForeColor = ColorConstants.LightGrayText, - AutoSize = true, - DrawPosition = new Vector2(50, 42 + i * 16), - Visible = i < _scrollBar.LinesToRender - }; - nextLabel.SetScrollWheelHandler(_scrollBar); - nextLabel.ResizeBasedOnText(); - nextLabel.SetParentControl(this); - nextLabel.Initialize(); - - _childItems.Add(nextLabel); - } + Text = quest, + ForeColor = ColorConstants.LightGrayText, + AutoSize = true, + DrawPosition = new Vector2(50, 42 + i * 16), + Visible = i < _scrollBar.LinesToRender + }; + nextLabel.SetScrollWheelHandler(_scrollBar); + nextLabel.ResizeBasedOnText(); + nextLabel.SetParentControl(this); + nextLabel.Initialize(); - _scrollBar.ScrollToTop(); - _scrollBar.UpdateDimensions(paperdollData.QuestNames.Count); + _childItems.Add(nextLabel); } - // copied from QuestStatusListDialogItem - private static Rectangle GetIconSourceRectangle(QuestStatusIcon index) - { - return new Rectangle((int)index * 15, 0, 15, 15); - } + _scrollBar.ScrollToTop(); + _scrollBar.UpdateDimensions(paperdollData.QuestNames.Count); + } + + // copied from QuestStatusListDialogItem + private static Rectangle GetIconSourceRectangle(QuestStatusIcon index) + { + return new Rectangle((int)index * 15, 0, 15, 15); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ChangePasswordDialog.cs b/EndlessClient/Dialogs/ChangePasswordDialog.cs index 37089edbe..dd53ec096 100644 --- a/EndlessClient/Dialogs/ChangePasswordDialog.cs +++ b/EndlessClient/Dialogs/ChangePasswordDialog.cs @@ -14,130 +14,129 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class ChangePasswordDialog : BaseEODialog { - public class ChangePasswordDialog : BaseEODialog + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; + private readonly IXNATextBox[] _inputBoxes; + private readonly IXNAButton _ok, _cancel; + + private string Username => _inputBoxes[0].Text; + private string OldPassword => _inputBoxes[1].Text; + private string NewPassword => _inputBoxes[2].Text; + private string ConfirmPassword => _inputBoxes[3].Text; + + public IChangePasswordParameters Result => new ChangePasswordParameters(Username, OldPassword, NewPassword); + + public ChangePasswordDialog(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IContentProvider contentProvider, + IEOMessageBoxFactory eoMessageBoxFactory, + IPlayerInfoProvider playerInfoProvider, + IEODialogButtonService dialogButtonService, + IXnaControlSoundMapper xnaControlSoundMapper) + : base(nativeGraphicsManager, gameStateProvider) { - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - private readonly IXNATextBox[] _inputBoxes; - private readonly IXNAButton _ok, _cancel; - - private string Username => _inputBoxes[0].Text; - private string OldPassword => _inputBoxes[1].Text; - private string NewPassword => _inputBoxes[2].Text; - private string ConfirmPassword => _inputBoxes[3].Text; - - public IChangePasswordParameters Result => new ChangePasswordParameters(Username, OldPassword, NewPassword); - - public ChangePasswordDialog(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IContentProvider contentProvider, - IEOMessageBoxFactory eoMessageBoxFactory, - IPlayerInfoProvider playerInfoProvider, - IEODialogButtonService dialogButtonService, - IXnaControlSoundMapper xnaControlSoundMapper) - : base(nativeGraphicsManager, gameStateProvider) - { - _eoMessageBoxFactory = eoMessageBoxFactory; - _playerInfoProvider = playerInfoProvider; - _xnaControlSoundMapper = xnaControlSoundMapper; + _eoMessageBoxFactory = eoMessageBoxFactory; + _playerInfoProvider = playerInfoProvider; + _xnaControlSoundMapper = xnaControlSoundMapper; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 21); + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 21); - var cursorTexture = contentProvider.Textures[ContentProvider.Cursor]; + var cursorTexture = contentProvider.Textures[ContentProvider.Cursor]; - _inputBoxes = new IXNATextBox[4]; - for (int i = 0; i < _inputBoxes.Length; ++i) + _inputBoxes = new IXNATextBox[4]; + for (int i = 0; i < _inputBoxes.Length; ++i) + { + var tb = new XNATextBox(new Rectangle(198, 60 + i * 30, 137, 19), Constants.FontSize08, caretTexture: cursorTexture) { - var tb = new XNATextBox(new Rectangle(198, 60 + i * 30, 137, 19), Constants.FontSize08, caretTexture: cursorTexture) - { - LeftPadding = 5, - DefaultText = " ", - MaxChars = i == 0 ? 16 : 12, - PasswordBox = i > 1, - TextColor = ColorConstants.LightBeigeText, - TabOrder = i + 1, - }; - _inputBoxes[i] = tb; - } - - _inputBoxes[0].Selected = true; - - _ok = new XNAButton( - dialogButtonService.SmallButtonSheet, - new Vector2(157, 195), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - _ok.OnClick += OnButtonPressed; - - _cancel = new XNAButton( - dialogButtonService.SmallButtonSheet, - new Vector2(250, 195), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); - - CenterInGameView(); + LeftPadding = 5, + DefaultText = " ", + MaxChars = i == 0 ? 16 : 12, + PasswordBox = i > 1, + TextColor = ColorConstants.LightBeigeText, + TabOrder = i + 1, + }; + _inputBoxes[i] = tb; } - public override void Initialize() - { - foreach (var tb in _inputBoxes) - { - tb.Initialize(); - tb.SetParentControl(this); - _xnaControlSoundMapper.BindSoundToControl(tb); - } + _inputBoxes[0].Selected = true; - _ok.Initialize(); - _ok.SetParentControl(this); - _xnaControlSoundMapper.BindSoundToControl(_ok, Option.Some(Audio.SoundEffectID.DialogButtonClick)); + _ok = new XNAButton( + dialogButtonService.SmallButtonSheet, + new Vector2(157, 195), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + _ok.OnClick += OnButtonPressed; - _cancel.Initialize(); - _cancel.SetParentControl(this); - _xnaControlSoundMapper.BindSoundToControl(_cancel, Option.Some(Audio.SoundEffectID.DialogButtonClick)); + _cancel = new XNAButton( + dialogButtonService.SmallButtonSheet, + new Vector2(250, 195), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); - base.Initialize(); - } + CenterInGameView(); + } - private void OnButtonPressed(object sender, EventArgs e) + public override void Initialize() + { + foreach (var tb in _inputBoxes) { - if (_inputBoxes.Any(tb => string.IsNullOrWhiteSpace(tb.Text))) - { - return; - } + tb.Initialize(); + tb.SetParentControl(this); + _xnaControlSoundMapper.BindSoundToControl(tb); + } - if (Username != _playerInfoProvider.LoggedInAccountName) - { - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHANGE_PASSWORD_MISMATCH); - messageBox.ShowDialog(); - return; - } + _ok.Initialize(); + _ok.SetParentControl(this); + _xnaControlSoundMapper.BindSoundToControl(_ok, Option.Some(Audio.SoundEffectID.DialogButtonClick)); - if (OldPassword != _playerInfoProvider.PlayerPassword) - { - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHANGE_PASSWORD_MISMATCH); - messageBox.ShowDialog(); - return; - } + _cancel.Initialize(); + _cancel.SetParentControl(this); + _xnaControlSoundMapper.BindSoundToControl(_cancel, Option.Some(Audio.SoundEffectID.DialogButtonClick)); - if (NewPassword != ConfirmPassword) - { - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ACCOUNT_CREATE_PASSWORD_MISMATCH); - messageBox.ShowDialog(); - return; - } + base.Initialize(); + } - if (NewPassword.Length < 6) - { - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ACCOUNT_CREATE_PASSWORD_TOO_SHORT); - messageBox.ShowDialog(); - return; - } + private void OnButtonPressed(object sender, EventArgs e) + { + if (_inputBoxes.Any(tb => string.IsNullOrWhiteSpace(tb.Text))) + { + return; + } + + if (Username != _playerInfoProvider.LoggedInAccountName) + { + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHANGE_PASSWORD_MISMATCH); + messageBox.ShowDialog(); + return; + } + + if (OldPassword != _playerInfoProvider.PlayerPassword) + { + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHANGE_PASSWORD_MISMATCH); + messageBox.ShowDialog(); + return; + } - Close(XNADialogResult.OK); + if (NewPassword != ConfirmPassword) + { + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ACCOUNT_CREATE_PASSWORD_MISMATCH); + messageBox.ShowDialog(); + return; } + + if (NewPassword.Length < 6) + { + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ACCOUNT_CREATE_PASSWORD_TOO_SHORT); + messageBox.ShowDialog(); + return; + } + + Close(XNADialogResult.OK); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ChestDialog.cs b/EndlessClient/Dialogs/ChestDialog.cs index 7cd10cab2..3db9fd8e3 100644 --- a/EndlessClient/Dialogs/ChestDialog.cs +++ b/EndlessClient/Dialogs/ChestDialog.cs @@ -17,107 +17,106 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class ChestDialog : ScrollingListDialog { - public class ChestDialog : ScrollingListDialog - { - private readonly IChestActions _chestActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - private readonly IChestDataProvider _chestDataProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICharacterProvider _characterProvider; + private readonly IChestActions _chestActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IMapItemGraphicProvider _mapItemGraphicProvider; + private readonly IChestDataProvider _chestDataProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICharacterProvider _characterProvider; - private HashSet _cachedItems; + private HashSet _cachedItems; - public ChestDialog(INativeGraphicsManager nativeGraphicsManager, - IChestActions chestActions, - IEOMessageBoxFactory messageBoxFactory, - IEODialogButtonService dialogButtonService, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - IInventorySpaceValidator inventorySpaceValidator, - IMapItemGraphicProvider mapItemGraphicProvider, - IChestDataProvider chestDataProvider, - IEIFFileProvider eifFileProvider, - ICharacterProvider characterProvider) - : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.Chest) - { - _chestActions = chestActions; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _inventorySpaceValidator = inventorySpaceValidator; - _mapItemGraphicProvider = mapItemGraphicProvider; - _chestDataProvider = chestDataProvider; - _eifFileProvider = eifFileProvider; - _characterProvider = characterProvider; + public ChestDialog(INativeGraphicsManager nativeGraphicsManager, + IChestActions chestActions, + IEOMessageBoxFactory messageBoxFactory, + IEODialogButtonService dialogButtonService, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + IInventorySpaceValidator inventorySpaceValidator, + IMapItemGraphicProvider mapItemGraphicProvider, + IChestDataProvider chestDataProvider, + IEIFFileProvider eifFileProvider, + ICharacterProvider characterProvider) + : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.Chest) + { + _chestActions = chestActions; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _inventorySpaceValidator = inventorySpaceValidator; + _mapItemGraphicProvider = mapItemGraphicProvider; + _chestDataProvider = chestDataProvider; + _eifFileProvider = eifFileProvider; + _characterProvider = characterProvider; - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.Cancel; + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.Cancel; - _cachedItems = new HashSet(); + _cachedItems = new HashSet(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - EOResourceID.STATUS_LABEL_CHEST_YOU_OPENED, - " " + _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_DRAG_AND_DROP_ITEMS)); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + EOResourceID.STATUS_LABEL_CHEST_YOU_OPENED, + " " + _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_DRAG_AND_DROP_ITEMS)); + } - protected override void OnUpdateControl(GameTime gameTime) + protected override void OnUpdateControl(GameTime gameTime) + { + if (!_cachedItems.SetEquals(_chestDataProvider.Items)) { - if (!_cachedItems.SetEquals(_chestDataProvider.Items)) - { - _cachedItems = _chestDataProvider.Items.ToHashSet(); - RefreshItemList(); - } - - base.OnUpdateControl(gameTime); + _cachedItems = _chestDataProvider.Items.ToHashSet(); + RefreshItemList(); } - private void RefreshItemList() - { - ClearItemList(); + base.OnUpdateControl(gameTime); + } - foreach (var item in _cachedItems) + private void RefreshItemList() + { + ClearItemList(); + + foreach (var item in _cachedItems) + { + var itemData = _eifFileProvider.EIFFile[item.ItemID]; + string subText = + $"x {item.Amount} " + + $"{(itemData.Type == ItemType.Armor ? "(" + _localizedStringFinder.GetString(EOResourceID.FEMALE - itemData.Gender) + ")" : "")}"; + var nextItem = new ListDialogItem(this, ListItemType) { - var itemData = _eifFileProvider.EIFFile[item.ItemID]; - string subText = - $"x {item.Amount} " + - $"{(itemData.Type == ItemType.Armor ? "(" + _localizedStringFinder.GetString(EOResourceID.FEMALE - itemData.Gender) + ")" : "")}"; - var nextItem = new ListDialogItem(this, ListItemType) - { - PrimaryText = itemData.Name, - SubText = subText, - IconGraphic = _mapItemGraphicProvider.GetItemGraphic(item.ItemID, item.Amount), - ShowIconBackGround = true, - }; - nextItem.RightClick += (_, _) => TakeItem(item, itemData); + PrimaryText = itemData.Name, + SubText = subText, + IconGraphic = _mapItemGraphicProvider.GetItemGraphic(item.ItemID, item.Amount), + ShowIconBackGround = true, + }; + nextItem.RightClick += (_, _) => TakeItem(item, itemData); - AddItemToList(nextItem, sortList: false); - } + AddItemToList(nextItem, sortList: false); } + } - private void TakeItem(ChestItem item, EIFRecord itemData) + private void TakeItem(ChestItem item, EIFRecord itemData) + { + if (!_inventorySpaceValidator.ItemFits(item.ItemID)) { - if (!_inventorySpaceValidator.ItemFits(item.ItemID)) - { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); - } - else if (itemData.Weight * item.Amount + _characterProvider.MainCharacter.Stats[CharacterStat.Weight] > _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]) - { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); - } - else - { - _chestActions.TakeItemFromChest(item.ItemID); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); + } + else if (itemData.Weight * item.Amount + _characterProvider.MainCharacter.Stats[CharacterStat.Weight] > _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]) + { + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + } + else + { + _chestActions.TakeItemFromChest(item.ItemID); } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/CreateCharacterDialog.cs b/EndlessClient/Dialogs/CreateCharacterDialog.cs index 3a46497ff..f104246c6 100644 --- a/EndlessClient/Dialogs/CreateCharacterDialog.cs +++ b/EndlessClient/Dialogs/CreateCharacterDialog.cs @@ -14,179 +14,178 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class CreateCharacterDialog : BaseEODialog { - public class CreateCharacterDialog : BaseEODialog + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; + private readonly IXNATextBox _inputBox; + private readonly IXNAButton[] _arrowButtons = new IXNAButton[4]; + + private readonly IXNAButton _ok, _cancel; + + private readonly CreateCharacterControl _characterControl; + + private readonly Rectangle[] _srcRectangles = new Rectangle[4]; + private readonly Texture2D _charCreateSheet; + + public string Name => _inputBox.Text.Trim(); + + private CharacterRenderProperties RenderProperties => _characterControl.RenderProperties; + public int Gender => RenderProperties.Gender; + public int HairStyle => RenderProperties.HairStyle; + public int HairColor => RenderProperties.HairColor; + public int Race => RenderProperties.Race; + + public CreateCharacterDialog( + INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + ICharacterRendererFactory rendererFactory, + IContentProvider contentProvider, + IEOMessageBoxFactory messageBoxFactory, + IEODialogButtonService eoDialogButtonService, + IXnaControlSoundMapper xnaControlSoundMapper) + : base(nativeGraphicsManager, gameStateProvider) { - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - private readonly IXNATextBox _inputBox; - private readonly IXNAButton[] _arrowButtons = new IXNAButton[4]; - - private readonly IXNAButton _ok, _cancel; - - private readonly CreateCharacterControl _characterControl; - - private readonly Rectangle[] _srcRectangles = new Rectangle[4]; - private readonly Texture2D _charCreateSheet; - - public string Name => _inputBox.Text.Trim(); - - private CharacterRenderProperties RenderProperties => _characterControl.RenderProperties; - public int Gender => RenderProperties.Gender; - public int HairStyle => RenderProperties.HairStyle; - public int HairColor => RenderProperties.HairColor; - public int Race => RenderProperties.Race; - - public CreateCharacterDialog( - INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - ICharacterRendererFactory rendererFactory, - IContentProvider contentProvider, - IEOMessageBoxFactory messageBoxFactory, - IEODialogButtonService eoDialogButtonService, - IXnaControlSoundMapper xnaControlSoundMapper) - : base(nativeGraphicsManager, gameStateProvider) + _messageBoxFactory = messageBoxFactory; + _xnaControlSoundMapper = xnaControlSoundMapper; + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 20); + + _charCreateSheet = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 22); + + var cursorTexture = contentProvider.Textures[ContentProvider.Cursor]; + _inputBox = new XNATextBox(new Rectangle(80, 57, 138, 19), Constants.FontSize08, caretTexture: cursorTexture) + { + LeftPadding = 5, + DefaultText = " ", + Text = " ", + MaxChars = 12, + Selected = true, + TextColor = ColorConstants.LightBeigeText, + Visible = true + }; + _inputBox.SetParentControl(this); + _inputBox.Selected = true; + + for (int i = 0; i < _arrowButtons.Length; ++i) { - _messageBoxFactory = messageBoxFactory; - _xnaControlSoundMapper = xnaControlSoundMapper; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 20); - - _charCreateSheet = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 22); - - var cursorTexture = contentProvider.Textures[ContentProvider.Cursor]; - _inputBox = new XNATextBox(new Rectangle(80, 57, 138, 19), Constants.FontSize08, caretTexture: cursorTexture) - { - LeftPadding = 5, - DefaultText = " ", - Text = " ", - MaxChars = 12, - Selected = true, - TextColor = ColorConstants.LightBeigeText, - Visible = true - }; - _inputBox.SetParentControl(this); - _inputBox.Selected = true; - - for (int i = 0; i < _arrowButtons.Length; ++i) - { - var btn = new XNAButton(_charCreateSheet, - new Vector2(196, 85 + i * 26), - new Rectangle(185, 38, 19, 19), - new Rectangle(206, 38, 19, 19)); - btn.OnClick += ArrowButtonClick; - btn.SetParentControl(this); - _arrowButtons[i] = btn; - } - - _characterControl = new CreateCharacterControl(rendererFactory) - { - DrawPosition = new Vector2(235, 58) - }; - _characterControl.SetParentControl(this); - - _srcRectangles[0] = new Rectangle(0, 38, 23, 19); - _srcRectangles[1] = new Rectangle(0, 19, 23, 19); - _srcRectangles[2] = new Rectangle(0, 0, 23, 19); - _srcRectangles[3] = new Rectangle(46, 38, 23, 19); - - _ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(157, 195), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - _ok.OnClick += (s, e) => ClickOk(); - _ok.SetParentControl(this); - - _cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(250, 195), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); - _cancel.SetParentControl(this); - - CenterInGameView(); + var btn = new XNAButton(_charCreateSheet, + new Vector2(196, 85 + i * 26), + new Rectangle(185, 38, 19, 19), + new Rectangle(206, 38, 19, 19)); + btn.OnClick += ArrowButtonClick; + btn.SetParentControl(this); + _arrowButtons[i] = btn; } - public override void Initialize() + _characterControl = new CreateCharacterControl(rendererFactory) { - _characterControl.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_characterControl); + DrawPosition = new Vector2(235, 58) + }; + _characterControl.SetParentControl(this); + + _srcRectangles[0] = new Rectangle(0, 38, 23, 19); + _srcRectangles[1] = new Rectangle(0, 19, 23, 19); + _srcRectangles[2] = new Rectangle(0, 0, 23, 19); + _srcRectangles[3] = new Rectangle(46, 38, 23, 19); + + _ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(157, 195), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + _ok.OnClick += (s, e) => ClickOk(); + _ok.SetParentControl(this); + + _cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(250, 195), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); + _cancel.SetParentControl(this); + + CenterInGameView(); + } - _inputBox.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_inputBox); + public override void Initialize() + { + _characterControl.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_characterControl); - foreach (var button in _arrowButtons) - { - button.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(button, Option.Some(Audio.SoundEffectID.TextBoxFocus)); - } + _inputBox.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_inputBox); - _ok.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_ok, Option.Some(Audio.SoundEffectID.DialogButtonClick)); + foreach (var button in _arrowButtons) + { + button.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(button, Option.Some(Audio.SoundEffectID.TextBoxFocus)); + } - _cancel.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_cancel, Option.Some(Audio.SoundEffectID.DialogButtonClick)); + _ok.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_ok, Option.Some(Audio.SoundEffectID.DialogButtonClick)); - base.Initialize(); - } + _cancel.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_cancel, Option.Some(Audio.SoundEffectID.DialogButtonClick)); - protected override void OnDrawControl(GameTime gt) - { - base.OnDrawControl(gt); + base.Initialize(); + } - _spriteBatch.Begin(); + protected override void OnDrawControl(GameTime gt) + { + base.OnDrawControl(gt); - for (int i = 0; i < 4; ++i) - { - _spriteBatch.Draw(_charCreateSheet, - new Vector2(170 + DrawPositionWithParentOffset.X, - 84 + i * 27 + DrawPositionWithParentOffset.Y), - _srcRectangles[i], Color.White); - } + _spriteBatch.Begin(); - _spriteBatch.End(); + for (int i = 0; i < 4; ++i) + { + _spriteBatch.Draw(_charCreateSheet, + new Vector2(170 + DrawPositionWithParentOffset.X, + 84 + i * 27 + DrawPositionWithParentOffset.Y), + _srcRectangles[i], Color.White); } - private void ArrowButtonClick(object sender, EventArgs e) + _spriteBatch.End(); + } + + private void ArrowButtonClick(object sender, EventArgs e) + { + if (sender == _arrowButtons[0]) + { + _characterControl.NextGender(); + _srcRectangles[0] = new Rectangle(0 + 23 * RenderProperties.Gender, 38, 23, 19); + } + else if (sender == _arrowButtons[1]) { - if (sender == _arrowButtons[0]) - { - _characterControl.NextGender(); - _srcRectangles[0] = new Rectangle(0 + 23 * RenderProperties.Gender, 38, 23, 19); - } - else if (sender == _arrowButtons[1]) - { + _characterControl.NextHairStyle(); + if (RenderProperties.HairStyle == 0) //skip bald _characterControl.NextHairStyle(); - if (RenderProperties.HairStyle == 0) //skip bald - _characterControl.NextHairStyle(); - - _srcRectangles[1] = new Rectangle(0 + 23 * (RenderProperties.HairStyle - 1), 19, 23, 19); - } - else if (sender == _arrowButtons[2]) - { - _characterControl.NextHairColor(); - _srcRectangles[2] = new Rectangle(0 + 23 * RenderProperties.HairColor, 0, 23, 19); - } - else if (sender == _arrowButtons[3]) - { - _characterControl.NextRace(); - _srcRectangles[3] = new Rectangle(46 + 23 * RenderProperties.Race, 38, 23, 19); - } + + _srcRectangles[1] = new Rectangle(0 + 23 * (RenderProperties.HairStyle - 1), 19, 23, 19); + } + else if (sender == _arrowButtons[2]) + { + _characterControl.NextHairColor(); + _srcRectangles[2] = new Rectangle(0 + 23 * RenderProperties.HairColor, 0, 23, 19); } + else if (sender == _arrowButtons[3]) + { + _characterControl.NextRace(); + _srcRectangles[3] = new Rectangle(46 + 23 * RenderProperties.Race, 38, 23, 19); + } + } - private void ClickOk() + private void ClickOk() + { + if (_inputBox.Text.Length < 4) + { + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CHARACTER_CREATE_NAME_TOO_SHORT, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } + else { - if (_inputBox.Text.Length < 4) - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CHARACTER_CREATE_NAME_TOO_SHORT, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } - else - { - Close(XNADialogResult.OK); - } + Close(XNADialogResult.OK); } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/EODialogButton.cs b/EndlessClient/Dialogs/EODialogButton.cs index e065433f5..c55232e46 100644 --- a/EndlessClient/Dialogs/EODialogButton.cs +++ b/EndlessClient/Dialogs/EODialogButton.cs @@ -1,9 +1,8 @@ -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public enum EODialogButtons { - public enum EODialogButtons - { - Ok, - Cancel, - OkCancel, - } + Ok, + Cancel, + OkCancel, } \ No newline at end of file diff --git a/EndlessClient/Dialogs/EOMessageBox.cs b/EndlessClient/Dialogs/EOMessageBox.cs index a5889e812..aa1084ee6 100644 --- a/EndlessClient/Dialogs/EOMessageBox.cs +++ b/EndlessClient/Dialogs/EOMessageBox.cs @@ -6,124 +6,123 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public enum EOMessageBoxStyle { - public enum EOMessageBoxStyle - { - SmallDialogLargeHeader, - SmallDialogSmallHeader, - LargeDialogSmallHeader - } + SmallDialogLargeHeader, + SmallDialogSmallHeader, + LargeDialogSmallHeader +} - public class EOMessageBox : BaseEODialog +public class EOMessageBox : BaseEODialog +{ + private readonly IXNALabel _messageLabel, _captionLabel; + private readonly IXNAButton _ok, _cancel; + + public EOMessageBox(INativeGraphicsManager graphicsManager, + IGameStateProvider gameStateProvider, + IEODialogButtonService eoDialogButtonService, + string message, + string caption = "", + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader, + EODialogButtons whichButtons = EODialogButtons.Ok) + : base(graphicsManager, gameStateProvider) { - private readonly IXNALabel _messageLabel, _captionLabel; - private readonly IXNAButton _ok, _cancel; - - public EOMessageBox(INativeGraphicsManager graphicsManager, - IGameStateProvider gameStateProvider, - IEODialogButtonService eoDialogButtonService, - string message, - string caption = "", - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader, - EODialogButtons whichButtons = EODialogButtons.Ok) - : base(graphicsManager, gameStateProvider) + var useSmallHeader = style != EOMessageBoxStyle.SmallDialogLargeHeader; + + int graphic; + switch (style) { - var useSmallHeader = style != EOMessageBoxStyle.SmallDialogLargeHeader; + case EOMessageBoxStyle.SmallDialogLargeHeader: graphic = 18; break; + case EOMessageBoxStyle.SmallDialogSmallHeader: graphic = 23; break; + case EOMessageBoxStyle.LargeDialogSmallHeader: graphic = 25; break; + default: throw new ArgumentOutOfRangeException(nameof(style), "Unrecognized dialog style!"); + } - int graphic; - switch (style) - { - case EOMessageBoxStyle.SmallDialogLargeHeader: graphic = 18; break; - case EOMessageBoxStyle.SmallDialogSmallHeader: graphic = 23; break; - case EOMessageBoxStyle.LargeDialogSmallHeader: graphic = 25; break; - default: throw new ArgumentOutOfRangeException(nameof(style), "Unrecognized dialog style!"); - } + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, graphic); - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, graphic); + _messageLabel = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + ForeColor = ColorConstants.LightGrayDialogMessage, + Text = message, + TextWidth = 254, + DrawPosition = new Vector2(19, useSmallHeader ? 40 : 62), + WrapBehavior = WrapBehavior.WrapToNewLine, + }; - _messageLabel = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - ForeColor = ColorConstants.LightGrayDialogMessage, - Text = message, - TextWidth = 254, - DrawPosition = new Vector2(19, useSmallHeader ? 40 : 62), - WrapBehavior = WrapBehavior.WrapToNewLine, - }; + _messageLabel.SetParentControl(this); - _messageLabel.SetParentControl(this); + _captionLabel = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + ForeColor = ColorConstants.LightYellowText, + Text = caption, + TextWidth = 254, + DrawPosition = useSmallHeader ? new Vector2(18, 12) : new Vector2(60, 27) + }; + _captionLabel.SetParentControl(this); + + var smallButtonSheet = eoDialogButtonService.SmallButtonSheet; + var okOut = eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok); + var okOver = eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok); + var cancelOut = eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel); + var cancelOver = eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel); + + switch (whichButtons) + { + case EODialogButtons.Ok: + _ok = new XNAButton(smallButtonSheet, new Vector2(181, 113), okOut, okOver); + _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); + _ok.SetParentControl(this); + break; + case EODialogButtons.Cancel: + _cancel = new XNAButton(smallButtonSheet, new Vector2(181, 113), cancelOut, cancelOver); + _cancel.OnClick += (sender, e) => Close(XNADialogResult.Cancel); + _cancel.SetParentControl(this); + break; + case EODialogButtons.OkCancel: + //implement this more fully when it is needed + //update draw location of ok button to be on left? + _ok = new XNAButton(smallButtonSheet, new Vector2(89, 113), okOut, okOver); + _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); + _ok.SetParentControl(this); + + _cancel = new XNAButton(smallButtonSheet, new Vector2(181, 113), cancelOut, cancelOver); + _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); + _cancel.SetParentControl(this); + break; + } - _captionLabel = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - ForeColor = ColorConstants.LightYellowText, - Text = caption, - TextWidth = 254, - DrawPosition = useSmallHeader ? new Vector2(18, 12) : new Vector2(60, 27) - }; - _captionLabel.SetParentControl(this); - - var smallButtonSheet = eoDialogButtonService.SmallButtonSheet; - var okOut = eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok); - var okOver = eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok); - var cancelOut = eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel); - var cancelOver = eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel); - - switch (whichButtons) + if (useSmallHeader) + { + if (_ok != null) { - case EODialogButtons.Ok: - _ok = new XNAButton(smallButtonSheet, new Vector2(181, 113), okOut, okOver); - _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); - _ok.SetParentControl(this); - break; - case EODialogButtons.Cancel: - _cancel = new XNAButton(smallButtonSheet, new Vector2(181, 113), cancelOut, cancelOver); - _cancel.OnClick += (sender, e) => Close(XNADialogResult.Cancel); - _cancel.SetParentControl(this); - break; - case EODialogButtons.OkCancel: - //implement this more fully when it is needed - //update draw location of ok button to be on left? - _ok = new XNAButton(smallButtonSheet, new Vector2(89, 113), okOut, okOver); - _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); - _ok.SetParentControl(this); - - _cancel = new XNAButton(smallButtonSheet, new Vector2(181, 113), cancelOut, cancelOver); - _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); - _cancel.SetParentControl(this); - break; + _ok.DrawPosition = new Vector2(_ok.DrawPosition.X, + style == EOMessageBoxStyle.SmallDialogSmallHeader ? 82 : 148); } - if (useSmallHeader) + if (_cancel != null) { - if (_ok != null) - { - _ok.DrawPosition = new Vector2(_ok.DrawPosition.X, - style == EOMessageBoxStyle.SmallDialogSmallHeader ? 82 : 148); - } - - if (_cancel != null) - { - _cancel.DrawPosition = new Vector2(_cancel.DrawPosition.X, - style == EOMessageBoxStyle.SmallDialogSmallHeader ? 82 : 148); - } + _cancel.DrawPosition = new Vector2(_cancel.DrawPosition.X, + style == EOMessageBoxStyle.SmallDialogSmallHeader ? 82 : 148); } - - CenterInGameView(); } - public override void Initialize() - { - _messageLabel.Initialize(); - _captionLabel.Initialize(); + CenterInGameView(); + } - if (_ok != null) - _ok.Initialize(); - if (_cancel != null) - _cancel.Initialize(); + public override void Initialize() + { + _messageLabel.Initialize(); + _captionLabel.Initialize(); - base.Initialize(); - } + if (_ok != null) + _ok.Initialize(); + if (_cancel != null) + _cancel.Initialize(); + + base.Initialize(); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs b/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs index fe2f63539..54603a0a5 100644 --- a/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs +++ b/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs @@ -2,31 +2,30 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.Dialogs.Extensions +namespace EndlessClient.Dialogs.Extensions; + +public static class EquipLocationExtensions { - public static class EquipLocationExtensions + public static Rectangle GetEquipLocationRectangle(this EquipLocation loc) { - public static Rectangle GetEquipLocationRectangle(this EquipLocation loc) + switch (loc) { - switch (loc) - { - case EquipLocation.Boots: return new Rectangle(87, 220, 56, 54); - case EquipLocation.Accessory: return new Rectangle(55, 250, 23, 23); - case EquipLocation.Gloves: return new Rectangle(22, 188, 56, 54); - case EquipLocation.Belt: return new Rectangle(87, 188, 56, 23); - case EquipLocation.Armor: return new Rectangle(86, 82, 56, 98); - case EquipLocation.Necklace: return new Rectangle(152, 51, 56, 23); - case EquipLocation.Hat: return new Rectangle(87, 21, 56, 54); - case EquipLocation.Shield: return new Rectangle(152, 82, 56, 98); - case EquipLocation.Weapon: return new Rectangle(22, 82, 56, 98); - case EquipLocation.Ring1: return new Rectangle(152, 190, 23, 23); - case EquipLocation.Ring2: return new Rectangle(185, 190, 23, 23); - case EquipLocation.Armlet1: return new Rectangle(152, 220, 23, 23); - case EquipLocation.Armlet2: return new Rectangle(185, 220, 23, 23); - case EquipLocation.Bracer1: return new Rectangle(152, 250, 23, 23); - case EquipLocation.Bracer2: return new Rectangle(185, 250, 23, 23); - default: throw new ArgumentOutOfRangeException(nameof(loc), "That is not a valid equipment location"); - } + case EquipLocation.Boots: return new Rectangle(87, 220, 56, 54); + case EquipLocation.Accessory: return new Rectangle(55, 250, 23, 23); + case EquipLocation.Gloves: return new Rectangle(22, 188, 56, 54); + case EquipLocation.Belt: return new Rectangle(87, 188, 56, 23); + case EquipLocation.Armor: return new Rectangle(86, 82, 56, 98); + case EquipLocation.Necklace: return new Rectangle(152, 51, 56, 23); + case EquipLocation.Hat: return new Rectangle(87, 21, 56, 54); + case EquipLocation.Shield: return new Rectangle(152, 82, 56, 98); + case EquipLocation.Weapon: return new Rectangle(22, 82, 56, 98); + case EquipLocation.Ring1: return new Rectangle(152, 190, 23, 23); + case EquipLocation.Ring2: return new Rectangle(185, 190, 23, 23); + case EquipLocation.Armlet1: return new Rectangle(152, 220, 23, 23); + case EquipLocation.Armlet2: return new Rectangle(185, 220, 23, 23); + case EquipLocation.Bracer1: return new Rectangle(152, 250, 23, 23); + case EquipLocation.Bracer2: return new Rectangle(185, 250, 23, 23); + default: throw new ArgumentOutOfRangeException(nameof(loc), "That is not a valid equipment location"); } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs b/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs index ca9207f4d..7dc3a0077 100644 --- a/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs @@ -8,70 +8,69 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class BankAccountDialogFactory : IBankAccountDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IBankActions _bankActions; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IItemTransferDialogFactory _itemTransferDialogFactory; - private readonly IHudControlProvider _hudControlProvider; - private readonly IBankDataProvider _bankDataProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEIFFileProvider _eifFileProvider; +namespace EndlessClient.Dialogs.Factories; - public BankAccountDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IBankActions bankActions, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - IItemTransferDialogFactory itemTransferDialogFactory, - IHudControlProvider hudControlProvider, - IBankDataProvider bankDataProvider, - ICharacterInventoryProvider characterInventoryProvider, - IEIFFileProvider eifFileProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _bankActions = bankActions; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _itemTransferDialogFactory = itemTransferDialogFactory; - _hudControlProvider = hudControlProvider; - _bankDataProvider = bankDataProvider; - _characterInventoryProvider = characterInventoryProvider; - _eifFileProvider = eifFileProvider; - } +[AutoMappedType] +public class BankAccountDialogFactory : IBankAccountDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IBankActions _bankActions; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IItemTransferDialogFactory _itemTransferDialogFactory; + private readonly IHudControlProvider _hudControlProvider; + private readonly IBankDataProvider _bankDataProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEIFFileProvider _eifFileProvider; - public BankAccountDialog Create() - { - return new BankAccountDialog(_nativeGraphicsManager, - _bankActions, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _statusLabelSetter, - _messageBoxFactory, - _itemTransferDialogFactory, - _hudControlProvider, - _bankDataProvider, - _characterInventoryProvider, - _eifFileProvider); - } + public BankAccountDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IBankActions bankActions, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + IItemTransferDialogFactory itemTransferDialogFactory, + IHudControlProvider hudControlProvider, + IBankDataProvider bankDataProvider, + ICharacterInventoryProvider characterInventoryProvider, + IEIFFileProvider eifFileProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _bankActions = bankActions; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _itemTransferDialogFactory = itemTransferDialogFactory; + _hudControlProvider = hudControlProvider; + _bankDataProvider = bankDataProvider; + _characterInventoryProvider = characterInventoryProvider; + _eifFileProvider = eifFileProvider; } - public interface IBankAccountDialogFactory + public BankAccountDialog Create() { - BankAccountDialog Create(); + return new BankAccountDialog(_nativeGraphicsManager, + _bankActions, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _statusLabelSetter, + _messageBoxFactory, + _itemTransferDialogFactory, + _hudControlProvider, + _bankDataProvider, + _characterInventoryProvider, + _eifFileProvider); } +} + +public interface IBankAccountDialogFactory +{ + BankAccountDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs b/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs index ec9055cb3..9bfe5832f 100644 --- a/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs @@ -13,66 +13,65 @@ using EOLib.Localization; using System.Collections.Generic; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class BarberDialogFactory : IBarberDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly IEODialogButtonService _dialogButtonService; - private readonly ICharacterRepository _characterRepository; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IBarberActions _barberActions; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ISfxPlayer _sfxPlayer; +namespace EndlessClient.Dialogs.Factories; - public BarberDialogFactory(INativeGraphicsManager nativeGraphicsManager, - ICharacterRendererFactory characterRendererFactory, - IEODialogButtonService dialogButtonService, - ICharacterRepository characterRepository, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IBarberActions barberActions, - ICharacterInventoryProvider characterInventoryProvider, - IEOMessageBoxFactory messageBoxFactory, - IEIFFileProvider eifFileProvider, - ISfxPlayer sfxPlayer) - { - _nativeGraphicsManager = nativeGraphicsManager; - _characterRendererFactory = characterRendererFactory; - _dialogButtonService = dialogButtonService; - _characterRepository = characterRepository; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _barberActions = barberActions; - _characterInventoryProvider = characterInventoryProvider; - _messageBoxFactory = messageBoxFactory; - _eifFileProvider = eifFileProvider; - _sfxPlayer = sfxPlayer; - } +[AutoMappedType] +public class BarberDialogFactory : IBarberDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly IEODialogButtonService _dialogButtonService; + private readonly ICharacterRepository _characterRepository; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IBarberActions _barberActions; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ISfxPlayer _sfxPlayer; - public BarberDialog Create() - { - return new BarberDialog(_nativeGraphicsManager, - _characterRendererFactory, - _dialogButtonService, - _characterRepository, - _dialogIconService, - _localizedStringFinder, - _barberActions, - _characterInventoryProvider, - _messageBoxFactory, - _eifFileProvider, - _sfxPlayer); - } + public BarberDialogFactory(INativeGraphicsManager nativeGraphicsManager, + ICharacterRendererFactory characterRendererFactory, + IEODialogButtonService dialogButtonService, + ICharacterRepository characterRepository, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IBarberActions barberActions, + ICharacterInventoryProvider characterInventoryProvider, + IEOMessageBoxFactory messageBoxFactory, + IEIFFileProvider eifFileProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _characterRendererFactory = characterRendererFactory; + _dialogButtonService = dialogButtonService; + _characterRepository = characterRepository; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _barberActions = barberActions; + _characterInventoryProvider = characterInventoryProvider; + _messageBoxFactory = messageBoxFactory; + _eifFileProvider = eifFileProvider; + _sfxPlayer = sfxPlayer; } - public interface IBarberDialogFactory + public BarberDialog Create() { - BarberDialog Create(); + return new BarberDialog(_nativeGraphicsManager, + _characterRendererFactory, + _dialogButtonService, + _characterRepository, + _dialogIconService, + _localizedStringFinder, + _barberActions, + _characterInventoryProvider, + _messageBoxFactory, + _eifFileProvider, + _sfxPlayer); } +} + +public interface IBarberDialogFactory +{ + BarberDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BardDialogFactory.cs b/EndlessClient/Dialogs/Factories/BardDialogFactory.cs index 9be90b362..ba1f94286 100644 --- a/EndlessClient/Dialogs/Factories/BardDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BardDialogFactory.cs @@ -3,34 +3,33 @@ using EndlessClient.Dialogs.Services; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class BardDialogFactory : IBardDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IBardController _bardController; - private readonly IEODialogButtonService _dialogButtonService; +namespace EndlessClient.Dialogs.Factories; - public BardDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IBardController bardController, - IEODialogButtonService dialogButtonService) - { - _nativeGraphicsManager = nativeGraphicsManager; - _bardController = bardController; - _dialogButtonService = dialogButtonService; - } +[AutoMappedType] +public class BardDialogFactory : IBardDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IBardController _bardController; + private readonly IEODialogButtonService _dialogButtonService; - public BardDialog Create() - { - return new BardDialog(_nativeGraphicsManager, - _bardController, - _dialogButtonService); - } + public BardDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IBardController bardController, + IEODialogButtonService dialogButtonService) + { + _nativeGraphicsManager = nativeGraphicsManager; + _bardController = bardController; + _dialogButtonService = dialogButtonService; } - public interface IBardDialogFactory + public BardDialog Create() { - BardDialog Create(); + return new BardDialog(_nativeGraphicsManager, + _bardController, + _dialogButtonService); } +} + +public interface IBardDialogFactory +{ + BardDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs b/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs index 167d2cbd5..a0f1fb2dd 100644 --- a/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs @@ -8,62 +8,61 @@ using EOLib.Graphics; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class BoardDialogFactory : IBoardDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IBoardActions _boardActions; - private readonly IBoardRepository _boardRepository; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IContentProvider _contentProvider; - private readonly IHudControlProvider _hudControlProvider; +namespace EndlessClient.Dialogs.Factories; - public BoardDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService eoDialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IEOMessageBoxFactory eoMessageBoxFactory, - IBoardActions boardActions, - IBoardRepository boardRepository, - IPlayerInfoProvider playerInfoProvider, - ICharacterProvider characterProvider, - IContentProvider contentProvider, - IHudControlProvider hudControlProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _eoDialogButtonService = eoDialogButtonService; - _localizedStringFinder = localizedStringFinder; - _eoMessageBoxFactory = eoMessageBoxFactory; - _boardActions = boardActions; - _boardRepository = boardRepository; - _playerInfoProvider = playerInfoProvider; - _characterProvider = characterProvider; - _contentProvider = contentProvider; - _hudControlProvider = hudControlProvider; - } +[AutoMappedType] +public class BoardDialogFactory : IBoardDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IBoardActions _boardActions; + private readonly IBoardRepository _boardRepository; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IContentProvider _contentProvider; + private readonly IHudControlProvider _hudControlProvider; - public BoardDialog Create() - { - return new BoardDialog(_nativeGraphicsManager, - _eoDialogButtonService, - _localizedStringFinder, - _eoMessageBoxFactory, - _boardActions, - _boardRepository, - _playerInfoProvider, - _characterProvider, - _contentProvider, - _hudControlProvider); - } + public BoardDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService eoDialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IEOMessageBoxFactory eoMessageBoxFactory, + IBoardActions boardActions, + IBoardRepository boardRepository, + IPlayerInfoProvider playerInfoProvider, + ICharacterProvider characterProvider, + IContentProvider contentProvider, + IHudControlProvider hudControlProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _eoDialogButtonService = eoDialogButtonService; + _localizedStringFinder = localizedStringFinder; + _eoMessageBoxFactory = eoMessageBoxFactory; + _boardActions = boardActions; + _boardRepository = boardRepository; + _playerInfoProvider = playerInfoProvider; + _characterProvider = characterProvider; + _contentProvider = contentProvider; + _hudControlProvider = hudControlProvider; } - public interface IBoardDialogFactory + public BoardDialog Create() { - BoardDialog Create(); + return new BoardDialog(_nativeGraphicsManager, + _eoDialogButtonService, + _localizedStringFinder, + _eoMessageBoxFactory, + _boardActions, + _boardRepository, + _playerInfoProvider, + _characterProvider, + _contentProvider, + _hudControlProvider); } +} + +public interface IBoardDialogFactory +{ + BoardDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BookDialogFactory.cs b/EndlessClient/Dialogs/Factories/BookDialogFactory.cs index 0ab0c369f..3ee54fd75 100644 --- a/EndlessClient/Dialogs/Factories/BookDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BookDialogFactory.cs @@ -4,41 +4,40 @@ using EOLib.Graphics; using EOLib.IO.Repositories; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class BookDialogFactory : IBookDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IPubFileProvider _pubFileProvider; - private readonly IPaperdollProvider _paperdollProvider; +namespace EndlessClient.Dialogs.Factories; - public BookDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService eoDialogButtonService, - IPubFileProvider pubFileProvider, - IPaperdollProvider paperdollProvider) - { +[AutoMappedType] +public class BookDialogFactory : IBookDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IPubFileProvider _pubFileProvider; + private readonly IPaperdollProvider _paperdollProvider; - _nativeGraphicsManager = nativeGraphicsManager; - _eoDialogButtonService = eoDialogButtonService; - _pubFileProvider = pubFileProvider; - _paperdollProvider = paperdollProvider; - } + public BookDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService eoDialogButtonService, + IPubFileProvider pubFileProvider, + IPaperdollProvider paperdollProvider) + { - public BookDialog Create(Character character, bool isMainCharacter) - { - return new BookDialog(_nativeGraphicsManager, - _eoDialogButtonService, - _pubFileProvider, - _paperdollProvider, - character, - isMainCharacter); - } + _nativeGraphicsManager = nativeGraphicsManager; + _eoDialogButtonService = eoDialogButtonService; + _pubFileProvider = pubFileProvider; + _paperdollProvider = paperdollProvider; } - public interface IBookDialogFactory + public BookDialog Create(Character character, bool isMainCharacter) { - BookDialog Create(Character character, bool isMainCharacter); + return new BookDialog(_nativeGraphicsManager, + _eoDialogButtonService, + _pubFileProvider, + _paperdollProvider, + character, + isMainCharacter); } +} + +public interface IBookDialogFactory +{ + BookDialog Create(Character character, bool isMainCharacter); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ChangePasswordDialogFactory.cs b/EndlessClient/Dialogs/Factories/ChangePasswordDialogFactory.cs index c6069b765..947a92090 100644 --- a/EndlessClient/Dialogs/Factories/ChangePasswordDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ChangePasswordDialogFactory.cs @@ -7,45 +7,44 @@ using EOLib.Domain.Login; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories +namespace EndlessClient.Dialogs.Factories; + +[MappedType(BaseType = typeof(IChangePasswordDialogFactory))] +public class ChangePasswordDialogFactory : IChangePasswordDialogFactory { - [MappedType(BaseType = typeof(IChangePasswordDialogFactory))] - public class ChangePasswordDialogFactory : IChangePasswordDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGameStateProvider _gameStateProvider; - private readonly IContentProvider _contentProvider; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGameStateProvider _gameStateProvider; + private readonly IContentProvider _contentProvider; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - public ChangePasswordDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IContentProvider contentProvider, - IEOMessageBoxFactory eoMessageBoxFactory, - IPlayerInfoProvider playerInfoProvider, - IEODialogButtonService eoDialogButtonService, - IXnaControlSoundMapper xnaControlSoundMapper) - { - _nativeGraphicsManager = nativeGraphicsManager; - _gameStateProvider = gameStateProvider; - _contentProvider = contentProvider; - _eoMessageBoxFactory = eoMessageBoxFactory; - _playerInfoProvider = playerInfoProvider; - _eoDialogButtonService = eoDialogButtonService; - _xnaControlSoundMapper = xnaControlSoundMapper; - } + public ChangePasswordDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IContentProvider contentProvider, + IEOMessageBoxFactory eoMessageBoxFactory, + IPlayerInfoProvider playerInfoProvider, + IEODialogButtonService eoDialogButtonService, + IXnaControlSoundMapper xnaControlSoundMapper) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gameStateProvider = gameStateProvider; + _contentProvider = contentProvider; + _eoMessageBoxFactory = eoMessageBoxFactory; + _playerInfoProvider = playerInfoProvider; + _eoDialogButtonService = eoDialogButtonService; + _xnaControlSoundMapper = xnaControlSoundMapper; + } - public ChangePasswordDialog BuildChangePasswordDialog() - { - return new ChangePasswordDialog(_nativeGraphicsManager, - _gameStateProvider, - _contentProvider, - _eoMessageBoxFactory, - _playerInfoProvider, - _eoDialogButtonService, - _xnaControlSoundMapper); - } + public ChangePasswordDialog BuildChangePasswordDialog() + { + return new ChangePasswordDialog(_nativeGraphicsManager, + _gameStateProvider, + _contentProvider, + _eoMessageBoxFactory, + _playerInfoProvider, + _eoDialogButtonService, + _xnaControlSoundMapper); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs b/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs index 7326a6b18..db4022776 100644 --- a/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs @@ -10,66 +10,65 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class ChestDialogFactory : IChestDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChestActions _chestActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - private readonly IChestDataProvider _chestDataProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICharacterProvider _characterProvider; +namespace EndlessClient.Dialogs.Factories; - public ChestDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IChestActions chestActions, - IEOMessageBoxFactory messageBoxFactory, - IEODialogButtonService dialogButtonService, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - IInventorySpaceValidator inventorySpaceValidator, - IMapItemGraphicProvider mapItemGraphicProvider, - IChestDataProvider chestDataProvider, - IEIFFileProvider eifFileProvider, - ICharacterProvider characterProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _chestActions = chestActions; - _messageBoxFactory = messageBoxFactory; - _dialogButtonService = dialogButtonService; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _inventorySpaceValidator = inventorySpaceValidator; - _mapItemGraphicProvider = mapItemGraphicProvider; - _chestDataProvider = chestDataProvider; - _eifFileProvider = eifFileProvider; - _characterProvider = characterProvider; - } +[AutoMappedType] +public class ChestDialogFactory : IChestDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChestActions _chestActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IMapItemGraphicProvider _mapItemGraphicProvider; + private readonly IChestDataProvider _chestDataProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICharacterProvider _characterProvider; - public ChestDialog Create() - { - return new ChestDialog(_nativeGraphicsManager, - _chestActions, - _messageBoxFactory, - _dialogButtonService, - _statusLabelSetter, - _localizedStringFinder, - _inventorySpaceValidator, - _mapItemGraphicProvider, - _chestDataProvider, - _eifFileProvider, - _characterProvider); - } + public ChestDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IChestActions chestActions, + IEOMessageBoxFactory messageBoxFactory, + IEODialogButtonService dialogButtonService, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + IInventorySpaceValidator inventorySpaceValidator, + IMapItemGraphicProvider mapItemGraphicProvider, + IChestDataProvider chestDataProvider, + IEIFFileProvider eifFileProvider, + ICharacterProvider characterProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _chestActions = chestActions; + _messageBoxFactory = messageBoxFactory; + _dialogButtonService = dialogButtonService; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _inventorySpaceValidator = inventorySpaceValidator; + _mapItemGraphicProvider = mapItemGraphicProvider; + _chestDataProvider = chestDataProvider; + _eifFileProvider = eifFileProvider; + _characterProvider = characterProvider; } - public interface IChestDialogFactory + public ChestDialog Create() { - ChestDialog Create(); + return new ChestDialog(_nativeGraphicsManager, + _chestActions, + _messageBoxFactory, + _dialogButtonService, + _statusLabelSetter, + _localizedStringFinder, + _inventorySpaceValidator, + _mapItemGraphicProvider, + _chestDataProvider, + _eifFileProvider, + _characterProvider); } +} + +public interface IChestDialogFactory +{ + ChestDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/CreateAccountProgressDialogFactory.cs b/EndlessClient/Dialogs/Factories/CreateAccountProgressDialogFactory.cs index 5bd8e664e..9b5dc4f8a 100644 --- a/EndlessClient/Dialogs/Factories/CreateAccountProgressDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/CreateAccountProgressDialogFactory.cs @@ -6,45 +6,44 @@ using EOLib.Localization; using XNAControls; -namespace EndlessClient.Dialogs.Factories -{ - [MappedType(BaseType = typeof(ICreateAccountProgressDialogFactory))] - public class CreateAccountProgressDialogFactory : ICreateAccountProgressDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGameStateProvider _gameStateProvider; - private readonly IConfigurationProvider _configProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEODialogButtonService _eoDialogButtonService; +namespace EndlessClient.Dialogs.Factories; - public CreateAccountProgressDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IConfigurationProvider configProvider, - ILocalizedStringFinder localizedStringFinder, - IEODialogButtonService eoDialogButtonService) - { - _nativeGraphicsManager = nativeGraphicsManager; - _gameStateProvider = gameStateProvider; - _configProvider = configProvider; - _localizedStringFinder = localizedStringFinder; - _eoDialogButtonService = eoDialogButtonService; - } - - public IXNADialog BuildCreateAccountProgressDialog() - { - var message = _localizedStringFinder.GetString(DialogResourceID.ACCOUNT_CREATE_ACCEPTED + 1); - var caption = _localizedStringFinder.GetString(DialogResourceID.ACCOUNT_CREATE_ACCEPTED); +[MappedType(BaseType = typeof(ICreateAccountProgressDialogFactory))] +public class CreateAccountProgressDialogFactory : ICreateAccountProgressDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGameStateProvider _gameStateProvider; + private readonly IConfigurationProvider _configProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEODialogButtonService _eoDialogButtonService; - return new ProgressDialog(_nativeGraphicsManager, - _gameStateProvider, - _configProvider, - _eoDialogButtonService, - message, caption); - } + public CreateAccountProgressDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IConfigurationProvider configProvider, + ILocalizedStringFinder localizedStringFinder, + IEODialogButtonService eoDialogButtonService) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gameStateProvider = gameStateProvider; + _configProvider = configProvider; + _localizedStringFinder = localizedStringFinder; + _eoDialogButtonService = eoDialogButtonService; } - public interface ICreateAccountProgressDialogFactory + public IXNADialog BuildCreateAccountProgressDialog() { - IXNADialog BuildCreateAccountProgressDialog(); + var message = _localizedStringFinder.GetString(DialogResourceID.ACCOUNT_CREATE_ACCEPTED + 1); + var caption = _localizedStringFinder.GetString(DialogResourceID.ACCOUNT_CREATE_ACCEPTED); + + return new ProgressDialog(_nativeGraphicsManager, + _gameStateProvider, + _configProvider, + _eoDialogButtonService, + message, caption); } +} + +public interface ICreateAccountProgressDialogFactory +{ + IXNADialog BuildCreateAccountProgressDialog(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs b/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs index 4342a1a98..f3536b098 100644 --- a/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs @@ -6,45 +6,44 @@ using EOLib.Graphics; using XNAControls; -namespace EndlessClient.Dialogs.Factories +namespace EndlessClient.Dialogs.Factories; + +[MappedType(BaseType = typeof(ICreateAccountWarningDialogFactory))] +public class CreateAccountWarningDialogFactory : ICreateAccountWarningDialogFactory { - [MappedType(BaseType = typeof(ICreateAccountWarningDialogFactory))] - public class CreateAccountWarningDialogFactory : ICreateAccountWarningDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IContentProvider _contentProvider; - private readonly IGameStateProvider _gameStateProvider; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly ISfxPlayer _sfxPlayer; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IContentProvider _contentProvider; + private readonly IGameStateProvider _gameStateProvider; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly ISfxPlayer _sfxPlayer; - public CreateAccountWarningDialogFactory( - INativeGraphicsManager nativeGraphicsManager, - IContentProvider contentProvider, - IGameStateProvider gameStateProvider, - IEODialogButtonService eoDialogButtonService, - ISfxPlayer sfxPlayer) - { - _nativeGraphicsManager = nativeGraphicsManager; - _contentProvider = contentProvider; - _gameStateProvider = gameStateProvider; - _eoDialogButtonService = eoDialogButtonService; - _sfxPlayer = sfxPlayer; - } + public CreateAccountWarningDialogFactory( + INativeGraphicsManager nativeGraphicsManager, + IContentProvider contentProvider, + IGameStateProvider gameStateProvider, + IEODialogButtonService eoDialogButtonService, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _contentProvider = contentProvider; + _gameStateProvider = gameStateProvider; + _eoDialogButtonService = eoDialogButtonService; + _sfxPlayer = sfxPlayer; + } - public IXNADialog ShowCreateAccountWarningDialog(string warningMessage) + public IXNADialog ShowCreateAccountWarningDialog(string warningMessage) + { + var dialog = new ScrollingMessageDialog(_nativeGraphicsManager, _contentProvider, _gameStateProvider, _eoDialogButtonService) { - var dialog = new ScrollingMessageDialog(_nativeGraphicsManager, _contentProvider, _gameStateProvider, _eoDialogButtonService) - { - MessageText = warningMessage - }; - dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + MessageText = warningMessage + }; + dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - return dialog; - } + return dialog; } +} - public interface ICreateAccountWarningDialogFactory - { - IXNADialog ShowCreateAccountWarningDialog(string warningMessage); - } +public interface ICreateAccountWarningDialogFactory +{ + IXNADialog ShowCreateAccountWarningDialog(string warningMessage); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/CreateCharacterDialogFactory.cs b/EndlessClient/Dialogs/Factories/CreateCharacterDialogFactory.cs index 4e772a8be..3e7327374 100644 --- a/EndlessClient/Dialogs/Factories/CreateCharacterDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/CreateCharacterDialogFactory.cs @@ -7,50 +7,49 @@ using EndlessClient.UIControls; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories -{ - [MappedType(BaseType = typeof(ICreateCharacterDialogFactory))] - public class CreateCharacterDialogFactory : ICreateCharacterDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGameStateProvider _gameStateProvider; - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly IContentProvider _contentProvider; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; +namespace EndlessClient.Dialogs.Factories; - public CreateCharacterDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - ICharacterRendererFactory characterRendererFactory, - IContentProvider contentProvider, - IEOMessageBoxFactory eoMessageBoxFactory, - IEODialogButtonService dialogButtonService, - IXnaControlSoundMapper xnaControlSoundMapper) - { - _nativeGraphicsManager = nativeGraphicsManager; - _gameStateProvider = gameStateProvider; - _characterRendererFactory = characterRendererFactory; - _contentProvider = contentProvider; - _eoMessageBoxFactory = eoMessageBoxFactory; - _dialogButtonService = dialogButtonService; - _xnaControlSoundMapper = xnaControlSoundMapper; - } +[MappedType(BaseType = typeof(ICreateCharacterDialogFactory))] +public class CreateCharacterDialogFactory : ICreateCharacterDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGameStateProvider _gameStateProvider; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly IContentProvider _contentProvider; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - public CreateCharacterDialog BuildCreateCharacterDialog() - { - return new CreateCharacterDialog(_nativeGraphicsManager, - _gameStateProvider, - _characterRendererFactory, - _contentProvider, - _eoMessageBoxFactory, - _dialogButtonService, - _xnaControlSoundMapper); - } + public CreateCharacterDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + ICharacterRendererFactory characterRendererFactory, + IContentProvider contentProvider, + IEOMessageBoxFactory eoMessageBoxFactory, + IEODialogButtonService dialogButtonService, + IXnaControlSoundMapper xnaControlSoundMapper) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gameStateProvider = gameStateProvider; + _characterRendererFactory = characterRendererFactory; + _contentProvider = contentProvider; + _eoMessageBoxFactory = eoMessageBoxFactory; + _dialogButtonService = dialogButtonService; + _xnaControlSoundMapper = xnaControlSoundMapper; } - public interface ICreateCharacterDialogFactory + public CreateCharacterDialog BuildCreateCharacterDialog() { - CreateCharacterDialog BuildCreateCharacterDialog(); + return new CreateCharacterDialog(_nativeGraphicsManager, + _gameStateProvider, + _characterRendererFactory, + _contentProvider, + _eoMessageBoxFactory, + _dialogButtonService, + _xnaControlSoundMapper); } +} + +public interface ICreateCharacterDialogFactory +{ + CreateCharacterDialog BuildCreateCharacterDialog(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/EOMessageBoxFactory.cs b/EndlessClient/Dialogs/Factories/EOMessageBoxFactory.cs index c62eae05f..d18710c3b 100644 --- a/EndlessClient/Dialogs/Factories/EOMessageBoxFactory.cs +++ b/EndlessClient/Dialogs/Factories/EOMessageBoxFactory.cs @@ -7,96 +7,95 @@ using Optional; using XNAControls; -namespace EndlessClient.Dialogs.Factories +namespace EndlessClient.Dialogs.Factories; + +[MappedType(BaseType = typeof(IEOMessageBoxFactory))] +public class EOMessageBoxFactory : IEOMessageBoxFactory { - [MappedType(BaseType = typeof(IEOMessageBoxFactory))] - public class EOMessageBoxFactory : IEOMessageBoxFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGameStateProvider _gameStateProvider; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IActiveDialogRepository _activeDialogRepository; - private readonly ISfxPlayer _sfxPlayer; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGameStateProvider _gameStateProvider; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IActiveDialogRepository _activeDialogRepository; + private readonly ISfxPlayer _sfxPlayer; - public EOMessageBoxFactory(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IEODialogButtonService eoDialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IActiveDialogRepository activeDialogRepository, - ISfxPlayer sfxPlayer) - { - _nativeGraphicsManager = nativeGraphicsManager; - _gameStateProvider = gameStateProvider; - _eoDialogButtonService = eoDialogButtonService; - _localizedStringFinder = localizedStringFinder; - _activeDialogRepository = activeDialogRepository; - _sfxPlayer = sfxPlayer; - } + public EOMessageBoxFactory(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IEODialogButtonService eoDialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IActiveDialogRepository activeDialogRepository, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gameStateProvider = gameStateProvider; + _eoDialogButtonService = eoDialogButtonService; + _localizedStringFinder = localizedStringFinder; + _activeDialogRepository = activeDialogRepository; + _sfxPlayer = sfxPlayer; + } - public IXNADialog CreateMessageBox(string message, - string caption = "", - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) - { + public IXNADialog CreateMessageBox(string message, + string caption = "", + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) + { - var messageBox = new EOMessageBox(_nativeGraphicsManager, - _gameStateProvider, - _eoDialogButtonService, - message, - caption, - style, - whichButtons); - messageBox.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - messageBox.DialogClosed += (_, _) => _activeDialogRepository.MessageBox = Option.None(); + var messageBox = new EOMessageBox(_nativeGraphicsManager, + _gameStateProvider, + _eoDialogButtonService, + message, + caption, + style, + whichButtons); + messageBox.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + messageBox.DialogClosed += (_, _) => _activeDialogRepository.MessageBox = Option.None(); - _activeDialogRepository.MessageBox = Option.Some(messageBox); + _activeDialogRepository.MessageBox = Option.Some(messageBox); - return messageBox; - } + return messageBox; + } - public IXNADialog CreateMessageBox(DialogResourceID resource, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) - { - return CreateMessageBox(_localizedStringFinder.GetString(resource + 1), - _localizedStringFinder.GetString(resource), - whichButtons, - style); - } + public IXNADialog CreateMessageBox(DialogResourceID resource, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) + { + return CreateMessageBox(_localizedStringFinder.GetString(resource + 1), + _localizedStringFinder.GetString(resource), + whichButtons, + style); + } - public IXNADialog CreateMessageBox(string prependData, - DialogResourceID resource, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) - { - var message = prependData + _localizedStringFinder.GetString(resource + 1); - return CreateMessageBox(message, - _localizedStringFinder.GetString(resource), - whichButtons, - style); - } + public IXNADialog CreateMessageBox(string prependData, + DialogResourceID resource, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) + { + var message = prependData + _localizedStringFinder.GetString(resource + 1); + return CreateMessageBox(message, + _localizedStringFinder.GetString(resource), + whichButtons, + style); + } - public IXNADialog CreateMessageBox(DialogResourceID resource, - string extraData, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) - { - var message = _localizedStringFinder.GetString(resource + 1) + extraData; - return CreateMessageBox(message, - _localizedStringFinder.GetString(resource), - whichButtons, - style); - } + public IXNADialog CreateMessageBox(DialogResourceID resource, + string extraData, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) + { + var message = _localizedStringFinder.GetString(resource + 1) + extraData; + return CreateMessageBox(message, + _localizedStringFinder.GetString(resource), + whichButtons, + style); + } - public IXNADialog CreateMessageBox(EOResourceID message, - EOResourceID caption, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) - { - var messageText = _localizedStringFinder.GetString(message); - var captionText = _localizedStringFinder.GetString(caption); - return CreateMessageBox(messageText, captionText, whichButtons, style); - } + public IXNADialog CreateMessageBox(EOResourceID message, + EOResourceID caption, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) + { + var messageText = _localizedStringFinder.GetString(message); + var captionText = _localizedStringFinder.GetString(caption); + return CreateMessageBox(messageText, captionText, whichButtons, style); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs b/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs index d46c7c18a..bd0ad4374 100644 --- a/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs @@ -14,127 +14,126 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs.Factories +namespace EndlessClient.Dialogs.Factories; + +[AutoMappedType] +public class FriendIgnoreListDialogFactory : IFriendIgnoreListDialogFactory { - [AutoMappedType] - public class FriendIgnoreListDialogFactory : IFriendIgnoreListDialogFactory + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ICharacterProvider _characterProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly IOnlinePlayerProvider _onlinePlayerProvider; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IFriendIgnoreListService _friendIgnoreListService; + + public FriendIgnoreListDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + ICharacterProvider characterProvider, + IHudControlProvider hudControlProvider, + IOnlinePlayerProvider onlinePlayerProvider, + ITextInputDialogFactory textInputDialogFactory, + IEOMessageBoxFactory eoMessageBoxFactory, + IFriendIgnoreListService friendIgnoreListService) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ICharacterProvider _characterProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly IOnlinePlayerProvider _onlinePlayerProvider; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IFriendIgnoreListService _friendIgnoreListService; - - public FriendIgnoreListDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - ICharacterProvider characterProvider, - IHudControlProvider hudControlProvider, - IOnlinePlayerProvider onlinePlayerProvider, - ITextInputDialogFactory textInputDialogFactory, - IEOMessageBoxFactory eoMessageBoxFactory, - IFriendIgnoreListService friendIgnoreListService) - { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _localizedStringFinder = localizedStringFinder; - _characterProvider = characterProvider; - _hudControlProvider = hudControlProvider; - _onlinePlayerProvider = onlinePlayerProvider; - _textInputDialogFactory = textInputDialogFactory; - _eoMessageBoxFactory = eoMessageBoxFactory; - _friendIgnoreListService = friendIgnoreListService; - } - - public FriendIgnoreListDialog Create(bool isFriendList) + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _localizedStringFinder = localizedStringFinder; + _characterProvider = characterProvider; + _hudControlProvider = hudControlProvider; + _onlinePlayerProvider = onlinePlayerProvider; + _textInputDialogFactory = textInputDialogFactory; + _eoMessageBoxFactory = eoMessageBoxFactory; + _friendIgnoreListService = friendIgnoreListService; + } + + public FriendIgnoreListDialog Create(bool isFriendList) + { + var textFileLines = _friendIgnoreListService.LoadList(isFriendList ? Constants.FriendListFile : Constants.IgnoreListFile); + + var dialog = new FriendIgnoreListDialog(_nativeGraphicsManager, _dialogButtonService, _onlinePlayerProvider) { - var textFileLines = _friendIgnoreListService.LoadList(isFriendList ? Constants.FriendListFile : Constants.IgnoreListFile); + Buttons = ScrollingListDialogButtons.AddCancel, + ListItemType = ListDialogItem.ListItemStyle.Small, + }; - var dialog = new FriendIgnoreListDialog(_nativeGraphicsManager, _dialogButtonService, _onlinePlayerProvider) - { - Buttons = ScrollingListDialogButtons.AddCancel, - ListItemType = ListDialogItem.ListItemStyle.Small, - }; + var listItems = textFileLines.Select(x => new ListDialogItem(dialog, ListDialogItem.ListItemStyle.Small) { PrimaryText = x }).ToList(); + foreach (var item in listItems) + SetClickEventHandlers(item, dialog, isFriendList); + dialog.SetItemList(listItems); - var listItems = textFileLines.Select(x => new ListDialogItem(dialog, ListDialogItem.ListItemStyle.Small) { PrimaryText = x }).ToList(); - foreach (var item in listItems) - SetClickEventHandlers(item, dialog, isFriendList); - dialog.SetItemList(listItems); + dialog.Title = GetDialogTitle(dialog, isFriendList); - dialog.Title = GetDialogTitle(dialog, isFriendList); + dialog.AddAction += (_, _) => InvokeAdd(isFriendList, dialog); + dialog.DialogClosing += (_, _) => + { + if (isFriendList) + _friendIgnoreListService.SaveFriends(Constants.FriendListFile, dialog.NamesList); + else + _friendIgnoreListService.SaveIgnored(Constants.IgnoreListFile, dialog.NamesList); + }; - dialog.AddAction += (_, _) => InvokeAdd(isFriendList, dialog); - dialog.DialogClosing += (_, _) => - { - if (isFriendList) - _friendIgnoreListService.SaveFriends(Constants.FriendListFile, dialog.NamesList); - else - _friendIgnoreListService.SaveIgnored(Constants.IgnoreListFile, dialog.NamesList); - }; + return dialog; + } - return dialog; - } + private void InvokeAdd(bool isFriendList, ScrollingListDialog parentDialog) + { + string prompt = _localizedStringFinder.GetString(isFriendList ? EOResourceID.DIALOG_WHO_TO_MAKE_FRIEND : EOResourceID.DIALOG_WHO_TO_MAKE_IGNORE); + var inputDialog = _textInputDialogFactory.Create(prompt); - private void InvokeAdd(bool isFriendList, ScrollingListDialog parentDialog) + inputDialog.DialogClosing += (_, e) => { - string prompt = _localizedStringFinder.GetString(isFriendList ? EOResourceID.DIALOG_WHO_TO_MAKE_FRIEND : EOResourceID.DIALOG_WHO_TO_MAKE_IGNORE); - var inputDialog = _textInputDialogFactory.Create(prompt); + if (e.Result == XNADialogResult.Cancel) + return; - inputDialog.DialogClosing += (_, e) => + if (inputDialog.ResponseText.Length < 4) { - if (e.Result == XNADialogResult.Cancel) - return; - - if (inputDialog.ResponseText.Length < 4) - { - e.Cancel = true; - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHARACTER_CREATE_NAME_TOO_SHORT); - messageBox.ShowDialog(); - return; - } - - if (parentDialog.NamesList.Any(name => string.Equals(name, inputDialog.ResponseText, StringComparison.InvariantCultureIgnoreCase))) - { - e.Cancel = true; - var messageBox = _eoMessageBoxFactory.CreateMessageBox("You are already friends with that person!", "Invalid entry!", EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); - messageBox.ShowDialog(); - return; - } - - var charName = char.ToUpper(inputDialog.ResponseText[0]) + inputDialog.ResponseText.Substring(1); - var newItem = new ListDialogItem(parentDialog, ListDialogItem.ListItemStyle.Small) { PrimaryText = charName }; - SetClickEventHandlers(newItem, parentDialog, isFriendList); - - parentDialog.AddItemToList(newItem, sortList: true); - parentDialog.Title = GetDialogTitle(parentDialog, isFriendList); - }; - - inputDialog.ShowDialog(); - } - - private void SetClickEventHandlers(ListDialogItem item, ScrollingListDialog dialog, bool isFriendList) - { - item.LeftClick += (o, e) => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{item.PrimaryText} "; - item.RightClick += (o, e) => + e.Cancel = true; + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHARACTER_CREATE_NAME_TOO_SHORT); + messageBox.ShowDialog(); + return; + } + + if (parentDialog.NamesList.Any(name => string.Equals(name, inputDialog.ResponseText, StringComparison.InvariantCultureIgnoreCase))) { - dialog.RemoveFromList(item); - dialog.Title = GetDialogTitle(dialog, isFriendList); - }; - } + e.Cancel = true; + var messageBox = _eoMessageBoxFactory.CreateMessageBox("You are already friends with that person!", "Invalid entry!", EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); + messageBox.ShowDialog(); + return; + } - private string GetDialogTitle(ScrollingListDialog dialog, bool isFriendList) + var charName = char.ToUpper(inputDialog.ResponseText[0]) + inputDialog.ResponseText.Substring(1); + var newItem = new ListDialogItem(parentDialog, ListDialogItem.ListItemStyle.Small) { PrimaryText = charName }; + SetClickEventHandlers(newItem, parentDialog, isFriendList); + + parentDialog.AddItemToList(newItem, sortList: true); + parentDialog.Title = GetDialogTitle(parentDialog, isFriendList); + }; + + inputDialog.ShowDialog(); + } + + private void SetClickEventHandlers(ListDialogItem item, ScrollingListDialog dialog, bool isFriendList) + { + item.LeftClick += (o, e) => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{item.PrimaryText} "; + item.RightClick += (o, e) => { - var friendOrIgnoreStr = _localizedStringFinder.GetString(isFriendList ? EOResourceID.STATUS_LABEL_FRIEND_LIST : EOResourceID.STATUS_LABEL_IGNORE_LIST); - return $"{_characterProvider.MainCharacter.Name}'s {friendOrIgnoreStr} [{dialog.NamesList.Count}]"; - } + dialog.RemoveFromList(item); + dialog.Title = GetDialogTitle(dialog, isFriendList); + }; } - public interface IFriendIgnoreListDialogFactory + private string GetDialogTitle(ScrollingListDialog dialog, bool isFriendList) { - FriendIgnoreListDialog Create(bool isFriendList); + var friendOrIgnoreStr = _localizedStringFinder.GetString(isFriendList ? EOResourceID.STATUS_LABEL_FRIEND_LIST : EOResourceID.STATUS_LABEL_IGNORE_LIST); + return $"{_characterProvider.MainCharacter.Name}'s {friendOrIgnoreStr} [{dialog.NamesList.Count}]"; } +} + +public interface IFriendIgnoreListDialogFactory +{ + FriendIgnoreListDialog Create(bool isFriendList); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/GameLoadingDialogFactory.cs b/EndlessClient/Dialogs/Factories/GameLoadingDialogFactory.cs index 55123086b..5414b575a 100644 --- a/EndlessClient/Dialogs/Factories/GameLoadingDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/GameLoadingDialogFactory.cs @@ -4,38 +4,37 @@ using EOLib.Graphics; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [MappedType(BaseType = typeof(IGameLoadingDialogFactory))] - public class GameLoadingDialogFactory : IGameLoadingDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGameStateProvider _gameStateProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; +namespace EndlessClient.Dialogs.Factories; - public GameLoadingDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - ILocalizedStringFinder localizedStringFinder) - { - _nativeGraphicsManager = nativeGraphicsManager; - _gameStateProvider = gameStateProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - _localizedStringFinder = localizedStringFinder; - } +[MappedType(BaseType = typeof(IGameLoadingDialogFactory))] +public class GameLoadingDialogFactory : IGameLoadingDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGameStateProvider _gameStateProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; - public GameLoadingDialog CreateGameLoadingDialog() - { - return new GameLoadingDialog(_nativeGraphicsManager, - _gameStateProvider, - _clientWindowSizeProvider, - _localizedStringFinder); - } + public GameLoadingDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + ILocalizedStringFinder localizedStringFinder) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gameStateProvider = gameStateProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + _localizedStringFinder = localizedStringFinder; } - public interface IGameLoadingDialogFactory + public GameLoadingDialog CreateGameLoadingDialog() { - GameLoadingDialog CreateGameLoadingDialog(); + return new GameLoadingDialog(_nativeGraphicsManager, + _gameStateProvider, + _clientWindowSizeProvider, + _localizedStringFinder); } +} + +public interface IGameLoadingDialogFactory +{ + GameLoadingDialog CreateGameLoadingDialog(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs b/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs index 5560d1b46..740fccd25 100644 --- a/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs @@ -8,74 +8,73 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Dialogs.Factories +namespace EndlessClient.Dialogs.Factories; + +[AutoMappedType(IsSingleton = true)] +public class HelpDialogFactory : IHelpDialogFactory { - [AutoMappedType(IsSingleton = true)] - public class HelpDialogFactory : IHelpDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IContentProvider _contentProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IHelpActions _helpActions; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IContentProvider _contentProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IHelpActions _helpActions; - public HelpDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IContentProvider contentProvider, - ILocalizedStringFinder localizedStringFinder, - IHelpActions helpActions) - { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _contentProvider = contentProvider; - _localizedStringFinder = localizedStringFinder; - _helpActions = helpActions; - } + public HelpDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IContentProvider contentProvider, + ILocalizedStringFinder localizedStringFinder, + IHelpActions helpActions) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _contentProvider = contentProvider; + _localizedStringFinder = localizedStringFinder; + _helpActions = helpActions; + } - public ScrollingListDialog Create() + public ScrollingListDialog Create() + { + var dlg = new ScrollingListDialog(_nativeGraphicsManager, _dialogButtonService, DialogType.Help) { - var dlg = new ScrollingListDialog(_nativeGraphicsManager, _dialogButtonService, DialogType.Help) - { - Title = _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP), - Buttons = ScrollingListDialogButtons.Cancel, - ListItemType = ListDialogItem.ListItemStyle.Small, - }; - - dlg.AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize08pt5], - insertLineBreaks: false, - linkClickActions: GetActions(), - messages: GetMessages()); + Title = _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP), + Buttons = ScrollingListDialogButtons.Cancel, + ListItemType = ListDialogItem.ListItemStyle.Small, + }; - return dlg; - } + dlg.AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize08pt5], + insertLineBreaks: false, + linkClickActions: GetActions(), + messages: GetMessages()); - private string[] GetMessages() - { - return new[] - { - _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_SUMMARY_1), - string.Empty, - _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_SUMMARY_2), - string.Empty, - _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_RESET_PASSWORD), - _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_REPORT_SOMEONE), - _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_SPEAK_TO_ADMIN), - }; - } + return dlg; + } - private List GetActions() + private string[] GetMessages() + { + return new[] { - return new List - { - _helpActions.ResetPassword, - _helpActions.ReportSomeone, - _helpActions.SpeakToAdmin, - }; - } + _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_SUMMARY_1), + string.Empty, + _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_SUMMARY_2), + string.Empty, + _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_RESET_PASSWORD), + _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_REPORT_SOMEONE), + _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_SPEAK_TO_ADMIN), + }; } - public interface IHelpDialogFactory + private List GetActions() { - ScrollingListDialog Create(); + return new List + { + _helpActions.ResetPassword, + _helpActions.ReportSomeone, + _helpActions.SpeakToAdmin, + }; } +} + +public interface IHelpDialogFactory +{ + ScrollingListDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs b/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs index 80054bf4e..48d76e9d4 100644 --- a/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs @@ -1,7 +1,6 @@ -namespace EndlessClient.Dialogs.Factories +namespace EndlessClient.Dialogs.Factories; + +public interface IChangePasswordDialogFactory { - public interface IChangePasswordDialogFactory - { - ChangePasswordDialog BuildChangePasswordDialog(); - } + ChangePasswordDialog BuildChangePasswordDialog(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs b/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs index aa345a1e1..afbc638cc 100644 --- a/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs +++ b/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs @@ -1,32 +1,31 @@ using EOLib.Localization; using XNAControls; -namespace EndlessClient.Dialogs.Factories +namespace EndlessClient.Dialogs.Factories; + +public interface IEOMessageBoxFactory { - public interface IEOMessageBoxFactory - { - IXNADialog CreateMessageBox(string message, - string caption = "", - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); + IXNADialog CreateMessageBox(string message, + string caption = "", + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); - IXNADialog CreateMessageBox(DialogResourceID resource, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); + IXNADialog CreateMessageBox(DialogResourceID resource, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); - IXNADialog CreateMessageBox(string prependData, - DialogResourceID resource, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); + IXNADialog CreateMessageBox(string prependData, + DialogResourceID resource, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); - IXNADialog CreateMessageBox(DialogResourceID resource, - string extraData, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); + IXNADialog CreateMessageBox(DialogResourceID resource, + string extraData, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); - IXNADialog CreateMessageBox(EOResourceID message, - EOResourceID caption, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); - } + IXNADialog CreateMessageBox(EOResourceID message, + EOResourceID caption, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs b/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs index 15a389ce4..684328b8e 100644 --- a/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs @@ -6,62 +6,61 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class InnkeeperDialogFactory : IInnkeeperDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ICitizenActions _citizenActions; - private readonly IContentProvider _contentProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly ICitizenDataProvider _citizenDataProvider; +namespace EndlessClient.Dialogs.Factories; - public InnkeeperDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IEOMessageBoxFactory messageBoxFactory, - ITextInputDialogFactory textInputDialogFactory, - ICitizenActions citizenActions, - IContentProvider contentProvider, - IENFFileProvider enfFileProvider, - ICitizenDataProvider citizenDataProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _messageBoxFactory = messageBoxFactory; - _textInputDialogFactory = textInputDialogFactory; - _citizenActions = citizenActions; - _contentProvider = contentProvider; - _enfFileProvider = enfFileProvider; - _citizenDataProvider = citizenDataProvider; - } +[AutoMappedType] +public class InnkeeperDialogFactory : IInnkeeperDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ICitizenActions _citizenActions; + private readonly IContentProvider _contentProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly ICitizenDataProvider _citizenDataProvider; - public InnkeeperDialog Create() - { - return new InnkeeperDialog(_nativeGraphicsManager, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _messageBoxFactory, - _textInputDialogFactory, - _citizenActions, - _contentProvider, - _enfFileProvider, - _citizenDataProvider); - } + public InnkeeperDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IEOMessageBoxFactory messageBoxFactory, + ITextInputDialogFactory textInputDialogFactory, + ICitizenActions citizenActions, + IContentProvider contentProvider, + IENFFileProvider enfFileProvider, + ICitizenDataProvider citizenDataProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _messageBoxFactory = messageBoxFactory; + _textInputDialogFactory = textInputDialogFactory; + _citizenActions = citizenActions; + _contentProvider = contentProvider; + _enfFileProvider = enfFileProvider; + _citizenDataProvider = citizenDataProvider; } - public interface IInnkeeperDialogFactory + public InnkeeperDialog Create() { - InnkeeperDialog Create(); + return new InnkeeperDialog(_nativeGraphicsManager, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _messageBoxFactory, + _textInputDialogFactory, + _citizenActions, + _contentProvider, + _enfFileProvider, + _citizenDataProvider); } +} + +public interface IInnkeeperDialogFactory +{ + InnkeeperDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ItemTransferDialogFactory.cs b/EndlessClient/Dialogs/Factories/ItemTransferDialogFactory.cs index 80c328881..17058494e 100644 --- a/EndlessClient/Dialogs/Factories/ItemTransferDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ItemTransferDialogFactory.cs @@ -7,58 +7,57 @@ using EOLib.Localization; using XNAControls; -namespace EndlessClient.Dialogs.Factories +namespace EndlessClient.Dialogs.Factories; + +[AutoMappedType] +public class ItemTransferDialogFactory : IItemTransferDialogFactory { - [AutoMappedType] - public class ItemTransferDialogFactory : IItemTransferDialogFactory + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatTextBoxActions _chatTextBoxActions; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IContentProvider _contentProvider; + private readonly ISfxPlayer _sfxPlayer; + + public ItemTransferDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IContentProvider contentProvider, + ISfxPlayer sfxPlayer) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatTextBoxActions _chatTextBoxActions; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IContentProvider _contentProvider; - private readonly ISfxPlayer _sfxPlayer; + _nativeGraphicsManager = nativeGraphicsManager; + _chatTextBoxActions = chatTextBoxActions; + _eoDialogButtonService = eoDialogButtonService; + _localizedStringFinder = localizedStringFinder; + _contentProvider = contentProvider; + _sfxPlayer = sfxPlayer; + } - public ItemTransferDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IContentProvider contentProvider, - ISfxPlayer sfxPlayer) - { - _nativeGraphicsManager = nativeGraphicsManager; - _chatTextBoxActions = chatTextBoxActions; - _eoDialogButtonService = eoDialogButtonService; - _localizedStringFinder = localizedStringFinder; - _contentProvider = contentProvider; - _sfxPlayer = sfxPlayer; - } + public ItemTransferDialog CreateItemTransferDialog(string itemName, ItemTransferDialog.TransferType transferType, int totalAmount, EOResourceID message) + { + var dlg = new ItemTransferDialog(_nativeGraphicsManager, + _chatTextBoxActions, + _eoDialogButtonService, + _localizedStringFinder, + _contentProvider, + itemName, + transferType, + totalAmount, + message); - public ItemTransferDialog CreateItemTransferDialog(string itemName, ItemTransferDialog.TransferType transferType, int totalAmount, EOResourceID message) + dlg.DialogClosing += (sender, args) => { - var dlg = new ItemTransferDialog(_nativeGraphicsManager, - _chatTextBoxActions, - _eoDialogButtonService, - _localizedStringFinder, - _contentProvider, - itemName, - transferType, - totalAmount, - message); - - dlg.DialogClosing += (sender, args) => + if (args.Result == XNADialogResult.Cancel) { - if (args.Result == XNADialogResult.Cancel) - { - _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - } - }; - return dlg; - } + _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + } + }; + return dlg; } +} - public interface IItemTransferDialogFactory - { - ItemTransferDialog CreateItemTransferDialog(string itemName, ItemTransferDialog.TransferType transferType, int totalAmount, EOResourceID message); - } +public interface IItemTransferDialogFactory +{ + ItemTransferDialog CreateItemTransferDialog(string itemName, ItemTransferDialog.TransferType transferType, int totalAmount, EOResourceID message); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs b/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs index 926646a63..9d8476163 100644 --- a/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs @@ -6,62 +6,61 @@ using EOLib.Graphics; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class JukeboxDialogFactory : IJukeboxDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IDataFileProvider _dataFileProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IJukeboxActions _jukeboxActions; - private readonly IJukeboxRepository _jukeboxRepository; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly ISfxPlayer _sfxPlayer; +namespace EndlessClient.Dialogs.Factories; - public JukeboxDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IDataFileProvider dataFileProvider, - IEOMessageBoxFactory messageBoxFactory, - IJukeboxActions jukeboxActions, - IJukeboxRepository jukeboxRepository, - ICharacterInventoryProvider characterInventoryProvider, - ISfxPlayer sfxPlayer) - { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _dataFileProvider = dataFileProvider; - _messageBoxFactory = messageBoxFactory; - _jukeboxActions = jukeboxActions; - _jukeboxRepository = jukeboxRepository; - _characterInventoryProvider = characterInventoryProvider; - _sfxPlayer = sfxPlayer; - } +[AutoMappedType] +public class JukeboxDialogFactory : IJukeboxDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IDataFileProvider _dataFileProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IJukeboxActions _jukeboxActions; + private readonly IJukeboxRepository _jukeboxRepository; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly ISfxPlayer _sfxPlayer; - public JukeboxDialog Create() - { - return new JukeboxDialog(_nativeGraphicsManager, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _dataFileProvider, - _messageBoxFactory, - _jukeboxActions, - _jukeboxRepository, - _characterInventoryProvider, - _sfxPlayer); - } + public JukeboxDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IDataFileProvider dataFileProvider, + IEOMessageBoxFactory messageBoxFactory, + IJukeboxActions jukeboxActions, + IJukeboxRepository jukeboxRepository, + ICharacterInventoryProvider characterInventoryProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _dataFileProvider = dataFileProvider; + _messageBoxFactory = messageBoxFactory; + _jukeboxActions = jukeboxActions; + _jukeboxRepository = jukeboxRepository; + _characterInventoryProvider = characterInventoryProvider; + _sfxPlayer = sfxPlayer; } - public interface IJukeboxDialogFactory + public JukeboxDialog Create() { - JukeboxDialog Create(); + return new JukeboxDialog(_nativeGraphicsManager, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _dataFileProvider, + _messageBoxFactory, + _jukeboxActions, + _jukeboxRepository, + _characterInventoryProvider, + _sfxPlayer); } +} + +public interface IJukeboxDialogFactory +{ + JukeboxDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/LawDialogFactory.cs b/EndlessClient/Dialogs/Factories/LawDialogFactory.cs index 0a9538435..e2ccca349 100644 --- a/EndlessClient/Dialogs/Factories/LawDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/LawDialogFactory.cs @@ -7,58 +7,57 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class LawDialogFactory : ILawDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ILawActions _lawActions; - private readonly IContentProvider _contentProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IENFFileProvider _enfFileProvider; +namespace EndlessClient.Dialogs.Factories; - public LawDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - ITextInputDialogFactory textInputDialogFactory, - ILawActions lawActions, - IContentProvider contentProvider, - ICurrentMapStateProvider currentMapStateProvider, - IENFFileProvider enfFileProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _textInputDialogFactory = textInputDialogFactory; - _lawActions = lawActions; - _contentProvider = contentProvider; - _currentMapStateProvider = currentMapStateProvider; - _enfFileProvider = enfFileProvider; - } +[AutoMappedType] +public class LawDialogFactory : ILawDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ILawActions _lawActions; + private readonly IContentProvider _contentProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IENFFileProvider _enfFileProvider; - public LawDialog Create() - { - return new LawDialog(_nativeGraphicsManager, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _textInputDialogFactory, - _lawActions, - _contentProvider, - _currentMapStateProvider, - _enfFileProvider); - } + public LawDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + ITextInputDialogFactory textInputDialogFactory, + ILawActions lawActions, + IContentProvider contentProvider, + ICurrentMapStateProvider currentMapStateProvider, + IENFFileProvider enfFileProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _textInputDialogFactory = textInputDialogFactory; + _lawActions = lawActions; + _contentProvider = contentProvider; + _currentMapStateProvider = currentMapStateProvider; + _enfFileProvider = enfFileProvider; } - public interface ILawDialogFactory + public LawDialog Create() { - LawDialog Create(); + return new LawDialog(_nativeGraphicsManager, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _textInputDialogFactory, + _lawActions, + _contentProvider, + _currentMapStateProvider, + _enfFileProvider); } +} + +public interface ILawDialogFactory +{ + LawDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs b/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs index fc9065bee..499aff5ba 100644 --- a/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs @@ -9,66 +9,65 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class LockerDialogFactory : ILockerDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ILockerActions _lockerActions; - private readonly IEODialogButtonService _dialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ICharacterProvider _characterProvider; - private readonly ILockerDataProvider _lockerDataProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly IEIFFileProvider _eifFileProvider; +namespace EndlessClient.Dialogs.Factories; - public LockerDialogFactory(INativeGraphicsManager nativeGraphicsManager, - ILockerActions lockerActions, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IInventorySpaceValidator inventorySpaceValidator, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - ICharacterProvider characterProvider, - ILockerDataProvider lockerDataProvider, - IHudControlProvider hudControlProvider, - IEIFFileProvider eifFileProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _lockerActions = lockerActions; - _dialogButtonService = dialogButtonService; - _localizedStringFinder = localizedStringFinder; - _inventorySpaceValidator = inventorySpaceValidator; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _characterProvider = characterProvider; - _lockerDataProvider = lockerDataProvider; - _hudControlProvider = hudControlProvider; - _eifFileProvider = eifFileProvider; - } +[AutoMappedType] +public class LockerDialogFactory : ILockerDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ILockerActions _lockerActions; + private readonly IEODialogButtonService _dialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ICharacterProvider _characterProvider; + private readonly ILockerDataProvider _lockerDataProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly IEIFFileProvider _eifFileProvider; - public LockerDialog Create() - { - return new LockerDialog(_nativeGraphicsManager, - _lockerActions, - _dialogButtonService, - _localizedStringFinder, - _inventorySpaceValidator, - _statusLabelSetter, - _messageBoxFactory, - _characterProvider, - _lockerDataProvider, - _hudControlProvider, - _eifFileProvider); - } + public LockerDialogFactory(INativeGraphicsManager nativeGraphicsManager, + ILockerActions lockerActions, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IInventorySpaceValidator inventorySpaceValidator, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + ICharacterProvider characterProvider, + ILockerDataProvider lockerDataProvider, + IHudControlProvider hudControlProvider, + IEIFFileProvider eifFileProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _lockerActions = lockerActions; + _dialogButtonService = dialogButtonService; + _localizedStringFinder = localizedStringFinder; + _inventorySpaceValidator = inventorySpaceValidator; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _characterProvider = characterProvider; + _lockerDataProvider = lockerDataProvider; + _hudControlProvider = hudControlProvider; + _eifFileProvider = eifFileProvider; } - public interface ILockerDialogFactory + public LockerDialog Create() { - LockerDialog Create(); + return new LockerDialog(_nativeGraphicsManager, + _lockerActions, + _dialogButtonService, + _localizedStringFinder, + _inventorySpaceValidator, + _statusLabelSetter, + _messageBoxFactory, + _characterProvider, + _lockerDataProvider, + _hudControlProvider, + _eifFileProvider); } +} + +public interface ILockerDialogFactory +{ + LockerDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs b/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs index b1ec454e0..7fa760f19 100644 --- a/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs @@ -9,69 +9,68 @@ using EOLib.Graphics; using EOLib.IO.Repositories; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType(IsSingleton = true)] - public class PaperdollDialogFactory : IPaperdollDialogFactory - { - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ISfxPlayer _sfxPlayer; - private readonly IPaperdollProvider _paperdollProvider; - private readonly IPubFileProvider _pubFileProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly INativeGraphicsManager _nativeGraphicsManager; - private IInventoryController _inventoryController; - - public PaperdollDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IPaperdollProvider paperdollProvider, - IPubFileProvider pubFileProvider, - IHudControlProvider hudControlProvider, - IEODialogButtonService eoDialogButtonService, - IInventorySpaceValidator inventorySpaceValidator, - IEOMessageBoxFactory eoMessageBoxFactory, - IStatusLabelSetter statusLabelSetter, - ISfxPlayer sfxPlayer) - { - _paperdollProvider = paperdollProvider; - _pubFileProvider = pubFileProvider; - _hudControlProvider = hudControlProvider; - _nativeGraphicsManager = nativeGraphicsManager; - _eoDialogButtonService = eoDialogButtonService; - _inventorySpaceValidator = inventorySpaceValidator; - _eoMessageBoxFactory = eoMessageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _sfxPlayer = sfxPlayer; - } +namespace EndlessClient.Dialogs.Factories; - public PaperdollDialog Create(Character character, bool isMainCharacter) - { - return new PaperdollDialog(_nativeGraphicsManager, - _inventoryController, - _paperdollProvider, - _pubFileProvider, - _hudControlProvider, - _eoDialogButtonService, - _inventorySpaceValidator, - _eoMessageBoxFactory, - _statusLabelSetter, - _sfxPlayer, - character, - isMainCharacter); - } +[AutoMappedType(IsSingleton = true)] +public class PaperdollDialogFactory : IPaperdollDialogFactory +{ + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ISfxPlayer _sfxPlayer; + private readonly IPaperdollProvider _paperdollProvider; + private readonly IPubFileProvider _pubFileProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private IInventoryController _inventoryController; - public void InjectInventoryController(IInventoryController inventoryController) - { - _inventoryController = inventoryController; - } + public PaperdollDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IPaperdollProvider paperdollProvider, + IPubFileProvider pubFileProvider, + IHudControlProvider hudControlProvider, + IEODialogButtonService eoDialogButtonService, + IInventorySpaceValidator inventorySpaceValidator, + IEOMessageBoxFactory eoMessageBoxFactory, + IStatusLabelSetter statusLabelSetter, + ISfxPlayer sfxPlayer) + { + _paperdollProvider = paperdollProvider; + _pubFileProvider = pubFileProvider; + _hudControlProvider = hudControlProvider; + _nativeGraphicsManager = nativeGraphicsManager; + _eoDialogButtonService = eoDialogButtonService; + _inventorySpaceValidator = inventorySpaceValidator; + _eoMessageBoxFactory = eoMessageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _sfxPlayer = sfxPlayer; } - public interface IPaperdollDialogFactory + public PaperdollDialog Create(Character character, bool isMainCharacter) { - PaperdollDialog Create(Character character, bool isMainCharacter); + return new PaperdollDialog(_nativeGraphicsManager, + _inventoryController, + _paperdollProvider, + _pubFileProvider, + _hudControlProvider, + _eoDialogButtonService, + _inventorySpaceValidator, + _eoMessageBoxFactory, + _statusLabelSetter, + _sfxPlayer, + character, + isMainCharacter); + } - void InjectInventoryController(IInventoryController inventoryController); + public void InjectInventoryController(IInventoryController inventoryController) + { + _inventoryController = inventoryController; } +} + +public interface IPaperdollDialogFactory +{ + PaperdollDialog Create(Character character, bool isMainCharacter); + + void InjectInventoryController(IInventoryController inventoryController); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs b/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs index 73b9e7d77..f29f7c6f5 100644 --- a/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs @@ -5,46 +5,45 @@ using EOLib.Graphics; using EOLib.IO.Repositories; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class QuestDialogFactory : IQuestDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IQuestActions _questActions; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IQuestDataProvider _questDataProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly IContentProvider _contentProvider; +namespace EndlessClient.Dialogs.Factories; - public QuestDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IQuestActions questActions, - IEODialogButtonService dialogButtonService, - IQuestDataProvider questDataProvider, - IENFFileProvider enfFileProvider, - IContentProvider contentProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _questActions = questActions; - _dialogButtonService = dialogButtonService; - _questDataProvider = questDataProvider; - _enfFileProvider = enfFileProvider; - _contentProvider = contentProvider; - } +[AutoMappedType] +public class QuestDialogFactory : IQuestDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IQuestActions _questActions; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IQuestDataProvider _questDataProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly IContentProvider _contentProvider; - public QuestDialog Create() - { - return new QuestDialog(_nativeGraphicsManager, - _questActions, - _dialogButtonService, - _questDataProvider, - _enfFileProvider, - _contentProvider); - } + public QuestDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IQuestActions questActions, + IEODialogButtonService dialogButtonService, + IQuestDataProvider questDataProvider, + IENFFileProvider enfFileProvider, + IContentProvider contentProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _questActions = questActions; + _dialogButtonService = dialogButtonService; + _questDataProvider = questDataProvider; + _enfFileProvider = enfFileProvider; + _contentProvider = contentProvider; } - public interface IQuestDialogFactory + public QuestDialog Create() { - QuestDialog Create(); + return new QuestDialog(_nativeGraphicsManager, + _questActions, + _dialogButtonService, + _questDataProvider, + _enfFileProvider, + _contentProvider); } +} + +public interface IQuestDialogFactory +{ + QuestDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs b/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs index 18ca65f3a..215f040d8 100644 --- a/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs @@ -5,42 +5,41 @@ using EOLib.Graphics; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class QuestStatusDialogFactory : IQuestStatusDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IQuestDataProvider _questDataProvider; - private readonly ICharacterProvider _characterProvider; +namespace EndlessClient.Dialogs.Factories; - public QuestStatusDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IQuestDataProvider questDataProvider, - ICharacterProvider characterProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _localizedStringFinder = localizedStringFinder; - _questDataProvider = questDataProvider; - _characterProvider = characterProvider; - } +[AutoMappedType] +public class QuestStatusDialogFactory : IQuestStatusDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IQuestDataProvider _questDataProvider; + private readonly ICharacterProvider _characterProvider; - public QuestStatusDialog Create() - { - return new QuestStatusDialog(_nativeGraphicsManager, - _dialogButtonService, - _localizedStringFinder, - _questDataProvider, - _characterProvider); - } + public QuestStatusDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IQuestDataProvider questDataProvider, + ICharacterProvider characterProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _localizedStringFinder = localizedStringFinder; + _questDataProvider = questDataProvider; + _characterProvider = characterProvider; } - public interface IQuestStatusDialogFactory + public QuestStatusDialog Create() { - QuestStatusDialog Create(); + return new QuestStatusDialog(_nativeGraphicsManager, + _dialogButtonService, + _localizedStringFinder, + _questDataProvider, + _characterProvider); } +} + +public interface IQuestStatusDialogFactory +{ + QuestStatusDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs b/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs index 5bf061e6a..48a52d906 100644 --- a/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs @@ -2,29 +2,28 @@ using EndlessClient.Dialogs.Services; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class ScrollingListDialogFactory : IScrollingListDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; +namespace EndlessClient.Dialogs.Factories; - public ScrollingListDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService) - { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - } +[AutoMappedType] +public class ScrollingListDialogFactory : IScrollingListDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; - public ScrollingListDialog Create(DialogType size) - { - return new ScrollingListDialog(_nativeGraphicsManager, _dialogButtonService, size); - } + public ScrollingListDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; } - public interface IScrollingListDialogFactory + public ScrollingListDialog Create(DialogType size) { - ScrollingListDialog Create(DialogType size); + return new ScrollingListDialog(_nativeGraphicsManager, _dialogButtonService, size); } +} + +public interface IScrollingListDialogFactory +{ + ScrollingListDialog Create(DialogType size); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs b/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs index 548c7a48b..5651ca3e9 100644 --- a/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs @@ -4,46 +4,45 @@ using EOLib.Graphics; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class SessionExpDialogFactory : ISessionExpDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ICharacterProvider _characterProvider; - private readonly IExperienceTableProvider _expTableProvider; - private readonly ICharacterSessionProvider _characterSessionProvider; +namespace EndlessClient.Dialogs.Factories; - public SessionExpDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - ICharacterProvider characterProvider, - IExperienceTableProvider expTableProvider, - ICharacterSessionProvider characterSessionProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _localizedStringFinder = localizedStringFinder; - _characterProvider = characterProvider; - _expTableProvider = expTableProvider; - _characterSessionProvider = characterSessionProvider; - } +[AutoMappedType] +public class SessionExpDialogFactory : ISessionExpDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ICharacterProvider _characterProvider; + private readonly IExperienceTableProvider _expTableProvider; + private readonly ICharacterSessionProvider _characterSessionProvider; - public SessionExpDialog Create() - { - return new SessionExpDialog(_nativeGraphicsManager, - _dialogButtonService, - _localizedStringFinder, - _characterProvider, - _expTableProvider, - _characterSessionProvider); - } + public SessionExpDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + ICharacterProvider characterProvider, + IExperienceTableProvider expTableProvider, + ICharacterSessionProvider characterSessionProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _localizedStringFinder = localizedStringFinder; + _characterProvider = characterProvider; + _expTableProvider = expTableProvider; + _characterSessionProvider = characterSessionProvider; } - public interface ISessionExpDialogFactory + public SessionExpDialog Create() { - SessionExpDialog Create(); + return new SessionExpDialog(_nativeGraphicsManager, + _dialogButtonService, + _localizedStringFinder, + _characterProvider, + _expTableProvider, + _characterSessionProvider); } +} + +public interface ISessionExpDialogFactory +{ + SessionExpDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs b/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs index ed7d589d5..711a382d4 100644 --- a/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs @@ -8,70 +8,69 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class ShopDialogFactory : IShopDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IShopActions _shopActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IItemTransferDialogFactory _itemTransferDialogFactory; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IShopDataProvider _shopDataProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IInventorySpaceValidator _inventorySpaceValidator; +namespace EndlessClient.Dialogs.Factories; - public ShopDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IShopActions shopActions, - IEOMessageBoxFactory messageBoxFactory, - IItemTransferDialogFactory itemTransferDialogFactory, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IShopDataProvider shopDataProvider, - ICharacterInventoryProvider characterInventoryProvider, - IEIFFileProvider eifFileProvider, - ICharacterProvider characterProvider, - IInventorySpaceValidator inventorySpaceValidator) - { - _nativeGraphicsManager = nativeGraphicsManager; - _shopActions = shopActions; - _messageBoxFactory = messageBoxFactory; - _itemTransferDialogFactory = itemTransferDialogFactory; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _shopDataProvider = shopDataProvider; - _characterInventoryProvider = characterInventoryProvider; - _eifFileProvider = eifFileProvider; - _characterProvider = characterProvider; - _inventorySpaceValidator = inventorySpaceValidator; - } +[AutoMappedType] +public class ShopDialogFactory : IShopDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IShopActions _shopActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IItemTransferDialogFactory _itemTransferDialogFactory; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IShopDataProvider _shopDataProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IInventorySpaceValidator _inventorySpaceValidator; - public ShopDialog Create() - { - return new ShopDialog(_nativeGraphicsManager, - _shopActions, - _messageBoxFactory, - _itemTransferDialogFactory, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _shopDataProvider, - _characterInventoryProvider, - _eifFileProvider, - _characterProvider, - _inventorySpaceValidator); - } + public ShopDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IShopActions shopActions, + IEOMessageBoxFactory messageBoxFactory, + IItemTransferDialogFactory itemTransferDialogFactory, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IShopDataProvider shopDataProvider, + ICharacterInventoryProvider characterInventoryProvider, + IEIFFileProvider eifFileProvider, + ICharacterProvider characterProvider, + IInventorySpaceValidator inventorySpaceValidator) + { + _nativeGraphicsManager = nativeGraphicsManager; + _shopActions = shopActions; + _messageBoxFactory = messageBoxFactory; + _itemTransferDialogFactory = itemTransferDialogFactory; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _shopDataProvider = shopDataProvider; + _characterInventoryProvider = characterInventoryProvider; + _eifFileProvider = eifFileProvider; + _characterProvider = characterProvider; + _inventorySpaceValidator = inventorySpaceValidator; } - public interface IShopDialogFactory + public ShopDialog Create() { - ShopDialog Create(); + return new ShopDialog(_nativeGraphicsManager, + _shopActions, + _messageBoxFactory, + _itemTransferDialogFactory, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _shopDataProvider, + _characterInventoryProvider, + _eifFileProvider, + _characterProvider, + _inventorySpaceValidator); } +} + +public interface IShopDialogFactory +{ + ShopDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs b/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs index e17ff74c8..30e4e722d 100644 --- a/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs @@ -8,74 +8,73 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class SkillmasterDialogFactory : ISkillmasterDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ISkillmasterActions _skillmasterActions; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ISkillDataProvider _skillDataProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IPubFileProvider _pubFileProvider; - private readonly IContentProvider _contentProvider; +namespace EndlessClient.Dialogs.Factories; - public SkillmasterDialogFactory(INativeGraphicsManager nativeGraphicsManager, - ISkillmasterActions skillmasterActions, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - ITextInputDialogFactory textInputDialogFactory, - ISkillDataProvider skillDataProvider, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IPubFileProvider pubFileProvider, - IContentProvider contentProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _skillmasterActions = skillmasterActions; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _textInputDialogFactory = textInputDialogFactory; - _skillDataProvider = skillDataProvider; - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _pubFileProvider = pubFileProvider; - _contentProvider = contentProvider; - } +[AutoMappedType] +public class SkillmasterDialogFactory : ISkillmasterDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ISkillmasterActions _skillmasterActions; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ISkillDataProvider _skillDataProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IPubFileProvider _pubFileProvider; + private readonly IContentProvider _contentProvider; - public SkillmasterDialog Create() - { - return new SkillmasterDialog(_nativeGraphicsManager, - _skillmasterActions, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _statusLabelSetter, - _messageBoxFactory, - _textInputDialogFactory, - _skillDataProvider, - _characterProvider, - _characterInventoryProvider, - _pubFileProvider, - _contentProvider); - } + public SkillmasterDialogFactory(INativeGraphicsManager nativeGraphicsManager, + ISkillmasterActions skillmasterActions, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + ITextInputDialogFactory textInputDialogFactory, + ISkillDataProvider skillDataProvider, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IPubFileProvider pubFileProvider, + IContentProvider contentProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _skillmasterActions = skillmasterActions; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _textInputDialogFactory = textInputDialogFactory; + _skillDataProvider = skillDataProvider; + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _pubFileProvider = pubFileProvider; + _contentProvider = contentProvider; } - public interface ISkillmasterDialogFactory + public SkillmasterDialog Create() { - SkillmasterDialog Create(); + return new SkillmasterDialog(_nativeGraphicsManager, + _skillmasterActions, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _statusLabelSetter, + _messageBoxFactory, + _textInputDialogFactory, + _skillDataProvider, + _characterProvider, + _characterInventoryProvider, + _pubFileProvider, + _contentProvider); } +} + +public interface ISkillmasterDialogFactory +{ + SkillmasterDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs b/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs index b72776cd5..4fec511a4 100644 --- a/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs @@ -5,45 +5,44 @@ using EndlessClient.HUD.Chat; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class TextInputDialogFactory : ITextInputDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatTextBoxActions _chatTextBoxActions; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IContentProvider _contentProvider; - private readonly ISfxPlayer _sfxPlayer; +namespace EndlessClient.Dialogs.Factories; - public TextInputDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - IContentProvider contentProvider, - ISfxPlayer sfxPlayer) - { - _nativeGraphicsManager = nativeGraphicsManager; - _chatTextBoxActions = chatTextBoxActions; - _eoDialogButtonService = eoDialogButtonService; - _contentProvider = contentProvider; - _sfxPlayer = sfxPlayer; - } +[AutoMappedType] +public class TextInputDialogFactory : ITextInputDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatTextBoxActions _chatTextBoxActions; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IContentProvider _contentProvider; + private readonly ISfxPlayer _sfxPlayer; - public TextInputDialog Create(string prompt, int maxInputChars = 12) - { - var dlg = new TextInputDialog(_nativeGraphicsManager, - _chatTextBoxActions, - _eoDialogButtonService, - _contentProvider, - prompt, - maxInputChars); - dlg.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - return dlg; - } + public TextInputDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + IContentProvider contentProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _chatTextBoxActions = chatTextBoxActions; + _eoDialogButtonService = eoDialogButtonService; + _contentProvider = contentProvider; + _sfxPlayer = sfxPlayer; } - public interface ITextInputDialogFactory + public TextInputDialog Create(string prompt, int maxInputChars = 12) { - TextInputDialog Create(string prompt, int maxInputChars = 12); + var dlg = new TextInputDialog(_nativeGraphicsManager, + _chatTextBoxActions, + _eoDialogButtonService, + _contentProvider, + prompt, + maxInputChars); + dlg.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + return dlg; } +} + +public interface ITextInputDialogFactory +{ + TextInputDialog Create(string prompt, int maxInputChars = 12); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs b/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs index 111ddbda3..fd1da7ffa 100644 --- a/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs @@ -5,50 +5,49 @@ using EndlessClient.HUD.Chat; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class TextMultiInputDialogFactory : ITextMultiInputDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatTextBoxActions _chatTextBoxActions; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IContentProvider _contentProvider; - private readonly ISfxPlayer _sfxPlayer; +namespace EndlessClient.Dialogs.Factories; - public TextMultiInputDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - IContentProvider contentProvider, - ISfxPlayer sfxPlayer) - { - _nativeGraphicsManager = nativeGraphicsManager; - _chatTextBoxActions = chatTextBoxActions; - _eoDialogButtonService = eoDialogButtonService; - _contentProvider = contentProvider; - _sfxPlayer = sfxPlayer; - } +[AutoMappedType] +public class TextMultiInputDialogFactory : ITextMultiInputDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatTextBoxActions _chatTextBoxActions; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IContentProvider _contentProvider; + private readonly ISfxPlayer _sfxPlayer; - public TextMultiInputDialog Create(string title, string prompt, TextMultiInputDialog.DialogSize size, params TextMultiInputDialog.InputInfo[] inputInfo) - { - var dlg = new TextMultiInputDialog(_nativeGraphicsManager, - _chatTextBoxActions, - _eoDialogButtonService, - _contentProvider, - size, - title, - prompt, - inputInfo); - dlg.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - return dlg; - } + public TextMultiInputDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + IContentProvider contentProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _chatTextBoxActions = chatTextBoxActions; + _eoDialogButtonService = eoDialogButtonService; + _contentProvider = contentProvider; + _sfxPlayer = sfxPlayer; } - public interface ITextMultiInputDialogFactory + public TextMultiInputDialog Create(string title, string prompt, TextMultiInputDialog.DialogSize size, params TextMultiInputDialog.InputInfo[] inputInfo) { - TextMultiInputDialog Create(string title, - string prompt, - TextMultiInputDialog.DialogSize size, - params TextMultiInputDialog.InputInfo[] inputInfo); + var dlg = new TextMultiInputDialog(_nativeGraphicsManager, + _chatTextBoxActions, + _eoDialogButtonService, + _contentProvider, + size, + title, + prompt, + inputInfo); + dlg.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + return dlg; } +} + +public interface ITextMultiInputDialogFactory +{ + TextMultiInputDialog Create(string title, + string prompt, + TextMultiInputDialog.DialogSize size, + params TextMultiInputDialog.InputInfo[] inputInfo); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs b/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs index bfd49b8b4..e064f5b0d 100644 --- a/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs @@ -10,70 +10,69 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories -{ - [AutoMappedType] - public class TradeDialogFactory : ITradeDialogFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ITradeActions _tradeActions; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly ITradeProvider _tradeProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - private readonly ISfxPlayer _sfxPlayer; +namespace EndlessClient.Dialogs.Factories; - public TradeDialogFactory(INativeGraphicsManager nativeGraphicsManager, - ITradeActions tradeActions, - ILocalizedStringFinder localizedStringFinder, - IEODialogButtonService dialogButtonService, - IEOMessageBoxFactory messageBoxFactory, - IStatusLabelSetter statusLabelSetter, - IInventorySpaceValidator inventorySpaceValidator, - ITradeProvider tradeProvider, - ICharacterProvider characterProvider, - IEIFFileProvider eifFileProvider, - IMapItemGraphicProvider mapItemGraphicProvider, - ISfxPlayer sfxPlayer) - { - _nativeGraphicsManager = nativeGraphicsManager; - _tradeActions = tradeActions; - _localizedStringFinder = localizedStringFinder; - _dialogButtonService = dialogButtonService; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _inventorySpaceValidator = inventorySpaceValidator; - _tradeProvider = tradeProvider; - _characterProvider = characterProvider; - _eifFileProvider = eifFileProvider; - _mapItemGraphicProvider = mapItemGraphicProvider; - _sfxPlayer = sfxPlayer; - } +[AutoMappedType] +public class TradeDialogFactory : ITradeDialogFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ITradeActions _tradeActions; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly ITradeProvider _tradeProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IMapItemGraphicProvider _mapItemGraphicProvider; + private readonly ISfxPlayer _sfxPlayer; - public TradeDialog Create() - { - return new TradeDialog(_nativeGraphicsManager, - _tradeActions, - _localizedStringFinder, - _dialogButtonService, - _messageBoxFactory, - _statusLabelSetter, - _inventorySpaceValidator, - _tradeProvider, - _characterProvider, - _eifFileProvider, - _mapItemGraphicProvider, - _sfxPlayer); - } + public TradeDialogFactory(INativeGraphicsManager nativeGraphicsManager, + ITradeActions tradeActions, + ILocalizedStringFinder localizedStringFinder, + IEODialogButtonService dialogButtonService, + IEOMessageBoxFactory messageBoxFactory, + IStatusLabelSetter statusLabelSetter, + IInventorySpaceValidator inventorySpaceValidator, + ITradeProvider tradeProvider, + ICharacterProvider characterProvider, + IEIFFileProvider eifFileProvider, + IMapItemGraphicProvider mapItemGraphicProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _tradeActions = tradeActions; + _localizedStringFinder = localizedStringFinder; + _dialogButtonService = dialogButtonService; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _inventorySpaceValidator = inventorySpaceValidator; + _tradeProvider = tradeProvider; + _characterProvider = characterProvider; + _eifFileProvider = eifFileProvider; + _mapItemGraphicProvider = mapItemGraphicProvider; + _sfxPlayer = sfxPlayer; } - public interface ITradeDialogFactory + public TradeDialog Create() { - TradeDialog Create(); + return new TradeDialog(_nativeGraphicsManager, + _tradeActions, + _localizedStringFinder, + _dialogButtonService, + _messageBoxFactory, + _statusLabelSetter, + _inventorySpaceValidator, + _tradeProvider, + _characterProvider, + _eifFileProvider, + _mapItemGraphicProvider, + _sfxPlayer); } +} + +public interface ITradeDialogFactory +{ + TradeDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/FriendIgnoreListDialog.cs b/EndlessClient/Dialogs/FriendIgnoreListDialog.cs index ba481f3c8..c1cbccc8b 100644 --- a/EndlessClient/Dialogs/FriendIgnoreListDialog.cs +++ b/EndlessClient/Dialogs/FriendIgnoreListDialog.cs @@ -5,34 +5,33 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class FriendIgnoreListDialog : ScrollingListDialog { - public class FriendIgnoreListDialog : ScrollingListDialog - { - private readonly IOnlinePlayerProvider _onlinePlayerProvider; + private readonly IOnlinePlayerProvider _onlinePlayerProvider; - private HashSet _cachedOnlinePlayers; + private HashSet _cachedOnlinePlayers; - public FriendIgnoreListDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IOnlinePlayerProvider onlinePlayerProvider) - : base(nativeGraphicsManager, dialogButtonService, DialogType.FriendIgnore) - { - _onlinePlayerProvider = onlinePlayerProvider; - _cachedOnlinePlayers = new HashSet(); - } + public FriendIgnoreListDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IOnlinePlayerProvider onlinePlayerProvider) + : base(nativeGraphicsManager, dialogButtonService, DialogType.FriendIgnore) + { + _onlinePlayerProvider = onlinePlayerProvider; + _cachedOnlinePlayers = new HashSet(); + } - protected override void OnUpdateControl(GameTime gameTime) + protected override void OnUpdateControl(GameTime gameTime) + { + if (!_cachedOnlinePlayers.SetEquals(_onlinePlayerProvider.OnlinePlayers)) { - if (!_cachedOnlinePlayers.SetEquals(_onlinePlayerProvider.OnlinePlayers)) - { - _cachedOnlinePlayers = _onlinePlayerProvider.OnlinePlayers.ToHashSet(); + _cachedOnlinePlayers = _onlinePlayerProvider.OnlinePlayers.ToHashSet(); - ClearHighlightedText(); - HighlightTextByLabel(_cachedOnlinePlayers.Select(x => x.Name).ToList()); - } - - base.OnUpdateControl(gameTime); + ClearHighlightedText(); + HighlightTextByLabel(_cachedOnlinePlayers.Select(x => x.Name).ToList()); } + + base.OnUpdateControl(gameTime); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/GameLoadingDialog.cs b/EndlessClient/Dialogs/GameLoadingDialog.cs index 67fde1c75..af9b87c4e 100644 --- a/EndlessClient/Dialogs/GameLoadingDialog.cs +++ b/EndlessClient/Dialogs/GameLoadingDialog.cs @@ -8,129 +8,128 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class GameLoadingDialog : BaseEODialog { - public class GameLoadingDialog : BaseEODialog + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly Texture2D _backgroundSprite; + private readonly IXNALabel _message, _caption; + + private DateTime _lastBackgroundUpdate; + private int _bgSrcIndex; + + public GameLoadingDialog(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + ILocalizedStringFinder localizedStringFinder) + : base(nativeGraphicsManager, gameStateProvider) { - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly Texture2D _backgroundSprite; - private readonly IXNALabel _message, _caption; - - private DateTime _lastBackgroundUpdate; - private int _bgSrcIndex; - - public GameLoadingDialog(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - ILocalizedStringFinder localizedStringFinder) - : base(nativeGraphicsManager, gameStateProvider) - { - _localizedStringFinder = localizedStringFinder; - _backgroundSprite = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 33); - - DrawPosition = new Vector2(clientWindowSizeProvider.Width - _backgroundSprite.Width / 4 - 10, - clientWindowSizeProvider.Height - _backgroundSprite.Height - 10); + _localizedStringFinder = localizedStringFinder; + _backgroundSprite = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 33); - SetSize(_backgroundSprite.Width / 4, _backgroundSprite.Height); + DrawPosition = new Vector2(clientWindowSizeProvider.Width - _backgroundSprite.Width / 4 - 10, + clientWindowSizeProvider.Height - _backgroundSprite.Height - 10); - _bgSrcIndex = 0; - _lastBackgroundUpdate = DateTime.Now; + SetSize(_backgroundSprite.Width / 4, _backgroundSprite.Height); - _caption = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_PLEASE_WAIT), - ForeColor = ColorConstants.LightYellowText, - DrawPosition = new Vector2(12, 9) - }; - _caption.SetParentControl(this); - - var gen = new Random(); - var messageTextID = (EOResourceID)gen.Next((int)EOResourceID.LOADING_GAME_HINT_FIRST, (int)EOResourceID.LOADING_GAME_HINT_LAST); - var localizedMessage = _localizedStringFinder.GetString(messageTextID); - - _message = new XNALabel(Constants.FontSize08) - { - AutoSize = true, - TextWidth = 175, - ForeColor = ColorConstants.MediumGrayText, - Text = localizedMessage, - DrawPosition = new Vector2(18, 61) - }; - _message.SetParentControl(this); - } + _bgSrcIndex = 0; + _lastBackgroundUpdate = DateTime.Now; - public override void Initialize() + _caption = new XNALabel(Constants.FontSize10) { - _caption.Initialize(); - _message.Initialize(); - - base.Initialize(); - } - - protected override void OnUpdateControl(GameTime gt) + AutoSize = true, + Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_PLEASE_WAIT), + ForeColor = ColorConstants.LightYellowText, + DrawPosition = new Vector2(12, 9) + }; + _caption.SetParentControl(this); + + var gen = new Random(); + var messageTextID = (EOResourceID)gen.Next((int)EOResourceID.LOADING_GAME_HINT_FIRST, (int)EOResourceID.LOADING_GAME_HINT_LAST); + var localizedMessage = _localizedStringFinder.GetString(messageTextID); + + _message = new XNALabel(Constants.FontSize08) { - if ((int)(DateTime.Now - _lastBackgroundUpdate).TotalMilliseconds > 500) - { - _bgSrcIndex = _bgSrcIndex == 3 ? 0 : _bgSrcIndex + 1; - _lastBackgroundUpdate = DateTime.Now; - } + AutoSize = true, + TextWidth = 175, + ForeColor = ColorConstants.MediumGrayText, + Text = localizedMessage, + DrawPosition = new Vector2(18, 61) + }; + _message.SetParentControl(this); + } - base.OnUpdateControl(gt); - } + public override void Initialize() + { + _caption.Initialize(); + _message.Initialize(); - protected override void OnDrawControl(GameTime gt) - { - _spriteBatch.Begin(); - _spriteBatch.Draw(_backgroundSprite, - DrawAreaWithParentOffset, - new Rectangle(_bgSrcIndex * (_backgroundSprite.Width / 4), 0, _backgroundSprite.Width / 4, _backgroundSprite.Height), - Color.White); - _spriteBatch.End(); - - base.OnDrawControl(gt); - } + base.Initialize(); + } - public void SetState(GameLoadingDialogState whichState) + protected override void OnUpdateControl(GameTime gt) + { + if ((int)(DateTime.Now - _lastBackgroundUpdate).TotalMilliseconds > 500) { - switch (whichState) - { - case GameLoadingDialogState.Map: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_MAP); - break; - case GameLoadingDialogState.Item: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_ITEMS); - break; - case GameLoadingDialogState.NPC: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_NPCS); - break; - case GameLoadingDialogState.Spell: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_SKILLS); - break; - case GameLoadingDialogState.Class: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_CLASSES); - break; - case GameLoadingDialogState.LoadingGame: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_LOADING_GAME); - break; - default: - throw new ArgumentOutOfRangeException(nameof(whichState), whichState, null); - } + _bgSrcIndex = _bgSrcIndex == 3 ? 0 : _bgSrcIndex + 1; + _lastBackgroundUpdate = DateTime.Now; } - public void CloseDialog() + base.OnUpdateControl(gt); + } + + protected override void OnDrawControl(GameTime gt) + { + _spriteBatch.Begin(); + _spriteBatch.Draw(_backgroundSprite, + DrawAreaWithParentOffset, + new Rectangle(_bgSrcIndex * (_backgroundSprite.Width / 4), 0, _backgroundSprite.Width / 4, _backgroundSprite.Height), + Color.White); + _spriteBatch.End(); + + base.OnDrawControl(gt); + } + + public void SetState(GameLoadingDialogState whichState) + { + switch (whichState) { - Close(XNADialogResult.NO_BUTTON_PRESSED); + case GameLoadingDialogState.Map: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_MAP); + break; + case GameLoadingDialogState.Item: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_ITEMS); + break; + case GameLoadingDialogState.NPC: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_NPCS); + break; + case GameLoadingDialogState.Spell: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_SKILLS); + break; + case GameLoadingDialogState.Class: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_CLASSES); + break; + case GameLoadingDialogState.LoadingGame: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_LOADING_GAME); + break; + default: + throw new ArgumentOutOfRangeException(nameof(whichState), whichState, null); } } - public enum GameLoadingDialogState + public void CloseDialog() { - Map, - Item, - NPC, - Spell, - Class, - LoadingGame + Close(XNADialogResult.NO_BUTTON_PRESSED); } +} + +public enum GameLoadingDialogState +{ + Map, + Item, + NPC, + Spell, + Class, + LoadingGame } \ No newline at end of file diff --git a/EndlessClient/Dialogs/InnkeeperDialog.cs b/EndlessClient/Dialogs/InnkeeperDialog.cs index 22bd4d0cb..a1ff42106 100644 --- a/EndlessClient/Dialogs/InnkeeperDialog.cs +++ b/EndlessClient/Dialogs/InnkeeperDialog.cs @@ -13,242 +13,241 @@ using System.Collections.Generic; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class InnkeeperDialog : ScrollingListDialog { - public class InnkeeperDialog : ScrollingListDialog + private enum InnkeeperDialogState { - private enum InnkeeperDialogState - { - // initial menu: Registration and Sleep items - Initial, - // registration menu: sign up and unsubscribe items - Registration, - // sign up text + link - SignUp, - // unsubscribe text + link - Unsubscribe - } + // initial menu: Registration and Sleep items + Initial, + // registration menu: sign up and unsubscribe items + Registration, + // sign up text + link + SignUp, + // unsubscribe text + link + Unsubscribe + } - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ICitizenActions _citizenActions; - private readonly IContentProvider _contentProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly ICitizenDataProvider _citizenDataProvider; - private InnkeeperDialogState _state; - private int _lastVendorId; - - public InnkeeperDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IEOMessageBoxFactory messageBoxFactory, - ITextInputDialogFactory textInputDialogFactory, - ICitizenActions citizenActions, - IContentProvider contentProvider, - IENFFileProvider enfFileProvider, - ICitizenDataProvider citizenDataProvider) - : base(nativeGraphicsManager, dialogButtonService, DialogType.Inn) + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ICitizenActions _citizenActions; + private readonly IContentProvider _contentProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly ICitizenDataProvider _citizenDataProvider; + private InnkeeperDialogState _state; + private int _lastVendorId; + + public InnkeeperDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IEOMessageBoxFactory messageBoxFactory, + ITextInputDialogFactory textInputDialogFactory, + ICitizenActions citizenActions, + IContentProvider contentProvider, + IENFFileProvider enfFileProvider, + ICitizenDataProvider citizenDataProvider) + : base(nativeGraphicsManager, dialogButtonService, DialogType.Inn) + { + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _messageBoxFactory = messageBoxFactory; + _textInputDialogFactory = textInputDialogFactory; + _citizenActions = citizenActions; + _contentProvider = contentProvider; + _enfFileProvider = enfFileProvider; + _citizenDataProvider = citizenDataProvider; + + SetState(InnkeeperDialogState.Initial); + + BackAction += (_, _) => { - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _messageBoxFactory = messageBoxFactory; - _textInputDialogFactory = textInputDialogFactory; - _citizenActions = citizenActions; - _contentProvider = contentProvider; - _enfFileProvider = enfFileProvider; - _citizenDataProvider = citizenDataProvider; - - SetState(InnkeeperDialogState.Initial); - - BackAction += (_, _) => - { - if (_state == InnkeeperDialogState.SignUp || _state == InnkeeperDialogState.Unsubscribe) - SetState(InnkeeperDialogState.Registration); - else if (_state == InnkeeperDialogState.Registration) - SetState(InnkeeperDialogState.Initial); - }; - } + if (_state == InnkeeperDialogState.SignUp || _state == InnkeeperDialogState.Unsubscribe) + SetState(InnkeeperDialogState.Registration); + else if (_state == InnkeeperDialogState.Registration) + SetState(InnkeeperDialogState.Initial); + }; + } - protected override void OnUpdateControl(GameTime gameTime) + protected override void OnUpdateControl(GameTime gameTime) + { + if (_citizenDataProvider.BehaviorID.Map(x => x != _lastVendorId).ValueOr(false)) { - if (_citizenDataProvider.BehaviorID.Map(x => x != _lastVendorId).ValueOr(false)) - { - _lastVendorId = _citizenDataProvider.BehaviorID.ValueOr(0); - - _enfFileProvider.ENFFile.SingleOrNone(x => x.Type == NPCType.Inn && x.VendorID == _lastVendorId) - .MatchSome(innkeeperData => Title = innkeeperData.Name); - } + _lastVendorId = _citizenDataProvider.BehaviorID.ValueOr(0); - base.OnUpdateControl(gameTime); + _enfFileProvider.ENFFile.SingleOrNone(x => x.Type == NPCType.Inn && x.VendorID == _lastVendorId) + .MatchSome(innkeeperData => Title = innkeeperData.Name); } - private void SetState(InnkeeperDialogState state) - { - if (state != InnkeeperDialogState.Initial && _state == state) - return; + base.OnUpdateControl(gameTime); + } - _state = state; + private void SetState(InnkeeperDialogState state) + { + if (state != InnkeeperDialogState.Initial && _state == state) + return; - ClearItemList(); + _state = state; - switch (_state) - { - case InnkeeperDialogState.Initial: - { - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.Cancel; + ClearItemList(); - var registrationItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Registration), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_REGISTRATION_SERVICE), - SubText = _localizedStringFinder.GetString(EOResourceID.INN_CITIZEN_REGISTRATION_SERVICE), - OffsetY = 45, - }; - registrationItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.Registration); - registrationItem.RightClick += (_, _) => SetState(InnkeeperDialogState.Registration); - - var sleepItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.InnSleep), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_SLEEP), - SubText = _localizedStringFinder.GetString(EOResourceID.INN_FULL_HP_RECOVERY), - OffsetY = 45, - }; - sleepItem.LeftClick += (_, _) => _citizenActions.RequestSleep(); - sleepItem.RightClick += (_, _) => _citizenActions.RequestSleep(); - - SetItemList(new List { registrationItem, sleepItem }); - } - break; - case InnkeeperDialogState.Registration: - { - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.BackCancel; + switch (_state) + { + case InnkeeperDialogState.Initial: + { + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.Cancel; - var signUpItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.SignUp), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_SIGN_UP), - SubText = _localizedStringFinder.GetString(EOResourceID.INN_BECOME_A_CITIZEN), - OffsetY = 45, - }; - signUpItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.SignUp); - signUpItem.RightClick += (_, _) => SetState(InnkeeperDialogState.SignUp); - - var unsubscribeItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Unsubscribe), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_UNSUBSCRIBE), - SubText = _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_CITIZENSHIP), - OffsetY = 45, - }; - unsubscribeItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.Unsubscribe); - unsubscribeItem.RightClick += (_, _) => SetState(InnkeeperDialogState.Unsubscribe); - - SetItemList(new List { signUpItem, unsubscribeItem }); - } - break; - case InnkeeperDialogState.SignUp: + var registrationItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) { - ListItemType = ListDialogItem.ListItemStyle.Small; - Buttons = ScrollingListDialogButtons.BackCancel; - - AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], - insertLineBreaks: true, - new List + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Registration), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_REGISTRATION_SERVICE), + SubText = _localizedStringFinder.GetString(EOResourceID.INN_CITIZEN_REGISTRATION_SERVICE), + OffsetY = 45, + }; + registrationItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.Registration); + registrationItem.RightClick += (_, _) => SetState(InnkeeperDialogState.Registration); + + var sleepItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.InnSleep), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_SLEEP), + SubText = _localizedStringFinder.GetString(EOResourceID.INN_FULL_HP_RECOVERY), + OffsetY = 45, + }; + sleepItem.LeftClick += (_, _) => _citizenActions.RequestSleep(); + sleepItem.RightClick += (_, _) => _citizenActions.RequestSleep(); + + SetItemList(new List { registrationItem, sleepItem }); + } + break; + case InnkeeperDialogState.Registration: + { + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.BackCancel; + + var signUpItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + { + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.SignUp), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_SIGN_UP), + SubText = _localizedStringFinder.GetString(EOResourceID.INN_BECOME_A_CITIZEN), + OffsetY = 45, + }; + signUpItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.SignUp); + signUpItem.RightClick += (_, _) => SetState(InnkeeperDialogState.SignUp); + + var unsubscribeItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Unsubscribe), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_UNSUBSCRIBE), + SubText = _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_CITIZENSHIP), + OffsetY = 45, + }; + unsubscribeItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.Unsubscribe); + unsubscribeItem.RightClick += (_, _) => SetState(InnkeeperDialogState.Unsubscribe); + + SetItemList(new List { signUpItem, unsubscribeItem }); + } + break; + case InnkeeperDialogState.SignUp: + { + ListItemType = ListDialogItem.ListItemStyle.Small; + Buttons = ScrollingListDialogButtons.BackCancel; + + AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], + insertLineBreaks: true, + new List + { + () => { - () => + if (_citizenDataProvider.CurrentHomeID.HasValue) { - if (_citizenDataProvider.CurrentHomeID.HasValue) - { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.INN_YOU_ARE_ALREADY_A_CITIZEN_OF_A_TOWN, EOResourceID.INN_REGISTRATION_SERVICE); - dlg.ShowDialog(); - } - else - { - var answers = new List(3); + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.INN_YOU_ARE_ALREADY_A_CITIZEN_OF_A_TOWN, EOResourceID.INN_REGISTRATION_SERVICE); + dlg.ShowDialog(); + } + else + { + var answers = new List(3); - Func createDlg = i => _textInputDialogFactory.Create($"{i + 1}. {_citizenDataProvider.Questions[i]}"); + Func createDlg = i => _textInputDialogFactory.Create($"{i + 1}. {_citizenDataProvider.Questions[i]}"); - // we can't suspend the context and await the result of the dialogs because XNAControls isn't that powerful, - // so we have to get the result in the DialogClosing event handler after we know the user is done entering their input - var dlg1 = createDlg(0); - dlg1.DialogClosing += (_, e1) => + // we can't suspend the context and await the result of the dialogs because XNAControls isn't that powerful, + // so we have to get the result in the DialogClosing event handler after we know the user is done entering their input + var dlg1 = createDlg(0); + dlg1.DialogClosing += (_, e1) => + { + if (e1.Result != XNADialogResult.OK) + return; + + var dlg2 = createDlg(1); + dlg2.DialogClosing += (_, e2) => { - if (e1.Result != XNADialogResult.OK) + if (e2.Result != XNADialogResult.OK) return; - var dlg2 = createDlg(1); - dlg2.DialogClosing += (_, e2) => + var dlg3 = createDlg(2); + dlg3.DialogClosing += (_, e3) => { - if (e2.Result != XNADialogResult.OK) + if (e3.Result != XNADialogResult.OK) return; - var dlg3 = createDlg(2); - dlg3.DialogClosing += (_, e3) => + var answers = new List { - if (e3.Result != XNADialogResult.OK) - return; - - var answers = new List - { - dlg1.ResponseText, - dlg2.ResponseText, - dlg3.ResponseText - }; - - _citizenActions.SignUp(answers); + dlg1.ResponseText, + dlg2.ResponseText, + dlg3.ResponseText }; - dlg3.ShowDialog(); + _citizenActions.SignUp(answers); }; - dlg2.ShowDialog(); + dlg3.ShowDialog(); }; - dlg1.ShowDialog(); - } - }, - }, - _localizedStringFinder.GetString(EOResourceID.INN_SIGN_UP), - _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_1), - _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_2), - _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_LINK)); - } - break; - case InnkeeperDialogState.Unsubscribe: - { - ListItemType = ListDialogItem.ListItemStyle.Small; - Buttons = ScrollingListDialogButtons.BackCancel; + dlg2.ShowDialog(); + }; - AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], - insertLineBreaks: true, - new List + dlg1.ShowDialog(); + } + }, + }, + _localizedStringFinder.GetString(EOResourceID.INN_SIGN_UP), + _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_1), + _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_2), + _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_LINK)); + } + break; + case InnkeeperDialogState.Unsubscribe: + { + ListItemType = ListDialogItem.ListItemStyle.Small; + Buttons = ScrollingListDialogButtons.BackCancel; + + AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], + insertLineBreaks: true, + new List + { + () => { - () => - { - _citizenActions.Unsubscribe(); - SetState(InnkeeperDialogState.Registration); - }, + _citizenActions.Unsubscribe(); + SetState(InnkeeperDialogState.Registration); }, - _localizedStringFinder.GetString(EOResourceID.INN_UNSUBSCRIBE), - _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_TEXT_1), - _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_TEXT_LINK)); - } - break; - } + }, + _localizedStringFinder.GetString(EOResourceID.INN_UNSUBSCRIBE), + _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_TEXT_1), + _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_TEXT_LINK)); + } + break; } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ItemTransferDialog.cs b/EndlessClient/Dialogs/ItemTransferDialog.cs index 838106e9f..169c2528f 100644 --- a/EndlessClient/Dialogs/ItemTransferDialog.cs +++ b/EndlessClient/Dialogs/ItemTransferDialog.cs @@ -10,214 +10,212 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class ItemTransferDialog : BaseEODialog { - public class ItemTransferDialog : BaseEODialog + public enum TransferType { - public enum TransferType - { - DropItems, - JunkItems, - GiveItems, - TradeItems, - ShopTransfer, - BankTransfer - } + DropItems, + JunkItems, + GiveItems, + TradeItems, + ShopTransfer, + BankTransfer + } - private readonly Texture2D _backgroundTexture; - private readonly Rectangle _backgroundTextureSource; + private readonly Texture2D _backgroundTexture; + private readonly Rectangle _backgroundTextureSource; - private readonly Rectangle? _titleBarTextureSource; + private readonly Rectangle? _titleBarTextureSource; - private readonly int _totalAmount; + private readonly int _totalAmount; - private readonly IXNALabel _descLabel; - private readonly IXNATextBox _amount; - private readonly IXNAButton _slider, _okButton, _cancelButton; + private readonly IXNALabel _descLabel; + private readonly IXNATextBox _amount; + private readonly IXNAButton _slider, _okButton, _cancelButton; - public int SelectedAmount => int.Parse(_amount.Text); + public int SelectedAmount => int.Parse(_amount.Text); - private bool _sliderDragging; + private bool _sliderDragging; - public ItemTransferDialog(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IContentProvider contentProvider, - string itemName, - TransferType transferType, - int totalAmount, - EOResourceID message) - : base(nativeGraphicsManager, isInGame: true) - { - if (!IsValidMessage(message)) - throw new ArgumentOutOfRangeException(nameof(message), "Use one of the approved messages."); + public ItemTransferDialog(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IContentProvider contentProvider, + string itemName, + TransferType transferType, + int totalAmount, + EOResourceID message) + : base(nativeGraphicsManager, isInGame: true) + { + if (!IsValidMessage(message)) + throw new ArgumentOutOfRangeException(nameof(message), "Use one of the approved messages."); - _backgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); - _backgroundTextureSource = new Rectangle(38, 0, 265, 170); + _backgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); + _backgroundTextureSource = new Rectangle(38, 0, 265, 170); - // set so CenterInGameView works properly (expected BackgroundTexture to be set) - BackgroundTexture = new Texture2D(Game.GraphicsDevice, _backgroundTextureSource.Width, _backgroundTextureSource.Height); + // set so CenterInGameView works properly (expected BackgroundTexture to be set) + BackgroundTexture = new Texture2D(Game.GraphicsDevice, _backgroundTextureSource.Width, _backgroundTextureSource.Height); - SetSize(_backgroundTextureSource.Width, _backgroundTextureSource.Height); - CenterInGameView(); + SetSize(_backgroundTextureSource.Width, _backgroundTextureSource.Height); + CenterInGameView(); - if (transferType != TransferType.DropItems) - { - _titleBarTextureSource = new Rectangle(40, 172 + ((int)transferType - 1) * 24, 240, 22); - } - - _okButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(60, 125), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)) - { - Visible = true - }; - _okButton.OnClick += (s, e) => Close(XNADialogResult.OK); - - _cancelButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(153, 125), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)) - { - Visible = true - }; - _cancelButton.OnClick += (s, e) => Close(XNADialogResult.Cancel); + if (transferType != TransferType.DropItems) + { + _titleBarTextureSource = new Rectangle(40, 172 + ((int)transferType - 1) * 24, 240, 22); + } - _descLabel = new XNALabel(Constants.FontSize10) - { - DrawArea = new Rectangle(20, 42, 231, 33), - ForeColor = ColorConstants.LightGrayDialogMessage, - TextWidth = 200, - Text = $"{localizedStringFinder.GetString(EOResourceID.DIALOG_TRANSFER_HOW_MUCH)} {itemName} {localizedStringFinder.GetString(message)}" - }; + _okButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(60, 125), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)) + { + Visible = true + }; + _okButton.OnClick += (s, e) => Close(XNADialogResult.OK); + + _cancelButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(153, 125), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)) + { + Visible = true + }; + _cancelButton.OnClick += (s, e) => Close(XNADialogResult.Cancel); - _amount = new XNATextBox(new Rectangle(163, 95, 77, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) - { - Visible = true, - Enabled = true, - MaxChars = 8, //max drop/junk at a time will be 99,999,999 - TextColor = ColorConstants.LightBeigeText, - Text = "1", - Selected = true, - }; - _amount.OnTextChanged += AmountTextChanged; - - DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); - - _totalAmount = totalAmount; - - //slider control - var sliderTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 29); - //5th index when 'out', 6th index when 'over' - Rectangle sliderOutSource = new Rectangle(0, 15 * 5, 16, 15); - Rectangle sliderOverSource = new Rectangle(0, 15 * 6, 16, 15); - - //starting coords are 25, 96 - _slider = new XNAButton(sliderTexture, new Vector2(25, 96), sliderOutSource, sliderOverSource); - _slider.OnClickDrag += SliderClickDrag; - } + _descLabel = new XNALabel(Constants.FontSize10) + { + DrawArea = new Rectangle(20, 42, 231, 33), + ForeColor = ColorConstants.LightGrayDialogMessage, + TextWidth = 200, + Text = $"{localizedStringFinder.GetString(EOResourceID.DIALOG_TRANSFER_HOW_MUCH)} {itemName} {localizedStringFinder.GetString(message)}" + }; - public override void Initialize() + _amount = new XNATextBox(new Rectangle(163, 95, 77, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) { - _okButton.Initialize(); - _okButton.SetParentControl(this); + Visible = true, + Enabled = true, + MaxChars = 8, //max drop/junk at a time will be 99,999,999 + TextColor = ColorConstants.LightBeigeText, + Text = "1", + Selected = true, + }; + _amount.OnTextChanged += AmountTextChanged; + + DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); + + _totalAmount = totalAmount; + + //slider control + var sliderTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 29); + //5th index when 'out', 6th index when 'over' + Rectangle sliderOutSource = new Rectangle(0, 15 * 5, 16, 15); + Rectangle sliderOverSource = new Rectangle(0, 15 * 6, 16, 15); + + //starting coords are 25, 96 + _slider = new XNAButton(sliderTexture, new Vector2(25, 96), sliderOutSource, sliderOverSource); + _slider.OnClickDrag += SliderClickDrag; + } - _cancelButton.Initialize(); - _cancelButton.SetParentControl(this); + public override void Initialize() + { + _okButton.Initialize(); + _okButton.SetParentControl(this); - _descLabel.Initialize(); - _descLabel.SetParentControl(this); + _cancelButton.Initialize(); + _cancelButton.SetParentControl(this); - _amount.Initialize(); - _amount.SetParentControl(this); + _descLabel.Initialize(); + _descLabel.SetParentControl(this); - _slider.Initialize(); - _slider.SetParentControl(this); + _amount.Initialize(); + _amount.SetParentControl(this); - base.Initialize(); - } + _slider.Initialize(); + _slider.SetParentControl(this); + + base.Initialize(); + } + + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); + _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _backgroundTextureSource, Color.White); - protected override void OnDrawControl(GameTime gameTime) + if (_titleBarTextureSource != null) { - _spriteBatch.Begin(); - _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _backgroundTextureSource, Color.White); + _spriteBatch.Draw(_backgroundTexture, DrawPositionWithParentOffset + new Vector2(11, 10), _titleBarTextureSource, Color.White); + } - if (_titleBarTextureSource != null) - { - _spriteBatch.Draw(_backgroundTexture, DrawPositionWithParentOffset + new Vector2(11, 10), _titleBarTextureSource, Color.White); - } + _spriteBatch.End(); - _spriteBatch.End(); + base.OnDrawControl(gameTime); + } - base.OnDrawControl(gameTime); + protected override void Dispose(bool disposing) + { + if (disposing) + { + BackgroundTexture.Dispose(); } - protected override void Dispose(bool disposing) - { - if (disposing) - { - BackgroundTexture.Dispose(); - } + base.Dispose(disposing); + } - base.Dispose(disposing); - } + private void SliderClickDrag(object sender, MouseEventArgs e) + { + _sliderDragging = true; //ignores updates to slider location during text change - private void SliderClickDrag(object sender, MouseEventArgs e) - { - _sliderDragging = true; //ignores updates to slider location during text change + //range rectangle is 122, 15 + var sliderArea = new Rectangle(25, 96, 122 - _slider.DrawArea.Width, 15); + var newX = e.DistanceMoved.X + (int)_slider.DrawPosition.X; - //range rectangle is 122, 15 - var sliderArea = new Rectangle(25, 96, 122 - _slider.DrawArea.Width, 15); - var newX = e.DistanceMoved.X + (int)_slider.DrawPosition.X; + if (newX < sliderArea.X) + newX = sliderArea.X; + else if (newX > sliderArea.Width + sliderArea.X) + newX = sliderArea.Width + sliderArea.X; - if (newX < sliderArea.X) - newX = sliderArea.X; - else if (newX > sliderArea.Width + sliderArea.X) - newX = sliderArea.Width + sliderArea.X; + _slider.DrawPosition = new Vector2(newX, _slider.DrawPosition.Y); - _slider.DrawPosition = new Vector2(newX, _slider.DrawPosition.Y); + var ratio = (newX - sliderArea.X) / (float)sliderArea.Width; + _amount.Text = ((int)Math.Round(ratio * _totalAmount) + 1).ToString(); - var ratio = (newX - sliderArea.X) / (float)sliderArea.Width; - _amount.Text = ((int)Math.Round(ratio * _totalAmount) + 1).ToString(); + _sliderDragging = false; + } - _sliderDragging = false; + private void AmountTextChanged(object sender, EventArgs e) + { + int amt = 0; + if (_amount.Text != "" && (!int.TryParse(_amount.Text, out amt) || amt > _totalAmount)) + { + amt = _totalAmount; + _amount.Text = $"{_totalAmount}"; + } + else if (_amount.Text != "" && amt < 0) + { + amt = 1; + _amount.Text = $"{amt}"; } - private void AmountTextChanged(object sender, EventArgs e) + if (!_sliderDragging) { - int amt = 0; - if (_amount.Text != "" && (!int.TryParse(_amount.Text, out amt) || amt > _totalAmount)) + if (amt <= 1) { - amt = _totalAmount; - _amount.Text = $"{_totalAmount}"; + _slider.DrawPosition = new Vector2(25, 96); } - else if (_amount.Text != "" && amt < 0) + else { - amt = 1; - _amount.Text = $"{amt}"; + int xCoord = (int)Math.Round((amt / (double)_totalAmount) * (122 - _slider.DrawArea.Width)); + _slider.DrawPosition = new Vector2(25 + xCoord, 96); } - - if (!_sliderDragging) - { - if (amt <= 1) - { - _slider.DrawPosition = new Vector2(25, 96); - } - else - { - int xCoord = (int)Math.Round((amt / (double)_totalAmount) * (122 - _slider.DrawArea.Width)); - _slider.DrawPosition = new Vector2(25 + xCoord, 96); - } - } - } - - private static bool IsValidMessage(EOResourceID msg) - { - var name = Enum.GetName(typeof(EOResourceID), msg); - return name.Contains("DIALOG_TRANSFER"); } } + private static bool IsValidMessage(EOResourceID msg) + { + var name = Enum.GetName(typeof(EOResourceID), msg); + return name.Contains("DIALOG_TRANSFER"); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/JukeboxDialog.cs b/EndlessClient/Dialogs/JukeboxDialog.cs index f6df54d5a..95db75c58 100644 --- a/EndlessClient/Dialogs/JukeboxDialog.cs +++ b/EndlessClient/Dialogs/JukeboxDialog.cs @@ -13,163 +13,162 @@ using System.Collections.Generic; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class JukeboxDialog : ScrollingListDialog { - public class JukeboxDialog : ScrollingListDialog + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IJukeboxActions _jukeboxActions; + private readonly IJukeboxRepository _jukeboxRepository; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly ISfxPlayer _sfxPlayer; + + private readonly IEDFFile _songNames; + + private ListDialogItem _changeSongItem, _playSongItem; + + private DateTime _openedTime; + + private Option _lastRequestedName; + private int _songIndex; + + public JukeboxDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IDataFileProvider dataFileProvider, + IEOMessageBoxFactory messageBoxFactory, + IJukeboxActions jukeboxActions, + IJukeboxRepository jukeboxRepository, + ICharacterInventoryProvider characterInventoryProvider, + ISfxPlayer sfxPlayer) + : base(nativeGraphicsManager, dialogButtonService, DialogType.Jukebox) { - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IJukeboxActions _jukeboxActions; - private readonly IJukeboxRepository _jukeboxRepository; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly ISfxPlayer _sfxPlayer; - - private readonly IEDFFile _songNames; - - private ListDialogItem _changeSongItem, _playSongItem; - - private DateTime _openedTime; - - private Option _lastRequestedName; - private int _songIndex; - - public JukeboxDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IDataFileProvider dataFileProvider, - IEOMessageBoxFactory messageBoxFactory, - IJukeboxActions jukeboxActions, - IJukeboxRepository jukeboxRepository, - ICharacterInventoryProvider characterInventoryProvider, - ISfxPlayer sfxPlayer) - : base(nativeGraphicsManager, dialogButtonService, DialogType.Jukebox) - { - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _messageBoxFactory = messageBoxFactory; - _jukeboxActions = jukeboxActions; - _jukeboxRepository = jukeboxRepository; - _characterInventoryProvider = characterInventoryProvider; - _sfxPlayer = sfxPlayer; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _messageBoxFactory = messageBoxFactory; + _jukeboxActions = jukeboxActions; + _jukeboxRepository = jukeboxRepository; + _characterInventoryProvider = characterInventoryProvider; + _sfxPlayer = sfxPlayer; - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.Cancel; + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.Cancel; - _songNames = dataFileProvider.DataFiles[DataFiles.JukeBoxSongs]; - _openedTime = DateTime.Now; + _songNames = dataFileProvider.DataFiles[DataFiles.JukeBoxSongs]; + _openedTime = DateTime.Now; - Title = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_IS_READY); - } + Title = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_IS_READY); + } - public override void Initialize() + public override void Initialize() + { + _changeSongItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) { - _changeSongItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.JukeboxBrowse), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_BROWSE_THROUGH_SONGS), - SubText = FormatSubtitle(_songNames.Data[_songIndex]), - ShowIconBackGround = false, - OffsetY = 60, - }; - _changeSongItem.LeftClick += ChangeSongItem_Click; - - _playSongItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.JukeboxPlay), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_PLAY_SONG), - SubText = FormatSubtitle("25 gold"), - ShowIconBackGround = false, - OffsetY = 60, - }; - _playSongItem.LeftClick += PlaySongItem_Click; - - SetItemList(new List { _changeSongItem, _playSongItem }); - - base.Initialize(); - } - - public override void Update(GameTime gameTime) + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.JukeboxBrowse), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_BROWSE_THROUGH_SONGS), + SubText = FormatSubtitle(_songNames.Data[_songIndex]), + ShowIconBackGround = false, + OffsetY = 60, + }; + _changeSongItem.LeftClick += ChangeSongItem_Click; + + _playSongItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) { - if ((DateTime.Now - _openedTime).TotalSeconds >= 95) - { - _jukeboxRepository.PlayingRequestName = Option.None(); - _openedTime = DateTime.Now.AddMinutes(100); - } - - _jukeboxRepository.PlayingRequestName.Match( - requestedName => - { - if (_lastRequestedName.Map(x => !x.Equals(requestedName)).ValueOr(true)) - { - _lastRequestedName = Option.Some(requestedName); - - var titleString = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_PLAYING_REQUEST); - if (!string.IsNullOrWhiteSpace(requestedName)) - titleString += $" ({requestedName})"; - - Title = titleString; - } - }, - () => - { - if (_lastRequestedName.HasValue) - { - _lastRequestedName = Option.None(); - Title = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_IS_READY); - } - }); - - base.Update(gameTime); - } + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.JukeboxPlay), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_PLAY_SONG), + SubText = FormatSubtitle("25 gold"), + ShowIconBackGround = false, + OffsetY = 60, + }; + _playSongItem.LeftClick += PlaySongItem_Click; + + SetItemList(new List { _changeSongItem, _playSongItem }); + + base.Initialize(); + } - private void ChangeSongItem_Click(object sender, MouseEventArgs e) + public override void Update(GameTime gameTime) + { + if ((DateTime.Now - _openedTime).TotalSeconds >= 95) { - _songIndex = (_songIndex + 1) % _songNames.Data.Count; - _changeSongItem.SubText = FormatSubtitle(_songNames.Data[_songIndex]); + _jukeboxRepository.PlayingRequestName = Option.None(); + _openedTime = DateTime.Now.AddMinutes(100); } - private void PlaySongItem_Click(object sender, MouseEventArgs e) - { - if (_jukeboxRepository.PlayingRequestName.HasValue) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.JUKEBOX_REQUESTED_RECENTLY); - dlg.ShowDialog(); - return; - } - - if (_characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1).Map(x => x.Amount < 25).ValueOr(true)) + _jukeboxRepository.PlayingRequestName.Match( + requestedName => { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, " gold"); - dlg.ShowDialog(); - return; - } + if (_lastRequestedName.Map(x => !x.Equals(requestedName)).ValueOr(true)) + { + _lastRequestedName = Option.Some(requestedName); - var confirmDlg = _messageBoxFactory.CreateMessageBox( - $"{_localizedStringFinder.GetString(EOResourceID.JUKEBOX_REQUEST_SONG_FOR)} 25 gold?", - _localizedStringFinder.GetString(EOResourceID.JUKEBOX_REQUEST_SONG), - EODialogButtons.OkCancel); + var titleString = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_PLAYING_REQUEST); + if (!string.IsNullOrWhiteSpace(requestedName)) + titleString += $" ({requestedName})"; - confirmDlg.DialogClosing += (_, e) => + Title = titleString; + } + }, + () => { - if (e.Result == XNADialogResult.OK) + if (_lastRequestedName.HasValue) { - _jukeboxActions.RequestSong(_songIndex); - _sfxPlayer.PlaySfx(SoundEffectID.BuySell); - - Close(XNADialogResult.NO_BUTTON_PRESSED); + _lastRequestedName = Option.None(); + Title = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_IS_READY); } - }; + }); + + base.Update(gameTime); + } - confirmDlg.ShowDialog(); + private void ChangeSongItem_Click(object sender, MouseEventArgs e) + { + _songIndex = (_songIndex + 1) % _songNames.Data.Count; + _changeSongItem.SubText = FormatSubtitle(_songNames.Data[_songIndex]); + } + + private void PlaySongItem_Click(object sender, MouseEventArgs e) + { + if (_jukeboxRepository.PlayingRequestName.HasValue) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.JUKEBOX_REQUESTED_RECENTLY); + dlg.ShowDialog(); + return; } - private string FormatSubtitle(string additionalText) + if (_characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1).Map(x => x.Amount < 25).ValueOr(true)) { - return _localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT) + " : " + additionalText; + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, " gold"); + dlg.ShowDialog(); + return; } + + var confirmDlg = _messageBoxFactory.CreateMessageBox( + $"{_localizedStringFinder.GetString(EOResourceID.JUKEBOX_REQUEST_SONG_FOR)} 25 gold?", + _localizedStringFinder.GetString(EOResourceID.JUKEBOX_REQUEST_SONG), + EODialogButtons.OkCancel); + + confirmDlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + { + _jukeboxActions.RequestSong(_songIndex); + _sfxPlayer.PlaySfx(SoundEffectID.BuySell); + + Close(XNADialogResult.NO_BUTTON_PRESSED); + } + }; + + confirmDlg.ShowDialog(); + } + + private string FormatSubtitle(string additionalText) + { + return _localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT) + " : " + additionalText; } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/LawDialog.cs b/EndlessClient/Dialogs/LawDialog.cs index 1a8a8f950..825efd9c4 100644 --- a/EndlessClient/Dialogs/LawDialog.cs +++ b/EndlessClient/Dialogs/LawDialog.cs @@ -14,185 +14,184 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class LawDialog : ScrollingListDialog { - public class LawDialog : ScrollingListDialog + private enum LawDialogState { - private enum LawDialogState - { - // initial menu - Initial, - // registration menu: marriage/divorce items - Registration, - Marriage, - Divorce, - } + // initial menu + Initial, + // registration menu: marriage/divorce items + Registration, + Marriage, + Divorce, + } - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ILawActions _lawActions; - private readonly IContentProvider _contentProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IENFFileProvider _enfFileProvider; - - private LawDialogState _state; - - public LawDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - ITextInputDialogFactory textInputDialogFactory, - ILawActions lawActions, - IContentProvider contentProvider, - ICurrentMapStateProvider currentMapStateProvider, - IENFFileProvider enfFileProvider) - : base(nativeGraphicsManager, dialogButtonService, DialogType.Law) - { - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _textInputDialogFactory = textInputDialogFactory; - _lawActions = lawActions; - _contentProvider = contentProvider; - _currentMapStateProvider = currentMapStateProvider; - _enfFileProvider = enfFileProvider; - - SetState(LawDialogState.Initial); - - BackAction += (_, _) => - { - if (_state == LawDialogState.Marriage || _state == LawDialogState.Divorce) - SetState(LawDialogState.Registration); - else if (_state == LawDialogState.Registration) - SetState(LawDialogState.Initial); - }; - - _currentMapStateProvider.NPCs - .Select(x => _enfFileProvider.ENFFile[x.ID]) - .SingleOrNone(x => x.Type == NPCType.Law) - .MatchSome(x => Title = x.Name); - } + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ILawActions _lawActions; + private readonly IContentProvider _contentProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IENFFileProvider _enfFileProvider; + + private LawDialogState _state; + + public LawDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + ITextInputDialogFactory textInputDialogFactory, + ILawActions lawActions, + IContentProvider contentProvider, + ICurrentMapStateProvider currentMapStateProvider, + IENFFileProvider enfFileProvider) + : base(nativeGraphicsManager, dialogButtonService, DialogType.Law) + { + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _textInputDialogFactory = textInputDialogFactory; + _lawActions = lawActions; + _contentProvider = contentProvider; + _currentMapStateProvider = currentMapStateProvider; + _enfFileProvider = enfFileProvider; - private void SetState(LawDialogState state) + SetState(LawDialogState.Initial); + + BackAction += (_, _) => { - if (state != LawDialogState.Initial && _state == state) - return; + if (_state == LawDialogState.Marriage || _state == LawDialogState.Divorce) + SetState(LawDialogState.Registration); + else if (_state == LawDialogState.Registration) + SetState(LawDialogState.Initial); + }; + + _currentMapStateProvider.NPCs + .Select(x => _enfFileProvider.ENFFile[x.ID]) + .SingleOrNone(x => x.Type == NPCType.Law) + .MatchSome(x => Title = x.Name); + } - _state = state; + private void SetState(LawDialogState state) + { + if (state != LawDialogState.Initial && _state == state) + return; - ClearItemList(); + _state = state; - switch (_state) - { - case LawDialogState.Initial: - { - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.Cancel; + ClearItemList(); - var registrationItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Registration), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REGISTRATION_SERVICE), - SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_MARRIAGE_OR_DIVORCE), - OffsetY = 45, - }; - registrationItem.LeftClick += (_, _) => SetState(LawDialogState.Registration); - registrationItem.RightClick += (_, _) => SetState(LawDialogState.Registration); - - AddItemToList(registrationItem, sortList: false); - } - break; - case LawDialogState.Registration: - { - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.BackCancel; + switch (_state) + { + case LawDialogState.Initial: + { + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.Cancel; - var marriageItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.SignUp), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_MARRIAGE), - SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_WEDDING_APPROVAL), - OffsetY = 45, - }; - marriageItem.LeftClick += (_, _) => SetState(LawDialogState.Marriage); - marriageItem.RightClick += (_, _) => SetState(LawDialogState.Marriage); - - var divorceItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Unsubscribe), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE), - SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_BREAK_UP), - OffsetY = 45, - }; - divorceItem.LeftClick += (_, _) => SetState(LawDialogState.Divorce); - divorceItem.RightClick += (_, _) => SetState(LawDialogState.Divorce); - - SetItemList(new List { marriageItem, divorceItem }); - } - break; - case LawDialogState.Marriage: + var registrationItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) { - ListItemType = ListDialogItem.ListItemStyle.Small; - Buttons = ScrollingListDialogButtons.BackCancel; - - AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], - insertLineBreaks: true, - new List + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Registration), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REGISTRATION_SERVICE), + SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_MARRIAGE_OR_DIVORCE), + OffsetY = 45, + }; + registrationItem.LeftClick += (_, _) => SetState(LawDialogState.Registration); + registrationItem.RightClick += (_, _) => SetState(LawDialogState.Registration); + + AddItemToList(registrationItem, sortList: false); + } + break; + case LawDialogState.Registration: + { + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.BackCancel; + + var marriageItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + { + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.SignUp), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_MARRIAGE), + SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_WEDDING_APPROVAL), + OffsetY = 45, + }; + marriageItem.LeftClick += (_, _) => SetState(LawDialogState.Marriage); + marriageItem.RightClick += (_, _) => SetState(LawDialogState.Marriage); + + var divorceItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Unsubscribe), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE), + SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_BREAK_UP), + OffsetY = 45, + }; + divorceItem.LeftClick += (_, _) => SetState(LawDialogState.Divorce); + divorceItem.RightClick += (_, _) => SetState(LawDialogState.Divorce); + + SetItemList(new List { marriageItem, divorceItem }); + } + break; + case LawDialogState.Marriage: + { + ListItemType = ListDialogItem.ListItemStyle.Small; + Buttons = ScrollingListDialogButtons.BackCancel; + + AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], + insertLineBreaks: true, + new List + { + () => { - () => + var dlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PROMPT_ENTER_NAME_MARRY)); + dlg.DialogClosing += (_, e) => { - var dlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PROMPT_ENTER_NAME_MARRY)); - dlg.DialogClosing += (_, e) => - { - if (e.Result != XNADialogResult.OK) - return; - - _lawActions.RequestMarriage(dlg.ResponseText); - }; - dlg.ShowDialog(); - }, - }, - _localizedStringFinder.GetString(EOResourceID.WEDDING_MARRIAGE), - _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_1), - _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_2), - _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_LINK)); - } - break; - case LawDialogState.Divorce: - { - ListItemType = ListDialogItem.ListItemStyle.Small; - Buttons = ScrollingListDialogButtons.BackCancel; + if (e.Result != XNADialogResult.OK) + return; - AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], - insertLineBreaks: true, - new List + _lawActions.RequestMarriage(dlg.ResponseText); + }; + dlg.ShowDialog(); + }, + }, + _localizedStringFinder.GetString(EOResourceID.WEDDING_MARRIAGE), + _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_1), + _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_2), + _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_LINK)); + } + break; + case LawDialogState.Divorce: + { + ListItemType = ListDialogItem.ListItemStyle.Small; + Buttons = ScrollingListDialogButtons.BackCancel; + + AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], + insertLineBreaks: true, + new List + { + () => { - () => + var dlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PROMPT_ENTER_NAME_DIVORCE)); + dlg.DialogClosing += (_, e) => { - var dlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PROMPT_ENTER_NAME_DIVORCE)); - dlg.DialogClosing += (_, e) => - { - if (e.Result != XNADialogResult.OK) - return; - - _lawActions.RequestDivorce(dlg.ResponseText); - }; - dlg.ShowDialog(); - }, + if (e.Result != XNADialogResult.OK) + return; + + _lawActions.RequestDivorce(dlg.ResponseText); + }; + dlg.ShowDialog(); }, - _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE), - _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_1), - _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_2), - _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_LINK)); - } - break; - } + }, + _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE), + _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_1), + _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_2), + _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_LINK)); + } + break; } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ListDialogItem.cs b/EndlessClient/Dialogs/ListDialogItem.cs index ffa4f2e5d..6fb3858df 100644 --- a/EndlessClient/Dialogs/ListDialogItem.cs +++ b/EndlessClient/Dialogs/ListDialogItem.cs @@ -7,294 +7,293 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class ListDialogItem : XNAControl { - public class ListDialogItem : XNAControl + public enum ListItemStyle { - public enum ListItemStyle - { - Small, - SmallKeyValue, - Large - } + Small, + SmallKeyValue, + Large + } - private int _index; - private int _xOffset, _yOffset; + private int _index; + private int _xOffset, _yOffset; - protected IXNALabel _primaryText; - protected IXNALabel _subText; + protected IXNALabel _primaryText; + protected IXNALabel _subText; - private readonly Texture2D _gfxPadThing; - private readonly Texture2D _backgroundColor; + private readonly Texture2D _gfxPadThing; + private readonly Texture2D _backgroundColor; - private readonly BaseEODialog _parentDialog; + private readonly BaseEODialog _parentDialog; - private bool _drawBackground; + private bool _drawBackground; - public int Index + public int Index + { + get { return _index; } + set { - get { return _index; } - set - { - _index = value; - DrawPosition = new Vector2(DrawPosition.X, OffsetY + (_index * (Style == ListItemStyle.Large ? 36 : 16))); - } + _index = value; + DrawPosition = new Vector2(DrawPosition.X, OffsetY + (_index * (Style == ListItemStyle.Large ? 36 : 16))); } + } - public int OffsetX + public int OffsetX + { + get { - get - { - return _xOffset; - } - set - { - int oldOff = _xOffset; - _xOffset = value; - DrawPosition += new Vector2(_xOffset - oldOff, 0); - } + return _xOffset; + } + set + { + int oldOff = _xOffset; + _xOffset = value; + DrawPosition += new Vector2(_xOffset - oldOff, 0); } + } - public int OffsetY + public int OffsetY + { + get { - get - { - return _yOffset; - } - set - { - int oldOff = _yOffset; - _yOffset = value; - DrawPosition += new Vector2(0, _yOffset - oldOff); - } + return _yOffset; } + set + { + int oldOff = _yOffset; + _yOffset = value; + DrawPosition += new Vector2(0, _yOffset - oldOff); + } + } - public ListItemStyle Style { get; set; } + public ListItemStyle Style { get; set; } - public string PrimaryText + public string PrimaryText + { + get { return _primaryText.Text; } + set { - get { return _primaryText.Text; } - set - { - _primaryText.Text = value; - _primaryText.ResizeBasedOnText(); - } + _primaryText.Text = value; + _primaryText.ResizeBasedOnText(); } + } - public string SubText + public string SubText + { + get { return _subText.Text; } + set { - get { return _subText.Text; } - set - { - _subText.Text = value; - if (Style != ListItemStyle.SmallKeyValue) - _subText.ResizeBasedOnText(); - } + _subText.Text = value; + if (Style != ListItemStyle.SmallKeyValue) + _subText.ResizeBasedOnText(); } + } - public Texture2D IconGraphic { get; set; } + public Texture2D IconGraphic { get; set; } - public Rectangle? IconGraphicSource { get; set; } + public Rectangle? IconGraphicSource { get; set; } - public bool ShowIconBackGround { get; set; } + public bool ShowIconBackGround { get; set; } - public bool ShowSubtext - { - get => _subText.Visible; - set => ((XNAControl)_subText).Visible = value; - } + public bool ShowSubtext + { + get => _subText.Visible; + set => ((XNAControl)_subText).Visible = value; + } - public bool UnderlineLinks { get; set; } = true; + public bool UnderlineLinks { get; set; } = true; - public object Data { get; set; } + public object Data { get; set; } - public event EventHandler RightClick; - public event EventHandler LeftClick; + public event EventHandler RightClick; + public event EventHandler LeftClick; - public ListDialogItem(BaseEODialog parent, ListItemStyle style, int listIndex = -1) - { - _parentDialog = parent; + public ListDialogItem(BaseEODialog parent, ListItemStyle style, int listIndex = -1) + { + _parentDialog = parent; - DrawPosition += new Vector2(17, 0); + DrawPosition += new Vector2(17, 0); - Style = style; - if (listIndex >= 0) - Index = listIndex; + Style = style; + if (listIndex >= 0) + Index = listIndex; - SetSize(232, Style == ListItemStyle.Large ? 36 : 13); + SetSize(232, Style == ListItemStyle.Large ? 36 : 13); - int colorFactor = Style == ListItemStyle.Large ? 0xc8 : 0xb4; + int colorFactor = Style == ListItemStyle.Large ? 0xc8 : 0xb4; - _primaryText = new XNALabel(Constants.FontSize08pt5) + _primaryText = new XNALabel(Constants.FontSize08pt5) + { + AutoSize = false, + BackColor = Color.Transparent, + ForeColor = Color.FromNonPremultiplied(colorFactor, colorFactor, colorFactor, 0xff), + DrawPosition = Style == ListItemStyle.Large ? new Vector2(56, 5) : new Vector2(2, 0), + TextAlign = LabelAlignment.TopLeft, + Text = " " + }; + _primaryText.ResizeBasedOnText(); + _primaryText.SetParentControl(this); + _primaryText.Initialize(); + + if (Style == ListItemStyle.SmallKeyValue) + { + _subText = new XNALabel(Constants.FontSize08pt5) { - AutoSize = false, - BackColor = Color.Transparent, - ForeColor = Color.FromNonPremultiplied(colorFactor, colorFactor, colorFactor, 0xff), - DrawPosition = Style == ListItemStyle.Large ? new Vector2(56, 5) : new Vector2(2, 0), - TextAlign = LabelAlignment.TopLeft, - Text = " " + BackColor = _primaryText.BackColor, + ForeColor = _primaryText.ForeColor, + DrawArea = new Rectangle(2, 0, 225, 13), + TextAlign = LabelAlignment.Right, + Text = " ", + Visible = true }; - _primaryText.ResizeBasedOnText(); - _primaryText.SetParentControl(this); - _primaryText.Initialize(); - - if (Style == ListItemStyle.SmallKeyValue) - { - _subText = new XNALabel(Constants.FontSize08pt5) - { - BackColor = _primaryText.BackColor, - ForeColor = _primaryText.ForeColor, - DrawArea = new Rectangle(2, 0, 225, 13), - TextAlign = LabelAlignment.Right, - Text = " ", - Visible = true - }; - } - else + } + else + { + _subText = new XNALabel(Constants.FontSize08pt5) { - _subText = new XNALabel(Constants.FontSize08pt5) - { - AutoSize = true, - BackColor = _primaryText.BackColor, - ForeColor = _primaryText.ForeColor, - DrawPosition = Style == ListItemStyle.Large ? new Vector2(56, 20) : new Vector2(100, 0), - Text = " ", - Visible = Style == ListItemStyle.Large - }; - _subText.ResizeBasedOnText(); - } - _subText.SetParentControl(this); - _subText.Initialize(); + AutoSize = true, + BackColor = _primaryText.BackColor, + ForeColor = _primaryText.ForeColor, + DrawPosition = Style == ListItemStyle.Large ? new Vector2(56, 20) : new Vector2(100, 0), + Text = " ", + Visible = Style == ListItemStyle.Large + }; + _subText.ResizeBasedOnText(); + } + _subText.SetParentControl(this); + _subText.Initialize(); - _gfxPadThing = parent.GraphicsManager.TextureFromResource(GFXTypes.MapTiles, 0, true); - ShowIconBackGround = Style == ListItemStyle.Large; + _gfxPadThing = parent.GraphicsManager.TextureFromResource(GFXTypes.MapTiles, 0, true); + ShowIconBackGround = Style == ListItemStyle.Large; - _backgroundColor = new Texture2D(Game.GraphicsDevice, 1, 1); - _backgroundColor.SetData(new[] { Color.White }); + _backgroundColor = new Texture2D(Game.GraphicsDevice, 1, 1); + _backgroundColor.SetData(new[] { Color.White }); - SetParentControl(parent); + SetParentControl(parent); - OnMouseEnter += (_, _) => _drawBackground = true; - OnMouseLeave += (_, _) => _drawBackground = false; + OnMouseEnter += (_, _) => _drawBackground = true; + OnMouseLeave += (_, _) => _drawBackground = false; - OffsetY = Style == ListItemStyle.Large ? 25 : 45; - } + OffsetY = Style == ListItemStyle.Large ? 25 : 45; + } - public void SetPrimaryClickAction(EventHandler onClickAction) + public void SetPrimaryClickAction(EventHandler onClickAction) + { + var oldText = _primaryText; + _primaryText = new XNAHyperLink(Constants.FontSize08pt5) { - var oldText = _primaryText; - _primaryText = new XNAHyperLink(Constants.FontSize08pt5) - { - AutoSize = false, - BackColor = oldText.BackColor, - DrawArea = oldText.DrawArea, - ForeColor = oldText.ForeColor, - MouseOverColor = oldText.ForeColor, - Text = oldText.Text, - Underline = UnderlineLinks - }; - - ((XNAHyperLink)_primaryText).OnClick += onClickAction; + AutoSize = false, + BackColor = oldText.BackColor, + DrawArea = oldText.DrawArea, + ForeColor = oldText.ForeColor, + MouseOverColor = oldText.ForeColor, + Text = oldText.Text, + Underline = UnderlineLinks + }; - _primaryText.SetParentControl(this); - _primaryText.Initialize(); - _primaryText.ResizeBasedOnText(); + ((XNAHyperLink)_primaryText).OnClick += onClickAction; - oldText.Dispose(); + _primaryText.SetParentControl(this); + _primaryText.Initialize(); + _primaryText.ResizeBasedOnText(); - if (Style == ListItemStyle.Small || Style == ListItemStyle.SmallKeyValue) - LeftClick += onClickAction; - } + oldText.Dispose(); - public void SetSubtextClickAction(EventHandler onClickAction) - { - if (Style == ListItemStyle.Small || Style == ListItemStyle.SmallKeyValue) - throw new InvalidOperationException("Unable to set subtext click action when style is Small"); + if (Style == ListItemStyle.Small || Style == ListItemStyle.SmallKeyValue) + LeftClick += onClickAction; + } - var oldText = _subText; - _subText = new XNAHyperLink(Constants.FontSize08pt5) - { - AutoSize = false, - BackColor = oldText.BackColor, - DrawArea = oldText.DrawArea, - ForeColor = oldText.ForeColor, - MouseOverColor = oldText.ForeColor, - Text = oldText.Text, - Underline = UnderlineLinks - }; + public void SetSubtextClickAction(EventHandler onClickAction) + { + if (Style == ListItemStyle.Small || Style == ListItemStyle.SmallKeyValue) + throw new InvalidOperationException("Unable to set subtext click action when style is Small"); - ((XNAHyperLink)_subText).OnClick += onClickAction; + var oldText = _subText; + _subText = new XNAHyperLink(Constants.FontSize08pt5) + { + AutoSize = false, + BackColor = oldText.BackColor, + DrawArea = oldText.DrawArea, + ForeColor = oldText.ForeColor, + MouseOverColor = oldText.ForeColor, + Text = oldText.Text, + Underline = UnderlineLinks + }; + + ((XNAHyperLink)_subText).OnClick += onClickAction; + + _subText.SetParentControl(this); + _subText.Initialize(); + _subText.ResizeBasedOnText(); + + oldText.Dispose(); + } - _subText.SetParentControl(this); - _subText.Initialize(); - _subText.ResizeBasedOnText(); + public void Highlight() + { + _primaryText.ForeColor = Color.FromNonPremultiplied(0xf0, 0xf0, 0xf0, 0xff); + } - oldText.Dispose(); - } + public void ClearHighlight() + { + int colorFactor = Style == ListItemStyle.Large ? 0xc8 : 0xb4; + _primaryText.ForeColor = Color.FromNonPremultiplied(colorFactor, colorFactor, colorFactor, 0xff); + } - public void Highlight() - { - _primaryText.ForeColor = Color.FromNonPremultiplied(0xf0, 0xf0, 0xf0, 0xff); - } + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - public void ClearHighlight() + _spriteBatch.Begin(); + if (_drawBackground) { - int colorFactor = Style == ListItemStyle.Large ? 0xc8 : 0xb4; - _primaryText.ForeColor = Color.FromNonPremultiplied(colorFactor, colorFactor, colorFactor, 0xff); + _spriteBatch.Draw(_backgroundColor, DrawAreaWithParentOffset, Color.FromNonPremultiplied(255, 255, 255, 16)); } - protected override void OnDrawControl(GameTime gameTime) + if (Style == ListItemStyle.Large) { - base.OnDrawControl(gameTime); - - _spriteBatch.Begin(); - if (_drawBackground) + if (ShowIconBackGround) { - _spriteBatch.Draw(_backgroundColor, DrawAreaWithParentOffset, Color.FromNonPremultiplied(255, 255, 255, 16)); + _spriteBatch.Draw(_gfxPadThing, DrawPositionWithParentOffset + GetCoordsFromGraphic(_gfxPadThing.Bounds), Color.White); } - if (Style == ListItemStyle.Large) + if (IconGraphic != null) { - if (ShowIconBackGround) - { - _spriteBatch.Draw(_gfxPadThing, DrawPositionWithParentOffset + GetCoordsFromGraphic(_gfxPadThing.Bounds), Color.White); - } - - if (IconGraphic != null) - { - var graphicOffset = IconGraphicSource.HasValue ? GetCoordsFromGraphic(IconGraphicSource.Value) : GetCoordsFromGraphic(IconGraphic.Bounds); - _spriteBatch.Draw(IconGraphic, DrawPositionWithParentOffset + graphicOffset, IconGraphicSource, Color.White); - } + var graphicOffset = IconGraphicSource.HasValue ? GetCoordsFromGraphic(IconGraphicSource.Value) : GetCoordsFromGraphic(IconGraphic.Bounds); + _spriteBatch.Draw(IconGraphic, DrawPositionWithParentOffset + graphicOffset, IconGraphicSource, Color.White); } - - _spriteBatch.End(); } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (eventArgs.Button == MouseButton.Left) - { - LeftClick?.Invoke(this, eventArgs); - } - else if (eventArgs.Button == MouseButton.Right) - { - RightClick?.Invoke(this, eventArgs); - } + _spriteBatch.End(); + } - return true; + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (eventArgs.Button == MouseButton.Left) + { + LeftClick?.Invoke(this, eventArgs); } - - private static Vector2 GetCoordsFromGraphic(Rectangle sourceTextureArea) + else if (eventArgs.Button == MouseButton.Right) { - return new Vector2((float)Math.Round((56 - sourceTextureArea.Width) / 2f), (float)Math.Round((36 - sourceTextureArea.Height) / 2f)); + RightClick?.Invoke(this, eventArgs); } - protected override void Dispose(bool disposing) - { - if (disposing) - _backgroundColor.Dispose(); + return true; + } - base.Dispose(disposing); - } + private static Vector2 GetCoordsFromGraphic(Rectangle sourceTextureArea) + { + return new Vector2((float)Math.Round((56 - sourceTextureArea.Width) / 2f), (float)Math.Round((36 - sourceTextureArea.Height) / 2f)); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + _backgroundColor.Dispose(); + + base.Dispose(disposing); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/LockerDialog.cs b/EndlessClient/Dialogs/LockerDialog.cs index accc1eb83..93371fa05 100644 --- a/EndlessClient/Dialogs/LockerDialog.cs +++ b/EndlessClient/Dialogs/LockerDialog.cs @@ -16,109 +16,108 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class LockerDialog : ScrollingListDialog { - public class LockerDialog : ScrollingListDialog + private readonly ILockerActions _lockerActions; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ICharacterProvider _characterProvider; + private readonly ILockerDataProvider _lockerDataProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly InventoryPanel _inventoryPanel; + + private HashSet _cachedItems; + + public LockerDialog(INativeGraphicsManager nativeGraphicsManager, + ILockerActions lockerActions, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IInventorySpaceValidator inventorySpaceValidator, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + ICharacterProvider characterProvider, + ILockerDataProvider lockerDataProvider, + IHudControlProvider hudControlProvider, + IEIFFileProvider eifFileProvider) + : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.Locker) + { + _lockerActions = lockerActions; + _localizedStringFinder = localizedStringFinder; + _inventorySpaceValidator = inventorySpaceValidator; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _characterProvider = characterProvider; + _lockerDataProvider = lockerDataProvider; + _eifFileProvider = eifFileProvider; + _inventoryPanel = hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); + + _cachedItems = new HashSet(); + + Title = GetDialogTitle(); + Buttons = ScrollingListDialogButtons.Cancel; + ListItemType = ListDialogItem.ListItemStyle.Large; + } + + protected override void OnUpdateControl(GameTime gameTime) { - private readonly ILockerActions _lockerActions; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ICharacterProvider _characterProvider; - private readonly ILockerDataProvider _lockerDataProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly InventoryPanel _inventoryPanel; - - private HashSet _cachedItems; - - public LockerDialog(INativeGraphicsManager nativeGraphicsManager, - ILockerActions lockerActions, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IInventorySpaceValidator inventorySpaceValidator, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - ICharacterProvider characterProvider, - ILockerDataProvider lockerDataProvider, - IHudControlProvider hudControlProvider, - IEIFFileProvider eifFileProvider) - : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.Locker) + if (!_cachedItems.SetEquals(_lockerDataProvider.Items)) { - _lockerActions = lockerActions; - _localizedStringFinder = localizedStringFinder; - _inventorySpaceValidator = inventorySpaceValidator; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _characterProvider = characterProvider; - _lockerDataProvider = lockerDataProvider; - _eifFileProvider = eifFileProvider; - _inventoryPanel = hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); - - _cachedItems = new HashSet(); - - Title = GetDialogTitle(); - Buttons = ScrollingListDialogButtons.Cancel; - ListItemType = ListDialogItem.ListItemStyle.Large; + _cachedItems = _lockerDataProvider.Items.ToHashSet(); + UpdateItemList(); } - protected override void OnUpdateControl(GameTime gameTime) - { - if (!_cachedItems.SetEquals(_lockerDataProvider.Items)) - { - _cachedItems = _lockerDataProvider.Items.ToHashSet(); - UpdateItemList(); - } + base.OnUpdateControl(gameTime); + } - base.OnUpdateControl(gameTime); - } + private void UpdateItemList() + { + ClearItemList(); - private void UpdateItemList() - { - ClearItemList(); + Title = GetDialogTitle(); - Title = GetDialogTitle(); + foreach (var item in _cachedItems) + { + var itemData = _eifFileProvider.EIFFile[item.ItemID]; - foreach (var item in _cachedItems) + var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) { - var itemData = _eifFileProvider.EIFFile[item.ItemID]; - - var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) - { - PrimaryText = itemData.Name, - SubText = $"x{item.Amount} {(itemData.Type == ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - itemData.Gender)})" : string.Empty)}", - IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * itemData.Graphic - 1, true), - OffsetY = 45 - }; - listItem.RightClick += (_, _) => TakeItem(itemData, item); - - AddItemToList(listItem, sortList: false); - } + PrimaryText = itemData.Name, + SubText = $"x{item.Amount} {(itemData.Type == ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - itemData.Gender)})" : string.Empty)}", + IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * itemData.Graphic - 1, true), + OffsetY = 45 + }; + listItem.RightClick += (_, _) => TakeItem(itemData, item); + + AddItemToList(listItem, sortList: false); } + } - private void TakeItem(EIFRecord itemData, InventoryItem item) + private void TakeItem(EIFRecord itemData, InventoryItem item) + { + if (!_inventorySpaceValidator.ItemFits(item.ItemID)) { - if (!_inventorySpaceValidator.ItemFits(item.ItemID)) - { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); - } - else if (itemData.Weight * item.Amount + _characterProvider.MainCharacter.Stats[CharacterStat.Weight] > _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]) - { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); - } - else - { - _lockerActions.TakeItemFromLocker(item.ItemID); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); } - - private string GetDialogTitle() + else if (itemData.Weight * item.Amount + _characterProvider.MainCharacter.Stats[CharacterStat.Weight] > _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]) + { + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + } + else { - return _characterProvider.MainCharacter.Name + "'s " + _localizedStringFinder.GetString(EOResourceID.DIALOG_TITLE_PRIVATE_LOCKER) + $" [{_lockerDataProvider.Items.Count}]"; + _lockerActions.TakeItemFromLocker(item.ItemID); } } + + private string GetDialogTitle() + { + return _characterProvider.MainCharacter.Name + "'s " + _localizedStringFinder.GetString(EOResourceID.DIALOG_TITLE_PRIVATE_LOCKER) + $" [{_lockerDataProvider.Items.Count}]"; + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/PaperdollDialog.cs b/EndlessClient/Dialogs/PaperdollDialog.cs index 5d102b03d..3d603f334 100644 --- a/EndlessClient/Dialogs/PaperdollDialog.cs +++ b/EndlessClient/Dialogs/PaperdollDialog.cs @@ -19,140 +19,139 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class PaperdollDialog : PlayerInfoDialog { - public class PaperdollDialog : PlayerInfoDialog + private readonly IInventoryController _inventoryController; + private readonly IPubFileProvider _pubFileProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ISfxPlayer _sfxPlayer; + + private readonly InventoryPanel _inventoryPanel; + + private readonly List _childItems; + + public PaperdollDialog(INativeGraphicsManager nativeGraphicsManager, + IInventoryController inventoryController, + IPaperdollProvider paperdollProvider, + IPubFileProvider pubFileProvider, + IHudControlProvider hudControlProvider, + IEODialogButtonService eoDialogButtonService, + IInventorySpaceValidator inventorySpaceValidator, + IEOMessageBoxFactory eoMessageBoxFactory, + IStatusLabelSetter statusLabelSetter, + ISfxPlayer sfxPlayer, + Character character, bool isMainCharacter) + : base(nativeGraphicsManager, eoDialogButtonService, pubFileProvider, paperdollProvider, character, isMainCharacter) { - private readonly IInventoryController _inventoryController; - private readonly IPubFileProvider _pubFileProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ISfxPlayer _sfxPlayer; - - private readonly InventoryPanel _inventoryPanel; - - private readonly List _childItems; - - public PaperdollDialog(INativeGraphicsManager nativeGraphicsManager, - IInventoryController inventoryController, - IPaperdollProvider paperdollProvider, - IPubFileProvider pubFileProvider, - IHudControlProvider hudControlProvider, - IEODialogButtonService eoDialogButtonService, - IInventorySpaceValidator inventorySpaceValidator, - IEOMessageBoxFactory eoMessageBoxFactory, - IStatusLabelSetter statusLabelSetter, - ISfxPlayer sfxPlayer, - Character character, bool isMainCharacter) - : base(nativeGraphicsManager, eoDialogButtonService, pubFileProvider, paperdollProvider, character, isMainCharacter) - { - _pubFileProvider = pubFileProvider; - _hudControlProvider = hudControlProvider; - _inventorySpaceValidator = inventorySpaceValidator; - _eoMessageBoxFactory = eoMessageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _sfxPlayer = sfxPlayer; - _inventoryController = inventoryController; + _pubFileProvider = pubFileProvider; + _hudControlProvider = hudControlProvider; + _inventorySpaceValidator = inventorySpaceValidator; + _eoMessageBoxFactory = eoMessageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _sfxPlayer = sfxPlayer; + _inventoryController = inventoryController; - _inventoryPanel = _hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); + _inventoryPanel = _hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); - _childItems = new List(); + _childItems = new List(); - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 49); - BackgroundTextureSource = new Rectangle(0, BackgroundTexture.Height / 2 * Character.RenderProperties.Gender, DrawArea.Width, BackgroundTexture.Height / 2); + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 49); + BackgroundTextureSource = new Rectangle(0, BackgroundTexture.Height / 2 * Character.RenderProperties.Gender, DrawArea.Width, BackgroundTexture.Height / 2); - CenterInGameView(); + CenterInGameView(); - if (!Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, 15); - } + if (!Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, 15); + } - public bool NoItemsDragging() => !_childItems.Any(x => x.IsBeingDragged); + public bool NoItemsDragging() => !_childItems.Any(x => x.IsBeingDragged); - protected override void UpdateDisplayedData(PaperdollData paperdollData) + protected override void UpdateDisplayedData(PaperdollData paperdollData) + { + base.UpdateDisplayedData(paperdollData); + + foreach (var control in _childItems) { - base.UpdateDisplayedData(paperdollData); + control.SetControlUnparented(); + control.Dispose(); + } - foreach (var control in _childItems) - { - control.SetControlUnparented(); - control.Dispose(); - } + foreach (EquipLocation equipLocation in Enum.GetValues(typeof(EquipLocation))) + { + if (equipLocation == EquipLocation.PAPERDOLL_MAX) + break; - foreach (EquipLocation equipLocation in Enum.GetValues(typeof(EquipLocation))) - { - if (equipLocation == EquipLocation.PAPERDOLL_MAX) - break; + if (!paperdollData.Paperdoll.ContainsKey(equipLocation)) + continue; - if (!paperdollData.Paperdoll.ContainsKey(equipLocation)) - continue; + var id = paperdollData.Paperdoll[equipLocation]; + var eifRecord = id.SomeWhen(i => i > 0).Map(i => _pubFileProvider.EIFFile[i]); + var paperdollItem = new PaperdollDialogItem(GraphicsManager, _sfxPlayer, _inventoryPanel, this, _isMainCharacter, equipLocation, eifRecord) + { + DrawArea = equipLocation.GetEquipLocationRectangle() + }; - var id = paperdollData.Paperdoll[equipLocation]; - var eifRecord = id.SomeWhen(i => i > 0).Map(i => _pubFileProvider.EIFFile[i]); - var paperdollItem = new PaperdollDialogItem(GraphicsManager, _sfxPlayer, _inventoryPanel, this, _isMainCharacter, equipLocation, eifRecord) + paperdollItem.OnMouseEnter += (_, _) => + { + EOResourceID msg; + switch (equipLocation) { - DrawArea = equipLocation.GetEquipLocationRectangle() - }; - - paperdollItem.OnMouseEnter += (_, _) => + case EquipLocation.Boots: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BOOTS_EQUIPMENT; break; + case EquipLocation.Accessory: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_MISC_EQUIPMENT; break; + case EquipLocation.Gloves: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_GLOVES_EQUIPMENT; break; + case EquipLocation.Belt: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BELT_EQUIPMENT; break; + case EquipLocation.Armor: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_ARMOR_EQUIPMENT; break; + case EquipLocation.Necklace: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_NECKLACE_EQUIPMENT; break; + case EquipLocation.Hat: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_HAT_EQUIPMENT; break; + case EquipLocation.Shield: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_SHIELD_EQUIPMENT; break; + case EquipLocation.Weapon: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_WEAPON_EQUIPMENT; break; + case EquipLocation.Ring1: + case EquipLocation.Ring2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_RING_EQUIPMENT; break; + case EquipLocation.Armlet1: + case EquipLocation.Armlet2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_ARMLET_EQUIPMENT; break; + case EquipLocation.Bracer1: + case EquipLocation.Bracer2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BRACER_EQUIPMENT; break; + default: throw new ArgumentOutOfRangeException(); + } + + var extra = eifRecord.Match(rec => $", {rec.Name}", () => string.Empty); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, msg, extra); + }; + + paperdollItem.UnequipAction += itemInfo => + { + if (itemInfo.Special == ItemSpecial.Cursed) { - EOResourceID msg; - switch (equipLocation) - { - case EquipLocation.Boots: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BOOTS_EQUIPMENT; break; - case EquipLocation.Accessory: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_MISC_EQUIPMENT; break; - case EquipLocation.Gloves: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_GLOVES_EQUIPMENT; break; - case EquipLocation.Belt: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BELT_EQUIPMENT; break; - case EquipLocation.Armor: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_ARMOR_EQUIPMENT; break; - case EquipLocation.Necklace: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_NECKLACE_EQUIPMENT; break; - case EquipLocation.Hat: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_HAT_EQUIPMENT; break; - case EquipLocation.Shield: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_SHIELD_EQUIPMENT; break; - case EquipLocation.Weapon: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_WEAPON_EQUIPMENT; break; - case EquipLocation.Ring1: - case EquipLocation.Ring2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_RING_EQUIPMENT; break; - case EquipLocation.Armlet1: - case EquipLocation.Armlet2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_ARMLET_EQUIPMENT; break; - case EquipLocation.Bracer1: - case EquipLocation.Bracer2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BRACER_EQUIPMENT; break; - default: throw new ArgumentOutOfRangeException(); - } - - var extra = eifRecord.Match(rec => $", {rec.Name}", () => string.Empty); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, msg, extra); - }; - - paperdollItem.UnequipAction += itemInfo => + var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_CURSED_ITEM, EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); + msgBox.ShowDialog(); + } + else { - if (itemInfo.Special == ItemSpecial.Cursed) + eifRecord.MatchSome(rec => { - var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_CURSED_ITEM, EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); - msgBox.ShowDialog(); - } - else - { - eifRecord.MatchSome(rec => + if (!_inventorySpaceValidator.ItemFits(rec.ID)) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_UNEQUIP_NO_SPACE_LEFT); + } + else { - if (!_inventorySpaceValidator.ItemFits(rec.ID)) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_UNEQUIP_NO_SPACE_LEFT); - } - else - { - // packet reply handles updating the paperdoll for the character which will unrender the equipment - _inventoryController.UnequipItem(equipLocation); - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - } - }); - } - }; - - paperdollItem.SetParentControl(this); - paperdollItem.Initialize(); - - _childItems.Add(paperdollItem); - } + // packet reply handles updating the paperdoll for the character which will unrender the equipment + _inventoryController.UnequipItem(equipLocation); + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + } + }); + } + }; + + paperdollItem.SetParentControl(this); + paperdollItem.Initialize(); + + _childItems.Add(paperdollItem); } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/PaperdollDialogItem.cs b/EndlessClient/Dialogs/PaperdollDialogItem.cs index 5209495bf..4b97403a7 100644 --- a/EndlessClient/Dialogs/PaperdollDialogItem.cs +++ b/EndlessClient/Dialogs/PaperdollDialogItem.cs @@ -11,114 +11,113 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class PaperdollDialogItem : XNAPictureBox { - public class PaperdollDialogItem : XNAPictureBox - { - private readonly ISfxPlayer _sfxPlayer; - private readonly InventoryPanel _inventoryPanel; - private readonly PaperdollDialog _paperdollDialog; - private readonly bool _isMainCharacter; - private readonly Option _itemInfo; + private readonly ISfxPlayer _sfxPlayer; + private readonly InventoryPanel _inventoryPanel; + private readonly PaperdollDialog _paperdollDialog; + private readonly bool _isMainCharacter; + private readonly Option _itemInfo; - private bool _beingDragged; + private bool _beingDragged; - public EquipLocation EquipLocation { get; } + public EquipLocation EquipLocation { get; } - public int ItemID => _itemInfo.Match(r => r.ID, () => 0); + public int ItemID => _itemInfo.Match(r => r.ID, () => 0); - public event Action UnequipAction; + public event Action UnequipAction; - public bool IsBeingDragged => _beingDragged; + public bool IsBeingDragged => _beingDragged; - public PaperdollDialogItem(INativeGraphicsManager nativeGraphicsManager, - ISfxPlayer sfxPlayer, - InventoryPanel inventoryPanel, - PaperdollDialog paperdollDialog, - bool isMainCharacter, - EquipLocation location, - Option itemInfo) - { - _sfxPlayer = sfxPlayer; - _inventoryPanel = inventoryPanel; - _paperdollDialog = paperdollDialog; - _isMainCharacter = isMainCharacter; - EquipLocation = location; - _itemInfo = itemInfo; - - _itemInfo.MatchSome(r => Texture = nativeGraphicsManager.TextureFromResource(GFXTypes.Items, r.Graphic * 2, true)); - StretchMode = StretchMode.CenterInFrame; - } + public PaperdollDialogItem(INativeGraphicsManager nativeGraphicsManager, + ISfxPlayer sfxPlayer, + InventoryPanel inventoryPanel, + PaperdollDialog paperdollDialog, + bool isMainCharacter, + EquipLocation location, + Option itemInfo) + { + _sfxPlayer = sfxPlayer; + _inventoryPanel = inventoryPanel; + _paperdollDialog = paperdollDialog; + _isMainCharacter = isMainCharacter; + EquipLocation = location; + _itemInfo = itemInfo; + + _itemInfo.MatchSome(r => Texture = nativeGraphicsManager.TextureFromResource(GFXTypes.Items, r.Graphic * 2, true)); + StretchMode = StretchMode.CenterInFrame; + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_isMainCharacter || !_itemInfo.HasValue) - return false; + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_isMainCharacter || !_itemInfo.HasValue) + return false; - if (eventArgs.Button == MouseButton.Left) - { - if (_inventoryPanel.MouseOver && _inventoryPanel.MouseOverPreviously) - { - StopDragging(); - _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); - } - } - else if (eventArgs.Button == MouseButton.Right) + if (eventArgs.Button == MouseButton.Left) + { + if (_inventoryPanel.MouseOver && _inventoryPanel.MouseOverPreviously) { - if (_beingDragged) - StopDragging(); - else - _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); + StopDragging(); + _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); } - - return true; } - - protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) + else if (eventArgs.Button == MouseButton.Right) { - if (!_isMainCharacter || !_itemInfo.HasValue) - return false; + if (_beingDragged) + StopDragging(); + else + _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); + } + + return true; + } - _beingDragged = true; - SetControlUnparented(); - Game.Components.Add(this); + protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_isMainCharacter || !_itemInfo.HasValue) + return false; - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + _beingDragged = true; + SetControlUnparented(); + Game.Components.Add(this); - DrawOrder = 1000; - return true; - } + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_isMainCharacter || !_itemInfo.HasValue) - return false; + DrawOrder = 1000; + return true; + } - DrawPosition = new Vector2(eventArgs.Position.X - (DrawArea.Width / 2), eventArgs.Position.Y - (DrawArea.Height / 2)); + protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_isMainCharacter || !_itemInfo.HasValue) + return false; - return true; - } + DrawPosition = new Vector2(eventArgs.Position.X - (DrawArea.Width / 2), eventArgs.Position.Y - (DrawArea.Height / 2)); - protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_isMainCharacter || !_itemInfo.HasValue) - return false; + return true; + } - if (_inventoryPanel.MouseOver && _inventoryPanel.MouseOverPreviously) - _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); + protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_isMainCharacter || !_itemInfo.HasValue) + return false; - StopDragging(); + if (_inventoryPanel.MouseOver && _inventoryPanel.MouseOverPreviously) + _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); - return true; - } + StopDragging(); - private void StopDragging() - { - _beingDragged = false; - SetParentControl(_paperdollDialog); - DrawArea = EquipLocation.GetEquipLocationRectangle(); + return true; + } - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - } + private void StopDragging() + { + _beingDragged = false; + SetParentControl(_paperdollDialog); + DrawArea = EquipLocation.GetEquipLocationRectangle(); + + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/PlayerInfoDialog.cs b/EndlessClient/Dialogs/PlayerInfoDialog.cs index ca98e9f21..c4c1b13e7 100644 --- a/EndlessClient/Dialogs/PlayerInfoDialog.cs +++ b/EndlessClient/Dialogs/PlayerInfoDialog.cs @@ -12,154 +12,153 @@ using Optional.Unsafe; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class PlayerInfoDialog : BaseEODialog { - public class PlayerInfoDialog : BaseEODialog + private static readonly Rectangle _iconDrawRect = new Rectangle(227, 258, 44, 21); + + private readonly IPubFileProvider _pubFileProvider; + private readonly IPaperdollProvider _paperdollProvider; + protected readonly bool _isMainCharacter; + + private readonly Texture2D _characterIconSheet; + private Option _characterIconSourceRect; + + private readonly IXNALabel _name, + _home, + _class, + _partner, + _title, + _guild, + _rank; + + public Character Character { get; } + + private Option _paperdollData; + + public PlayerInfoDialog(INativeGraphicsManager graphicsManager, + IEODialogButtonService eoDialogButtonService, + IPubFileProvider pubFileProvider, + IPaperdollProvider paperdollProvider, + Character character, + bool isMainCharacter) + : base(graphicsManager, isInGame: true) { - private static readonly Rectangle _iconDrawRect = new Rectangle(227, 258, 44, 21); - - private readonly IPubFileProvider _pubFileProvider; - private readonly IPaperdollProvider _paperdollProvider; - protected readonly bool _isMainCharacter; - - private readonly Texture2D _characterIconSheet; - private Option _characterIconSourceRect; - - private readonly IXNALabel _name, - _home, - _class, - _partner, - _title, - _guild, - _rank; - - public Character Character { get; } - - private Option _paperdollData; - - public PlayerInfoDialog(INativeGraphicsManager graphicsManager, - IEODialogButtonService eoDialogButtonService, - IPubFileProvider pubFileProvider, - IPaperdollProvider paperdollProvider, - Character character, - bool isMainCharacter) - : base(graphicsManager, isInGame: true) - { - _pubFileProvider = pubFileProvider; - _paperdollProvider = paperdollProvider; + _pubFileProvider = pubFileProvider; + _paperdollProvider = paperdollProvider; - Character = character; - _isMainCharacter = isMainCharacter; + Character = character; + _isMainCharacter = isMainCharacter; - _characterIconSheet = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); - _characterIconSourceRect = Option.None(); + _characterIconSheet = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); + _characterIconSourceRect = Option.None(); - _name = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 22, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _name.SetParentControl(this); + _name = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 22, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _name.SetParentControl(this); - _home = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 52, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _home.SetParentControl(this); + _home = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 52, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _home.SetParentControl(this); - _class = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 82, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _class.SetParentControl(this); + _class = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 82, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _class.SetParentControl(this); - _partner = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 112, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _partner.SetParentControl(this); + _partner = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 112, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _partner.SetParentControl(this); - _title = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 142, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _title.SetParentControl(this); + _title = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 142, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _title.SetParentControl(this); - _guild = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 202, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _guild.SetParentControl(this); + _guild = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 202, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _guild.SetParentControl(this); - _rank = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 232, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _rank.SetParentControl(this); + _rank = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 232, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _rank.SetParentControl(this); - var okButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(276, 253), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - okButton.OnClick += (_, _) => Close(XNADialogResult.OK); - okButton.Initialize(); - okButton.SetParentControl(this); + var okButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(276, 253), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + okButton.OnClick += (_, _) => Close(XNADialogResult.OK); + okButton.Initialize(); + okButton.SetParentControl(this); - _paperdollData = Option.None(); - } + _paperdollData = Option.None(); + } - public override void Initialize() - { - _name.Initialize(); - _home.Initialize(); - _class.Initialize(); - _partner.Initialize(); - _title.Initialize(); - _guild.Initialize(); - _rank.Initialize(); - - base.Initialize(); - } - - protected override void OnUpdateControl(GameTime gameTime) - { - _paperdollData = _paperdollData.FlatMap(paperdollData => - paperdollData.NoneWhen(d => _paperdollProvider.VisibleCharacterPaperdolls.ContainsKey(Character.ID) && - !_paperdollProvider.VisibleCharacterPaperdolls[Character.ID].Equals(d))); + public override void Initialize() + { + _name.Initialize(); + _home.Initialize(); + _class.Initialize(); + _partner.Initialize(); + _title.Initialize(); + _guild.Initialize(); + _rank.Initialize(); + + base.Initialize(); + } - _paperdollData.MatchNone(() => - { - if (_paperdollProvider.VisibleCharacterPaperdolls.ContainsKey(Character.ID)) - { - var paperdollData = _paperdollProvider.VisibleCharacterPaperdolls[Character.ID]; - _paperdollData = Option.Some(paperdollData); - UpdateDisplayedData(paperdollData); - } - }); - - base.OnUpdateControl(gameTime); - } - - protected override void OnDrawControl(GameTime gameTime) + protected override void OnUpdateControl(GameTime gameTime) + { + _paperdollData = _paperdollData.FlatMap(paperdollData => + paperdollData.NoneWhen(d => _paperdollProvider.VisibleCharacterPaperdolls.ContainsKey(Character.ID) && + !_paperdollProvider.VisibleCharacterPaperdolls[Character.ID].Equals(d))); + + _paperdollData.MatchNone(() => { - base.OnDrawControl(gameTime); + if (_paperdollProvider.VisibleCharacterPaperdolls.ContainsKey(Character.ID)) + { + var paperdollData = _paperdollProvider.VisibleCharacterPaperdolls[Character.ID]; + _paperdollData = Option.Some(paperdollData); + UpdateDisplayedData(paperdollData); + } + }); - _spriteBatch.Begin(); + base.OnUpdateControl(gameTime); + } - _characterIconSourceRect.MatchSome(sourceRect => - { - _spriteBatch.Draw(_characterIconSheet, - new Vector2( - DrawAreaWithParentOffset.X + _iconDrawRect.X + (_iconDrawRect.Width / 2) - (sourceRect.Width / 2), - DrawAreaWithParentOffset.Y + _iconDrawRect.Y + (_iconDrawRect.Height / 2) - (sourceRect.Height / 2)), - sourceRect, - Color.White); - }); - - _spriteBatch.End(); - } - - protected virtual void UpdateDisplayedData(PaperdollData paperdollData) + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); + + _spriteBatch.Begin(); + + _characterIconSourceRect.MatchSome(sourceRect => { - _name.Text = Capitalize(paperdollData.Name); - _home.Text = Capitalize(paperdollData.Home); + _spriteBatch.Draw(_characterIconSheet, + new Vector2( + DrawAreaWithParentOffset.X + _iconDrawRect.X + (_iconDrawRect.Width / 2) - (sourceRect.Width / 2), + DrawAreaWithParentOffset.Y + _iconDrawRect.Y + (_iconDrawRect.Height / 2) - (sourceRect.Height / 2)), + sourceRect, + Color.White); + }); + + _spriteBatch.End(); + } - paperdollData.Class.SomeWhen(x => x != 0) - .MatchSome(classId => _class.Text = Capitalize(_pubFileProvider.ECFFile[classId].Name)); + protected virtual void UpdateDisplayedData(PaperdollData paperdollData) + { + _name.Text = Capitalize(paperdollData.Name); + _home.Text = Capitalize(paperdollData.Home); - _partner.Text = Capitalize(paperdollData.Partner); - _title.Text = Capitalize(paperdollData.Title); - _guild.Text = Capitalize(paperdollData.Guild); - _rank.Text = Capitalize(paperdollData.Rank); + paperdollData.Class.SomeWhen(x => x != 0) + .MatchSome(classId => _class.Text = Capitalize(_pubFileProvider.ECFFile[classId].Name)); - _characterIconSourceRect = Option.Some(GetOnlineIconSourceRectangle(paperdollData.Icon)); - } + _partner.Text = Capitalize(paperdollData.Partner); + _title.Text = Capitalize(paperdollData.Title); + _guild.Text = Capitalize(paperdollData.Guild); + _rank.Text = Capitalize(paperdollData.Rank); - private static string Capitalize(string input) => - string.IsNullOrEmpty(input) ? string.Empty : char.ToUpper(input[0]) + input[1..].ToLower(); + _characterIconSourceRect = Option.Some(GetOnlineIconSourceRectangle(paperdollData.Icon)); + } - private static Rectangle GetOnlineIconSourceRectangle(CharacterIcon icon) - { - var (x, y, width, height) = icon.ToChatIcon().GetChatIconRectangleBounds().ValueOrDefault(); - return new Rectangle(x, y, width, height); - } + private static string Capitalize(string input) => + string.IsNullOrEmpty(input) ? string.Empty : char.ToUpper(input[0]) + input[1..].ToLower(); + + private static Rectangle GetOnlineIconSourceRectangle(CharacterIcon icon) + { + var (x, y, width, height) = icon.ToChatIcon().GetChatIconRectangleBounds().ValueOrDefault(); + return new Rectangle(x, y, width, height); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ProgressDialog.cs b/EndlessClient/Dialogs/ProgressDialog.cs index 1bcf03e12..fc05181fc 100644 --- a/EndlessClient/Dialogs/ProgressDialog.cs +++ b/EndlessClient/Dialogs/ProgressDialog.cs @@ -9,117 +9,116 @@ using System.Threading; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class ProgressDialog : BaseEODialog { - public class ProgressDialog : BaseEODialog + private readonly IConfigurationProvider _configurationProvider; + + private readonly IXNALabel _messageLabel, _captionLabel; + private readonly IXNAButton _cancelButton; + + private TimeSpan? timeOpened; + private readonly Texture2D _pbBackgroundTexture, _pbForegroundTexture; + private int _pbWidth, _cancelRequests; + + public ProgressDialog(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IConfigurationProvider configurationProvider, + IEODialogButtonService eoDialogButtonService, + string messageText, + string captionText) + : base(nativeGraphicsManager, gameStateProvider) { - private readonly IConfigurationProvider _configurationProvider; - - private readonly IXNALabel _messageLabel, _captionLabel; - private readonly IXNAButton _cancelButton; - - private TimeSpan? timeOpened; - private readonly Texture2D _pbBackgroundTexture, _pbForegroundTexture; - private int _pbWidth, _cancelRequests; - - public ProgressDialog(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IConfigurationProvider configurationProvider, - IEODialogButtonService eoDialogButtonService, - string messageText, - string captionText) - : base(nativeGraphicsManager, gameStateProvider) - { - _configurationProvider = configurationProvider; - - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 18); - - _messageLabel = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - ForeColor = ColorConstants.LightYellowText, - Text = messageText, - TextWidth = 254, - DrawPosition = new Vector2(18, 57) - }; - _messageLabel.SetParentControl(this); - - _captionLabel = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - ForeColor = ColorConstants.LightYellowText, - Text = captionText, - DrawPosition = new Vector2(59, 23) - }; - _captionLabel.SetParentControl(this); - - _cancelButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(181, 113), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - _cancelButton.OnClick += DoCancel; - _cancelButton.SetParentControl(this); - - _pbBackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 19); - - _pbForegroundTexture = new Texture2D(Game.GraphicsDevice, 1, _pbBackgroundTexture.Height - 2); //foreground texture is just a fill - var pbForeFill = new Color[_pbForegroundTexture.Width * _pbForegroundTexture.Height]; - for (int i = 0; i < pbForeFill.Length; ++i) - pbForeFill[i] = Color.FromNonPremultiplied(0xb4, 0xdc, 0xe6, 0xff); - _pbForegroundTexture.SetData(pbForeFill); - - CenterInGameView(); - } + _configurationProvider = configurationProvider; - public override void Initialize() + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 18); + + _messageLabel = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + ForeColor = ColorConstants.LightYellowText, + Text = messageText, + TextWidth = 254, + DrawPosition = new Vector2(18, 57) + }; + _messageLabel.SetParentControl(this); + + _captionLabel = new XNALabel(Constants.FontSize10) { - _messageLabel.Initialize(); - _captionLabel.Initialize(); - _cancelButton.Initialize(); + AutoSize = true, + ForeColor = ColorConstants.LightYellowText, + Text = captionText, + DrawPosition = new Vector2(59, 23) + }; + _captionLabel.SetParentControl(this); + + _cancelButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(181, 113), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + _cancelButton.OnClick += DoCancel; + _cancelButton.SetParentControl(this); + + _pbBackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 19); + + _pbForegroundTexture = new Texture2D(Game.GraphicsDevice, 1, _pbBackgroundTexture.Height - 2); //foreground texture is just a fill + var pbForeFill = new Color[_pbForegroundTexture.Width * _pbForegroundTexture.Height]; + for (int i = 0; i < pbForeFill.Length; ++i) + pbForeFill[i] = Color.FromNonPremultiplied(0xb4, 0xdc, 0xe6, 0xff); + _pbForegroundTexture.SetData(pbForeFill); + + CenterInGameView(); + } - base.Initialize(); - } + public override void Initialize() + { + _messageLabel.Initialize(); + _captionLabel.Initialize(); + _cancelButton.Initialize(); - protected override void OnUpdateControl(GameTime gt) - { - if (timeOpened == null) - timeOpened = gt.TotalGameTime; + base.Initialize(); + } + + protected override void OnUpdateControl(GameTime gt) + { + if (timeOpened == null) + timeOpened = gt.TotalGameTime; - var pbPercent = (int)((gt.TotalGameTime.TotalSeconds - timeOpened.Value.TotalSeconds) / _configurationProvider.AccountCreateTimeout.TotalSeconds * 100); - _pbWidth = (int)Math.Round(pbPercent / 100.0f * _pbBackgroundTexture.Width); + var pbPercent = (int)((gt.TotalGameTime.TotalSeconds - timeOpened.Value.TotalSeconds) / _configurationProvider.AccountCreateTimeout.TotalSeconds * 100); + _pbWidth = (int)Math.Round(pbPercent / 100.0f * _pbBackgroundTexture.Width); - if (pbPercent >= 100) - Close(XNADialogResult.NO_BUTTON_PRESSED); + if (pbPercent >= 100) + Close(XNADialogResult.NO_BUTTON_PRESSED); - base.OnUpdateControl(gt); - } + base.OnUpdateControl(gt); + } - protected override void OnDrawControl(GameTime gt) - { - base.OnDrawControl(gt); + protected override void OnDrawControl(GameTime gt) + { + base.OnDrawControl(gt); - var pbBackgroundPosition = new Vector2(15 + DrawPositionWithParentOffset.X, 95 + DrawPositionWithParentOffset.Y); - var pbForgroundArea = new Rectangle(18 + DrawAreaWithParentOffset.X, 98 + DrawAreaWithParentOffset.Y, _pbWidth - 6, _pbForegroundTexture.Height - 4); + var pbBackgroundPosition = new Vector2(15 + DrawPositionWithParentOffset.X, 95 + DrawPositionWithParentOffset.Y); + var pbForgroundArea = new Rectangle(18 + DrawAreaWithParentOffset.X, 98 + DrawAreaWithParentOffset.Y, _pbWidth - 6, _pbForegroundTexture.Height - 4); - _spriteBatch.Begin(); - _spriteBatch.Draw(_pbBackgroundTexture, pbBackgroundPosition, Color.White); - _spriteBatch.Draw(_pbForegroundTexture, pbForgroundArea, Color.White); - _spriteBatch.End(); - } + _spriteBatch.Begin(); + _spriteBatch.Draw(_pbBackgroundTexture, pbBackgroundPosition, Color.White); + _spriteBatch.Draw(_pbForegroundTexture, pbForgroundArea, Color.White); + _spriteBatch.End(); + } + + private void DoCancel(object sender, EventArgs e) + { + if (Interlocked.Increment(ref _cancelRequests) != 1) + return; - private void DoCancel(object sender, EventArgs e) + try + { + Close(XNADialogResult.Cancel); + } + finally { - if (Interlocked.Increment(ref _cancelRequests) != 1) - return; - - try - { - Close(XNADialogResult.Cancel); - } - finally - { - Interlocked.Exchange(ref _cancelRequests, 0); - } + Interlocked.Exchange(ref _cancelRequests, 0); } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/QuestDialog.cs b/EndlessClient/Dialogs/QuestDialog.cs index de1328595..d9e2309bc 100644 --- a/EndlessClient/Dialogs/QuestDialog.cs +++ b/EndlessClient/Dialogs/QuestDialog.cs @@ -12,180 +12,179 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs -{ - public class QuestDialog : ScrollingListDialog - { - private readonly IQuestActions _questActions; - private readonly IQuestDataProvider _questDataProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly IContentProvider _contentProvider; +namespace EndlessClient.Dialogs; - private Option _cachedData; +public class QuestDialog : ScrollingListDialog +{ + private readonly IQuestActions _questActions; + private readonly IQuestDataProvider _questDataProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly IContentProvider _contentProvider; - private int _pageIndex = 0; + private Option _cachedData; - public event EventHandler LinkClickAction; + private int _pageIndex = 0; - public QuestDialog(INativeGraphicsManager nativeGraphicsManager, - IQuestActions questActions, - IEODialogButtonService dialogButtonService, - IQuestDataProvider questDataProvider, - IENFFileProvider enfFileProvider, - IContentProvider contentProvider) - : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.NpcQuestDialog) - { - _questActions = questActions; - _questDataProvider = questDataProvider; - _enfFileProvider = enfFileProvider; - _contentProvider = contentProvider; + public event EventHandler LinkClickAction; - _cachedData = Option.None(); + public QuestDialog(INativeGraphicsManager nativeGraphicsManager, + IQuestActions questActions, + IEODialogButtonService dialogButtonService, + IQuestDataProvider questDataProvider, + IENFFileProvider enfFileProvider, + IContentProvider contentProvider) + : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.NpcQuestDialog) + { + _questActions = questActions; + _questDataProvider = questDataProvider; + _enfFileProvider = enfFileProvider; + _contentProvider = contentProvider; - ListItemType = ListDialogItem.ListItemStyle.Small; + _cachedData = Option.None(); - NextAction += NextPage; - BackAction += PreviousPage; - DialogClosing += (_, e) => - { - if (e.Result == XNADialogResult.OK) - _questActions.RespondToQuestDialog(DialogReply.Ok); - }; - } + ListItemType = ListDialogItem.ListItemStyle.Small; - protected override void OnUpdateControl(GameTime gameTime) + NextAction += NextPage; + BackAction += PreviousPage; + DialogClosing += (_, e) => { - _questDataProvider.QuestDialogData.MatchSome(data => UpdateCachedDataIfNeeded(_cachedData, data)); - base.OnUpdateControl(gameTime); - } + if (e.Result == XNADialogResult.OK) + _questActions.RespondToQuestDialog(DialogReply.Ok); + }; + } - private void UpdateCachedDataIfNeeded(Option cachedData, QuestDialogData repoData) - { - cachedData.Match( - some: cached => - { - _cachedData = Option.Some(repoData); - if (!cached.Equals(repoData)) - UpdateDialogControls(repoData); - }, - none: () => - { - _cachedData = Option.Some(repoData); + protected override void OnUpdateControl(GameTime gameTime) + { + _questDataProvider.QuestDialogData.MatchSome(data => UpdateCachedDataIfNeeded(_cachedData, data)); + base.OnUpdateControl(gameTime); + } + + private void UpdateCachedDataIfNeeded(Option cachedData, QuestDialogData repoData) + { + cachedData.Match( + some: cached => + { + _cachedData = Option.Some(repoData); + if (!cached.Equals(repoData)) UpdateDialogControls(repoData); - }); - } + }, + none: () => + { + _cachedData = Option.Some(repoData); + UpdateDialogControls(repoData); + }); + } - private void UpdateDialogControls(QuestDialogData repoData) - { - _pageIndex = 0; + private void UpdateDialogControls(QuestDialogData repoData) + { + _pageIndex = 0; - UpdateTitle(repoData); - UpdateDialogDisplayText(repoData); - UpdateButtons(repoData); - } + UpdateTitle(repoData); + UpdateDialogDisplayText(repoData); + UpdateButtons(repoData); + } - private void UpdateTitle(QuestDialogData repoData) + private void UpdateTitle(QuestDialogData repoData) + { + if (_questDataProvider.RequestedNPC != null) { - if (_questDataProvider.RequestedNPC != null) - { - var npcName = _enfFileProvider.ENFFile[_questDataProvider.RequestedNPC.ID].Name; - var titleText = npcName; - if (!repoData.DialogTitles.ContainsKey(repoData.VendorID) && repoData.DialogTitles.Count == 1) - titleText += $" - {repoData.DialogTitles.Single().Value}"; - else if (repoData.DialogTitles.ContainsKey(repoData.VendorID)) - titleText += $" - {repoData.DialogTitles[repoData.VendorID]}"; - - _titleText.Text = titleText; - _titleText.ResizeBasedOnText(); - } - else - { - _titleText.Text = string.Empty; - } + var npcName = _enfFileProvider.ENFFile[_questDataProvider.RequestedNPC.ID].Name; + var titleText = npcName; + if (!repoData.DialogTitles.ContainsKey(repoData.VendorID) && repoData.DialogTitles.Count == 1) + titleText += $" - {repoData.DialogTitles.Single().Value}"; + else if (repoData.DialogTitles.ContainsKey(repoData.VendorID)) + titleText += $" - {repoData.DialogTitles[repoData.VendorID]}"; + + _titleText.Text = titleText; + _titleText.ResizeBasedOnText(); } - - private void UpdateDialogDisplayText(QuestDialogData repoData) + else { - ClearItemList(); + _titleText.Text = string.Empty; + } + } - var rows = new List(); + private void UpdateDialogDisplayText(QuestDialogData repoData) + { + ClearItemList(); - var ts = new TextSplitter(repoData.PageText[_pageIndex], _contentProvider.Fonts[Constants.FontSize09]); - if (!ts.NeedsProcessing) - rows.Add(repoData.PageText[_pageIndex]); - else - rows.AddRange(ts.SplitIntoLines()); + var rows = new List(); - int index = 0; - foreach (var row in rows) - { - var rowItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) - { - PrimaryText = row, - }; + var ts = new TextSplitter(repoData.PageText[_pageIndex], _contentProvider.Fonts[Constants.FontSize09]); + if (!ts.NeedsProcessing) + rows.Add(repoData.PageText[_pageIndex]); + else + rows.AddRange(ts.SplitIntoLines()); - AddItemToList(rowItem, sortList: false); - } + int index = 0; + foreach (var row in rows) + { + var rowItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) + { + PrimaryText = row, + }; - // The links are only shown on the last page of the quest dialog - if (_pageIndex < repoData.PageText.Count - 1) - return; + AddItemToList(rowItem, sortList: false); + } - var item = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) { PrimaryText = " " }; - AddItemToList(item, sortList: false); + // The links are only shown on the last page of the quest dialog + if (_pageIndex < repoData.PageText.Count - 1) + return; - foreach (var action in repoData.Actions) - { - var actionItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) - { - PrimaryText = action.DisplayText - }; - - var linkIndex = action.ActionID; - actionItem.SetPrimaryClickAction((_, _) => - { - _questActions.RespondToQuestDialog(DialogReply.Link, linkIndex); - LinkClickAction?.Invoke(this, EventArgs.Empty); - Close(XNADialogResult.Cancel); - }); - - AddItemToList(actionItem, sortList: false); - } - } + var item = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) { PrimaryText = " " }; + AddItemToList(item, sortList: false); - private void UpdateButtons(QuestDialogData repoData) + foreach (var action in repoData.Actions) { - bool morePages = _pageIndex < repoData.PageText.Count - 1; - bool firstPage = _pageIndex == 0; - - if (firstPage && morePages) - Buttons = ScrollingListDialogButtons.CancelNext; - else if (!firstPage && morePages) - Buttons = ScrollingListDialogButtons.BackNext; - else if (firstPage) - Buttons = ScrollingListDialogButtons.CancelOk; - else - Buttons = ScrollingListDialogButtons.BackOk; - } + var actionItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) + { + PrimaryText = action.DisplayText + }; - private void NextPage(object sender, EventArgs e) - { - _cachedData.MatchSome(data => + var linkIndex = action.ActionID; + actionItem.SetPrimaryClickAction((_, _) => { - _pageIndex++; - UpdateDialogDisplayText(data); - UpdateButtons(data); + _questActions.RespondToQuestDialog(DialogReply.Link, linkIndex); + LinkClickAction?.Invoke(this, EventArgs.Empty); + Close(XNADialogResult.Cancel); }); + + AddItemToList(actionItem, sortList: false); } + } - private void PreviousPage(object sender, EventArgs e) + private void UpdateButtons(QuestDialogData repoData) + { + bool morePages = _pageIndex < repoData.PageText.Count - 1; + bool firstPage = _pageIndex == 0; + + if (firstPage && morePages) + Buttons = ScrollingListDialogButtons.CancelNext; + else if (!firstPage && morePages) + Buttons = ScrollingListDialogButtons.BackNext; + else if (firstPage) + Buttons = ScrollingListDialogButtons.CancelOk; + else + Buttons = ScrollingListDialogButtons.BackOk; + } + + private void NextPage(object sender, EventArgs e) + { + _cachedData.MatchSome(data => { - _cachedData.MatchSome(data => - { - _pageIndex--; - UpdateDialogDisplayText(data); - UpdateButtons(data); - }); - } + _pageIndex++; + UpdateDialogDisplayText(data); + UpdateButtons(data); + }); + } + + private void PreviousPage(object sender, EventArgs e) + { + _cachedData.MatchSome(data => + { + _pageIndex--; + UpdateDialogDisplayText(data); + UpdateButtons(data); + }); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/QuestStatusDialog.cs b/EndlessClient/Dialogs/QuestStatusDialog.cs index 2d3b4e65f..2f12a4a29 100644 --- a/EndlessClient/Dialogs/QuestStatusDialog.cs +++ b/EndlessClient/Dialogs/QuestStatusDialog.cs @@ -7,128 +7,127 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using System.Collections.Generic; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class QuestStatusDialog : ScrollingListDialog { - public class QuestStatusDialog : ScrollingListDialog - { - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IQuestDataProvider _questDataProvider; - private readonly ICharacterProvider _characterProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IQuestDataProvider _questDataProvider; + private readonly ICharacterProvider _characterProvider; - private IReadOnlyList _cachedProgress = new List(); - private IReadOnlyList _cachedHistory = new List(); + private IReadOnlyList _cachedProgress = new List(); + private IReadOnlyList _cachedHistory = new List(); - private QuestPage _page; + private QuestPage _page; + + public QuestStatusDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IQuestDataProvider questDataProvider, + ICharacterProvider characterProvider) + : base(nativeGraphicsManager, dialogButtonService, DialogType.QuestProgressHistory) + { + ListItemType = ListDialogItem.ListItemStyle.Small; + Buttons = ScrollingListDialogButtons.HistoryOk; + _localizedStringFinder = localizedStringFinder; + _questDataProvider = questDataProvider; + _characterProvider = characterProvider; + HistoryAction += (_, _) => ShowHistory(); + ProgressAction += (_, _) => ShowProgress(); + + _page = QuestPage.Progress; + } - public QuestStatusDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IQuestDataProvider questDataProvider, - ICharacterProvider characterProvider) - : base(nativeGraphicsManager, dialogButtonService, DialogType.QuestProgressHistory) + protected override void OnUpdateControl(GameTime gameTime) + { + if (_questDataProvider.QuestHistory != _cachedHistory) + { + _cachedHistory = _questDataProvider.QuestHistory; + if (_page == QuestPage.History) + ShowHistory(); + } + else if (_questDataProvider.QuestProgress != _cachedProgress) { - ListItemType = ListDialogItem.ListItemStyle.Small; - Buttons = ScrollingListDialogButtons.HistoryOk; - _localizedStringFinder = localizedStringFinder; - _questDataProvider = questDataProvider; - _characterProvider = characterProvider; - HistoryAction += (_, _) => ShowHistory(); - ProgressAction += (_, _) => ShowProgress(); - - _page = QuestPage.Progress; + _cachedProgress = _questDataProvider.QuestProgress; + if (_page == QuestPage.Progress) + ShowProgress(); } - protected override void OnUpdateControl(GameTime gameTime) + base.OnUpdateControl(gameTime); + } + + private void ShowHistory() + { + ClearItemList(); + SetTitle(QuestPage.History); + + if (_cachedHistory.Count == 0) { - if (_questDataProvider.QuestHistory != _cachedHistory) + var nextItem = new QuestStatusListDialogItem(this, QuestPage.History) { - _cachedHistory = _questDataProvider.QuestHistory; - if (_page == QuestPage.History) - ShowHistory(); - } - else if (_questDataProvider.QuestProgress != _cachedProgress) - { - _cachedProgress = _questDataProvider.QuestProgress; - if (_page == QuestPage.Progress) - ShowProgress(); - } - - base.OnUpdateControl(gameTime); + QuestName = _localizedStringFinder.GetString(EOResourceID.QUEST_DID_NOT_FINISH_ANY), + ShowIcons = false + }; + nextItem.SetScrollWheelHandler(this); + AddItemToList(nextItem, sortList: false); } - private void ShowHistory() + foreach (var questName in _cachedHistory) { - ClearItemList(); - SetTitle(QuestPage.History); - - if (_cachedHistory.Count == 0) + var nextItem = new QuestStatusListDialogItem(this, QuestPage.History) { - var nextItem = new QuestStatusListDialogItem(this, QuestPage.History) - { - QuestName = _localizedStringFinder.GetString(EOResourceID.QUEST_DID_NOT_FINISH_ANY), - ShowIcons = false - }; - nextItem.SetScrollWheelHandler(this); - AddItemToList(nextItem, sortList: false); - } - - foreach (var questName in _cachedHistory) - { - var nextItem = new QuestStatusListDialogItem(this, QuestPage.History) - { - QuestName = questName, - QuestProgress = _localizedStringFinder.GetString(EOResourceID.QUEST_COMPLETED), - }; - nextItem.SetScrollWheelHandler(this); - AddItemToList(nextItem, sortList: false); - } - - _scrollBar.ScrollToTop(); - Buttons = ScrollingListDialogButtons.ProgressOk; + QuestName = questName, + QuestProgress = _localizedStringFinder.GetString(EOResourceID.QUEST_COMPLETED), + }; + nextItem.SetScrollWheelHandler(this); + AddItemToList(nextItem, sortList: false); } - private void ShowProgress() - { - ClearItemList(); - SetTitle(QuestPage.Progress); + _scrollBar.ScrollToTop(); + Buttons = ScrollingListDialogButtons.ProgressOk; + } - if (_cachedProgress.Count == 0) - { - var nextItem = new QuestStatusListDialogItem(this, QuestPage.Progress) - { - QuestName = _localizedStringFinder.GetString(EOResourceID.QUEST_DID_NOT_START_ANY), - ShowIcons = false, - }; - nextItem.SetScrollWheelHandler(this); - AddItemToList(nextItem, sortList: false); - } - - foreach (var quest in _cachedProgress) + private void ShowProgress() + { + ClearItemList(); + SetTitle(QuestPage.Progress); + + if (_cachedProgress.Count == 0) + { + var nextItem = new QuestStatusListDialogItem(this, QuestPage.Progress) { - var nextItem = new QuestStatusListDialogItem(this, QuestPage.Progress) - { - QuestName = quest.Name, - QuestStep = quest.Description, - Icon = (QuestStatusListDialogItem.QuestStatusIcon)quest.IconIndex, - QuestProgress = quest.Target > 0 ? $"{quest.Progress} / {quest.Target}" : "n / a" - }; - nextItem.SetScrollWheelHandler(this); - AddItemToList(nextItem, sortList: false); - } - - _scrollBar.ScrollToTop(); - Buttons = ScrollingListDialogButtons.HistoryOk; + QuestName = _localizedStringFinder.GetString(EOResourceID.QUEST_DID_NOT_START_ANY), + ShowIcons = false, + }; + nextItem.SetScrollWheelHandler(this); + AddItemToList(nextItem, sortList: false); } - private void SetTitle(QuestPage page) + foreach (var quest in _cachedProgress) { - var resource = page == QuestPage.Progress - ? EOResourceID.QUEST_PROGRESS - : EOResourceID.QUEST_HISTORY; - var description = _localizedStringFinder.GetString(resource); - - Title = $"{_characterProvider.MainCharacter.Name}'s {description}"; + var nextItem = new QuestStatusListDialogItem(this, QuestPage.Progress) + { + QuestName = quest.Name, + QuestStep = quest.Description, + Icon = (QuestStatusListDialogItem.QuestStatusIcon)quest.IconIndex, + QuestProgress = quest.Target > 0 ? $"{quest.Progress} / {quest.Target}" : "n / a" + }; + nextItem.SetScrollWheelHandler(this); + AddItemToList(nextItem, sortList: false); } + + _scrollBar.ScrollToTop(); + Buttons = ScrollingListDialogButtons.HistoryOk; + } + + private void SetTitle(QuestPage page) + { + var resource = page == QuestPage.Progress + ? EOResourceID.QUEST_PROGRESS + : EOResourceID.QUEST_HISTORY; + var description = _localizedStringFinder.GetString(resource); + + Title = $"{_characterProvider.MainCharacter.Name}'s {description}"; } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/QuestStatusListDialogItem.cs b/EndlessClient/Dialogs/QuestStatusListDialogItem.cs index 2e3f99dfc..a728e179d 100644 --- a/EndlessClient/Dialogs/QuestStatusListDialogItem.cs +++ b/EndlessClient/Dialogs/QuestStatusListDialogItem.cs @@ -5,130 +5,129 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class QuestStatusListDialogItem : ListDialogItem { - public class QuestStatusListDialogItem : ListDialogItem + public enum QuestStatusIcon { - public enum QuestStatusIcon - { - None = 0, - Talk = 1, - Item = 2, - Kill = 3, - Step = 4, - Complete = 5, - None2 = 6, // ? - None3 = 7, // ? - }; + None = 0, + Talk = 1, + Item = 2, + Kill = 3, + Step = 4, + Complete = 5, + None2 = 6, // ? + None3 = 7, // ? + }; + + private static readonly Vector2 _firstIconPosition = new Vector2(6, 0); + private static readonly Vector2 _secondIconPosition = new Vector2(151, 0); + private readonly Vector2 _signalPosition; + + private readonly IXNALabel _progress; + private readonly Texture2D _iconTexture; + private readonly QuestPage _page; + + public QuestStatusIcon Icon { get; set; } + + public string QuestName + { + get => PrimaryText; + set => PrimaryText = value; + } - private static readonly Vector2 _firstIconPosition = new Vector2(6, 0); - private static readonly Vector2 _secondIconPosition = new Vector2(151, 0); - private readonly Vector2 _signalPosition; + public string QuestStep + { + get => SubText; + set => SubText = value; + } - private readonly IXNALabel _progress; - private readonly Texture2D _iconTexture; - private readonly QuestPage _page; + public string QuestProgress + { + get => _progress.Text; + set => _progress.Text = value; + } - public QuestStatusIcon Icon { get; set; } + public bool ShowIcons { get; set; } - public string QuestName - { - get => PrimaryText; - set => PrimaryText = value; - } + public QuestStatusListDialogItem(QuestStatusDialog parent, QuestPage page) + : base(parent, ListItemStyle.Small) + { + _iconTexture = parent.GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); + ShowIcons = true; - public string QuestStep - { - get => SubText; - set => SubText = value; - } + SetSize(427, 16); - public string QuestProgress - { - get => _progress.Text; - set => _progress.Text = value; - } + _primaryText.DrawPosition += new Vector2(25, 2); + _subText.DrawPosition = new Vector2(169, _primaryText.DrawPosition.Y); + ((DrawableGameComponent)_subText).Visible = true; - public bool ShowIcons { get; set; } + PrimaryText = " "; + SubText = " "; - public QuestStatusListDialogItem(QuestStatusDialog parent, QuestPage page) - : base(parent, ListItemStyle.Small) + _progress = new XNALabel(Constants.FontSize08pt5) { - _iconTexture = parent.GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); - ShowIcons = true; - - SetSize(427, 16); + DrawPosition = new Vector2(page == QuestPage.Progress ? 353 : 289, _primaryText.DrawPosition.Y), + AutoSize = true, + BackColor = _primaryText.BackColor, + ForeColor = _primaryText.ForeColor, + Text = " ", + Visible = true, + }; - _primaryText.DrawPosition += new Vector2(25, 2); - _subText.DrawPosition = new Vector2(169, _primaryText.DrawPosition.Y); - ((DrawableGameComponent)_subText).Visible = true; + _signalPosition = page == QuestPage.Progress + ? new Vector2(334, 2) + : new Vector2(270, 2); - PrimaryText = " "; - SubText = " "; + Icon = page == QuestPage.Progress + ? QuestStatusIcon.None + : QuestStatusIcon.Complete; + _page = page; + } - _progress = new XNALabel(Constants.FontSize08pt5) - { - DrawPosition = new Vector2(page == QuestPage.Progress ? 353 : 289, _primaryText.DrawPosition.Y), - AutoSize = true, - BackColor = _primaryText.BackColor, - ForeColor = _primaryText.ForeColor, - Text = " ", - Visible = true, - }; - - _signalPosition = page == QuestPage.Progress - ? new Vector2(334, 2) - : new Vector2(270, 2); - - Icon = page == QuestPage.Progress - ? QuestStatusIcon.None - : QuestStatusIcon.Complete; - _page = page; - } + public override void Initialize() + { + _progress.Initialize(); + _progress.SetParentControl(this); - public override void Initialize() - { - _progress.Initialize(); - _progress.SetParentControl(this); + base.Initialize(); + } - base.Initialize(); - } + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - protected override void OnDrawControl(GameTime gameTime) + if (ShowIcons) { - base.OnDrawControl(gameTime); + _spriteBatch.Begin(); - if (ShowIcons) - { - _spriteBatch.Begin(); + _spriteBatch.Draw(_iconTexture, + DrawPositionWithParentOffset + _firstIconPosition, + GetIconSourceRectangle(_page == QuestPage.Progress ? QuestStatusIcon.None : QuestStatusIcon.Complete), Color.White); + if (_page == QuestPage.Progress) + { _spriteBatch.Draw(_iconTexture, - DrawPositionWithParentOffset + _firstIconPosition, - GetIconSourceRectangle(_page == QuestPage.Progress ? QuestStatusIcon.None : QuestStatusIcon.Complete), Color.White); - - if (_page == QuestPage.Progress) - { - _spriteBatch.Draw(_iconTexture, - DrawPositionWithParentOffset + _secondIconPosition, - GetIconSourceRectangle(Icon), Color.White); - } + DrawPositionWithParentOffset + _secondIconPosition, + GetIconSourceRectangle(Icon), Color.White); + } - _spriteBatch.Draw(_iconTexture, - DrawPositionWithParentOffset + _signalPosition, - GetSignalSourceRectangle(), Color.White); + _spriteBatch.Draw(_iconTexture, + DrawPositionWithParentOffset + _signalPosition, + GetSignalSourceRectangle(), Color.White); - _spriteBatch.End(); - } + _spriteBatch.End(); } + } - private static Rectangle GetIconSourceRectangle(QuestStatusIcon index) - { - return new Rectangle((int)index * 15, 0, 15, 15); - } + private static Rectangle GetIconSourceRectangle(QuestStatusIcon index) + { + return new Rectangle((int)index * 15, 0, 15, 15); + } - private static Rectangle GetSignalSourceRectangle() - { - return new Rectangle(0, 15, 15, 15); - } + private static Rectangle GetSignalSourceRectangle() + { + return new Rectangle(0, 15, 15, 15); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ScrollingListDialog.cs b/EndlessClient/Dialogs/ScrollingListDialog.cs index d4eb5596c..9095866bf 100644 --- a/EndlessClient/Dialogs/ScrollingListDialog.cs +++ b/EndlessClient/Dialogs/ScrollingListDialog.cs @@ -13,597 +13,596 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +[Flags] +public enum ScrollingListDialogButtons { - [Flags] - public enum ScrollingListDialogButtons - { - None = 0x00, - Add = 0x01, - Cancel = 0x02, - Back = 0x04, - Next = 0x08, - Ok = 0x10, - History = 0x20, - Progress = 0x40, - Delete = 0x80, - DualButtons = 0x800, - // indicates a configuration in which a pairing of DualButtons is already defined, but the order is reversed - Alternate = 0x1000, - - AddCancel = DualButtons | Add | Cancel, - BackCancel = DualButtons | Back | Cancel, - BackOk = DualButtons | Back | Ok, - CancelOk = DualButtons | Cancel | Ok, - OkCancel = DualButtons | Cancel | Ok | Alternate, - BackNext = DualButtons | Back | Next, - CancelNext = DualButtons | Cancel | Next, - HistoryOk = DualButtons | History | Ok, - ProgressOk = DualButtons | Progress | Ok, - DeleteCancel = DualButtons | Delete | Cancel, - - // There is only one button, but we want it to show on the right side as if it were a dual button setting - OffsetCancel = DualButtons | Alternate | Cancel, - } + None = 0x00, + Add = 0x01, + Cancel = 0x02, + Back = 0x04, + Next = 0x08, + Ok = 0x10, + History = 0x20, + Progress = 0x40, + Delete = 0x80, + DualButtons = 0x800, + // indicates a configuration in which a pairing of DualButtons is already defined, but the order is reversed + Alternate = 0x1000, + + AddCancel = DualButtons | Add | Cancel, + BackCancel = DualButtons | Back | Cancel, + BackOk = DualButtons | Back | Ok, + CancelOk = DualButtons | Cancel | Ok, + OkCancel = DualButtons | Cancel | Ok | Alternate, + BackNext = DualButtons | Back | Next, + CancelNext = DualButtons | Cancel | Next, + HistoryOk = DualButtons | History | Ok, + ProgressOk = DualButtons | Progress | Ok, + DeleteCancel = DualButtons | Delete | Cancel, + + // There is only one button, but we want it to show on the right side as if it were a dual button setting + OffsetCancel = DualButtons | Alternate | Cancel, +} + +public enum DialogType +{ + // large + Shop, + FriendIgnore = Shop, + Locker = Shop, + Message = Shop, + Guild = Shop, + Inn = Shop, + Law = Shop, - public enum DialogType - { - // large - Shop, - FriendIgnore = Shop, - Locker = Shop, - Message = Shop, - Guild = Shop, - Inn = Shop, - Law = Shop, + // large / alternate background + Help, - // large / alternate background - Help, + // large no scroll + Chest, - // large no scroll - Chest, + // medium + QuestProgressHistory, + Board = QuestProgressHistory, - // medium - QuestProgressHistory, - Board = QuestProgressHistory, + // small + NpcQuestDialog, - // small - NpcQuestDialog, + // small no scroll + BankAccountDialog, - // small no scroll - BankAccountDialog, + Jukebox, + Barber, +} - Jukebox, - Barber, - } +public class ScrollingListDialog : BaseEODialog +{ + private readonly List _listItems; + protected readonly ScrollBar _scrollBar; - public class ScrollingListDialog : BaseEODialog - { - private readonly List _listItems; - protected readonly ScrollBar _scrollBar; + protected readonly IXNALabel _titleText; + private ListDialogItem.ListItemStyle _listItemType; - protected readonly IXNALabel _titleText; - private ListDialogItem.ListItemStyle _listItemType; + protected readonly XNAButton _add, _back, _cancel; + protected readonly XNAButton _next, _ok, _delete; + protected readonly XNAButton _history, _progress; - protected readonly XNAButton _add, _back, _cancel; - protected readonly XNAButton _next, _ok, _delete; - protected readonly XNAButton _history, _progress; + protected readonly Vector2 _button1Position, _button2Position, _buttonCenterPosition; - protected readonly Vector2 _button1Position, _button2Position, _buttonCenterPosition; + private ScrollingListDialogButtons _buttons; - private ScrollingListDialogButtons _buttons; + public IReadOnlyList NamesList => _listItems.Select(item => item.PrimaryText).ToList(); - public IReadOnlyList NamesList => _listItems.Select(item => item.PrimaryText).ToList(); + public string Title + { + get => _titleText.Text; + set => _titleText.Text = value; + } - public string Title + public int ItemsToShow + { + get { - get => _titleText.Text; - set => _titleText.Text = value; - } + if (ListItemType == ListDialogItem.ListItemStyle.Large) + return 5; - public int ItemsToShow - { - get + switch (DialogType) { - if (ListItemType == ListDialogItem.ListItemStyle.Large) - return 5; - - switch (DialogType) - { - case DialogType.Shop: - case DialogType.Help: - case DialogType.QuestProgressHistory: - return 12; - case DialogType.NpcQuestDialog: return 6; - default: throw new NotImplementedException(); - } + case DialogType.Shop: + case DialogType.Help: + case DialogType.QuestProgressHistory: + return 12; + case DialogType.NpcQuestDialog: return 6; + default: throw new NotImplementedException(); } } + } - public ListDialogItem.ListItemStyle ListItemType + public ListDialogItem.ListItemStyle ListItemType + { + get => _listItemType; + set { - get => _listItemType; - set - { - if (value == ListDialogItem.ListItemStyle.Large && DialogType == DialogType.NpcQuestDialog) - throw new InvalidOperationException("Can't use large ListDialogItem with small scrolling dialog"); + if (value == ListDialogItem.ListItemStyle.Large && DialogType == DialogType.NpcQuestDialog) + throw new InvalidOperationException("Can't use large ListDialogItem with small scrolling dialog"); - _listItemType = value; - _scrollBar.LinesToRender = ItemsToShow; - } + _listItemType = value; + _scrollBar.LinesToRender = ItemsToShow; } + } - public ScrollingListDialogButtons Buttons + public ScrollingListDialogButtons Buttons + { + get => _buttons; + set { - get => _buttons; - set + _buttons = value; + _add.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Add); + _back.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Back); + _next.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Next); + _ok.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Ok); + _cancel.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Cancel); + _history.Visible = Buttons.HasFlag(ScrollingListDialogButtons.History); + _progress.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Progress); + _delete.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Delete); + + if (Buttons.HasFlag(ScrollingListDialogButtons.DualButtons)) { - _buttons = value; - _add.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Add); - _back.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Back); - _next.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Next); - _ok.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Ok); - _cancel.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Cancel); - _history.Visible = Buttons.HasFlag(ScrollingListDialogButtons.History); - _progress.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Progress); - _delete.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Delete); - - if (Buttons.HasFlag(ScrollingListDialogButtons.DualButtons)) + if (Buttons == ScrollingListDialogButtons.BackCancel || + Buttons == ScrollingListDialogButtons.AddCancel || + Buttons == ScrollingListDialogButtons.DeleteCancel) { - if (Buttons == ScrollingListDialogButtons.BackCancel || - Buttons == ScrollingListDialogButtons.AddCancel || - Buttons == ScrollingListDialogButtons.DeleteCancel) - { - _add.DrawPosition = _button1Position; - _back.DrawPosition = _button1Position; - _delete.DrawPosition = _button1Position; - _cancel.DrawPosition = _button2Position; - } - else - { - var alternate = Buttons.HasFlag(ScrollingListDialogButtons.Alternate); - - _back.DrawPosition = _button1Position; - _cancel.DrawPosition = alternate ? _button2Position : _button1Position; - _history.DrawPosition = _button1Position; - _progress.DrawPosition = _button1Position; - - _next.DrawPosition = _button2Position; - _ok.DrawPosition = alternate ? _button1Position : _button2Position; - } + _add.DrawPosition = _button1Position; + _back.DrawPosition = _button1Position; + _delete.DrawPosition = _button1Position; + _cancel.DrawPosition = _button2Position; } else { - _add.DrawPosition = _buttonCenterPosition; - _back.DrawPosition = _buttonCenterPosition; - _next.DrawPosition = _buttonCenterPosition; - _ok.DrawPosition = _buttonCenterPosition; - _cancel.DrawPosition = _buttonCenterPosition; + var alternate = Buttons.HasFlag(ScrollingListDialogButtons.Alternate); + + _back.DrawPosition = _button1Position; + _cancel.DrawPosition = alternate ? _button2Position : _button1Position; + _history.DrawPosition = _button1Position; + _progress.DrawPosition = _button1Position; + + _next.DrawPosition = _button2Position; + _ok.DrawPosition = alternate ? _button1Position : _button2Position; } } + else + { + _add.DrawPosition = _buttonCenterPosition; + _back.DrawPosition = _buttonCenterPosition; + _next.DrawPosition = _buttonCenterPosition; + _ok.DrawPosition = _buttonCenterPosition; + _cancel.DrawPosition = _buttonCenterPosition; + } } + } - public DialogType DialogType { get; } - - public event EventHandler AddAction; - - public event EventHandler BackAction; + public DialogType DialogType { get; } - public event EventHandler NextAction; + public event EventHandler AddAction; - public event EventHandler HistoryAction; + public event EventHandler BackAction; - public event EventHandler ProgressAction; + public event EventHandler NextAction; - public ScrollingListDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - DialogType dialogType = DialogType.Shop) - : base(nativeGraphicsManager, isInGame: true) - { - DialogType = dialogType; + public event EventHandler HistoryAction; - _listItems = new List(); + public event EventHandler ProgressAction; - _titleText = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = GetTitleDrawArea(DialogType), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText, - Visible = DialogType != DialogType.Chest, - }; - _titleText.SetParentControl(this); - - _scrollBar = new ScrollBar(new Vector2(DialogType == DialogType.QuestProgressHistory ? 449 : 252, 44), new Vector2(16, GetScrollBarHeight(DialogType)), ScrollBarColors.LightOnMed, GraphicsManager) - { - Visible = DialogType != DialogType.Chest && DialogType != DialogType.BankAccountDialog && DialogType != DialogType.Jukebox, - }; - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); + public ScrollingListDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + DialogType dialogType = DialogType.Shop) + : base(nativeGraphicsManager, isInGame: true) + { + DialogType = dialogType; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, GetBackgroundTexture(DialogType)); - BackgroundTextureSource = GetBackgroundSourceRectangle(BackgroundTexture, DialogType); + _listItems = new List(); - _add = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Add), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Add)) - { - Visible = false, - UpdateOrder = 1, - }; - _add.SetParentControl(this); - _add.OnClick += (o, e) => AddAction?.Invoke(o, e); + _titleText = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = GetTitleDrawArea(DialogType), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText, + Visible = DialogType != DialogType.Chest, + }; + _titleText.SetParentControl(this); + + _scrollBar = new ScrollBar(new Vector2(DialogType == DialogType.QuestProgressHistory ? 449 : 252, 44), new Vector2(16, GetScrollBarHeight(DialogType)), ScrollBarColors.LightOnMed, GraphicsManager) + { + Visible = DialogType != DialogType.Chest && DialogType != DialogType.BankAccountDialog && DialogType != DialogType.Jukebox, + }; + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); - _back = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Back), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Back)) - { - Visible = false, - UpdateOrder = 1, - }; - _back.SetParentControl(this); - _back.OnClick += (o, e) => BackAction?.Invoke(o, e); + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, GetBackgroundTexture(DialogType)); + BackgroundTextureSource = GetBackgroundSourceRectangle(BackgroundTexture, DialogType); - _next = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Next), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Next)) - { - Visible = false, - UpdateOrder = 1, - }; - _next.SetParentControl(this); - _next.OnClick += (o, e) => NextAction?.Invoke(o, e); + _add = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Add), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Add)) + { + Visible = false, + UpdateOrder = 1, + }; + _add.SetParentControl(this); + _add.OnClick += (o, e) => AddAction?.Invoke(o, e); + + _back = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Back), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Back)) + { + Visible = false, + UpdateOrder = 1, + }; + _back.SetParentControl(this); + _back.OnClick += (o, e) => BackAction?.Invoke(o, e); + + _next = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Next), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Next)) + { + Visible = false, + UpdateOrder = 1, + }; + _next.SetParentControl(this); + _next.OnClick += (o, e) => NextAction?.Invoke(o, e); + + _history = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.History), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.History)) + { + Visible = false, + UpdateOrder = 1, + }; + _history.SetParentControl(this); + _history.OnClick += (o, e) => HistoryAction?.Invoke(o, e); + + _progress = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Progress), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Progress)) + { + Visible = false, + UpdateOrder = 1, + }; + _progress.SetParentControl(this); + _progress.OnClick += (o, e) => ProgressAction?.Invoke(o, e); + + _delete = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Delete), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Delete)) + { + Visible = false, + UpdateOrder = 1, + }; + _delete.SetParentControl(this); + _delete.OnClick += (o, e) => ProgressAction?.Invoke(o, e); + + _ok = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)) + { + Visible = false, + UpdateOrder = 2, + }; + _ok.SetParentControl(this); + _ok.OnClick += CloseButton_Click; + + _cancel = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)) + { + Visible = false, + UpdateOrder = 2, + }; + _cancel.SetParentControl(this); + _cancel.OnClick += CloseButton_Click; - _history = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.History), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.History)) - { - Visible = false, - UpdateOrder = 1, - }; - _history.SetParentControl(this); - _history.OnClick += (o, e) => HistoryAction?.Invoke(o, e); + _button1Position = GetButton1Position(DrawArea, _ok.DrawArea, DialogType); + _button2Position = GetButton2Position(DrawArea, _ok.DrawArea, DialogType); + _buttonCenterPosition = GetButtonCenterPosition(DrawArea, _ok.DrawArea, DialogType); - _progress = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Progress), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Progress)) - { - Visible = false, - UpdateOrder = 1, - }; - _progress.SetParentControl(this); - _progress.OnClick += (o, e) => ProgressAction?.Invoke(o, e); - - _delete = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Delete), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Delete)) - { - Visible = false, - UpdateOrder = 1, - }; - _delete.SetParentControl(this); - _delete.OnClick += (o, e) => ProgressAction?.Invoke(o, e); + Buttons = ScrollingListDialogButtons.AddCancel; - _ok = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)) - { - Visible = false, - UpdateOrder = 2, - }; - _ok.SetParentControl(this); - _ok.OnClick += CloseButton_Click; + CenterInGameView(); - _cancel = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)) - { - Visible = false, - UpdateOrder = 2, - }; - _cancel.SetParentControl(this); - _cancel.OnClick += CloseButton_Click; + if (!Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, 15); + } - _button1Position = GetButton1Position(DrawArea, _ok.DrawArea, DialogType); - _button2Position = GetButton2Position(DrawArea, _ok.DrawArea, DialogType); - _buttonCenterPosition = GetButtonCenterPosition(DrawArea, _ok.DrawArea, DialogType); + protected virtual void CloseButton_Click(object sender, MouseEventArgs e) + { + if (sender == _ok) + Close(XNADialogResult.OK); + else if (sender == _cancel) + Close(XNADialogResult.Cancel); + } - Buttons = ScrollingListDialogButtons.AddCancel; + public void SetItemList(List itemList) + { + if (!itemList.All(x => x.Style == ListItemType)) + throw new ArgumentException($"Expected items of type {ListItemType}", nameof(itemList)); - CenterInGameView(); + ClearItemList(); - if (!Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, 15); - } + _scrollBar.UpdateDimensions(itemList.Count); - protected virtual void CloseButton_Click(object sender, MouseEventArgs e) + for (int i = 0; i < itemList.Count; ++i) { - if (sender == _ok) - Close(XNADialogResult.OK); - else if (sender == _cancel) - Close(XNADialogResult.Cancel); + _listItems.Add(itemList[i]); + _listItems[i].Index = i; + if (i > _scrollBar.LinesToRender) + _listItems[i].Visible = false; + + _listItems[i].Initialize(); } + } - public void SetItemList(List itemList) - { - if (!itemList.All(x => x.Style == ListItemType)) - throw new ArgumentException($"Expected items of type {ListItemType}", nameof(itemList)); + public void AddItemToList(ListDialogItem item, bool sortList) + { + _listItems.Add(item); - ClearItemList(); + if (sortList) + _listItems.Sort((item1, item2) => item1.PrimaryText.CompareTo(item2.PrimaryText)); - _scrollBar.UpdateDimensions(itemList.Count); + for (int i = 0; i < _listItems.Count; ++i) + _listItems[i].Index = i; - for (int i = 0; i < itemList.Count; ++i) - { - _listItems.Add(itemList[i]); - _listItems[i].Index = i; - if (i > _scrollBar.LinesToRender) - _listItems[i].Visible = false; + item.Initialize(); - _listItems[i].Initialize(); - } - } + _scrollBar.UpdateDimensions(_listItems.Count); + } - public void AddItemToList(ListDialogItem item, bool sortList) - { - _listItems.Add(item); + public void RemoveFromList(ListDialogItem item) + { + _listItems.Remove(item); - if (sortList) - _listItems.Sort((item1, item2) => item1.PrimaryText.CompareTo(item2.PrimaryText)); + _scrollBar.UpdateDimensions(_listItems.Count); + if (_listItems.Count <= _scrollBar.LinesToRender) + _scrollBar.ScrollToTop(); - for (int i = 0; i < _listItems.Count; ++i) - _listItems[i].Index = i; + for (int i = 0; i < _listItems.Count; ++i) + _listItems[i].Index = i; - item.Initialize(); + item.Dispose(); + } - _scrollBar.UpdateDimensions(_listItems.Count); + public void HighlightTextByLabel(IReadOnlyList activeLabels) + { + var matchingListItems = _listItems.Where(x => activeLabels.Any(y => y.Equals(x.PrimaryText, StringComparison.InvariantCultureIgnoreCase))); + foreach (var item in matchingListItems) + { + item.Highlight(); } + } - public void RemoveFromList(ListDialogItem item) - { - _listItems.Remove(item); + public void ClearHighlightedText() + { + foreach (var item in _listItems) + item.ClearHighlight(); + } - _scrollBar.UpdateDimensions(_listItems.Count); - if (_listItems.Count <= _scrollBar.LinesToRender) - _scrollBar.ScrollToTop(); + public void ClearItemList() + { + foreach (var item in _listItems) + item.Dispose(); - for (int i = 0; i < _listItems.Count; ++i) - _listItems[i].Index = i; + _listItems.Clear(); + _scrollBar.UpdateDimensions(0); + _scrollBar.ScrollToTop(); + } - item.Dispose(); - } + public void AddTextAsListItems(BitmapFont font, bool insertLineBreaks, List linkClickActions, params string[] messages) + { + ListItemType = ListDialogItem.ListItemStyle.Small; - public void HighlightTextByLabel(IReadOnlyList activeLabels) + var drawStrings = new List(); + var ts = new TextSplitter(string.Empty, font) { LineLength = 200 }; + foreach (string s in messages) { - var matchingListItems = _listItems.Where(x => activeLabels.Any(y => y.Equals(x.PrimaryText, StringComparison.InvariantCultureIgnoreCase))); - foreach (var item in matchingListItems) + ts.Text = s; + drawStrings.AddRange(ts.NeedsProcessing ? ts.SplitIntoLines() : new[] { s }); + if (insertLineBreaks) { - item.Highlight(); + drawStrings.Add(" "); } } - public void ClearHighlightedText() - { - foreach (var item in _listItems) - item.ClearHighlight(); - } + int linkIndex = 0; - public void ClearItemList() + foreach (string s in drawStrings) { - foreach (var item in _listItems) - item.Dispose(); + var link = s.Length > 0 && s[0] == '*'; + var nextItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small) + { + PrimaryText = link ? s.Remove(0, 1) : s + }; - _listItems.Clear(); - _scrollBar.UpdateDimensions(0); - _scrollBar.ScrollToTop(); + if (link && linkIndex < linkClickActions.Count) + { + var linkClickAction = linkClickActions[linkIndex++]; + nextItem.SetPrimaryClickAction((_, _) => linkClickAction()); + } + + AddItemToList(nextItem, sortList: false); } - public void AddTextAsListItems(BitmapFont font, bool insertLineBreaks, List linkClickActions, params string[] messages) - { - ListItemType = ListDialogItem.ListItemStyle.Small; + } + + public override void Initialize() + { + _add.Initialize(); + _back.Initialize(); + _next.Initialize(); + _ok.Initialize(); + _cancel.Initialize(); + _scrollBar.Initialize(); + _titleText.Initialize(); + + base.Initialize(); + } - var drawStrings = new List(); - var ts = new TextSplitter(string.Empty, font) { LineLength = 200 }; - foreach (string s in messages) + protected override void OnUpdateControl(GameTime gameTime) + { + if (_listItems.Count > _scrollBar.LinesToRender) + { + for (int i = 0; i < _listItems.Count; ++i) { - ts.Text = s; - drawStrings.AddRange(ts.NeedsProcessing ? ts.SplitIntoLines() : new[] { s }); - if (insertLineBreaks) + var curr = _listItems[i]; + if (i < _scrollBar.ScrollOffset) { - drawStrings.Add(" "); + curr.Visible = false; + continue; } - } - - int linkIndex = 0; - foreach (string s in drawStrings) - { - var link = s.Length > 0 && s[0] == '*'; - var nextItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small) + if (i < _scrollBar.LinesToRender + _scrollBar.ScrollOffset) { - PrimaryText = link ? s.Remove(0, 1) : s - }; - - if (link && linkIndex < linkClickActions.Count) + curr.Visible = true; + curr.Index = i - _scrollBar.ScrollOffset; + } + else { - var linkClickAction = linkClickActions[linkIndex++]; - nextItem.SetPrimaryClickAction((_, _) => linkClickAction()); + curr.Visible = false; } - - AddItemToList(nextItem, sortList: false); } - } - - public override void Initialize() + else if (_listItems.Any(_item => !_item.Visible)) { - _add.Initialize(); - _back.Initialize(); - _next.Initialize(); - _ok.Initialize(); - _cancel.Initialize(); - _scrollBar.Initialize(); - _titleText.Initialize(); - - base.Initialize(); + _listItems.ForEach(_item => _item.Visible = true); } - protected override void OnUpdateControl(GameTime gameTime) - { - if (_listItems.Count > _scrollBar.LinesToRender) - { - for (int i = 0; i < _listItems.Count; ++i) - { - var curr = _listItems[i]; - if (i < _scrollBar.ScrollOffset) - { - curr.Visible = false; - continue; - } - - if (i < _scrollBar.LinesToRender + _scrollBar.ScrollOffset) - { - curr.Visible = true; - curr.Index = i - _scrollBar.ScrollOffset; - } - else - { - curr.Visible = false; - } - } - } - else if (_listItems.Any(_item => !_item.Visible)) - { - _listItems.ForEach(_item => _item.Visible = true); - } - - base.OnUpdateControl(gameTime); - } + base.OnUpdateControl(gameTime); + } - protected static Rectangle GetTitleDrawArea(DialogType size) + protected static Rectangle GetTitleDrawArea(DialogType size) + { + switch (size) { - switch (size) - { - case DialogType.Shop: - case DialogType.Help: - case DialogType.Chest: return new Rectangle(16, 13, 253, 19); - case DialogType.QuestProgressHistory: - return new Rectangle(18, 14, 452, 19); - case DialogType.Jukebox: return new Rectangle(24, 20, 263, 19); - case DialogType.NpcQuestDialog: return new Rectangle(16, 16, 255, 18); - case DialogType.BankAccountDialog: return new Rectangle(129, 20, 121, 16); - default: throw new NotImplementedException(); - } + case DialogType.Shop: + case DialogType.Help: + case DialogType.Chest: return new Rectangle(16, 13, 253, 19); + case DialogType.QuestProgressHistory: + return new Rectangle(18, 14, 452, 19); + case DialogType.Jukebox: return new Rectangle(24, 20, 263, 19); + case DialogType.NpcQuestDialog: return new Rectangle(16, 16, 255, 18); + case DialogType.BankAccountDialog: return new Rectangle(129, 20, 121, 16); + default: throw new NotImplementedException(); } + } - protected static int GetScrollBarHeight(DialogType size) + protected static int GetScrollBarHeight(DialogType size) + { + switch (size) { - switch (size) - { - case DialogType.Shop: - case DialogType.Help: - case DialogType.Chest: - case DialogType.QuestProgressHistory: - return 199; - case DialogType.Jukebox: - case DialogType.NpcQuestDialog: - case DialogType.BankAccountDialog: return 99; - default: throw new NotImplementedException(); - } + case DialogType.Shop: + case DialogType.Help: + case DialogType.Chest: + case DialogType.QuestProgressHistory: + return 199; + case DialogType.Jukebox: + case DialogType.NpcQuestDialog: + case DialogType.BankAccountDialog: return 99; + default: throw new NotImplementedException(); } + } - private static int GetBackgroundTexture(DialogType size) + private static int GetBackgroundTexture(DialogType size) + { + switch (size) { - switch (size) - { - case DialogType.Shop: return 52; - case DialogType.Help: return 64; - case DialogType.Chest: return 51; - case DialogType.QuestProgressHistory: return 59; - case DialogType.Jukebox: return 60; - case DialogType.NpcQuestDialog: return 67; - case DialogType.BankAccountDialog: return 53; - default: throw new NotImplementedException(); - } + case DialogType.Shop: return 52; + case DialogType.Help: return 64; + case DialogType.Chest: return 51; + case DialogType.QuestProgressHistory: return 59; + case DialogType.Jukebox: return 60; + case DialogType.NpcQuestDialog: return 67; + case DialogType.BankAccountDialog: return 53; + default: throw new NotImplementedException(); } + } - protected static Rectangle? GetBackgroundSourceRectangle(Texture2D backgroundTexture, DialogType size) + protected static Rectangle? GetBackgroundSourceRectangle(Texture2D backgroundTexture, DialogType size) + { + switch (size) { - switch (size) - { - case DialogType.Shop: - case DialogType.Help: - case DialogType.Chest: return null; - case DialogType.QuestProgressHistory: - return new Rectangle(0, 0, backgroundTexture.Width, backgroundTexture.Height / 2); - case DialogType.Jukebox: - case DialogType.NpcQuestDialog: - case DialogType.BankAccountDialog: return null; - default: throw new NotImplementedException(); - } + case DialogType.Shop: + case DialogType.Help: + case DialogType.Chest: return null; + case DialogType.QuestProgressHistory: + return new Rectangle(0, 0, backgroundTexture.Width, backgroundTexture.Height / 2); + case DialogType.Jukebox: + case DialogType.NpcQuestDialog: + case DialogType.BankAccountDialog: return null; + default: throw new NotImplementedException(); } + } - private static Vector2 GetButton1Position(Rectangle dialogArea, Rectangle buttonArea, DialogType size) + private static Vector2 GetButton1Position(Rectangle dialogArea, Rectangle buttonArea, DialogType size) + { + var yCoord = GetButtonYCoordinate(dialogArea); + switch (size) { - var yCoord = GetButtonYCoordinate(dialogArea); - switch (size) - { - // buttons are centered on these dialogs - case DialogType.Shop: - case DialogType.Help: - case DialogType.Chest: - case DialogType.BankAccountDialog: - case DialogType.Jukebox: return new Vector2((int)Math.Floor((dialogArea.Width - buttonArea.Width) / 2.0) - 48, yCoord); - // buttons are offset from center on these dialogs - case DialogType.QuestProgressHistory: - return new Vector2(288, yCoord); - case DialogType.NpcQuestDialog: return new Vector2(89, yCoord); - default: throw new NotImplementedException(); - } + // buttons are centered on these dialogs + case DialogType.Shop: + case DialogType.Help: + case DialogType.Chest: + case DialogType.BankAccountDialog: + case DialogType.Jukebox: return new Vector2((int)Math.Floor((dialogArea.Width - buttonArea.Width) / 2.0) - 48, yCoord); + // buttons are offset from center on these dialogs + case DialogType.QuestProgressHistory: + return new Vector2(288, yCoord); + case DialogType.NpcQuestDialog: return new Vector2(89, yCoord); + default: throw new NotImplementedException(); } + } - private static Vector2 GetButton2Position(Rectangle dialogArea, Rectangle buttonArea, DialogType size) + private static Vector2 GetButton2Position(Rectangle dialogArea, Rectangle buttonArea, DialogType size) + { + var yCoord = GetButtonYCoordinate(dialogArea); + switch (size) { - var yCoord = GetButtonYCoordinate(dialogArea); - switch (size) - { - // buttons are centered on these dialogs - case DialogType.Shop: - case DialogType.Help: - case DialogType.Chest: - case DialogType.BankAccountDialog: - case DialogType.Jukebox: return new Vector2((int)Math.Floor((dialogArea.Width - buttonArea.Width) / 2.0) + 48, yCoord); - // buttons are offset from center on these dialogs - case DialogType.QuestProgressHistory: - return new Vector2(380, yCoord); - case DialogType.NpcQuestDialog: return new Vector2(183, yCoord); - default: throw new NotImplementedException(); - } + // buttons are centered on these dialogs + case DialogType.Shop: + case DialogType.Help: + case DialogType.Chest: + case DialogType.BankAccountDialog: + case DialogType.Jukebox: return new Vector2((int)Math.Floor((dialogArea.Width - buttonArea.Width) / 2.0) + 48, yCoord); + // buttons are offset from center on these dialogs + case DialogType.QuestProgressHistory: + return new Vector2(380, yCoord); + case DialogType.NpcQuestDialog: return new Vector2(183, yCoord); + default: throw new NotImplementedException(); } + } - private static Vector2 GetButtonCenterPosition(Rectangle dialogArea, Rectangle buttonArea, DialogType dialogSize) - { - // chest dialog has a button built in to the graphic that needs to be covered up... - if (dialogSize == DialogType.Chest) - return new Vector2(92, 227); + private static Vector2 GetButtonCenterPosition(Rectangle dialogArea, Rectangle buttonArea, DialogType dialogSize) + { + // chest dialog has a button built in to the graphic that needs to be covered up... + if (dialogSize == DialogType.Chest) + return new Vector2(92, 227); - // bank dialog has a button built in to the graphic that needs to be covered up... - if (dialogSize == DialogType.BankAccountDialog) - return new Vector2(92, 191); + // bank dialog has a button built in to the graphic that needs to be covered up... + if (dialogSize == DialogType.BankAccountDialog) + return new Vector2(92, 191); - // jukebox dialog has a button built in to the graphic that needs to be covered up... - if (dialogSize == DialogType.Jukebox) - return new Vector2(92, 158); + // jukebox dialog has a button built in to the graphic that needs to be covered up... + if (dialogSize == DialogType.Jukebox) + return new Vector2(92, 158); - var yCoord = GetButtonYCoordinate(dialogArea); - return new Vector2((dialogArea.Width - buttonArea.Width) / 2, yCoord); - } + var yCoord = GetButtonYCoordinate(dialogArea); + return new Vector2((dialogArea.Width - buttonArea.Width) / 2, yCoord); + } - private static int GetButtonYCoordinate(Rectangle dialogArea) - { - // this should always be 38 from the bottom - return dialogArea.Height - 38; - } + private static int GetButtonYCoordinate(Rectangle dialogArea) + { + // this should always be 38 from the bottom + return dialogArea.Height - 38; } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ScrollingMessageDialog.cs b/EndlessClient/Dialogs/ScrollingMessageDialog.cs index 26d4762e5..619831db4 100644 --- a/EndlessClient/Dialogs/ScrollingMessageDialog.cs +++ b/EndlessClient/Dialogs/ScrollingMessageDialog.cs @@ -10,108 +10,107 @@ using System.Collections.Generic; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class ScrollingMessageDialog : BaseEODialog { - public class ScrollingMessageDialog : BaseEODialog - { - const int TEXT_LINE_HEIGHT = 16; + const int TEXT_LINE_HEIGHT = 16; - private readonly XNAButton _ok; - private readonly ScrollBar _scrollBar; - private readonly List _chatStrings = new List(); - private readonly TextSplitter _textSplitter; - private readonly BitmapFont _font; + private readonly XNAButton _ok; + private readonly ScrollBar _scrollBar; + private readonly List _chatStrings = new List(); + private readonly TextSplitter _textSplitter; + private readonly BitmapFont _font; - private static readonly Rectangle TextArea = new Rectangle(27, 69, 300, 110); + private static readonly Rectangle TextArea = new Rectangle(27, 69, 300, 110); - public string MessageText + public string MessageText + { + set { - set + _chatStrings.Clear(); + _textSplitter.Text = value; + + //special case: blank line, like in the news panel between news items + if (string.IsNullOrWhiteSpace(value)) { - _chatStrings.Clear(); - _textSplitter.Text = value; - - //special case: blank line, like in the news panel between news items - if (string.IsNullOrWhiteSpace(value)) - { - _chatStrings.Add(" "); - _scrollBar.UpdateDimensions(_chatStrings.Count); - return; - } - - //don't do multi-line processing if we don't need to - if (!_textSplitter.NeedsProcessing) - { - _chatStrings.Add(value); - _scrollBar.UpdateDimensions(_chatStrings.Count); - return; - } - - _chatStrings.AddRange(_textSplitter.SplitIntoLines()); + _chatStrings.Add(" "); + _scrollBar.UpdateDimensions(_chatStrings.Count); + return; + } + //don't do multi-line processing if we don't need to + if (!_textSplitter.NeedsProcessing) + { + _chatStrings.Add(value); _scrollBar.UpdateDimensions(_chatStrings.Count); - _scrollBar.LinesToRender = (int)Math.Round(110.0f / TEXT_LINE_HEIGHT); - if (_scrollBar.LinesToRender < _chatStrings.Count) - _scrollBar.SetDownArrowFlashSpeed(500); + return; } - } - public ScrollingMessageDialog(INativeGraphicsManager nativeGraphicsManager, - IContentProvider contentProvider, - IGameStateProvider gameStateProvider, - IEODialogButtonService eoDialogButtonService) - : base(nativeGraphicsManager, gameStateProvider) - { - _font = contentProvider.Fonts[Constants.FontSize08]; - _textSplitter = new TextSplitter("", _font) { LineLength = 280 }; + _chatStrings.AddRange(_textSplitter.SplitIntoLines()); - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 40); + _scrollBar.UpdateDimensions(_chatStrings.Count); + _scrollBar.LinesToRender = (int)Math.Round(110.0f / TEXT_LINE_HEIGHT); + if (_scrollBar.LinesToRender < _chatStrings.Count) + _scrollBar.SetDownArrowFlashSpeed(500); + } + } - var smallButtonSheet = eoDialogButtonService.SmallButtonSheet; + public ScrollingMessageDialog(INativeGraphicsManager nativeGraphicsManager, + IContentProvider contentProvider, + IGameStateProvider gameStateProvider, + IEODialogButtonService eoDialogButtonService) + : base(nativeGraphicsManager, gameStateProvider) + { + _font = contentProvider.Fonts[Constants.FontSize08]; + _textSplitter = new TextSplitter("", _font) { LineLength = 280 }; - _ok = new XNAButton(smallButtonSheet, - new Vector2(138, 197), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); - _ok.SetParentControl(this); + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 40); - _scrollBar = new ScrollBar(new Vector2(320, 66), new Vector2(16, 119), - ScrollBarColors.LightOnMed, GraphicsManager); - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); + var smallButtonSheet = eoDialogButtonService.SmallButtonSheet; - MessageText = ""; + _ok = new XNAButton(smallButtonSheet, + new Vector2(138, 197), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); + _ok.SetParentControl(this); - CenterInGameView(); - } + _scrollBar = new ScrollBar(new Vector2(320, 66), new Vector2(16, 119), + ScrollBarColors.LightOnMed, GraphicsManager); + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); - public override void Initialize() - { - _ok.Initialize(); - _scrollBar.Initialize(); + MessageText = ""; - base.Initialize(); - } + CenterInGameView(); + } - protected override void OnDrawControl(GameTime gt) - { - base.OnDrawControl(gt); + public override void Initialize() + { + _ok.Initialize(); + _scrollBar.Initialize(); + + base.Initialize(); + } - _spriteBatch.Begin(); - var pos = new Vector2(27 + (int)DrawPosition.X, 69 + (int)DrawPosition.Y); + protected override void OnDrawControl(GameTime gt) + { + base.OnDrawControl(gt); - for (int i = _scrollBar.ScrollOffset; i < _scrollBar.ScrollOffset + _scrollBar.LinesToRender; ++i) - { - if (i >= _chatStrings.Count) - break; + _spriteBatch.Begin(); + var pos = new Vector2(27 + (int)DrawPosition.X, 69 + (int)DrawPosition.Y); - var strToDraw = _chatStrings[i]; + for (int i = _scrollBar.ScrollOffset; i < _scrollBar.ScrollOffset + _scrollBar.LinesToRender; ++i) + { + if (i >= _chatStrings.Count) + break; - _spriteBatch.DrawString(_font, strToDraw, new Vector2(pos.X, pos.Y + (i - _scrollBar.ScrollOffset) * TEXT_LINE_HEIGHT), ColorConstants.LightGrayText); - } + var strToDraw = _chatStrings[i]; - _spriteBatch.End(); + _spriteBatch.DrawString(_font, strToDraw, new Vector2(pos.X, pos.Y + (i - _scrollBar.ScrollOffset) * TEXT_LINE_HEIGHT), ColorConstants.LightGrayText); } + + _spriteBatch.End(); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Services/EODialogButtonService.cs b/EndlessClient/Dialogs/Services/EODialogButtonService.cs index 84ee583cc..e417c80ae 100644 --- a/EndlessClient/Dialogs/Services/EODialogButtonService.cs +++ b/EndlessClient/Dialogs/Services/EODialogButtonService.cs @@ -3,55 +3,54 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Dialogs.Services +namespace EndlessClient.Dialogs.Services; + +public enum SmallButton +{ + Connect = 0, + Cancel, + Login, + Delete, + Ok, + Back, + Add, + Next, + History, + Progress, + NUM_BUTTONS +} + +[AutoMappedType] +public class EODialogButtonService : IEODialogButtonService { - public enum SmallButton + private readonly INativeGraphicsManager _nativeGraphicsManager; + + public Texture2D SmallButtonSheet => _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 15, true); + + public EODialogButtonService(INativeGraphicsManager nativeGraphicsManager) { - Connect = 0, - Cancel, - Login, - Delete, - Ok, - Back, - Add, - Next, - History, - Progress, - NUM_BUTTONS + _nativeGraphicsManager = nativeGraphicsManager; } - [AutoMappedType] - public class EODialogButtonService : IEODialogButtonService + public Rectangle GetSmallDialogButtonOutSource(SmallButton whichButton) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - - public Texture2D SmallButtonSheet => _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 15, true); - - public EODialogButtonService(INativeGraphicsManager nativeGraphicsManager) - { - _nativeGraphicsManager = nativeGraphicsManager; - } - - public Rectangle GetSmallDialogButtonOutSource(SmallButton whichButton) - { - var widthDelta = SmallButtonSheet.Width / 2; - var heightDelta = SmallButtonSheet.Height / (int)SmallButton.NUM_BUTTONS; - return new Rectangle(0, heightDelta * (int)whichButton, widthDelta, heightDelta); - } - - public Rectangle GetSmallDialogButtonOverSource(SmallButton whichButton) - { - var widthDelta = SmallButtonSheet.Width / 2; - var heightDelta = SmallButtonSheet.Height / (int)SmallButton.NUM_BUTTONS; - return new Rectangle(widthDelta, heightDelta * (int)whichButton, widthDelta, heightDelta); - } + var widthDelta = SmallButtonSheet.Width / 2; + var heightDelta = SmallButtonSheet.Height / (int)SmallButton.NUM_BUTTONS; + return new Rectangle(0, heightDelta * (int)whichButton, widthDelta, heightDelta); } - public interface IEODialogButtonService + public Rectangle GetSmallDialogButtonOverSource(SmallButton whichButton) { - Texture2D SmallButtonSheet { get; } - - Rectangle GetSmallDialogButtonOutSource(SmallButton whichButton); - Rectangle GetSmallDialogButtonOverSource(SmallButton whichButton); + var widthDelta = SmallButtonSheet.Width / 2; + var heightDelta = SmallButtonSheet.Height / (int)SmallButton.NUM_BUTTONS; + return new Rectangle(widthDelta, heightDelta * (int)whichButton, widthDelta, heightDelta); } +} + +public interface IEODialogButtonService +{ + Texture2D SmallButtonSheet { get; } + + Rectangle GetSmallDialogButtonOutSource(SmallButton whichButton); + Rectangle GetSmallDialogButtonOverSource(SmallButton whichButton); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Services/EODialogIconService.cs b/EndlessClient/Dialogs/Services/EODialogIconService.cs index 09f0d4dea..d746b3a2d 100644 --- a/EndlessClient/Dialogs/Services/EODialogIconService.cs +++ b/EndlessClient/Dialogs/Services/EODialogIconService.cs @@ -3,57 +3,56 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Dialogs.Services +namespace EndlessClient.Dialogs.Services; + +public enum DialogIcon +{ + Buy = 0, + Sell, + JukeboxBrowse = Sell, + BankDeposit, + BankWithdraw, + Craft, + BankLockerUpgrade, + + BarberHairModel = 6, + BarberChangeHairColor = 7, + BarberOk = 8, + + JukeboxPlay = 8, + Registration = 9, + + Learn = 20, + Forget = 21, + InnSleep = 22, + SignUp = 23, + Unsubscribe = 24 +} + +[AutoMappedType] +public class EODialogIconService : IEODialogIconService { - public enum DialogIcon + private readonly INativeGraphicsManager _nativeGraphicsManager; + + public Texture2D IconSheet => _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); + + public EODialogIconService(INativeGraphicsManager nativeGraphicsManager) { - Buy = 0, - Sell, - JukeboxBrowse = Sell, - BankDeposit, - BankWithdraw, - Craft, - BankLockerUpgrade, - - BarberHairModel = 6, - BarberChangeHairColor = 7, - BarberOk = 8, - - JukeboxPlay = 8, - Registration = 9, - - Learn = 20, - Forget = 21, - InnSleep = 22, - SignUp = 23, - Unsubscribe = 24 + _nativeGraphicsManager = nativeGraphicsManager; } - [AutoMappedType] - public class EODialogIconService : IEODialogIconService + public Rectangle GetDialogIconSource(DialogIcon whichIcon) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - - public Texture2D IconSheet => _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); + const int NUM_PER_ROW = 9; + const int ICON_SIZE = 31; - public EODialogIconService(INativeGraphicsManager nativeGraphicsManager) - { - _nativeGraphicsManager = nativeGraphicsManager; - } - - public Rectangle GetDialogIconSource(DialogIcon whichIcon) - { - const int NUM_PER_ROW = 9; - const int ICON_SIZE = 31; - - return new Rectangle(((int)whichIcon % NUM_PER_ROW) * ICON_SIZE, 291 + ((int)whichIcon / NUM_PER_ROW) * ICON_SIZE, ICON_SIZE, ICON_SIZE); - } + return new Rectangle(((int)whichIcon % NUM_PER_ROW) * ICON_SIZE, 291 + ((int)whichIcon / NUM_PER_ROW) * ICON_SIZE, ICON_SIZE, ICON_SIZE); } +} - public interface IEODialogIconService - { - Texture2D IconSheet { get; } +public interface IEODialogIconService +{ + Texture2D IconSheet { get; } - Rectangle GetDialogIconSource(DialogIcon whichIcon); - } + Rectangle GetDialogIconSource(DialogIcon whichIcon); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/SessionExpDialog.cs b/EndlessClient/Dialogs/SessionExpDialog.cs index f24dfda7b..c2bd5f5b1 100644 --- a/EndlessClient/Dialogs/SessionExpDialog.cs +++ b/EndlessClient/Dialogs/SessionExpDialog.cs @@ -8,119 +8,118 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class SessionExpDialog : BaseEODialog { - public class SessionExpDialog : BaseEODialog - { - private static readonly Rectangle _signalSource; - private static readonly Rectangle _iconSource; + private static readonly Rectangle _signalSource; + private static readonly Rectangle _iconSource; - private readonly Texture2D _icons; + private readonly Texture2D _icons; - static SessionExpDialog() - { - _signalSource = new Rectangle(0, 15, 15, 15); - _iconSource = new Rectangle(0, 0, 15, 15); - } + static SessionExpDialog() + { + _signalSource = new Rectangle(0, 15, 15, 15); + _iconSource = new Rectangle(0, 0, 15, 15); + } - public SessionExpDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - ICharacterProvider characterProvider, - IExperienceTableProvider expTableProvider, - ICharacterSessionProvider characterSessionProvider) - : base(nativeGraphicsManager, isInGame: true) - { - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 61); + public SessionExpDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + ICharacterProvider characterProvider, + IExperienceTableProvider expTableProvider, + ICharacterSessionProvider characterSessionProvider) + : base(nativeGraphicsManager, isInGame: true) + { + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 61); - _icons = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); + _icons = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); - var okButton = new XNAButton(dialogButtonService.SmallButtonSheet, - new Vector2(98, 214), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - okButton.OnClick += (_, _) => Close(XNADialogResult.OK); - okButton.SetParentControl(this); - okButton.Initialize(); + var okButton = new XNAButton(dialogButtonService.SmallButtonSheet, + new Vector2(98, 214), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + okButton.OnClick += (_, _) => Close(XNADialogResult.OK); + okButton.SetParentControl(this); + okButton.Initialize(); - var title = new XNALabel(Constants.FontSize08pt5) + var title = new XNALabel(Constants.FontSize08pt5) + { + DrawPosition = new Vector2(20, 16), + AutoSize = false, + Text = localizedStringFinder.GetString(EOResourceID.DIALOG_TITLE_PERFORMANCE), + ForeColor = ColorConstants.LightGrayText + }; + title.SetParentControl(this); + title.Initialize(); + + XNALabel[] leftSide = new XNALabel[8], rightSide = new XNALabel[8]; + for (int i = 0; i < leftSide.Length; i++) + { + leftSide[i] = new XNALabel(Constants.FontSize08pt5) { - DrawPosition = new Vector2(20, 16), + DrawPosition = new Vector2(38, 48 + 16 * i), AutoSize = false, - Text = localizedStringFinder.GetString(EOResourceID.DIALOG_TITLE_PERFORMANCE), ForeColor = ColorConstants.LightGrayText }; - title.SetParentControl(this); - title.Initialize(); + leftSide[i].SetParentControl(this); + leftSide[i].Initialize(); - XNALabel[] leftSide = new XNALabel[8], rightSide = new XNALabel[8]; - for (int i = 0; i < leftSide.Length; i++) + rightSide[i] = new XNALabel(Constants.FontSize08pt5) { - leftSide[i] = new XNALabel(Constants.FontSize08pt5) - { - DrawPosition = new Vector2(38, 48 + 16 * i), - AutoSize = false, - ForeColor = ColorConstants.LightGrayText - }; - leftSide[i].SetParentControl(this); - leftSide[i].Initialize(); - - rightSide[i] = new XNALabel(Constants.FontSize08pt5) - { - DrawPosition = new Vector2(158, 48 + 16 * i), - AutoSize = false, - ForeColor = ColorConstants.LightGrayText - }; - rightSide[i].SetParentControl(this); - rightSide[i].Initialize(); - } - - leftSide[0].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TOTALEXP); - leftSide[1].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_NEXT_LEVEL); - leftSide[2].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_EXP_NEEDED); - leftSide[3].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TODAY_EXP); - leftSide[4].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TOTAL_AVG); - leftSide[5].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TODAY_AVG); - leftSide[6].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_BEST_KILL); - leftSide[7].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_LAST_KILL); - - var c = characterProvider.MainCharacter; - var level = c.Stats[CharacterStat.Level]; - var exp = c.Stats[CharacterStat.Experience]; - var usage = c.Stats[CharacterStat.Usage]; - - rightSide[0].Text = $"{exp}"; - rightSide[1].Text = $"{expTableProvider.ExperienceByLevel[level + 1]}"; - rightSide[2].Text = $"{expTableProvider.ExperienceByLevel[level + 1] - exp}"; - rightSide[3].Text = $"{characterSessionProvider.TodayTotalExp}"; - rightSide[4].Text = $"{(int)(exp / (usage / 60.0))}"; - int sessionTimeMinutes = (int)(DateTime.Now - characterSessionProvider.SessionStartTime).TotalMinutes; - rightSide[5].Text = $"{(sessionTimeMinutes > 0 ? (int)(characterSessionProvider.TodayTotalExp / (sessionTimeMinutes / 60.0)) : 0)}"; - rightSide[6].Text = $"{characterSessionProvider.BestKillExp}"; - rightSide[7].Text = $"{characterSessionProvider.LastKillExp}"; - - Array.ForEach(leftSide, lbl => lbl.ResizeBasedOnText()); - Array.ForEach(rightSide, lbl => lbl.ResizeBasedOnText()); - - CenterInGameView(); - - if (!Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, 15); + DrawPosition = new Vector2(158, 48 + 16 * i), + AutoSize = false, + ForeColor = ColorConstants.LightGrayText + }; + rightSide[i].SetParentControl(this); + rightSide[i].Initialize(); } - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + leftSide[0].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TOTALEXP); + leftSide[1].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_NEXT_LEVEL); + leftSide[2].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_EXP_NEEDED); + leftSide[3].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TODAY_EXP); + leftSide[4].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TOTAL_AVG); + leftSide[5].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TODAY_AVG); + leftSide[6].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_BEST_KILL); + leftSide[7].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_LAST_KILL); + + var c = characterProvider.MainCharacter; + var level = c.Stats[CharacterStat.Level]; + var exp = c.Stats[CharacterStat.Experience]; + var usage = c.Stats[CharacterStat.Usage]; + + rightSide[0].Text = $"{exp}"; + rightSide[1].Text = $"{expTableProvider.ExperienceByLevel[level + 1]}"; + rightSide[2].Text = $"{expTableProvider.ExperienceByLevel[level + 1] - exp}"; + rightSide[3].Text = $"{characterSessionProvider.TodayTotalExp}"; + rightSide[4].Text = $"{(int)(exp / (usage / 60.0))}"; + int sessionTimeMinutes = (int)(DateTime.Now - characterSessionProvider.SessionStartTime).TotalMinutes; + rightSide[5].Text = $"{(sessionTimeMinutes > 0 ? (int)(characterSessionProvider.TodayTotalExp / (sessionTimeMinutes / 60.0)) : 0)}"; + rightSide[6].Text = $"{characterSessionProvider.BestKillExp}"; + rightSide[7].Text = $"{characterSessionProvider.LastKillExp}"; + + Array.ForEach(leftSide, lbl => lbl.ResizeBasedOnText()); + Array.ForEach(rightSide, lbl => lbl.ResizeBasedOnText()); + + CenterInGameView(); + + if (!Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, 15); + } + + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - _spriteBatch.Begin(); + _spriteBatch.Begin(); - for (int i = 0; i < 8; i++) - _spriteBatch.Draw(_icons, new Vector2(DrawPositionWithParentOffset.X + 18, DrawPositionWithParentOffset.Y + 47 + 16 * i), _iconSource, Color.White); + for (int i = 0; i < 8; i++) + _spriteBatch.Draw(_icons, new Vector2(DrawPositionWithParentOffset.X + 18, DrawPositionWithParentOffset.Y + 47 + 16 * i), _iconSource, Color.White); - for (int i = 0; i < 3; i++) - _spriteBatch.Draw(_icons, new Vector2(DrawPositionWithParentOffset.X + 142, DrawPositionWithParentOffset.Y + 48 + 16 * i), _signalSource, Color.White); + for (int i = 0; i < 3; i++) + _spriteBatch.Draw(_icons, new Vector2(DrawPositionWithParentOffset.X + 142, DrawPositionWithParentOffset.Y + 48 + 16 * i), _signalSource, Color.White); - _spriteBatch.End(); - } + _spriteBatch.End(); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ShopDialog.cs b/EndlessClient/Dialogs/ShopDialog.cs index 29e5c7efc..a11634219 100644 --- a/EndlessClient/Dialogs/ShopDialog.cs +++ b/EndlessClient/Dialogs/ShopDialog.cs @@ -14,401 +14,400 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class ShopDialog : ScrollingListDialog { - public class ShopDialog : ScrollingListDialog + private enum ShopState { - private enum ShopState - { - None, - Initial, - Buying, - Selling, - Crafting - } - - private readonly IShopActions _shopActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IItemTransferDialogFactory _itemTransferDialogFactory; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IShopDataProvider _shopDataProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private IReadOnlyList _buyItems, _sellItems; - private IReadOnlyList _craftItems; - - private ShopState _state; - - private Option _cachedShopId; - private HashSet _cachedInventory; - private ulong _tick; - - public ShopDialog(INativeGraphicsManager nativeGraphicsManager, - IShopActions shopActions, - IEOMessageBoxFactory messageBoxFactory, - IItemTransferDialogFactory itemTransferDialogFactory, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IShopDataProvider shopDataProvider, - ICharacterInventoryProvider characterInventoryProvider, - IEIFFileProvider eifFileProvider, - ICharacterProvider characterProvider, - IInventorySpaceValidator inventorySpaceValidator) - : base(nativeGraphicsManager, dialogButtonService) - { - _shopActions = shopActions; - _messageBoxFactory = messageBoxFactory; - _itemTransferDialogFactory = itemTransferDialogFactory; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _shopDataProvider = shopDataProvider; - _characterInventoryProvider = characterInventoryProvider; - _eifFileProvider = eifFileProvider; - _characterProvider = characterProvider; - _inventorySpaceValidator = inventorySpaceValidator; - - Buttons = ScrollingListDialogButtons.Cancel; - ListItemType = ListDialogItem.ListItemStyle.Large; - - BackAction += (_, _) => SetState(ShopState.Initial); + None, + Initial, + Buying, + Selling, + Crafting + } - _cachedInventory = new HashSet(_characterInventoryProvider.ItemInventory); - } + private readonly IShopActions _shopActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IItemTransferDialogFactory _itemTransferDialogFactory; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IShopDataProvider _shopDataProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private IReadOnlyList _buyItems, _sellItems; + private IReadOnlyList _craftItems; + + private ShopState _state; + + private Option _cachedShopId; + private HashSet _cachedInventory; + private ulong _tick; + + public ShopDialog(INativeGraphicsManager nativeGraphicsManager, + IShopActions shopActions, + IEOMessageBoxFactory messageBoxFactory, + IItemTransferDialogFactory itemTransferDialogFactory, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IShopDataProvider shopDataProvider, + ICharacterInventoryProvider characterInventoryProvider, + IEIFFileProvider eifFileProvider, + ICharacterProvider characterProvider, + IInventorySpaceValidator inventorySpaceValidator) + : base(nativeGraphicsManager, dialogButtonService) + { + _shopActions = shopActions; + _messageBoxFactory = messageBoxFactory; + _itemTransferDialogFactory = itemTransferDialogFactory; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _shopDataProvider = shopDataProvider; + _characterInventoryProvider = characterInventoryProvider; + _eifFileProvider = eifFileProvider; + _characterProvider = characterProvider; + _inventorySpaceValidator = inventorySpaceValidator; + + Buttons = ScrollingListDialogButtons.Cancel; + ListItemType = ListDialogItem.ListItemStyle.Large; + + BackAction += (_, _) => SetState(ShopState.Initial); + + _cachedInventory = new HashSet(_characterInventoryProvider.ItemInventory); + } - protected override void OnUpdateControl(GameTime gameTime) + protected override void OnUpdateControl(GameTime gameTime) + { + _cachedShopId.MatchNone(() => { - _cachedShopId.MatchNone(() => - { - _shopDataProvider.SessionID.SomeWhen(x => x > 0) - .MatchSome(x => - { - _cachedShopId = Option.Some(_shopDataProvider.SessionID); - - Title = _shopDataProvider.ShopName; + _shopDataProvider.SessionID.SomeWhen(x => x > 0) + .MatchSome(x => + { + _cachedShopId = Option.Some(_shopDataProvider.SessionID); - _buyItems = _shopDataProvider.TradeItems.Where(x => x.Buy > 0).ToList(); - _sellItems = _shopDataProvider.TradeItems.Where(x => x.Sell > 0 && _characterInventoryProvider.ItemInventory.Any(inv => inv.ItemID == x.ID && inv.Amount > 0)).ToList(); - _craftItems = _shopDataProvider.CraftItems; + Title = _shopDataProvider.ShopName; - SetState(ShopState.Initial); - }); - }); + _buyItems = _shopDataProvider.TradeItems.Where(x => x.Buy > 0).ToList(); + _sellItems = _shopDataProvider.TradeItems.Where(x => x.Sell > 0 && _characterInventoryProvider.ItemInventory.Any(inv => inv.ItemID == x.ID && inv.Amount > 0)).ToList(); + _craftItems = _shopDataProvider.CraftItems; - if (++_tick % 8 == 0 && !_cachedInventory.SetEquals(_characterInventoryProvider.ItemInventory)) - { - _sellItems = _shopDataProvider.TradeItems.Where(x => x.Sell > 0 && _characterInventoryProvider.ItemInventory.Any(inv => inv.ItemID == x.ID && inv.Amount > 0)).ToList(); - _cachedInventory = new HashSet(_characterInventoryProvider.ItemInventory); + SetState(ShopState.Initial); + }); + }); - if (_state == ShopState.Selling) - SetState(ShopState.Selling); - } + if (++_tick % 8 == 0 && !_cachedInventory.SetEquals(_characterInventoryProvider.ItemInventory)) + { + _sellItems = _shopDataProvider.TradeItems.Where(x => x.Sell > 0 && _characterInventoryProvider.ItemInventory.Any(inv => inv.ItemID == x.ID && inv.Amount > 0)).ToList(); + _cachedInventory = new HashSet(_characterInventoryProvider.ItemInventory); - base.OnUpdateControl(gameTime); + if (_state == ShopState.Selling) + SetState(ShopState.Selling); } - private void SetState(ShopState state) - { - if (state == ShopState.None) - return; + base.OnUpdateControl(gameTime); + } - if (state == ShopState.Buying && _buyItems.Count == 0) - { - var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOTHING_IS_FOR_SALE); - msg.ShowDialog(); + private void SetState(ShopState state) + { + if (state == ShopState.None) + return; - if (_state != ShopState.Initial) - SetState(ShopState.Initial); + if (state == ShopState.Buying && _buyItems.Count == 0) + { + var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOTHING_IS_FOR_SALE); + msg.ShowDialog(); - return; - } - else if (state == ShopState.Selling && _sellItems.Count == 0) - { - var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOT_BUYING_YOUR_ITEMS); - msg.ShowDialog(); + if (_state != ShopState.Initial) + SetState(ShopState.Initial); - if (_state != ShopState.Initial) - SetState(ShopState.Initial); + return; + } + else if (state == ShopState.Selling && _sellItems.Count == 0) + { + var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOT_BUYING_YOUR_ITEMS); + msg.ShowDialog(); - return; - } + if (_state != ShopState.Initial) + SetState(ShopState.Initial); + + return; + } - ClearItemList(); + ClearItemList(); - switch (state) - { - case ShopState.Initial: + switch (state) + { + case ShopState.Initial: + { + var buyItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) { - var buyItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_BUY_ITEMS), - SubText = $"{_buyItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_IN_STORE)}", - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Buy), - ShowIconBackGround = false, - OffsetY = 45, - }; - buyItem.LeftClick += (_, _) => SetState(ShopState.Buying); - - var sellItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_BUY_ITEMS), + SubText = $"{_buyItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_IN_STORE)}", + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Buy), + ShowIconBackGround = false, + OffsetY = 45, + }; + buyItem.LeftClick += (_, _) => SetState(ShopState.Buying); + + var sellItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_SELL_ITEMS), + SubText = $"{_sellItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_ACCEPTED)}", + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Sell), + ShowIconBackGround = false, + OffsetY = 45, + }; + sellItem.LeftClick += (_, _) => SetState(ShopState.Selling); + + AddItemToList(buyItem, sortList: false); + AddItemToList(sellItem, sortList: false); + + if (_craftItems.Count > 0) + { + var craftItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_SELL_ITEMS), - SubText = $"{_sellItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_ACCEPTED)}", + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_CRAFT_ITEMS), + SubText = $"{_craftItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_ACCEPTED)}", IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Sell), + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Craft), ShowIconBackGround = false, OffsetY = 45, }; - sellItem.LeftClick += (_, _) => SetState(ShopState.Selling); - - AddItemToList(buyItem, sortList: false); - AddItemToList(sellItem, sortList: false); + craftItem.LeftClick += (_, _) => SetState(ShopState.Crafting); - if (_craftItems.Count > 0) - { - var craftItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_CRAFT_ITEMS), - SubText = $"{_craftItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_ACCEPTED)}", - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Craft), - ShowIconBackGround = false, - OffsetY = 45, - }; - craftItem.LeftClick += (_, _) => SetState(ShopState.Crafting); - - AddItemToList(craftItem, sortList: false); - } - - Buttons = ScrollingListDialogButtons.Cancel; + AddItemToList(craftItem, sortList: false); } - break; - case ShopState.Buying: - case ShopState.Selling: + Buttons = ScrollingListDialogButtons.Cancel; + } + break; + + case ShopState.Buying: + case ShopState.Selling: + { + var buying = state == ShopState.Buying; + var items = new List(); + foreach (var item in buying ? _buyItems : _sellItems) { - var buying = state == ShopState.Buying; - var items = new List(); - foreach (var item in buying ? _buyItems : _sellItems) + var data = _eifFileProvider.EIFFile[item.ID]; + var genderExtra = data.Type == EOLib.IO.ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - data.Gender)})" : string.Empty; + var subText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_PRICE)}: {(buying ? item.Buy : item.Sell)} {genderExtra}"; + + var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) { - var data = _eifFileProvider.EIFFile[item.ID]; - var genderExtra = data.Type == EOLib.IO.ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - data.Gender)})" : string.Empty; - var subText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_PRICE)}: {(buying ? item.Buy : item.Sell)} {genderExtra}"; - - var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) - { - PrimaryText = data.Name, - SubText = subText, - IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic - 1, transparent: true), - OffsetY = 45 - }; - listItem.LeftClick += TradeItem; - listItem.RightClick += TradeItem; - - items.Add(listItem); - } - - SetItemList(items); - Buttons = ScrollingListDialogButtons.BackCancel; + PrimaryText = data.Name, + SubText = subText, + IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic - 1, transparent: true), + OffsetY = 45 + }; + listItem.LeftClick += TradeItem; + listItem.RightClick += TradeItem; + + items.Add(listItem); } - break; - case ShopState.Crafting: + SetItemList(items); + Buttons = ScrollingListDialogButtons.BackCancel; + } + break; + + case ShopState.Crafting: + { + var items = new List(); + foreach (var item in _craftItems) { - var items = new List(); - foreach (var item in _craftItems) + var data = _eifFileProvider.EIFFile[item.ID]; + var genderExtra = data.Type == EOLib.IO.ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - data.Gender)})" : string.Empty; + var subText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS)}: {item.Ingredients.Count} {genderExtra}"; + + var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) { - var data = _eifFileProvider.EIFFile[item.ID]; - var genderExtra = data.Type == EOLib.IO.ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - data.Gender)})" : string.Empty; - var subText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS)}: {item.Ingredients.Count} {genderExtra}"; - - var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) - { - PrimaryText = data.Name, - SubText = subText, - IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic - 1, transparent: true), - OffsetY = 45 - }; - listItem.LeftClick += CraftItem; - listItem.RightClick += CraftItem; - - items.Add(listItem); - } - - SetItemList(items); - Buttons = ScrollingListDialogButtons.BackCancel; + PrimaryText = data.Name, + SubText = subText, + IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic - 1, transparent: true), + OffsetY = 45 + }; + listItem.LeftClick += CraftItem; + listItem.RightClick += CraftItem; + + items.Add(listItem); } - break; - } - _state = state; + SetItemList(items); + Buttons = ScrollingListDialogButtons.BackCancel; + } + break; } - private void TradeItem(object sender, EventArgs e) - { - if (_state != ShopState.Buying && _state != ShopState.Selling) - return; + _state = state; + } - var listItemIndex = ((ListDialogItem)sender).Index + _scrollBar.ScrollOffset; - var buying = _state == ShopState.Buying; + private void TradeItem(object sender, EventArgs e) + { + if (_state != ShopState.Buying && _state != ShopState.Selling) + return; - var collection = (buying ? _buyItems : _sellItems); - if (listItemIndex >= collection.Count) - return; + var listItemIndex = ((ListDialogItem)sender).Index + _scrollBar.ScrollOffset; + var buying = _state == ShopState.Buying; - // todo: move some of this stuff into a controller class? - var shopItem = collection[listItemIndex]; - var data = _eifFileProvider.EIFFile[shopItem.ID]; + var collection = (buying ? _buyItems : _sellItems); + if (listItemIndex >= collection.Count) + return; - var inventoryItem = _characterInventoryProvider.ItemInventory - .SingleOrNone(x => buying ? x.ItemID == 1 : x.ItemID == shopItem.ID); + // todo: move some of this stuff into a controller class? + var shopItem = collection[listItemIndex]; + var data = _eifFileProvider.EIFFile[shopItem.ID]; - // todo: move this stuff into a validator class? - if (buying) - { - if (!_inventorySpaceValidator.ItemFits(data.ID)) - { - var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); - msg.ShowDialog(); - return; - } - - var stats = _characterProvider.MainCharacter.Stats; - if (data.Weight + stats[CharacterStat.Weight] > stats[CharacterStat.MaxWeight]) - { - var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - msg.ShowDialog(); - return; - } + var inventoryItem = _characterInventoryProvider.ItemInventory + .SingleOrNone(x => buying ? x.ItemID == 1 : x.ItemID == shopItem.ID); - var hasEnoughGold = inventoryItem.Match(some: x => x.Amount >= shopItem.Buy, none: () => false); - if (!hasEnoughGold) - { - var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, " gold."); - msg.ShowDialog(); - return; - } - } - else + // todo: move this stuff into a validator class? + if (buying) + { + if (!_inventorySpaceValidator.ItemFits(data.ID)) { - var hasEnoughItem = inventoryItem.Match(some: x => x.Amount > 0, none: () => false); - if (!hasEnoughItem) - { - var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOT_BUYING_YOUR_ITEMS); - msg.ShowDialog(); - return; - } + var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); + msg.ShowDialog(); + return; } - var needItemTransferDialog = (buying && shopItem.MaxBuy != 1) || (!buying && inventoryItem.Match(x => x.Amount != 1, () => false)); - - if (needItemTransferDialog) + var stats = _characterProvider.MainCharacter.Stats; + if (data.Weight + stats[CharacterStat.Weight] > stats[CharacterStat.MaxWeight]) { - var itemTransferDialog = _itemTransferDialogFactory.CreateItemTransferDialog(data.Name, - ItemTransferDialog.TransferType.ShopTransfer, - buying ? shopItem.MaxBuy : inventoryItem.Match(x => x.Amount, () => 0), - buying ? EOResourceID.DIALOG_TRANSFER_BUY : EOResourceID.DIALOG_TRANSFER_SELL); - itemTransferDialog.DialogClosing += (_, e) => - { - if (e.Result == XNADialogResult.OK) - ConfirmAndExecuteTrade(itemTransferDialog.SelectedAmount); - }; - - itemTransferDialog.ShowDialog(); - } - else - { - ConfirmAndExecuteTrade(amount: 1); + var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + msg.ShowDialog(); + return; } - void ConfirmAndExecuteTrade(int amount) + var hasEnoughGold = inventoryItem.Match(some: x => x.Amount >= shopItem.Buy, none: () => false); + if (!hasEnoughGold) { - var message = $"{_localizedStringFinder.GetString(buying ? EOResourceID.DIALOG_WORD_BUY : EOResourceID.DIALOG_WORD_SELL)} {amount} {data.Name} " + - $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_FOR)} {(buying ? shopItem.Buy : shopItem.Sell) * amount} gold?"; - var dlg = _messageBoxFactory.CreateMessageBox(message, _localizedStringFinder.GetString(buying ? EOResourceID.DIALOG_SHOP_BUY_ITEMS : EOResourceID.DIALOG_SHOP_SELL_ITEMS), EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => - { - if (e.Result == XNADialogResult.Cancel) - return; - - if (buying) - _shopActions.BuyItem(shopItem.ID, amount); - else - _shopActions.SellItem(shopItem.ID, amount); - }; - dlg.ShowDialog(); + var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, " gold."); + msg.ShowDialog(); + return; } } - - private void CraftItem(object sender, EventArgs e) + else { - if (_state != ShopState.Crafting) + var hasEnoughItem = inventoryItem.Match(some: x => x.Amount > 0, none: () => false); + if (!hasEnoughItem) + { + var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOT_BUYING_YOUR_ITEMS); + msg.ShowDialog(); return; + } + } - var listItemIndex = ((ListDialogItem)sender).Index + _scrollBar.ScrollOffset; + var needItemTransferDialog = (buying && shopItem.MaxBuy != 1) || (!buying && inventoryItem.Match(x => x.Amount != 1, () => false)); - if (listItemIndex >= _craftItems.Count) - return; + if (needItemTransferDialog) + { + var itemTransferDialog = _itemTransferDialogFactory.CreateItemTransferDialog(data.Name, + ItemTransferDialog.TransferType.ShopTransfer, + buying ? shopItem.MaxBuy : inventoryItem.Match(x => x.Amount, () => 0), + buying ? EOResourceID.DIALOG_TRANSFER_BUY : EOResourceID.DIALOG_TRANSFER_SELL); + itemTransferDialog.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + ConfirmAndExecuteTrade(itemTransferDialog.SelectedAmount); + }; - // todo: move some of this stuff into a controller class? - var craftItem = _craftItems[listItemIndex]; - var data = _eifFileProvider.EIFFile[craftItem.ID]; + itemTransferDialog.ShowDialog(); + } + else + { + ConfirmAndExecuteTrade(amount: 1); + } - // todo: move this stuff into a validator class? - foreach (var ingredient in craftItem.Ingredients) + void ConfirmAndExecuteTrade(int amount) + { + var message = $"{_localizedStringFinder.GetString(buying ? EOResourceID.DIALOG_WORD_BUY : EOResourceID.DIALOG_WORD_SELL)} {amount} {data.Name} " + + $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_FOR)} {(buying ? shopItem.Buy : shopItem.Sell) * amount} gold?"; + var dlg = _messageBoxFactory.CreateMessageBox(message, _localizedStringFinder.GetString(buying ? EOResourceID.DIALOG_SHOP_BUY_ITEMS : EOResourceID.DIALOG_SHOP_SELL_ITEMS), EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => { - if (!_characterInventoryProvider.ItemInventory.Any(x => x.ItemID == ingredient.ID && x.Amount >= ingredient.Amount)) - { - var message = BuildMessage(EOResourceID.DIALOG_SHOP_CRAFT_MISSING_INGREDIENTS); - var caption = BuildCaption(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS); + if (e.Result == XNADialogResult.Cancel) + return; - var dlg = _messageBoxFactory.CreateMessageBox(message, caption, EODialogButtons.Cancel, EOMessageBoxStyle.LargeDialogSmallHeader); - dlg.ShowDialog(); + if (buying) + _shopActions.BuyItem(shopItem.ID, amount); + else + _shopActions.SellItem(shopItem.ID, amount); + }; + dlg.ShowDialog(); + } + } - return; - } - } + private void CraftItem(object sender, EventArgs e) + { + if (_state != ShopState.Crafting) + return; - if (!_inventorySpaceValidator.ItemFits(data.ID)) + var listItemIndex = ((ListDialogItem)sender).Index + _scrollBar.ScrollOffset; + + if (listItemIndex >= _craftItems.Count) + return; + + // todo: move some of this stuff into a controller class? + var craftItem = _craftItems[listItemIndex]; + var data = _eifFileProvider.EIFFile[craftItem.ID]; + + // todo: move this stuff into a validator class? + foreach (var ingredient in craftItem.Ingredients) + { + if (!_characterInventoryProvider.ItemInventory.Any(x => x.ItemID == ingredient.ID && x.Amount >= ingredient.Amount)) { - var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); - msg.ShowDialog(); + var message = BuildMessage(EOResourceID.DIALOG_SHOP_CRAFT_MISSING_INGREDIENTS); + var caption = BuildCaption(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS); + + var dlg = _messageBoxFactory.CreateMessageBox(message, caption, EODialogButtons.Cancel, EOMessageBoxStyle.LargeDialogSmallHeader); + dlg.ShowDialog(); + return; } + } - var message2 = BuildMessage(EOResourceID.DIALOG_SHOP_CRAFT_PUT_INGREDIENTS_TOGETHER); - var caption2 = BuildCaption(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS); - - var dlg2 = _messageBoxFactory.CreateMessageBox(message2, caption2, EODialogButtons.OkCancel, EOMessageBoxStyle.LargeDialogSmallHeader); - dlg2.DialogClosing += (o, e) => - { - if (e.Result == XNADialogResult.Cancel) - return; + if (!_inventorySpaceValidator.ItemFits(data.ID)) + { + var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); + msg.ShowDialog(); + return; + } - _shopActions.CraftItem(craftItem.ID); - }; - dlg2.ShowDialog(); + var message2 = BuildMessage(EOResourceID.DIALOG_SHOP_CRAFT_PUT_INGREDIENTS_TOGETHER); + var caption2 = BuildCaption(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS); - string BuildMessage(EOResourceID resource) - { - var message = _localizedStringFinder.GetString(resource) + "\n\n"; + var dlg2 = _messageBoxFactory.CreateMessageBox(message2, caption2, EODialogButtons.OkCancel, EOMessageBoxStyle.LargeDialogSmallHeader); + dlg2.DialogClosing += (o, e) => + { + if (e.Result == XNADialogResult.Cancel) + return; - foreach (var ingred in craftItem.Ingredients) - { - var ingredData = _eifFileProvider.EIFFile[ingred.ID]; - message += $"+ {ingred.Amount} {ingredData.Name}\n"; - } + _shopActions.CraftItem(craftItem.ID); + }; + dlg2.ShowDialog(); - return message; - } + string BuildMessage(EOResourceID resource) + { + var message = _localizedStringFinder.GetString(resource) + "\n\n"; - string BuildCaption(EOResourceID resource) + foreach (var ingred in craftItem.Ingredients) { - return $"{_localizedStringFinder.GetString(resource)} {_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_FOR)} {data.Name}"; + var ingredData = _eifFileProvider.EIFFile[ingred.ID]; + message += $"+ {ingred.Amount} {ingredData.Name}\n"; } + + return message; + } + + string BuildCaption(EOResourceID resource) + { + return $"{_localizedStringFinder.GetString(resource)} {_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_FOR)} {data.Name}"; } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/SkillmasterDialog.cs b/EndlessClient/Dialogs/SkillmasterDialog.cs index 3f58ec8f2..aeba45ab5 100644 --- a/EndlessClient/Dialogs/SkillmasterDialog.cs +++ b/EndlessClient/Dialogs/SkillmasterDialog.cs @@ -16,386 +16,385 @@ using System.Text; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class SkillmasterDialog : ScrollingListDialog { - public class SkillmasterDialog : ScrollingListDialog + private enum SkillState + { + Initial, + Learn, + Forget, + ForgetAll + } + + private SkillState _state; + + private HashSet _cachedSkills; + private HashSet _cachedSpells; + private string _cachedTitle; + + private bool _showingRequirements; + private readonly ISkillmasterActions _skillmasterActions; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ISkillDataProvider _skillDataProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IPubFileProvider _pubFileProvider; + private readonly IContentProvider _contentProvider; + + public SkillmasterDialog(INativeGraphicsManager nativeGraphicsManager, + ISkillmasterActions skillmasterActions, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + ITextInputDialogFactory textInputDialogFactory, + ISkillDataProvider skillDataProvider, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IPubFileProvider pubFileProvider, + IContentProvider contentProvider) + : base(nativeGraphicsManager, dialogButtonService) { - private enum SkillState + Buttons = ScrollingListDialogButtons.Cancel; + ListItemType = ListDialogItem.ListItemStyle.Large; + + _cachedSkills = new HashSet(); + _cachedSpells = new HashSet(); + _cachedTitle = string.Empty; + + BackAction += BackClicked; + + _skillmasterActions = skillmasterActions; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _textInputDialogFactory = textInputDialogFactory; + _skillDataProvider = skillDataProvider; + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _pubFileProvider = pubFileProvider; + _contentProvider = contentProvider; + SetState(SkillState.Initial, regen: true); + } + + protected override void OnUpdateControl(GameTime gameTime) + { + if (_cachedTitle != _skillDataProvider.Title) { - Initial, - Learn, - Forget, - ForgetAll + Title = _cachedTitle = _skillDataProvider.Title; } - private SkillState _state; - - private HashSet _cachedSkills; - private HashSet _cachedSpells; - private string _cachedTitle; - - private bool _showingRequirements; - private readonly ISkillmasterActions _skillmasterActions; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ISkillDataProvider _skillDataProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IPubFileProvider _pubFileProvider; - private readonly IContentProvider _contentProvider; - - public SkillmasterDialog(INativeGraphicsManager nativeGraphicsManager, - ISkillmasterActions skillmasterActions, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - ITextInputDialogFactory textInputDialogFactory, - ISkillDataProvider skillDataProvider, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IPubFileProvider pubFileProvider, - IContentProvider contentProvider) - : base(nativeGraphicsManager, dialogButtonService) + if (!_cachedSkills.SetEquals(_skillDataProvider.Skills)) { - Buttons = ScrollingListDialogButtons.Cancel; - ListItemType = ListDialogItem.ListItemStyle.Large; - - _cachedSkills = new HashSet(); - _cachedSpells = new HashSet(); - _cachedTitle = string.Empty; - - BackAction += BackClicked; - - _skillmasterActions = skillmasterActions; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _textInputDialogFactory = textInputDialogFactory; - _skillDataProvider = skillDataProvider; - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _pubFileProvider = pubFileProvider; - _contentProvider = contentProvider; - SetState(SkillState.Initial, regen: true); + _cachedSkills = _skillDataProvider.Skills.ToHashSet(); + SetState(_state, regen: true); } - protected override void OnUpdateControl(GameTime gameTime) + if (!_cachedSpells.SetEquals(_characterInventoryProvider.SpellInventory)) { - if (_cachedTitle != _skillDataProvider.Title) - { - Title = _cachedTitle = _skillDataProvider.Title; - } - - if (!_cachedSkills.SetEquals(_skillDataProvider.Skills)) - { - _cachedSkills = _skillDataProvider.Skills.ToHashSet(); - SetState(_state, regen: true); - } + _cachedSpells = _characterInventoryProvider.SpellInventory.ToHashSet(); + SetState(_state, regen: true); + } - if (!_cachedSpells.SetEquals(_characterInventoryProvider.SpellInventory)) - { - _cachedSpells = _characterInventoryProvider.SpellInventory.ToHashSet(); - SetState(_state, regen: true); - } + base.OnUpdateControl(gameTime); + } - base.OnUpdateControl(gameTime); - } + private void BackClicked(object sender, EventArgs e) + { + ListItemType = ListDialogItem.ListItemStyle.Large; - private void BackClicked(object sender, EventArgs e) + if (_state == SkillState.Learn && _showingRequirements) { - ListItemType = ListDialogItem.ListItemStyle.Large; - - if (_state == SkillState.Learn && _showingRequirements) - { - SetState(SkillState.Learn, regen: true); - _showingRequirements = false; - } - else - { - SetState(SkillState.Initial); - } + SetState(SkillState.Learn, regen: true); + _showingRequirements = false; } - - private void SetState(SkillState newState, bool regen = false) + else { - SkillState old = _state; + SetState(SkillState.Initial); + } + } - if (old == newState && !regen) - return; + private void SetState(SkillState newState, bool regen = false) + { + SkillState old = _state; - int numToLearn = _cachedSkills.Count(x => !_cachedSpells.Any(si => si.ID == x.Id)); - int numToForget = _cachedSpells.Count; + if (old == newState && !regen) + return; - ClearItemList(); + int numToLearn = _cachedSkills.Count(x => !_cachedSpells.Any(si => si.ID == x.Id)); + int numToForget = _cachedSpells.Count; - if (newState == SkillState.Learn && numToLearn == 0) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_NOTHING_MORE_TO_LEARN); - dlg.ShowDialog(); - return; - } + ClearItemList(); - switch (newState) - { - case SkillState.Initial: - { - string learnNum = $"{numToLearn}{_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_ITEMS_TO_LEARN)}"; - string forgetNum = $"{numToForget}{_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_ITEMS_LEARNED)}"; + if (newState == SkillState.Learn && numToLearn == 0) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_NOTHING_MORE_TO_LEARN); + dlg.ShowDialog(); + return; + } - var learn = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEARN), - SubText = learnNum, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Learn), - ShowIconBackGround = false, - OffsetY = 45 - }; - learn.LeftClick += (_, _) => SetState(SkillState.Learn); - learn.RightClick += (_, _) => SetState(SkillState.Learn); - learn.SetParentControl(this); + switch (newState) + { + case SkillState.Initial: + { + string learnNum = $"{numToLearn}{_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_ITEMS_TO_LEARN)}"; + string forgetNum = $"{numToForget}{_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_ITEMS_LEARNED)}"; - var forget = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_FORGET), - SubText = forgetNum, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Forget), - ShowIconBackGround = false, - OffsetY = 45 - }; - forget.LeftClick += (_, _) => SetState(SkillState.Forget); - forget.RightClick += (_, _) => SetState(SkillState.Forget); - forget.SetParentControl(this); + var learn = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEARN), + SubText = learnNum, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Learn), + ShowIconBackGround = false, + OffsetY = 45 + }; + learn.LeftClick += (_, _) => SetState(SkillState.Learn); + learn.RightClick += (_, _) => SetState(SkillState.Learn); + learn.SetParentControl(this); + + var forget = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_FORGET), + SubText = forgetNum, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Forget), + ShowIconBackGround = false, + OffsetY = 45 + }; + forget.LeftClick += (_, _) => SetState(SkillState.Forget); + forget.RightClick += (_, _) => SetState(SkillState.Forget); + forget.SetParentControl(this); + + var forgetAll = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL), + SubText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_RESET_YOUR_CHARACTER), + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Forget), + ShowIconBackGround = false, + OffsetY = 45 + }; + forgetAll.LeftClick += (_, _) => SetState(SkillState.ForgetAll); + forgetAll.RightClick += (_, _) => SetState(SkillState.ForgetAll); + forgetAll.SetParentControl(this); + + SetItemList(new List { learn, forget, forgetAll }); + + Buttons = ScrollingListDialogButtons.Cancel; + } + break; + case SkillState.Learn: + { + foreach (var skill in _cachedSkills.Where(x => !_cachedSpells.Any(y => y.ID == x.Id))) + { + var skillRef = skill; + var spellData = _pubFileProvider.ESFFile[skill.Id]; - var forgetAll = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) + var icon = GraphicsManager.TextureFromResource(GFXTypes.SpellIcons, spellData.Icon); + var nextListItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL), - SubText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_RESET_YOUR_CHARACTER), - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Forget), + Visible = false, + PrimaryText = spellData.Name, + SubText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_REQUIREMENTS), + IconGraphic = icon, + IconGraphicSource = new Rectangle(0, 0, icon.Width / 2, icon.Height), ShowIconBackGround = false, OffsetY = 45 }; - forgetAll.LeftClick += (_, _) => SetState(SkillState.ForgetAll); - forgetAll.RightClick += (_, _) => SetState(SkillState.ForgetAll); - forgetAll.SetParentControl(this); - - SetItemList(new List { learn, forget, forgetAll }); - - Buttons = ScrollingListDialogButtons.Cancel; + nextListItem.LeftClick += (_, _) => Learn(skillRef); + nextListItem.RightClick += (o, e) => Learn(skillRef); + nextListItem.OnMouseEnter += (o, e) => ShowRequirementsLabel(skillRef); + nextListItem.SetSubtextClickAction((_, _) => ShowRequirements(skillRef)); + AddItemToList(nextListItem, false); } - break; - case SkillState.Learn: - { - foreach (var skill in _cachedSkills.Where(x => !_cachedSpells.Any(y => y.ID == x.Id))) - { - var skillRef = skill; - var spellData = _pubFileProvider.ESFFile[skill.Id]; - - var icon = GraphicsManager.TextureFromResource(GFXTypes.SpellIcons, spellData.Icon); - var nextListItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) - { - Visible = false, - PrimaryText = spellData.Name, - SubText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_REQUIREMENTS), - IconGraphic = icon, - IconGraphicSource = new Rectangle(0, 0, icon.Width / 2, icon.Height), - ShowIconBackGround = false, - OffsetY = 45 - }; - nextListItem.LeftClick += (_, _) => Learn(skillRef); - nextListItem.RightClick += (o, e) => Learn(skillRef); - nextListItem.OnMouseEnter += (o, e) => ShowRequirementsLabel(skillRef); - nextListItem.SetSubtextClickAction((_, _) => ShowRequirements(skillRef)); - AddItemToList(nextListItem, false); - } - - Buttons = ScrollingListDialogButtons.BackCancel; - } - break; - case SkillState.Forget: - { - var input = _textInputDialogFactory.Create(_localizedStringFinder.GetString(DialogResourceID.SKILL_PROMPT_TO_FORGET), 32); - - input.DialogClosing += (_, args) => - { - if (args.Result == XNADialogResult.Cancel) - return; - - _cachedSpells.SingleOrNone(s => string.Equals(_pubFileProvider.ESFFile[s.ID].Name, input.ResponseText, StringComparison.OrdinalIgnoreCase)) - .Match( - some: si => - { - _skillmasterActions.ForgetSkill(si.ID); - }, - none: () => - { - args.Cancel = true; - - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_FORGET_ERROR_NOT_LEARNED); - dlg.ShowDialog(); - }); - }; - input.ShowDialog(); + Buttons = ScrollingListDialogButtons.BackCancel; + } + break; + case SkillState.Forget: + { + var input = _textInputDialogFactory.Create(_localizedStringFinder.GetString(DialogResourceID.SKILL_PROMPT_TO_FORGET), 32); - //should show initial info in the actual dialog since this uses a pop-up input box - // to select a skill to remove - newState = SkillState.Initial; - goto case SkillState.Initial; - } - case SkillState.ForgetAll: + input.DialogClosing += (_, args) => { - ShowForgetAllMessage(); - Buttons = ScrollingListDialogButtons.BackCancel; - } - break; - } - - _state = newState; - } - - private void Learn(Skill skill) - { - - bool skillReqsMet = true; - foreach (var req in skill.SkillRequirements.Where(x => x > 0)) - { - if (!_characterInventoryProvider.SpellInventory.Any(s => s.ID == req)) + if (args.Result == XNADialogResult.Cancel) + return; + + _cachedSpells.SingleOrNone(s => string.Equals(_pubFileProvider.ESFFile[s.ID].Name, input.ResponseText, StringComparison.OrdinalIgnoreCase)) + .Match( + some: si => + { + _skillmasterActions.ForgetSkill(si.ID); + }, + none: () => + { + args.Cancel = true; + + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_FORGET_ERROR_NOT_LEARNED); + dlg.ShowDialog(); + }); + }; + + input.ShowDialog(); + + //should show initial info in the actual dialog since this uses a pop-up input box + // to select a skill to remove + newState = SkillState.Initial; + goto case SkillState.Initial; + } + case SkillState.ForgetAll: { - skillReqsMet = false; - break; + ShowForgetAllMessage(); + Buttons = ScrollingListDialogButtons.BackCancel; } - } + break; + } + + _state = newState; + } - var stats = _characterProvider.MainCharacter.Stats; + private void Learn(Skill skill) + { - if (!skillReqsMet || - stats[CharacterStat.Strength] < skill.StrRequirement || stats[CharacterStat.Intelligence] < skill.IntRequirement || stats[CharacterStat.Wisdom] < skill.WisRequirement || - stats[CharacterStat.Agility] < skill.AgiRequirement || stats[CharacterStat.Constitution] < skill.ConRequirement || stats[CharacterStat.Charisma] < skill.ChaRequirement || - stats[CharacterStat.Level] < skill.LevelRequirement || !_characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1 && x.Amount >= skill.GoldRequirement).HasValue) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_REQS_NOT_MET); - dlg.ShowDialog(); - } - else if (skill.ClassRequirement > 0 && _characterProvider.MainCharacter.ClassID != skill.ClassRequirement) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_WRONG_CLASS, $" {_pubFileProvider.ECFFile[skill.ClassRequirement].Name}!"); - dlg.ShowDialog(); - return; - } - else + bool skillReqsMet = true; + foreach (var req in skill.SkillRequirements.Where(x => x > 0)) + { + if (!_characterInventoryProvider.SpellInventory.Any(s => s.ID == req)) { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_CONFIRMATION, $" {_pubFileProvider.ESFFile[skill.Id].Name}?", EODialogButtons.OkCancel); - dlg.DialogClosing += (o, e) => - { - if (e.Result == XNADialogResult.OK) - _skillmasterActions.LearnSkill(skill.Id); - }; - dlg.ShowDialog(); + skillReqsMet = false; + break; } } - private void ShowRequirements(Skill skill) - { - _showingRequirements = true; - - ClearItemList(); - ListItemType = ListDialogItem.ListItemStyle.Small; + var stats = _characterProvider.MainCharacter.Stats; - var drawStrings = new List + if (!skillReqsMet || + stats[CharacterStat.Strength] < skill.StrRequirement || stats[CharacterStat.Intelligence] < skill.IntRequirement || stats[CharacterStat.Wisdom] < skill.WisRequirement || + stats[CharacterStat.Agility] < skill.AgiRequirement || stats[CharacterStat.Constitution] < skill.ConRequirement || stats[CharacterStat.Charisma] < skill.ChaRequirement || + stats[CharacterStat.Level] < skill.LevelRequirement || !_characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1 && x.Amount >= skill.GoldRequirement).HasValue) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_REQS_NOT_MET); + dlg.ShowDialog(); + } + else if (skill.ClassRequirement > 0 && _characterProvider.MainCharacter.ClassID != skill.ClassRequirement) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_WRONG_CLASS, $" {_pubFileProvider.ECFFile[skill.ClassRequirement].Name}!"); + dlg.ShowDialog(); + return; + } + else + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_CONFIRMATION, $" {_pubFileProvider.ESFFile[skill.Id].Name}?", EODialogButtons.OkCancel); + dlg.DialogClosing += (o, e) => { - _pubFileProvider.ESFFile[skill.Id].Name + (skill.ClassRequirement > 0 ? $" [{_pubFileProvider.ECFFile[skill.ClassRequirement].Name}]" : string.Empty), - " " + if (e.Result == XNADialogResult.OK) + _skillmasterActions.LearnSkill(skill.Id); }; + dlg.ShowDialog(); + } + } - if (skill.SkillRequirements.Any(x => x != 0)) - { - drawStrings.AddRange( - from req in skill.SkillRequirements - where req != 0 - select _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_SKILL) + ": " + _pubFileProvider.ESFFile[req].Name); - drawStrings.Add(" "); - } - - if (skill.StrRequirement > 0) - drawStrings.Add($"{skill.StrRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_STRENGTH)}"); - if (skill.IntRequirement > 0) - drawStrings.Add($"{skill.IntRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_INTELLIGENCE)}"); - if (skill.WisRequirement > 0) - drawStrings.Add($"{skill.WisRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_WISDOM)}"); - if (skill.AgiRequirement > 0) - drawStrings.Add($"{skill.AgiRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_AGILITY)}"); - if (skill.ConRequirement > 0) - drawStrings.Add($"{skill.ConRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CONSTITUTION)}"); - if (skill.ChaRequirement > 0) - drawStrings.Add($"{skill.ChaRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CHARISMA)}"); - - drawStrings.Add(" "); - drawStrings.Add($"{skill.LevelRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEVEL)}"); - drawStrings.Add($"{skill.GoldRequirement} {_pubFileProvider.EIFFile[1].Name}"); + private void ShowRequirements(Skill skill) + { + _showingRequirements = true; - SetItemList(drawStrings.Select(x => new ListDialogItem(this, ListItemType) { PrimaryText = x }).ToList()); - } + ClearItemList(); + ListItemType = ListDialogItem.ListItemStyle.Small; - private void ShowRequirementsLabel(Skill skill) + var drawStrings = new List { - var full = new StringBuilder(); - - full.Append($"{_pubFileProvider.ESFFile[skill.Id].Name} {skill.LevelRequirement} LVL, "); - - if (skill.StrRequirement > 0) - full.Append($"{skill.StrRequirement} STR, "); - if (skill.IntRequirement > 0) - full.Append($"{skill.IntRequirement} INT, "); - if (skill.WisRequirement > 0) - full.Append($"{skill.WisRequirement} WIS, "); - if (skill.AgiRequirement > 0) - full.Append($"{skill.AgiRequirement} AGI, "); - if (skill.ConRequirement > 0) - full.Append($"{skill.ConRequirement} CON, "); - if (skill.ChaRequirement > 0) - full.Append($"{skill.ChaRequirement} CHA, "); - if (skill.GoldRequirement > 0) - full.Append($"{skill.GoldRequirement} {_pubFileProvider.EIFFile[1].Name}"); - if (skill.ClassRequirement > 0) - full.Append($", {_pubFileProvider.ECFFile[skill.ClassRequirement].Name}"); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, full.ToString()); - } + _pubFileProvider.ESFFile[skill.Id].Name + (skill.ClassRequirement > 0 ? $" [{_pubFileProvider.ECFFile[skill.ClassRequirement].Name}]" : string.Empty), + " " + }; - private void ShowForgetAllMessage() + if (skill.SkillRequirements.Any(x => x != 0)) { - AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], - insertLineBreaks: true, - new List { ConfirmResetCharacter }, - _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL), - _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_1), - _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_2), - _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_3), - _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_CLICK_HERE_TO_FORGET_ALL) - ); + drawStrings.AddRange( + from req in skill.SkillRequirements + where req != 0 + select _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_SKILL) + ": " + _pubFileProvider.ESFFile[req].Name); + drawStrings.Add(" "); } - private void ConfirmResetCharacter() + if (skill.StrRequirement > 0) + drawStrings.Add($"{skill.StrRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_STRENGTH)}"); + if (skill.IntRequirement > 0) + drawStrings.Add($"{skill.IntRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_INTELLIGENCE)}"); + if (skill.WisRequirement > 0) + drawStrings.Add($"{skill.WisRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_WISDOM)}"); + if (skill.AgiRequirement > 0) + drawStrings.Add($"{skill.AgiRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_AGILITY)}"); + if (skill.ConRequirement > 0) + drawStrings.Add($"{skill.ConRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CONSTITUTION)}"); + if (skill.ChaRequirement > 0) + drawStrings.Add($"{skill.ChaRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CHARISMA)}"); + + drawStrings.Add(" "); + drawStrings.Add($"{skill.LevelRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEVEL)}"); + drawStrings.Add($"{skill.GoldRequirement} {_pubFileProvider.EIFFile[1].Name}"); + + SetItemList(drawStrings.Select(x => new ListDialogItem(this, ListItemType) { PrimaryText = x }).ToList()); + } + + private void ShowRequirementsLabel(Skill skill) + { + var full = new StringBuilder(); + + full.Append($"{_pubFileProvider.ESFFile[skill.Id].Name} {skill.LevelRequirement} LVL, "); + + if (skill.StrRequirement > 0) + full.Append($"{skill.StrRequirement} STR, "); + if (skill.IntRequirement > 0) + full.Append($"{skill.IntRequirement} INT, "); + if (skill.WisRequirement > 0) + full.Append($"{skill.WisRequirement} WIS, "); + if (skill.AgiRequirement > 0) + full.Append($"{skill.AgiRequirement} AGI, "); + if (skill.ConRequirement > 0) + full.Append($"{skill.ConRequirement} CON, "); + if (skill.ChaRequirement > 0) + full.Append($"{skill.ChaRequirement} CHA, "); + if (skill.GoldRequirement > 0) + full.Append($"{skill.GoldRequirement} {_pubFileProvider.EIFFile[1].Name}"); + if (skill.ClassRequirement > 0) + full.Append($", {_pubFileProvider.ECFFile[skill.ClassRequirement].Name}"); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, full.ToString()); + } + + private void ShowForgetAllMessage() + { + AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], + insertLineBreaks: true, + new List { ConfirmResetCharacter }, + _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL), + _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_1), + _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_2), + _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_3), + _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_CLICK_HERE_TO_FORGET_ALL) + ); + } + + private void ConfirmResetCharacter() + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_CONFIRMATION, EODialogButtons.OkCancel); + dlg.DialogClosing += (_, args) => { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_CONFIRMATION, EODialogButtons.OkCancel); - dlg.DialogClosing += (_, args) => + // todo: test how GameServer handles character reset with paperdoll items still equipped + if (args.Result == XNADialogResult.OK) { - // todo: test how GameServer handles character reset with paperdoll items still equipped - if (args.Result == XNADialogResult.OK) - { - _skillmasterActions.ResetCharacter(); - } - }; - dlg.ShowDialog(); - } + _skillmasterActions.ResetCharacter(); + } + }; + dlg.ShowDialog(); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/TextInputDialog.cs b/EndlessClient/Dialogs/TextInputDialog.cs index 4e6bea597..910ea6c3f 100644 --- a/EndlessClient/Dialogs/TextInputDialog.cs +++ b/EndlessClient/Dialogs/TextInputDialog.cs @@ -6,71 +6,70 @@ using Microsoft.Xna.Framework; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class TextInputDialog : BaseEODialog { - public class TextInputDialog : BaseEODialog - { - private readonly IXNATextBox _inputBox; + private readonly IXNATextBox _inputBox; - public string ResponseText => _inputBox.Text; + public string ResponseText => _inputBox.Text; - public TextInputDialog(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - IContentProvider contentProvider, - string prompt, - int maxInputChars = 12) - : base(nativeGraphicsManager, isInGame: true) - { - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 54); - SetSize(BackgroundTexture.Width, BackgroundTexture.Height); + public TextInputDialog(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + IContentProvider contentProvider, + string prompt, + int maxInputChars = 12) + : base(nativeGraphicsManager, isInGame: true) + { + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 54); + SetSize(BackgroundTexture.Width, BackgroundTexture.Height); - var lblPrompt = new XNALabel(Constants.FontSize10) - { - AutoSize = false, - DrawArea = new Rectangle(21, 19, 230, 49), - ForeColor = ColorConstants.LightGrayDialogMessage, - TextWidth = 225, - Text = prompt - }; - lblPrompt.Initialize(); - lblPrompt.SetParentControl(this); + var lblPrompt = new XNALabel(Constants.FontSize10) + { + AutoSize = false, + DrawArea = new Rectangle(21, 19, 230, 49), + ForeColor = ColorConstants.LightGrayDialogMessage, + TextWidth = 225, + Text = prompt + }; + lblPrompt.Initialize(); + lblPrompt.SetParentControl(this); - _inputBox = new XNATextBox(new Rectangle(37, 74, 192, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) - { - MaxChars = maxInputChars, - LeftPadding = 4, - TextColor = ColorConstants.LightBeigeText, - }; - _inputBox.SetParentControl(this); + _inputBox = new XNATextBox(new Rectangle(37, 74, 192, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) + { + MaxChars = maxInputChars, + LeftPadding = 4, + TextColor = ColorConstants.LightBeigeText, + }; + _inputBox.SetParentControl(this); - var ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(41, 103), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - ok.OnClick += (_, _) => Close(XNADialogResult.OK); - ok.SetParentControl(this); + var ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(41, 103), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + ok.OnClick += (_, _) => Close(XNADialogResult.OK); + ok.SetParentControl(this); - var cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(134, 103), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); - cancel.SetParentControl(this); + var cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(134, 103), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); + cancel.SetParentControl(this); - DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); + DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); - CenterInGameView(); - DrawPosition += new Vector2(0, 17); - } + CenterInGameView(); + DrawPosition += new Vector2(0, 17); + } - public override void Initialize() - { - _inputBox.Initialize(); + public override void Initialize() + { + _inputBox.Initialize(); - _inputBox.Selected = true; + _inputBox.Selected = true; - base.Initialize(); - } + base.Initialize(); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/TextMultiInputDialog.cs b/EndlessClient/Dialogs/TextMultiInputDialog.cs index 73af29c43..3db0f1c18 100644 --- a/EndlessClient/Dialogs/TextMultiInputDialog.cs +++ b/EndlessClient/Dialogs/TextMultiInputDialog.cs @@ -10,153 +10,152 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class TextMultiInputDialog : BaseEODialog { - public class TextMultiInputDialog : BaseEODialog + public enum DialogSize { - public enum DialogSize - { - Two, - Three, - Four, - Five, - FiveWithScroll, - } + Two, + Three, + Four, + Five, + FiveWithScroll, + } - public struct InputInfo - { - public string Label; - public int MaxChars; - } + public struct InputInfo + { + public string Label; + public int MaxChars; + } - // can't use base class functionality because otherwise the bottom part of the dialog is drawn over the buttons - private readonly Texture2D _background; - private readonly Rectangle _backgroundSourceRectangle; + // can't use base class functionality because otherwise the bottom part of the dialog is drawn over the buttons + private readonly Texture2D _background; + private readonly Rectangle _backgroundSourceRectangle; - private readonly Vector2 _bottomOverlayDrawPosition; - private readonly Rectangle _bottomOverlaySource; + private readonly Vector2 _bottomOverlayDrawPosition; + private readonly Rectangle _bottomOverlaySource; - private readonly IXNATextBox[] _inputBoxes; + private readonly IXNATextBox[] _inputBoxes; - public IReadOnlyList Responses => _inputBoxes.Select(x => x.Text).ToList(); + public IReadOnlyList Responses => _inputBoxes.Select(x => x.Text).ToList(); - public TextMultiInputDialog(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - IContentProvider contentProvider, - DialogSize size, - string title, - string prompt, - InputInfo[] inputInfo) - : base(nativeGraphicsManager, isInGame: true) - { - _background = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 57); + public TextMultiInputDialog(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + IContentProvider contentProvider, + DialogSize size, + string title, + string prompt, + InputInfo[] inputInfo) + : base(nativeGraphicsManager, isInGame: true) + { + _background = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 57); - switch (size) - { - case DialogSize.Two: - if (inputInfo.Length != 2) - { - throw new ArgumentException("Not enough input labels were provided"); - } + switch (size) + { + case DialogSize.Two: + if (inputInfo.Length != 2) + { + throw new ArgumentException("Not enough input labels were provided"); + } - _backgroundSourceRectangle = new Rectangle(0, 0, 330, 170); + _backgroundSourceRectangle = new Rectangle(0, 0, 330, 170); - SetSize(330, 170); - _bottomOverlayDrawPosition = new Vector2(0, 111); - _bottomOverlaySource = new Rectangle(0, 240, 330, 59); + SetSize(330, 170); + _bottomOverlayDrawPosition = new Vector2(0, 111); + _bottomOverlaySource = new Rectangle(0, 240, 330, 59); - _inputBoxes = new IXNATextBox[2]; - break; - default: throw new NotImplementedException(); - } + _inputBoxes = new IXNATextBox[2]; + break; + default: throw new NotImplementedException(); + } - var lblTitle = new XNALabel(Constants.FontSize10) + var lblTitle = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + ForeColor = ColorConstants.LightYellowText, + Text = title, + TextWidth = 254, + DrawPosition = new Vector2(18, 12), + }; + lblTitle.Initialize(); + lblTitle.SetParentControl(this); + + var lblPrompt = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + ForeColor = ColorConstants.LightGrayDialogMessage, + Text = prompt, + TextWidth = 254, + DrawPosition = new Vector2(19, 40), + WrapBehavior = WrapBehavior.WrapToNewLine, + }; + lblPrompt.Initialize(); + lblPrompt.SetParentControl(this); + + int yCoord = 69; + for (int i = 0; i < inputInfo.Length; i++) + { + var nextLabel = new XNALabel(Constants.FontSize10) { AutoSize = true, - ForeColor = ColorConstants.LightYellowText, - Text = title, - TextWidth = 254, - DrawPosition = new Vector2(18, 12), + ForeColor = ColorConstants.LightGrayDialogMessage, + Text = inputInfo[i].Label, + DrawPosition = new Vector2(24, yCoord), }; - lblTitle.Initialize(); - lblTitle.SetParentControl(this); + nextLabel.Initialize(); + nextLabel.SetParentControl(this); - var lblPrompt = new XNALabel(Constants.FontSize10) + _inputBoxes[i] = new XNATextBox(new Rectangle(126, yCoord, 168, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) { - AutoSize = true, - ForeColor = ColorConstants.LightGrayDialogMessage, - Text = prompt, - TextWidth = 254, - DrawPosition = new Vector2(19, 40), - WrapBehavior = WrapBehavior.WrapToNewLine, + MaxChars = inputInfo[i].MaxChars, + LeftPadding = 4, + TextColor = ColorConstants.LightBeigeText, + MaxWidth = 160, }; - lblPrompt.Initialize(); - lblPrompt.SetParentControl(this); + _inputBoxes[i].SetParentControl(this); - int yCoord = 69; - for (int i = 0; i < inputInfo.Length; i++) - { - var nextLabel = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - ForeColor = ColorConstants.LightGrayDialogMessage, - Text = inputInfo[i].Label, - DrawPosition = new Vector2(24, yCoord), - }; - nextLabel.Initialize(); - nextLabel.SetParentControl(this); - - _inputBoxes[i] = new XNATextBox(new Rectangle(126, yCoord, 168, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) - { - MaxChars = inputInfo[i].MaxChars, - LeftPadding = 4, - TextColor = ColorConstants.LightBeigeText, - MaxWidth = 160, - }; - _inputBoxes[i].SetParentControl(this); - - yCoord += 24; - } - - var ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(73, 125), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - ok.OnClick += (_, _) => Close(XNADialogResult.OK); - ok.SetParentControl(this); - - var cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(166, 125), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); - cancel.SetParentControl(this); - - DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); - - CenterInGameView(); + yCoord += 24; } - public override void Initialize() - { - foreach (var box in _inputBoxes) - box.Initialize(); + var ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(73, 125), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + ok.OnClick += (_, _) => Close(XNADialogResult.OK); + ok.SetParentControl(this); - _inputBoxes[0].Selected = true; + var cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(166, 125), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); + cancel.SetParentControl(this); - base.Initialize(); - } + DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); - protected override void OnDrawControl(GameTime gameTime) - { - // need to redo drawing background image so controls get drawn on top of background - _spriteBatch.Begin(); - _spriteBatch.Draw(_background, DrawAreaWithParentOffset, _backgroundSourceRectangle, Color.White); - _spriteBatch.Draw(_background, DrawPositionWithParentOffset + _bottomOverlayDrawPosition, _bottomOverlaySource, Color.White); - _spriteBatch.End(); + CenterInGameView(); + } - base.OnDrawControl(gameTime); - } + public override void Initialize() + { + foreach (var box in _inputBoxes) + box.Initialize(); + + _inputBoxes[0].Selected = true; + + base.Initialize(); + } + + protected override void OnDrawControl(GameTime gameTime) + { + // need to redo drawing background image so controls get drawn on top of background + _spriteBatch.Begin(); + _spriteBatch.Draw(_background, DrawAreaWithParentOffset, _backgroundSourceRectangle, Color.White); + _spriteBatch.Draw(_background, DrawPositionWithParentOffset + _bottomOverlayDrawPosition, _bottomOverlaySource, Color.White); + _spriteBatch.End(); + + base.OnDrawControl(gameTime); } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/TradeDialog.cs b/EndlessClient/Dialogs/TradeDialog.cs index 3a4f56235..1a52c7ab7 100644 --- a/EndlessClient/Dialogs/TradeDialog.cs +++ b/EndlessClient/Dialogs/TradeDialog.cs @@ -20,385 +20,384 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs +namespace EndlessClient.Dialogs; + +public class TradeDialog : BaseEODialog { - public class TradeDialog : BaseEODialog + private readonly ITradeActions _tradeActions; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly ITradeProvider _tradeProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IMapItemGraphicProvider _mapItemGraphicProvider; + private readonly ISfxPlayer _sfxPlayer; + + private readonly IXNAPanel _leftPanel, _rightPanel; + private readonly IXNALabel _leftPlayerName, _rightPlayerName; + private readonly IXNALabel _leftPlayerStatus, _rightPlayerStatus; + private readonly ScrollBar _leftScroll, _rightScroll; + + private readonly IXNAButton _ok, _cancel; + + private readonly List _leftItems, _rightItems; + + // cached values: updated/compared from domain state + private TradeOffer _leftOffer, _rightOffer; + private int _leftScrollOffset, _rightScrollOffset; + + // tracks state around the trade partner quickly changing an offer + // pops up warning for "other player trying to trick you" + private int _recentPartnerItemChanges; + private Stopwatch _partnerItemChangeTick; + + public TradeDialog(INativeGraphicsManager nativeGraphicsManager, + ITradeActions tradeActions, + ILocalizedStringFinder localizedStringFinder, + IEODialogButtonService dialogButtonService, + IEOMessageBoxFactory messageBoxFactory, + IStatusLabelSetter statusLabelSetter, + IInventorySpaceValidator inventorySpaceValidator, + ITradeProvider tradeProvider, + ICharacterProvider characterProvider, + IEIFFileProvider eifFileProvider, + IMapItemGraphicProvider mapItemGraphicProvider, + ISfxPlayer sfxPlayer) + : base(nativeGraphicsManager, isInGame: true) { - private readonly ITradeActions _tradeActions; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly ITradeProvider _tradeProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - private readonly ISfxPlayer _sfxPlayer; - - private readonly IXNAPanel _leftPanel, _rightPanel; - private readonly IXNALabel _leftPlayerName, _rightPlayerName; - private readonly IXNALabel _leftPlayerStatus, _rightPlayerStatus; - private readonly ScrollBar _leftScroll, _rightScroll; - - private readonly IXNAButton _ok, _cancel; - - private readonly List _leftItems, _rightItems; - - // cached values: updated/compared from domain state - private TradeOffer _leftOffer, _rightOffer; - private int _leftScrollOffset, _rightScrollOffset; - - // tracks state around the trade partner quickly changing an offer - // pops up warning for "other player trying to trick you" - private int _recentPartnerItemChanges; - private Stopwatch _partnerItemChangeTick; - - public TradeDialog(INativeGraphicsManager nativeGraphicsManager, - ITradeActions tradeActions, - ILocalizedStringFinder localizedStringFinder, - IEODialogButtonService dialogButtonService, - IEOMessageBoxFactory messageBoxFactory, - IStatusLabelSetter statusLabelSetter, - IInventorySpaceValidator inventorySpaceValidator, - ITradeProvider tradeProvider, - ICharacterProvider characterProvider, - IEIFFileProvider eifFileProvider, - IMapItemGraphicProvider mapItemGraphicProvider, - ISfxPlayer sfxPlayer) - : base(nativeGraphicsManager, isInGame: true) + _tradeActions = tradeActions; + _localizedStringFinder = localizedStringFinder; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _inventorySpaceValidator = inventorySpaceValidator; + _tradeProvider = tradeProvider; + _characterProvider = characterProvider; + _eifFileProvider = eifFileProvider; + _mapItemGraphicProvider = mapItemGraphicProvider; + _sfxPlayer = sfxPlayer; + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 50); + + _leftPanel = new XNAPanel { - _tradeActions = tradeActions; - _localizedStringFinder = localizedStringFinder; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _inventorySpaceValidator = inventorySpaceValidator; - _tradeProvider = tradeProvider; - _characterProvider = characterProvider; - _eifFileProvider = eifFileProvider; - _mapItemGraphicProvider = mapItemGraphicProvider; - _sfxPlayer = sfxPlayer; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 50); - - _leftPanel = new XNAPanel - { - DrawArea = new Rectangle(0, 0, BackgroundTexture.Width / 2, BackgroundTexture.Height), - }; - _leftPanel.SetParentControl(this); - - _rightPanel = new XNAPanel - { - DrawArea = new Rectangle(BackgroundTexture.Width / 2, 0, BackgroundTexture.Width / 2, BackgroundTexture.Height), - }; - _rightPanel.SetParentControl(this); + DrawArea = new Rectangle(0, 0, BackgroundTexture.Width / 2, BackgroundTexture.Height), + }; + _leftPanel.SetParentControl(this); - _leftPlayerName = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(20, 14, 166, 20), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText - }; - _leftPlayerName.SetParentControl(_leftPanel); - - _rightPlayerName = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(11, 14, 166, 20), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText - }; - _rightPlayerName.SetParentControl(_rightPanel); - - _leftPlayerStatus = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(195, 14, 79, 20), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText, - Text = _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING) - }; - _leftPlayerStatus.SetParentControl(_leftPanel); - - _rightPlayerStatus = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(185, 14, 79, 20), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText, - Text = _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING) - }; - _rightPlayerStatus.SetParentControl(_rightPanel); - - _leftScroll = new ScrollBar(new Vector2(252, 44), new Vector2(16, 199), ScrollBarColors.LightOnMed, GraphicsManager) { LinesToRender = 5 }; - _leftScroll.SetParentControl(_leftPanel); - _leftPanel.SetScrollWheelHandler(_leftScroll); - - _rightScroll = new ScrollBar(new Vector2(243, 44), new Vector2(16, 199), ScrollBarColors.LightOnMed, GraphicsManager) { LinesToRender = 5 }; - _rightScroll.SetParentControl(_rightPanel); - _rightPanel.SetScrollWheelHandler(_rightScroll); - - _ok = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(356, 252), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - _ok.OnClick += OkButtonClicked; - _ok.SetParentControl(this); - - _cancel = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(449, 252), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - _cancel.OnClick += CancelButtonClicked; - _cancel.SetParentControl(this); - - _leftItems = new List(); - _rightItems = new List(); - _leftOffer = new TradeOffer.Builder().ToImmutable(); - _rightOffer = new TradeOffer.Builder().ToImmutable(); - - CenterInGameView(); - - if (!Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, 15); - } + _rightPanel = new XNAPanel + { + DrawArea = new Rectangle(BackgroundTexture.Width / 2, 0, BackgroundTexture.Width / 2, BackgroundTexture.Height), + }; + _rightPanel.SetParentControl(this); - public override void Initialize() + _leftPlayerName = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(20, 14, 166, 20), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText + }; + _leftPlayerName.SetParentControl(_leftPanel); + + _rightPlayerName = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(11, 14, 166, 20), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText + }; + _rightPlayerName.SetParentControl(_rightPanel); + + _leftPlayerStatus = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(195, 14, 79, 20), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText, + Text = _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING) + }; + _leftPlayerStatus.SetParentControl(_leftPanel); + + _rightPlayerStatus = new XNALabel(Constants.FontSize08pt5) { - base.Initialize(); + DrawArea = new Rectangle(185, 14, 79, 20), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText, + Text = _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING) + }; + _rightPlayerStatus.SetParentControl(_rightPanel); + + _leftScroll = new ScrollBar(new Vector2(252, 44), new Vector2(16, 199), ScrollBarColors.LightOnMed, GraphicsManager) { LinesToRender = 5 }; + _leftScroll.SetParentControl(_leftPanel); + _leftPanel.SetScrollWheelHandler(_leftScroll); + + _rightScroll = new ScrollBar(new Vector2(243, 44), new Vector2(16, 199), ScrollBarColors.LightOnMed, GraphicsManager) { LinesToRender = 5 }; + _rightScroll.SetParentControl(_rightPanel); + _rightPanel.SetScrollWheelHandler(_rightScroll); + + _ok = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(356, 252), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + _ok.OnClick += OkButtonClicked; + _ok.SetParentControl(this); + + _cancel = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(449, 252), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + _cancel.OnClick += CancelButtonClicked; + _cancel.SetParentControl(this); + + _leftItems = new List(); + _rightItems = new List(); + _leftOffer = new TradeOffer.Builder().ToImmutable(); + _rightOffer = new TradeOffer.Builder().ToImmutable(); + + CenterInGameView(); + + if (!Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, 15); + } + + public override void Initialize() + { + base.Initialize(); + + _leftPanel.Initialize(); + _rightPanel.Initialize(); - _leftPanel.Initialize(); - _rightPanel.Initialize(); + _leftPlayerName.Initialize(); + _rightPlayerName.Initialize(); - _leftPlayerName.Initialize(); - _rightPlayerName.Initialize(); + _leftPlayerStatus.Initialize(); + _rightPlayerStatus.Initialize(); - _leftPlayerStatus.Initialize(); - _rightPlayerStatus.Initialize(); + _leftScroll.Initialize(); + _rightScroll.Initialize(); - _leftScroll.Initialize(); - _rightScroll.Initialize(); + _ok.Initialize(); + _cancel.Initialize(); + } + + protected override void OnUnconditionalUpdateControl(GameTime gameTime) + { + var updateItemVisibility = false; - _ok.Initialize(); - _cancel.Initialize(); + // player one offer will always be on the left; player two always on the right + if (_tradeProvider.PlayerOneOffer != null && !_tradeProvider.PlayerOneOffer.Equals(_leftOffer)) + { + UpdateOffer(_tradeProvider.PlayerOneOffer, _leftOffer, _leftPlayerName, _leftPlayerStatus, _leftPanel, _leftItems, -3); + _leftOffer = _tradeProvider.PlayerOneOffer; + _leftScroll.UpdateDimensions(_leftOffer.Items.Count); + updateItemVisibility = true; } - protected override void OnUnconditionalUpdateControl(GameTime gameTime) + if (_tradeProvider.PlayerTwoOffer != null && !_tradeProvider.PlayerTwoOffer.Equals(_rightOffer)) { - var updateItemVisibility = false; + UpdateOffer(_tradeProvider.PlayerTwoOffer, _rightOffer, _rightPlayerName, _rightPlayerStatus, _rightPanel, _rightItems, -10); + _rightOffer = _tradeProvider.PlayerTwoOffer; + _rightScroll.UpdateDimensions(_rightOffer.Items.Count); + updateItemVisibility = true; + } - // player one offer will always be on the left; player two always on the right - if (_tradeProvider.PlayerOneOffer != null && !_tradeProvider.PlayerOneOffer.Equals(_leftOffer)) - { - UpdateOffer(_tradeProvider.PlayerOneOffer, _leftOffer, _leftPlayerName, _leftPlayerStatus, _leftPanel, _leftItems, -3); - _leftOffer = _tradeProvider.PlayerOneOffer; - _leftScroll.UpdateDimensions(_leftOffer.Items.Count); - updateItemVisibility = true; - } + if (updateItemVisibility || _leftScrollOffset != _leftScroll.ScrollOffset) + { + UpdateItemScrollIndexes(_leftScroll, _leftItems); + _leftScrollOffset = _leftScroll.ScrollOffset; + } - if (_tradeProvider.PlayerTwoOffer != null && !_tradeProvider.PlayerTwoOffer.Equals(_rightOffer)) - { - UpdateOffer(_tradeProvider.PlayerTwoOffer, _rightOffer, _rightPlayerName, _rightPlayerStatus, _rightPanel, _rightItems, -10); - _rightOffer = _tradeProvider.PlayerTwoOffer; - _rightScroll.UpdateDimensions(_rightOffer.Items.Count); - updateItemVisibility = true; - } + if (updateItemVisibility || _rightScrollOffset != _rightScroll.ScrollOffset) + { + UpdateItemScrollIndexes(_rightScroll, _rightItems); + _rightScrollOffset = _rightScroll.ScrollOffset; + } + + if (_partnerItemChangeTick?.ElapsedMilliseconds > 1000 && _recentPartnerItemChanges > 0) + { + _recentPartnerItemChanges--; + _partnerItemChangeTick = Stopwatch.StartNew(); + } - if (updateItemVisibility || _leftScrollOffset != _leftScroll.ScrollOffset) + base.OnUnconditionalUpdateControl(gameTime); + } + + private void UpdateOffer(TradeOffer actualOffer, TradeOffer cachedOffer, + IXNALabel playerNameLabel, IXNALabel playerStatusLabel, + IXNAPanel parentPanel, + List listItems, + int listitemOffset) + { + if (actualOffer.PlayerName != cachedOffer.PlayerName || actualOffer.Items.Count != cachedOffer.Items.Count) + { + if (!string.IsNullOrEmpty(actualOffer.PlayerName)) { - UpdateItemScrollIndexes(_leftScroll, _leftItems); - _leftScrollOffset = _leftScroll.ScrollOffset; + playerNameLabel.Text = $"{char.ToUpper(actualOffer.PlayerName[0]) + actualOffer.PlayerName[1..]}{(actualOffer.Items.Any() ? $"[{actualOffer.Items.Count}]" : "")}"; } + } - if (updateItemVisibility || _rightScrollOffset != _rightScroll.ScrollOffset) + // todo: check if packets properly reset agrees to false when items change + if (actualOffer.Agrees != cachedOffer.Agrees) + { + playerStatusLabel.Text = actualOffer.Agrees + ? _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_AGREE) + : _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING); + + if (actualOffer.Agrees) { - UpdateItemScrollIndexes(_rightScroll, _rightItems); - _rightScrollOffset = _rightScroll.ScrollOffset; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + actualOffer.PlayerID == _characterProvider.MainCharacter.ID + ? EOResourceID.STATUS_LABEL_TRADE_YOU_ACCEPT + : EOResourceID.STATUS_LABEL_TRADE_OTHER_ACCEPT); } - - if (_partnerItemChangeTick?.ElapsedMilliseconds > 1000 && _recentPartnerItemChanges > 0) + else { - _recentPartnerItemChanges--; - _partnerItemChangeTick = Stopwatch.StartNew(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + actualOffer.PlayerID == _characterProvider.MainCharacter.ID + ? EOResourceID.STATUS_LABEL_TRADE_YOU_CANCEL + : EOResourceID.STATUS_LABEL_TRADE_OTHER_CANCEL); } - - base.OnUnconditionalUpdateControl(gameTime); } - private void UpdateOffer(TradeOffer actualOffer, TradeOffer cachedOffer, - IXNALabel playerNameLabel, IXNALabel playerStatusLabel, - IXNAPanel parentPanel, - List listItems, - int listitemOffset) + if (cachedOffer.Items == null || !actualOffer.Items.ToHashSet().SetEquals(cachedOffer.Items)) { - if (actualOffer.PlayerName != cachedOffer.PlayerName || actualOffer.Items.Count != cachedOffer.Items.Count) - { - if (!string.IsNullOrEmpty(actualOffer.PlayerName)) - { - playerNameLabel.Text = $"{char.ToUpper(actualOffer.PlayerName[0]) + actualOffer.PlayerName[1..]}{(actualOffer.Items.Any() ? $"[{actualOffer.Items.Count}]" : "")}"; - } - } + var added = actualOffer.Items.Except(cachedOffer.Items ?? Enumerable.Empty()); + var removed = (cachedOffer.Items ?? Enumerable.Empty()).Where(i => !actualOffer.Items.Contains(i)); - // todo: check if packets properly reset agrees to false when items change - if (actualOffer.Agrees != cachedOffer.Agrees) + foreach (var addedItem in added) { - playerStatusLabel.Text = actualOffer.Agrees - ? _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_AGREE) - : _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING); + var itemRec = _eifFileProvider.EIFFile[addedItem.ItemID]; + var subText = $"x {addedItem.Amount} {(itemRec.Type == ItemType.Armor ? $"({_localizedStringFinder.GetString(itemRec.Gender == 0 ? EOResourceID.FEMALE : EOResourceID.MALE)})" : string.Empty)}"; - if (actualOffer.Agrees) + var newListItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - actualOffer.PlayerID == _characterProvider.MainCharacter.ID - ? EOResourceID.STATUS_LABEL_TRADE_YOU_ACCEPT - : EOResourceID.STATUS_LABEL_TRADE_OTHER_ACCEPT); - } - else - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - actualOffer.PlayerID == _characterProvider.MainCharacter.ID - ? EOResourceID.STATUS_LABEL_TRADE_YOU_CANCEL - : EOResourceID.STATUS_LABEL_TRADE_OTHER_CANCEL); - } - } + Data = addedItem, + PrimaryText = itemRec.Name, + SubText = subText, + IconGraphic = _mapItemGraphicProvider.GetItemGraphic(addedItem.ItemID, addedItem.Amount), + OffsetX = listitemOffset, + OffsetY = 46 + }; - if (cachedOffer.Items == null || !actualOffer.Items.ToHashSet().SetEquals(cachedOffer.Items)) - { - var added = actualOffer.Items.Except(cachedOffer.Items ?? Enumerable.Empty()); - var removed = (cachedOffer.Items ?? Enumerable.Empty()).Where(i => !actualOffer.Items.Contains(i)); + if (actualOffer.PlayerID == _characterProvider.MainCharacter.ID) + newListItem.RightClick += (_, _) => _tradeActions.RemoveItemFromOffer(itemRec.ID); - foreach (var addedItem in added) - { - var itemRec = _eifFileProvider.EIFFile[addedItem.ItemID]; - var subText = $"x {addedItem.Amount} {(itemRec.Type == ItemType.Armor ? $"({_localizedStringFinder.GetString(itemRec.Gender == 0 ? EOResourceID.FEMALE : EOResourceID.MALE)})" : string.Empty)}"; + newListItem.SetParentControl(parentPanel); + listItems.Add(newListItem); - var newListItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) - { - Data = addedItem, - PrimaryText = itemRec.Name, - SubText = subText, - IconGraphic = _mapItemGraphicProvider.GetItemGraphic(addedItem.ItemID, addedItem.Amount), - OffsetX = listitemOffset, - OffsetY = 46 - }; + _sfxPlayer.PlaySfx(SoundEffectID.TradeItemOfferChanged); + } - if (actualOffer.PlayerID == _characterProvider.MainCharacter.ID) - newListItem.RightClick += (_, _) => _tradeActions.RemoveItemFromOffer(itemRec.ID); + foreach (var removedItem in removed) + { + listItems.SingleOrNone(y => ((InventoryItem)y.Data).Equals(removedItem)) + .MatchSome(listItem => + { + listItems.Remove(listItem); + listItem.Dispose(); + }); - newListItem.SetParentControl(parentPanel); - listItems.Add(newListItem); + _sfxPlayer.PlaySfx(SoundEffectID.TradeItemOfferChanged); + } - _sfxPlayer.PlaySfx(SoundEffectID.TradeItemOfferChanged); - } + if (cachedOffer.Items != null && actualOffer.PlayerID != 0 && actualOffer.PlayerID != _characterProvider.MainCharacter.ID) + { + _partnerItemChangeTick = Stopwatch.StartNew(); + _recentPartnerItemChanges++; - foreach (var removedItem in removed) + if (_recentPartnerItemChanges == 2) { - listItems.SingleOrNone(y => ((InventoryItem)y.Data).Equals(removedItem)) - .MatchSome(listItem => - { - listItems.Remove(listItem); - listItem.Dispose(); - }); - - _sfxPlayer.PlaySfx(SoundEffectID.TradeItemOfferChanged); - } + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_OTHER_PLAYER_TRICK_YOU); + dlg.ShowDialog(); - if (cachedOffer.Items != null && actualOffer.PlayerID != 0 && actualOffer.PlayerID != _characterProvider.MainCharacter.ID) + // this will prevent the message from showing more than once per trade (I'm too lazy to find something more elegant) + _recentPartnerItemChanges = -1000; + } + else if ((_leftOffer == cachedOffer ? _rightOffer : _leftOffer).Agrees) { - _partnerItemChangeTick = Stopwatch.StartNew(); - _recentPartnerItemChanges++; + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_ABORTED_OFFER_CHANGED); + dlg.ShowDialog(); - if (_recentPartnerItemChanges == 2) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_OTHER_PLAYER_TRICK_YOU); - dlg.ShowDialog(); - - // this will prevent the message from showing more than once per trade (I'm too lazy to find something more elegant) - _recentPartnerItemChanges = -1000; - } - else if ((_leftOffer == cachedOffer ? _rightOffer : _leftOffer).Agrees) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_ABORTED_OFFER_CHANGED); - dlg.ShowDialog(); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_TRADE_OTHER_PLAYER_CHANGED_OFFER); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_TRADE_OTHER_PLAYER_CHANGED_OFFER); } } } + } + + private void UpdateItemScrollIndexes(ScrollBar scrollBar, List items) + { + var scrollOffset = items.Count > scrollBar.LinesToRender ? scrollBar.ScrollOffset : 0; - private void UpdateItemScrollIndexes(ScrollBar scrollBar, List items) + for (int i = 0; i < items.Count; i++) { - var scrollOffset = items.Count > scrollBar.LinesToRender ? scrollBar.ScrollOffset : 0; + items[i].Visible = i >= scrollOffset && i < scrollBar.LinesToRender + scrollOffset; + items[i].Index = i - scrollOffset; + } + } - for (int i = 0; i < items.Count; i++) - { - items[i].Visible = i >= scrollOffset && i < scrollBar.LinesToRender + scrollOffset; - items[i].Index = i - scrollOffset; - } + private void OkButtonClicked(object sender, EventArgs e) + { + var (offer, partnerOffer) = _leftOffer.PlayerID == _characterProvider.MainCharacter.ID + ? (_leftOffer, _rightOffer) + : (_rightOffer, _leftOffer); + + if (offer.Agrees) + return; + + if (_leftOffer.Items.Count == 0 || _rightOffer.Items.Count == 0) + { + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRADE_BOTH_PLAYERS_OFFER_ONE_ITEM, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + return; } - private void OkButtonClicked(object sender, EventArgs e) + if (!_inventorySpaceValidator.ItemsFit(offer.Items, partnerOffer.Items)) { - var (offer, partnerOffer) = _leftOffer.PlayerID == _characterProvider.MainCharacter.ID - ? (_leftOffer, _rightOffer) - : (_rightOffer, _leftOffer); + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + return; + } - if (offer.Agrees) - return; + var partnerItemWeight = partnerOffer.Items + .Select(x => _eifFileProvider.EIFFile[x.ItemID].Weight * x.Amount) + .Aggregate((a, b) => a + b); + var offerItemWeight = offer.Items + .Select(x => _eifFileProvider.EIFFile[x.ItemID].Weight * x.Amount) + .Aggregate((a, b) => a + b); - if (_leftOffer.Items.Count == 0 || _rightOffer.Items.Count == 0) - { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRADE_BOTH_PLAYERS_OFFER_ONE_ITEM, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); - return; - } + var stats = _characterProvider.MainCharacter.Stats; + if (stats[CharacterStat.Weight] - offerItemWeight + partnerItemWeight > stats[CharacterStat.MaxWeight]) + { + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + return; + } - if (!_inventorySpaceValidator.ItemsFit(offer.Items, partnerOffer.Items)) + var finalCheckDlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_DO_YOU_AGREE, EODialogButtons.OkCancel); + finalCheckDlg.DialogClosing += (o, e) => + { + if (e.Result == XNADialogResult.OK) { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); - return; + _tradeActions.AgreeToTrade(true); } + }; + finalCheckDlg.ShowDialog(); + } - var partnerItemWeight = partnerOffer.Items - .Select(x => _eifFileProvider.EIFFile[x.ItemID].Weight * x.Amount) - .Aggregate((a, b) => a + b); - var offerItemWeight = offer.Items - .Select(x => _eifFileProvider.EIFFile[x.ItemID].Weight * x.Amount) - .Aggregate((a, b) => a + b); - - var stats = _characterProvider.MainCharacter.Stats; - if (stats[CharacterStat.Weight] - offerItemWeight + partnerItemWeight > stats[CharacterStat.MaxWeight]) - { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); - return; - } + private void CancelButtonClicked(object sender, EventArgs e) + { + var offer = _leftOffer.PlayerID == _characterProvider.MainCharacter.ID + ? _leftOffer + : _rightOffer; - var finalCheckDlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_DO_YOU_AGREE, EODialogButtons.OkCancel); - finalCheckDlg.DialogClosing += (o, e) => - { - if (e.Result == XNADialogResult.OK) - { - _tradeActions.AgreeToTrade(true); - } - }; - finalCheckDlg.ShowDialog(); + if (!offer.Agrees) + { + _tradeActions.CancelTrade(); + Close(XNADialogResult.Cancel); } - - private void CancelButtonClicked(object sender, EventArgs e) + else { - var offer = _leftOffer.PlayerID == _characterProvider.MainCharacter.ID - ? _leftOffer - : _rightOffer; - - if (!offer.Agrees) - { - _tradeActions.CancelTrade(); - Close(XNADialogResult.Cancel); - } - else - { - _tradeActions.AgreeToTrade(false); - } + _tradeActions.AgreeToTrade(false); } } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/DebugGameRunner.cs b/EndlessClient/GameExecution/DebugGameRunner.cs index 80eb2abab..2a108fc7a 100644 --- a/EndlessClient/GameExecution/DebugGameRunner.cs +++ b/EndlessClient/GameExecution/DebugGameRunner.cs @@ -1,13 +1,12 @@ using AutomaticTypeMapper; -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +/// +/// A game runner that does not catch any exceptions +/// +public class DebugGameRunner : GameRunnerBase { - /// - /// A game runner that does not catch any exceptions - /// - public class DebugGameRunner : GameRunnerBase - { - public DebugGameRunner(ITypeRegistry registry, string[] args) - : base(registry, args) { } - } + public DebugGameRunner(ITypeRegistry registry, string[] args) + : base(registry, args) { } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/EndlessGame.cs b/EndlessClient/GameExecution/EndlessGame.cs index 2cb41e3e2..fef84a3b3 100644 --- a/EndlessClient/GameExecution/EndlessGame.cs +++ b/EndlessClient/GameExecution/EndlessGame.cs @@ -24,277 +24,276 @@ using System.Linq; using System.Runtime.InteropServices; -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +[MappedType(BaseType = typeof(IEndlessGame), IsSingleton = true)] +public class EndlessGame : Game, IEndlessGame { - [MappedType(BaseType = typeof(IEndlessGame), IsSingleton = true)] - public class EndlessGame : Game, IEndlessGame - { - private readonly IClientWindowSizeRepository _windowSizeRepository; - private readonly IContentProvider _contentProvider; - private readonly IGraphicsDeviceRepository _graphicsDeviceRepository; - private readonly IGameWindowRepository _gameWindowRepository; - private readonly IControlSetRepository _controlSetRepository; - private readonly IControlSetFactory _controlSetFactory; - private readonly ITestModeLauncher _testModeLauncher; - private readonly IPubFileLoadActions _pubFileLoadActions; - private readonly ILoggerProvider _loggerProvider; - private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; - private readonly IConfigurationProvider _configurationProvider; - private readonly IMfxPlayer _mfxPlayer; - private readonly IXnaControlSoundMapper _soundMapper; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - private readonly IMainButtonController _mainButtonController; - - private GraphicsDeviceManager _graphicsDeviceManager; - - private KeyboardState _previousKeyState; - private TimeSpan _lastFrameUpdate; + private readonly IClientWindowSizeRepository _windowSizeRepository; + private readonly IContentProvider _contentProvider; + private readonly IGraphicsDeviceRepository _graphicsDeviceRepository; + private readonly IGameWindowRepository _gameWindowRepository; + private readonly IControlSetRepository _controlSetRepository; + private readonly IControlSetFactory _controlSetFactory; + private readonly ITestModeLauncher _testModeLauncher; + private readonly IPubFileLoadActions _pubFileLoadActions; + private readonly ILoggerProvider _loggerProvider; + private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; + private readonly IConfigurationProvider _configurationProvider; + private readonly IMfxPlayer _mfxPlayer; + private readonly IXnaControlSoundMapper _soundMapper; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + private readonly IMainButtonController _mainButtonController; + + private GraphicsDeviceManager _graphicsDeviceManager; + + private KeyboardState _previousKeyState; + private TimeSpan _lastFrameUpdate; #if DEBUG - private SpriteBatch _spriteBatch; - private Stopwatch _lastFrameRenderTime = Stopwatch.StartNew(); - private int _frames, _displayFrames; - private Texture2D _black; + private SpriteBatch _spriteBatch; + private Stopwatch _lastFrameRenderTime = Stopwatch.StartNew(); + private int _frames, _displayFrames; + private Texture2D _black; #endif - public EndlessGame(IClientWindowSizeRepository windowSizeRepository, - IContentProvider contentProvider, - IGraphicsDeviceRepository graphicsDeviceRepository, - IGameWindowRepository gameWindowRepository, - IControlSetRepository controlSetRepository, - IControlSetFactory controlSetFactory, - ITestModeLauncher testModeLauncher, - IPubFileLoadActions pubFileLoadActions, - ILoggerProvider loggerProvider, - IChatBubbleTextureProvider chatBubbleTextureProvider, - IConfigurationProvider configurationProvider, - IMfxPlayer mfxPlayer, - IXnaControlSoundMapper soundMapper, - IFixedTimeStepRepository fixedTimeStepRepository, - IMainButtonController mainButtonController) + public EndlessGame(IClientWindowSizeRepository windowSizeRepository, + IContentProvider contentProvider, + IGraphicsDeviceRepository graphicsDeviceRepository, + IGameWindowRepository gameWindowRepository, + IControlSetRepository controlSetRepository, + IControlSetFactory controlSetFactory, + ITestModeLauncher testModeLauncher, + IPubFileLoadActions pubFileLoadActions, + ILoggerProvider loggerProvider, + IChatBubbleTextureProvider chatBubbleTextureProvider, + IConfigurationProvider configurationProvider, + IMfxPlayer mfxPlayer, + IXnaControlSoundMapper soundMapper, + IFixedTimeStepRepository fixedTimeStepRepository, + IMainButtonController mainButtonController) + { + _windowSizeRepository = windowSizeRepository; + _contentProvider = contentProvider; + _graphicsDeviceRepository = graphicsDeviceRepository; + _gameWindowRepository = gameWindowRepository; + _controlSetRepository = controlSetRepository; + _controlSetFactory = controlSetFactory; + _testModeLauncher = testModeLauncher; + _pubFileLoadActions = pubFileLoadActions; + _loggerProvider = loggerProvider; + _chatBubbleTextureProvider = chatBubbleTextureProvider; + _configurationProvider = configurationProvider; + _mfxPlayer = mfxPlayer; + _soundMapper = soundMapper; + _fixedTimeStepRepository = fixedTimeStepRepository; + _mainButtonController = mainButtonController; + + _graphicsDeviceManager = new GraphicsDeviceManager(this) { - _windowSizeRepository = windowSizeRepository; - _contentProvider = contentProvider; - _graphicsDeviceRepository = graphicsDeviceRepository; - _gameWindowRepository = gameWindowRepository; - _controlSetRepository = controlSetRepository; - _controlSetFactory = controlSetFactory; - _testModeLauncher = testModeLauncher; - _pubFileLoadActions = pubFileLoadActions; - _loggerProvider = loggerProvider; - _chatBubbleTextureProvider = chatBubbleTextureProvider; - _configurationProvider = configurationProvider; - _mfxPlayer = mfxPlayer; - _soundMapper = soundMapper; - _fixedTimeStepRepository = fixedTimeStepRepository; - _mainButtonController = mainButtonController; - - _graphicsDeviceManager = new GraphicsDeviceManager(this) - { - PreferredBackBufferWidth = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH, - PreferredBackBufferHeight = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT - }; + PreferredBackBufferWidth = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH, + PreferredBackBufferHeight = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT + }; - Content.RootDirectory = "Content"; - } + Content.RootDirectory = "Content"; + } - protected override void Initialize() + protected override void Initialize() + { + Components.ComponentAdded += (o, e) => { - Components.ComponentAdded += (o, e) => + // this is bad hack + // all pre-game controls have a specific sound that should be mapped to them. + // in-game controls get their sounds mapped individually. + // + // Checking for GameStates.LoggedIn because the in-game controls are + // added to the components in the LoggedIn state + if (_controlSetRepository.CurrentControlSet.GameState != GameStates.LoggedIn) { - // this is bad hack - // all pre-game controls have a specific sound that should be mapped to them. - // in-game controls get their sounds mapped individually. - // - // Checking for GameStates.LoggedIn because the in-game controls are - // added to the components in the LoggedIn state - if (_controlSetRepository.CurrentControlSet.GameState != GameStates.LoggedIn) - { - _soundMapper.BindSoundToControl(e.GameComponent); - } - }; + _soundMapper.BindSoundToControl(e.GameComponent); + } + }; - base.Initialize(); + base.Initialize(); - IsMouseVisible = true; - IsFixedTimeStep = false; + IsMouseVisible = true; + IsFixedTimeStep = false; - TargetElapsedTime = TimeSpan.FromMilliseconds(FixedTimeStepRepository.TICK_TIME_MS); - InactiveSleepTime = TimeSpan.FromMilliseconds(0); + TargetElapsedTime = TimeSpan.FromMilliseconds(FixedTimeStepRepository.TICK_TIME_MS); + InactiveSleepTime = TimeSpan.FromMilliseconds(0); - _previousKeyState = Keyboard.GetState(); + _previousKeyState = Keyboard.GetState(); - // setting Width/Height in window size repository applies the change to disable vsync - _graphicsDeviceManager.SynchronizeWithVerticalRetrace = false; - _graphicsDeviceManager.IsFullScreen = false; - _windowSizeRepository.Width = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH; - _windowSizeRepository.Height = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT; + // setting Width/Height in window size repository applies the change to disable vsync + _graphicsDeviceManager.SynchronizeWithVerticalRetrace = false; + _graphicsDeviceManager.IsFullScreen = false; + _windowSizeRepository.Width = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH; + _windowSizeRepository.Height = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT; - _windowSizeRepository.GameWindowSizeChanged += (_, _) => - { - if (_windowSizeRepository.Width < ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT) - _windowSizeRepository.Width = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH; + _windowSizeRepository.GameWindowSizeChanged += (_, _) => + { + if (_windowSizeRepository.Width < ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT) + _windowSizeRepository.Width = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH; - if (_windowSizeRepository.Height < ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT) - _windowSizeRepository.Height = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT; - }; + if (_windowSizeRepository.Height < ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT) + _windowSizeRepository.Height = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT; + }; - Exiting += (_, _) => _mfxPlayer.StopBackgroundMusic(); - } + Exiting += (_, _) => _mfxPlayer.StopBackgroundMusic(); + } - protected override void LoadContent() - { + protected override void LoadContent() + { #if DEBUG - _spriteBatch = new SpriteBatch(GraphicsDevice); - _black = new Texture2D(GraphicsDevice, 1, 1); - _black.SetData(new[] { Color.Black }); + _spriteBatch = new SpriteBatch(GraphicsDevice); + _black = new Texture2D(GraphicsDevice, 1, 1); + _black.SetData(new[] { Color.Black }); #endif - _contentProvider.Load(); + _contentProvider.Load(); - //todo: all the things that should load stuff as part of game's load/initialize should be broken into a pattern - _chatBubbleTextureProvider.LoadContent(); + //todo: all the things that should load stuff as part of game's load/initialize should be broken into a pattern + _chatBubbleTextureProvider.LoadContent(); - //the GraphicsDevice/Window don't exist until Initialize() is called by the framework - //Ideally, this would be set in a DependencyContainer, but I'm not sure of a way to do that now - _graphicsDeviceRepository.GraphicsDevice = GraphicsDevice; - _graphicsDeviceRepository.GraphicsDeviceManager = _graphicsDeviceManager; - _gameWindowRepository.Window = Window; + //the GraphicsDevice/Window don't exist until Initialize() is called by the framework + //Ideally, this would be set in a DependencyContainer, but I'm not sure of a way to do that now + _graphicsDeviceRepository.GraphicsDevice = GraphicsDevice; + _graphicsDeviceRepository.GraphicsDeviceManager = _graphicsDeviceManager; + _gameWindowRepository.Window = Window; - SetUpInitialControlSet(); + SetUpInitialControlSet(); - if (_configurationProvider.MusicEnabled) - { - _mfxPlayer.PlayBackgroundMusic(1, EOLib.IO.Map.MusicControl.InterruptPlayRepeat); - } + if (_configurationProvider.MusicEnabled) + { + _mfxPlayer.PlayBackgroundMusic(1, EOLib.IO.Map.MusicControl.InterruptPlayRepeat); + } - AttemptToLoadPubFiles(); + AttemptToLoadPubFiles(); - base.LoadContent(); - } + base.LoadContent(); + } - protected override void Update(GameTime gameTime) + protected override void Update(GameTime gameTime) + { + // Force updates to wait every 12ms + // Some game components rely on slower update times. 60FPS was the original, but 12ms factors nicely in 120ms "ticks" + // See: https://github.com/ethanmoffat/EndlessClient/issues/199 + // Using IsFixedTimeStep = true with TargetUpdateTime set to 60FPS also limits the draw rate, which is not desired + if ((gameTime.TotalGameTime - _lastFrameUpdate).TotalMilliseconds >= FixedTimeStepRepository.TICK_TIME_MS) { - // Force updates to wait every 12ms - // Some game components rely on slower update times. 60FPS was the original, but 12ms factors nicely in 120ms "ticks" - // See: https://github.com/ethanmoffat/EndlessClient/issues/199 - // Using IsFixedTimeStep = true with TargetUpdateTime set to 60FPS also limits the draw rate, which is not desired - if ((gameTime.TotalGameTime - _lastFrameUpdate).TotalMilliseconds >= FixedTimeStepRepository.TICK_TIME_MS) - { #if DEBUG - var currentKeyState = Keyboard.GetState(); - if (KeyboardExtended.GetState().WasKeyJustDown(Keys.F5)) - { - _testModeLauncher.LaunchTestMode(); - } + var currentKeyState = Keyboard.GetState(); + if (KeyboardExtended.GetState().WasKeyJustDown(Keys.F5)) + { + _testModeLauncher.LaunchTestMode(); + } - _previousKeyState = currentKeyState; + _previousKeyState = currentKeyState; #endif - _fixedTimeStepRepository.Tick(); + _fixedTimeStepRepository.Tick(); #if !DEBUG - try + try + { + base.Update(gameTime); + } + catch + { + if (_configurationProvider.DebugCrashes) { - base.Update(gameTime); + throw; } - catch + else { - if (_configurationProvider.DebugCrashes) - { - throw; - } - else - { - _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); - } + _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); } + } #else - base.Update(gameTime); + base.Update(gameTime); #endif - _lastFrameUpdate = gameTime.TotalGameTime; - } + _lastFrameUpdate = gameTime.TotalGameTime; } + } - protected override void Draw(GameTime gameTime) - { - var isTestMode = _controlSetRepository.CurrentControlSet.GameState == GameStates.TestMode; - GraphicsDevice.Clear(isTestMode ? Color.White : Color.Black); + protected override void Draw(GameTime gameTime) + { + var isTestMode = _controlSetRepository.CurrentControlSet.GameState == GameStates.TestMode; + GraphicsDevice.Clear(isTestMode ? Color.White : Color.Black); - base.Draw(gameTime); + base.Draw(gameTime); #if DEBUG - _frames++; - - var fpsString = $"FPS: {_displayFrames}{(gameTime.IsRunningSlowly ? " (SLOW)" : string.Empty)}"; - var dim = _contentProvider.Fonts[Constants.FontSize09].MeasureString(fpsString); + _frames++; - _spriteBatch.Begin(); - _spriteBatch.Draw(_black, new Rectangle(18, 18, (int)dim.Width + 4, (int)dim.Height + 4), Color.White); - _spriteBatch.DrawString(_contentProvider.Fonts[Constants.FontSize09], fpsString, new Vector2(20, 20), Color.White); - _spriteBatch.End(); + var fpsString = $"FPS: {_displayFrames}{(gameTime.IsRunningSlowly ? " (SLOW)" : string.Empty)}"; + var dim = _contentProvider.Fonts[Constants.FontSize09].MeasureString(fpsString); - if (_lastFrameRenderTime.ElapsedMilliseconds > 1000) - { - _displayFrames = _frames; - _frames = 0; - _lastFrameRenderTime = Stopwatch.StartNew(); - } -#endif - } + _spriteBatch.Begin(); + _spriteBatch.Draw(_black, new Rectangle(18, 18, (int)dim.Width + 4, (int)dim.Height + 4), Color.White); + _spriteBatch.DrawString(_contentProvider.Fonts[Constants.FontSize09], fpsString, new Vector2(20, 20), Color.White); + _spriteBatch.End(); - private void AttemptToLoadPubFiles() + if (_lastFrameRenderTime.ElapsedMilliseconds > 1000) { - const string PUB_LOG_MSG = "**** Unable to load default PUB file: {0}. Exception message: {1}"; + _displayFrames = _frames; + _frames = 0; + _lastFrameRenderTime = Stopwatch.StartNew(); + } +#endif + } - try - { - _pubFileLoadActions.LoadItemFile(); - } - catch (Exception ex) when (ex is IOException || ex is ArgumentException) - { - _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.EIFFormat, 1), ex.Message); - } + private void AttemptToLoadPubFiles() + { + const string PUB_LOG_MSG = "**** Unable to load default PUB file: {0}. Exception message: {1}"; - try - { - _pubFileLoadActions.LoadNPCFile(); - } - catch (Exception ex) when (ex is IOException || ex is ArgumentException) - { - _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ENFFormat, 1), ex.Message); - } + try + { + _pubFileLoadActions.LoadItemFile(); + } + catch (Exception ex) when (ex is IOException || ex is ArgumentException) + { + _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.EIFFormat, 1), ex.Message); + } - try - { - _pubFileLoadActions.LoadSpellFile(); - } - catch (Exception ex) when (ex is IOException || ex is ArgumentException) - { - _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ESFFormat, 1), ex.Message); - } + try + { + _pubFileLoadActions.LoadNPCFile(); + } + catch (Exception ex) when (ex is IOException || ex is ArgumentException) + { + _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ENFFormat, 1), ex.Message); + } - try - { - _pubFileLoadActions.LoadClassFile(); - } - catch (Exception ex) when (ex is IOException || ex is ArgumentException) - { - _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ECFFormat, 1), ex.Message); - } + try + { + _pubFileLoadActions.LoadSpellFile(); + } + catch (Exception ex) when (ex is IOException || ex is ArgumentException) + { + _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ESFFormat, 1), ex.Message); } - private void SetUpInitialControlSet() + try { - var controls = _controlSetFactory.CreateControlsForState( - GameStates.Initial, - _controlSetRepository.CurrentControlSet); - _controlSetRepository.CurrentControlSet = controls; - - //since the controls are being created in LoadContent(), adding them to the default game - // doesn't call the Initialize() method on any controls, so it must be done here - foreach (var xnaControl in _controlSetRepository.CurrentControlSet.AllComponents) - xnaControl.Initialize(); + _pubFileLoadActions.LoadClassFile(); } + catch (Exception ex) when (ex is IOException || ex is ArgumentException) + { + _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ECFFormat, 1), ex.Message); + } + } + + private void SetUpInitialControlSet() + { + var controls = _controlSetFactory.CreateControlsForState( + GameStates.Initial, + _controlSetRepository.CurrentControlSet); + _controlSetRepository.CurrentControlSet = controls; + + //since the controls are being created in LoadContent(), adding them to the default game + // doesn't call the Initialize() method on any controls, so it must be done here + foreach (var xnaControl in _controlSetRepository.CurrentControlSet.AllComponents) + xnaControl.Initialize(); } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/GameRunnerBase.cs b/EndlessClient/GameExecution/GameRunnerBase.cs index 5d9eaf43f..72c538559 100644 --- a/EndlessClient/GameExecution/GameRunnerBase.cs +++ b/EndlessClient/GameExecution/GameRunnerBase.cs @@ -12,137 +12,136 @@ using System.Windows.Forms; #endif -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +public abstract class GameRunnerBase : IGameRunner { - public abstract class GameRunnerBase : IGameRunner + private readonly ITypeRegistry _registry; + private readonly string[] _args; + + protected GameRunnerBase(ITypeRegistry registry, string[] args) { - private readonly ITypeRegistry _registry; - private readonly string[] _args; + _registry = registry; + _args = args; + } - protected GameRunnerBase(ITypeRegistry registry, string[] args) + public virtual bool SetupDependencies() + { + _registry.RegisterDiscoveredTypes(); + + var initializers = _registry.ResolveAll(); + try + { + foreach (var initializer in initializers) + { + initializer.Initialize(); + } + } + catch (ConfigLoadException cle) + { + ShowErrorMessage(cle.Message, "Error loading config file!"); + return false; + } + catch (DataFileLoadException dfle) + { + ShowErrorMessage(dfle.Message, "Error loading data files!"); + return false; + } + catch (DirectoryNotFoundException dnfe) + { + ShowErrorMessage(dnfe.Message, "Missing required directory"); + return false; + } + catch (FileNotFoundException fnfe) + { + ShowErrorMessage(fnfe.Message, "Missing required file"); + return false; + } + catch (LibraryLoadException lle) { - _registry = registry; - _args = args; + var message = + $"There was an error loading GFX{(int)lle.WhichGFX:000}.EGF : {lle.WhichGFX}. Place all .GFX files in .\\gfx\\. The error message is:\n\n\"{lle.Message}\""; + ShowErrorMessage(message, "GFX Load Error"); + return false; } - public virtual bool SetupDependencies() + for (int i = 0; i < _args.Length; ++i) { - _registry.RegisterDiscoveredTypes(); + var arg = _args[i]; - var initializers = _registry.ResolveAll(); - try - { - foreach (var initializer in initializers) - { - initializer.Initialize(); - } - } - catch (ConfigLoadException cle) - { - ShowErrorMessage(cle.Message, "Error loading config file!"); - return false; - } - catch (DataFileLoadException dfle) - { - ShowErrorMessage(dfle.Message, "Error loading data files!"); - return false; - } - catch (DirectoryNotFoundException dnfe) - { - ShowErrorMessage(dnfe.Message, "Missing required directory"); - return false; - } - catch (FileNotFoundException fnfe) - { - ShowErrorMessage(fnfe.Message, "Missing required file"); - return false; - } - catch (LibraryLoadException lle) + if (string.Equals(arg, "--host") && i < _args.Length - 1) { - var message = - $"There was an error loading GFX{(int)lle.WhichGFX:000}.EGF : {lle.WhichGFX}. Place all .GFX files in .\\gfx\\. The error message is:\n\n\"{lle.Message}\""; - ShowErrorMessage(message, "GFX Load Error"); - return false; - } + var host = _args[i + 1]; + _registry.Resolve().Host = host; - for (int i = 0; i < _args.Length; ++i) + i++; + } + else if (string.Equals(arg, "--port") && i < _args.Length - 1) { - var arg = _args[i]; + var port = _args[i + 1]; - if (string.Equals(arg, "--host") && i < _args.Length - 1) + if (int.TryParse(port, out var intPort)) { - var host = _args[i + 1]; - _registry.Resolve().Host = host; - - i++; + _registry.Resolve().Port = intPort; } - else if (string.Equals(arg, "--port") && i < _args.Length - 1) - { - var port = _args[i + 1]; - - if (int.TryParse(port, out var intPort)) - { - _registry.Resolve().Port = intPort; - } - i++; - } - else if (string.Equals(arg, "--version") && i < _args.Length - 1) + i++; + } + else if (string.Equals(arg, "--version") && i < _args.Length - 1) + { + var versionStr = _args[i + 1]; + if (!byte.TryParse(versionStr, out var version)) { - var versionStr = _args[i + 1]; - if (!byte.TryParse(versionStr, out var version)) - { - Debug.WriteLine($"Version must be a byte (0-255)."); - } - else - { - _registry.Resolve() - .VersionBuild = version; - } - - i++; + Debug.WriteLine($"Version must be a byte (0-255)."); } - else if (string.Equals(arg, "--account_delay_ms") && i < _args.Length - 1) + else { - var accountCreateTimeStr = _args[i + 1]; - if (!int.TryParse(accountCreateTimeStr, out var accountCreateTime) || accountCreateTime < 2000) - { - Debug.WriteLine($"Account create timeout must be greater than or equal to 2000ms."); - } - else - { - _registry.Resolve() - .AccountCreateTimeout = TimeSpan.FromMilliseconds(accountCreateTime); - } - - i++; + _registry.Resolve() + .VersionBuild = version; } - else if (string.Equals(arg, "--debug")) + + i++; + } + else if (string.Equals(arg, "--account_delay_ms") && i < _args.Length - 1) + { + var accountCreateTimeStr = _args[i + 1]; + if (!int.TryParse(accountCreateTimeStr, out var accountCreateTime) || accountCreateTime < 2000) { - _registry.Resolve().DebugCrashes = true; + Debug.WriteLine($"Account create timeout must be greater than or equal to 2000ms."); } else { - Debug.WriteLine($"Unrecognized argument: {arg}. Will be ignored."); + _registry.Resolve() + .AccountCreateTimeout = TimeSpan.FromMilliseconds(accountCreateTime); } - } - return true; + i++; + } + else if (string.Equals(arg, "--debug")) + { + _registry.Resolve().DebugCrashes = true; + } + else + { + Debug.WriteLine($"Unrecognized argument: {arg}. Will be ignored."); + } } - private void ShowErrorMessage(string message, string caption) - { + return true; + } + + private void ShowErrorMessage(string message, string caption) + { #if !LINUX && !OSX - MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); #else - Console.WriteLine(message); + Console.WriteLine(message); #endif - } + } - public virtual void RunGame() - { - var game = _registry.Resolve(); - game.Run(); - } + public virtual void RunGame() + { + var game = _registry.Resolve(); + game.Run(); } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/GameStateActions.cs b/EndlessClient/GameExecution/GameStateActions.cs index 2673b7105..0175db872 100644 --- a/EndlessClient/GameExecution/GameStateActions.cs +++ b/EndlessClient/GameExecution/GameStateActions.cs @@ -14,149 +14,148 @@ using System.Linq; using XNAControls.Input; -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +[MappedType(BaseType = typeof(IGameStateActions))] +public class GameStateActions : IGameStateActions { - [MappedType(BaseType = typeof(IGameStateActions))] - public class GameStateActions : IGameStateActions + private readonly IGameStateRepository _gameStateRepository; + private readonly IControlSetRepository _controlSetRepository; + private readonly IControlSetFactory _controlSetFactory; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IPlayerInfoRepository _playerInfoRepository; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IMfxPlayer _mfxPlayer; + + public GameStateActions(IGameStateRepository gameStateRepository, + IControlSetRepository controlSetRepository, + IControlSetFactory controlSetFactory, + IEndlessGameProvider endlessGameProvider, + IPlayerInfoRepository playerInfoRepository, + IClientWindowSizeProvider clientWindowSizeProvider, + ISfxPlayer sfxPlayer, + IMfxPlayer mfxPlayer) { - private readonly IGameStateRepository _gameStateRepository; - private readonly IControlSetRepository _controlSetRepository; - private readonly IControlSetFactory _controlSetFactory; - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IPlayerInfoRepository _playerInfoRepository; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IMfxPlayer _mfxPlayer; - - public GameStateActions(IGameStateRepository gameStateRepository, - IControlSetRepository controlSetRepository, - IControlSetFactory controlSetFactory, - IEndlessGameProvider endlessGameProvider, - IPlayerInfoRepository playerInfoRepository, - IClientWindowSizeProvider clientWindowSizeProvider, - ISfxPlayer sfxPlayer, - IMfxPlayer mfxPlayer) - { - _gameStateRepository = gameStateRepository; - _controlSetRepository = controlSetRepository; - _controlSetFactory = controlSetFactory; - _endlessGameProvider = endlessGameProvider; - _playerInfoRepository = playerInfoRepository; - _clientWindowSizeProvider = clientWindowSizeProvider; - _sfxPlayer = sfxPlayer; - _mfxPlayer = mfxPlayer; - } + _gameStateRepository = gameStateRepository; + _controlSetRepository = controlSetRepository; + _controlSetFactory = controlSetFactory; + _endlessGameProvider = endlessGameProvider; + _playerInfoRepository = playerInfoRepository; + _clientWindowSizeProvider = clientWindowSizeProvider; + _sfxPlayer = sfxPlayer; + _mfxPlayer = mfxPlayer; + } - public void ChangeToState(GameStates newState) - { - if (newState == _gameStateRepository.CurrentState) - return; - - if (_gameStateRepository.CurrentState == GameStates.PlayingTheGame) - { - _playerInfoRepository.PlayerIsInGame = false; - - StorePanelLayout(Game, EventArgs.Empty); - Game.Exiting -= StorePanelLayout; - } - - var currentSet = _controlSetRepository.CurrentControlSet; - var nextSet = _controlSetFactory.CreateControlsForState(newState, currentSet); - - RemoveOldComponents(currentSet, nextSet); - AddNewComponents(nextSet); - - _gameStateRepository.CurrentState = newState; - _controlSetRepository.CurrentControlSet = nextSet; - - switch (_gameStateRepository.CurrentState) - { - case GameStates.None: - case GameStates.Initial: - { - _sfxPlayer.StopLoopingSfx(); - - // this replicates behavior of the vanilla client where returning to the main menu stops playing the background music - _mfxPlayer.StopBackgroundMusic(); - } - break; - case GameStates.LoggedIn: _sfxPlayer.PlaySfx(SoundEffectID.Login); break; - case GameStates.PlayingTheGame: - { - Game.Exiting += StorePanelLayout; - } - break; - } - } + public void ChangeToState(GameStates newState) + { + if (newState == _gameStateRepository.CurrentState) + return; - public void RefreshCurrentState() + if (_gameStateRepository.CurrentState == GameStates.PlayingTheGame) { - var currentSet = _controlSetRepository.CurrentControlSet; - var emptySet = new EmptyControlSet(); + _playerInfoRepository.PlayerIsInGame = false; - RemoveOldComponents(currentSet, emptySet); - var refreshedSet = _controlSetFactory.CreateControlsForState(currentSet.GameState, emptySet); - AddNewComponents(refreshedSet); - _controlSetRepository.CurrentControlSet = refreshedSet; + StorePanelLayout(Game, EventArgs.Empty); + Game.Exiting -= StorePanelLayout; } - public void ExitGame() - { - Game.Exit(); - } + var currentSet = _controlSetRepository.CurrentControlSet; + var nextSet = _controlSetFactory.CreateControlsForState(newState, currentSet); - private void AddNewComponents(IControlSet nextSet) + RemoveOldComponents(currentSet, nextSet); + AddNewComponents(nextSet); + + _gameStateRepository.CurrentState = newState; + _controlSetRepository.CurrentControlSet = nextSet; + + switch (_gameStateRepository.CurrentState) { - foreach (var component in nextSet.AllComponents.Except(nextSet.XNAControlComponents)) - if (!Game.Components.Contains(component)) - Game.Components.Add(component); + case GameStates.None: + case GameStates.Initial: + { + _sfxPlayer.StopLoopingSfx(); + + // this replicates behavior of the vanilla client where returning to the main menu stops playing the background music + _mfxPlayer.StopBackgroundMusic(); + } + break; + case GameStates.LoggedIn: _sfxPlayer.PlaySfx(SoundEffectID.Login); break; + case GameStates.PlayingTheGame: + { + Game.Exiting += StorePanelLayout; + } + break; } + } - private void RemoveOldComponents(IControlSet currentSet, IControlSet nextSet) - { - var componentsToRemove = FindUnusedComponents(currentSet, nextSet); - var disposableComponents = componentsToRemove - .Where(x => x is not PacketHandlerGameComponent && x is not InputManager && x is not DispatcherGameComponent) - .OfType(); + public void RefreshCurrentState() + { + var currentSet = _controlSetRepository.CurrentControlSet; + var emptySet = new EmptyControlSet(); - foreach (var component in disposableComponents) - component.Dispose(); - foreach (var component in componentsToRemove.Where(Game.Components.Contains)) - Game.Components.Remove(component); + RemoveOldComponents(currentSet, emptySet); + var refreshedSet = _controlSetFactory.CreateControlsForState(currentSet.GameState, emptySet); + AddNewComponents(refreshedSet); + _controlSetRepository.CurrentControlSet = refreshedSet; + } - currentSet.Dispose(); - } + public void ExitGame() + { + Game.Exit(); + } - private List FindUnusedComponents(IControlSet current, IControlSet next) - { - return current.AllComponents - .Where(component => !next.AllComponents.Contains(component)) - .ToList(); - } + private void AddNewComponents(IControlSet nextSet) + { + foreach (var component in nextSet.AllComponents.Except(nextSet.XNAControlComponents)) + if (!Game.Components.Contains(component)) + Game.Components.Add(component); + } - private void StorePanelLayout(object sender, EventArgs e) - { - if (!_clientWindowSizeProvider.Resizable) return; + private void RemoveOldComponents(IControlSet currentSet, IControlSet nextSet) + { + var componentsToRemove = FindUnusedComponents(currentSet, nextSet); + var disposableComponents = componentsToRemove + .Where(x => x is not PacketHandlerGameComponent && x is not InputManager && x is not DispatcherGameComponent) + .OfType(); + + foreach (var component in disposableComponents) + component.Dispose(); + foreach (var component in componentsToRemove.Where(Game.Components.Contains)) + Game.Components.Remove(component); - var panelConfig = new IniReader(Constants.PanelLayoutFile); - panelConfig.Sections["PANELS"] = new SortedList(); + currentSet.Dispose(); + } + + private List FindUnusedComponents(IControlSet current, IControlSet next) + { + return current.AllComponents + .Where(component => !next.AllComponents.Contains(component)) + .ToList(); + } - var panels = _controlSetRepository.CurrentControlSet.AllComponents.OfType(); - foreach (var panel in panels) - { - panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:X"] = ((int)panel.DrawPositionWithParentOffset.X).ToString(); - panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:Y"] = ((int)panel.DrawPositionWithParentOffset.Y).ToString(); - panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:Visible"] = panel.Visible.ToString(); - panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:DrawOrder"] = panel.DrawOrder.ToString(); - } + private void StorePanelLayout(object sender, EventArgs e) + { + if (!_clientWindowSizeProvider.Resizable) return; - panelConfig.Sections["DISPLAY"] = new SortedList(); - panelConfig.Sections["DISPLAY"]["Width"] = _clientWindowSizeProvider.Width.ToString(); - panelConfig.Sections["DISPLAY"]["Height"] = _clientWindowSizeProvider.Height.ToString(); + var panelConfig = new IniReader(Constants.PanelLayoutFile); + panelConfig.Sections["PANELS"] = new SortedList(); - panelConfig.Save(); + var panels = _controlSetRepository.CurrentControlSet.AllComponents.OfType(); + foreach (var panel in panels) + { + panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:X"] = ((int)panel.DrawPositionWithParentOffset.X).ToString(); + panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:Y"] = ((int)panel.DrawPositionWithParentOffset.Y).ToString(); + panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:Visible"] = panel.Visible.ToString(); + panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:DrawOrder"] = panel.DrawOrder.ToString(); } - private IEndlessGame Game => _endlessGameProvider.Game; + panelConfig.Sections["DISPLAY"] = new SortedList(); + panelConfig.Sections["DISPLAY"]["Width"] = _clientWindowSizeProvider.Width.ToString(); + panelConfig.Sections["DISPLAY"]["Height"] = _clientWindowSizeProvider.Height.ToString(); + + panelConfig.Save(); } + + private IEndlessGame Game => _endlessGameProvider.Game; } \ No newline at end of file diff --git a/EndlessClient/GameExecution/GameStates.cs b/EndlessClient/GameExecution/GameStates.cs index c73fd08df..a2e4ad5c6 100644 --- a/EndlessClient/GameExecution/GameStates.cs +++ b/EndlessClient/GameExecution/GameStates.cs @@ -1,41 +1,40 @@ -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +/// +/// Game states +/// +public enum GameStates { /// - /// Game states - /// - public enum GameStates - { - /// - /// Represents an noninitialized state (during game initialization) - /// - None, - /// - /// Initial State when game is launched - /// - Initial, - /// - /// State when an account is being created - /// - CreateAccount, - /// - /// State when Login button is clicked, but account is not yet authenticated - /// - Login, - /// - /// Account is authenticated. Show available characters for account - /// - LoggedIn, - /// - /// Roll credits... - /// - ViewCredits, - /// - /// In game - /// - PlayingTheGame, - /// - /// Test mode - for testing different character render states - /// - TestMode - } + /// Represents an noninitialized state (during game initialization) + /// + None, + /// + /// Initial State when game is launched + /// + Initial, + /// + /// State when an account is being created + /// + CreateAccount, + /// + /// State when Login button is clicked, but account is not yet authenticated + /// + Login, + /// + /// Account is authenticated. Show available characters for account + /// + LoggedIn, + /// + /// Roll credits... + /// + ViewCredits, + /// + /// In game + /// + PlayingTheGame, + /// + /// Test mode - for testing different character render states + /// + TestMode } \ No newline at end of file diff --git a/EndlessClient/GameExecution/IEndlessGame.cs b/EndlessClient/GameExecution/IEndlessGame.cs index d9066581d..f3af9b0ee 100644 --- a/EndlessClient/GameExecution/IEndlessGame.cs +++ b/EndlessClient/GameExecution/IEndlessGame.cs @@ -2,22 +2,21 @@ using Microsoft.Xna.Framework.Content; using System; -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +public interface IEndlessGame : IDisposable { - public interface IEndlessGame : IDisposable - { - event EventHandler Exiting; + event EventHandler Exiting; - GameComponentCollection Components { get; } + GameComponentCollection Components { get; } - ContentManager Content { get; } + ContentManager Content { get; } - GameWindow Window { get; } + GameWindow Window { get; } - bool IsActive { get; } + bool IsActive { get; } - void Run(); + void Run(); - void Exit(); - } + void Exit(); } \ No newline at end of file diff --git a/EndlessClient/GameExecution/IEndlessGameProvider.cs b/EndlessClient/GameExecution/IEndlessGameProvider.cs index 5320faa60..e5cc34860 100644 --- a/EndlessClient/GameExecution/IEndlessGameProvider.cs +++ b/EndlessClient/GameExecution/IEndlessGameProvider.cs @@ -1,21 +1,20 @@ using AutomaticTypeMapper; -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +public interface IEndlessGameRepository { - public interface IEndlessGameRepository - { - IEndlessGame Game { get; set; } - } + IEndlessGame Game { get; set; } +} - public interface IEndlessGameProvider - { - IEndlessGame Game { get; } - } +public interface IEndlessGameProvider +{ + IEndlessGame Game { get; } +} - [MappedType(BaseType = typeof(IEndlessGameRepository), IsSingleton = true)] - [MappedType(BaseType = typeof(IEndlessGameProvider), IsSingleton = true)] - public class EndlessGameRepository : IEndlessGameRepository, IEndlessGameProvider - { - public IEndlessGame Game { get; set; } - } +[MappedType(BaseType = typeof(IEndlessGameRepository), IsSingleton = true)] +[MappedType(BaseType = typeof(IEndlessGameProvider), IsSingleton = true)] +public class EndlessGameRepository : IEndlessGameRepository, IEndlessGameProvider +{ + public IEndlessGame Game { get; set; } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/IGameRunner.cs b/EndlessClient/GameExecution/IGameRunner.cs index 48347f597..6d020b636 100644 --- a/EndlessClient/GameExecution/IGameRunner.cs +++ b/EndlessClient/GameExecution/IGameRunner.cs @@ -1,9 +1,8 @@ -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +public interface IGameRunner { - public interface IGameRunner - { - bool SetupDependencies(); + bool SetupDependencies(); - void RunGame(); - } + void RunGame(); } \ No newline at end of file diff --git a/EndlessClient/GameExecution/IGameStateActions.cs b/EndlessClient/GameExecution/IGameStateActions.cs index cf109642b..37fbdf4dc 100644 --- a/EndlessClient/GameExecution/IGameStateActions.cs +++ b/EndlessClient/GameExecution/IGameStateActions.cs @@ -1,11 +1,10 @@ -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +public interface IGameStateActions { - public interface IGameStateActions - { - void ChangeToState(GameStates newState); + void ChangeToState(GameStates newState); - void RefreshCurrentState(); + void RefreshCurrentState(); - void ExitGame(); - } + void ExitGame(); } \ No newline at end of file diff --git a/EndlessClient/GameExecution/IGameStateRepository.cs b/EndlessClient/GameExecution/IGameStateRepository.cs index 288123615..e37dd0434 100644 --- a/EndlessClient/GameExecution/IGameStateRepository.cs +++ b/EndlessClient/GameExecution/IGameStateRepository.cs @@ -1,21 +1,20 @@ using AutomaticTypeMapper; -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +public interface IGameStateRepository { - public interface IGameStateRepository - { - GameStates CurrentState { get; set; } - } + GameStates CurrentState { get; set; } +} - public interface IGameStateProvider - { - GameStates CurrentState { get; } - } +public interface IGameStateProvider +{ + GameStates CurrentState { get; } +} - [MappedType(BaseType = typeof(IGameStateProvider), IsSingleton = true)] - [MappedType(BaseType = typeof(IGameStateRepository), IsSingleton = true)] - public class GameStateRepository : IGameStateRepository, IGameStateProvider - { - public GameStates CurrentState { get; set; } - } +[MappedType(BaseType = typeof(IGameStateProvider), IsSingleton = true)] +[MappedType(BaseType = typeof(IGameStateRepository), IsSingleton = true)] +public class GameStateRepository : IGameStateRepository, IGameStateProvider +{ + public GameStates CurrentState { get; set; } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/ReleaseGameRunner.cs b/EndlessClient/GameExecution/ReleaseGameRunner.cs index a03d47224..e1702b853 100644 --- a/EndlessClient/GameExecution/ReleaseGameRunner.cs +++ b/EndlessClient/GameExecution/ReleaseGameRunner.cs @@ -7,108 +7,107 @@ using System.Windows.Forms; #endif -namespace EndlessClient.GameExecution +namespace EndlessClient.GameExecution; + +/// +/// A game runner that catches exceptions and display exception information +/// +public class ReleaseGameRunner : GameRunnerBase { - /// - /// A game runner that catches exceptions and display exception information - /// - public class ReleaseGameRunner : GameRunnerBase - { - public ReleaseGameRunner(ITypeRegistry registry, string[] args) - : base(registry, args) { } + public ReleaseGameRunner(ITypeRegistry registry, string[] args) + : base(registry, args) { } - public override bool SetupDependencies() + public override bool SetupDependencies() + { + try + { + return base.SetupDependencies(); + } + catch (Exception ex) { - try - { - return base.SetupDependencies(); - } - catch (Exception ex) - { - if (OperatingSystem.IsWindows()) - ShowExceptionDialog(ex); - else - Console.WriteLine($"Exception thrown during dependency setup: {ex.Message}\n\n{ex.StackTrace}"); + if (OperatingSystem.IsWindows()) + ShowExceptionDialog(ex); + else + Console.WriteLine($"Exception thrown during dependency setup: {ex.Message}\n\n{ex.StackTrace}"); - return false; - } + return false; } + } - public override void RunGame() + public override void RunGame() + { + try { - try - { - base.RunGame(); - } - catch (Exception ex) - { - if (OperatingSystem.IsWindows()) - ShowExceptionDialog(ex); - else - Console.WriteLine($"Exception thrown during game execution: {ex.Message}\n\n{ex.StackTrace}"); - } + base.RunGame(); } - - [SupportedOSPlatform("Windows")] - private static void ShowExceptionDialog(Exception ex) + catch (Exception ex) { + if (OperatingSystem.IsWindows()) + ShowExceptionDialog(ex); + else + Console.WriteLine($"Exception thrown during game execution: {ex.Message}\n\n{ex.StackTrace}"); + } + } + + [SupportedOSPlatform("Windows")] + private static void ShowExceptionDialog(Exception ex) + { #if !LINUX && !OSX - Application.EnableVisualStyles(); + Application.EnableVisualStyles(); - var exForm = new Form - { - Width = 350, - Height = 200, - MaximizeBox = false, - MinimizeBox = false, - Padding = new Padding(10), - Text = "Application Error", - BackColor = System.Drawing.Color.White, - Icon = System.Drawing.SystemIcons.Error, - StartPosition = FormStartPosition.CenterScreen, - MinimumSize = new System.Drawing.Size(350, 200) - }; - exForm.FormClosed += (sender, e) => Environment.Exit(1); + var exForm = new Form + { + Width = 350, + Height = 200, + MaximizeBox = false, + MinimizeBox = false, + Padding = new Padding(10), + Text = "Application Error", + BackColor = System.Drawing.Color.White, + Icon = System.Drawing.SystemIcons.Error, + StartPosition = FormStartPosition.CenterScreen, + MinimumSize = new System.Drawing.Size(350, 200) + }; + exForm.FormClosed += (sender, e) => Environment.Exit(1); - var exLabel1 = new Label - { - AutoEllipsis = true, - Dock = DockStyle.Top, - Font = new System.Drawing.Font(Control.DefaultFont, System.Drawing.FontStyle.Bold), - Text = "An unhandled exception has caused the game to crash:" - }; + var exLabel1 = new Label + { + AutoEllipsis = true, + Dock = DockStyle.Top, + Font = new System.Drawing.Font(Control.DefaultFont, System.Drawing.FontStyle.Bold), + Text = "An unhandled exception has caused the game to crash:" + }; - var exLabel2 = new Label - { - AutoEllipsis = true, - Dock = DockStyle.Top, - Padding = new Padding(5, 0, 0, 0), - Text = ex.Message - }; + var exLabel2 = new Label + { + AutoEllipsis = true, + Dock = DockStyle.Top, + Padding = new Padding(5, 0, 0, 0), + Text = ex.Message + }; - var exLabel3 = new Label - { - AutoEllipsis = true, - Dock = DockStyle.Top, - Font = new System.Drawing.Font(Control.DefaultFont, System.Drawing.FontStyle.Bold), - Text = "Stack trace:" - }; + var exLabel3 = new Label + { + AutoEllipsis = true, + Dock = DockStyle.Top, + Font = new System.Drawing.Font(Control.DefaultFont, System.Drawing.FontStyle.Bold), + Text = "Stack trace:" + }; - var exTextBox1 = new TextBox - { - Dock = DockStyle.Fill, - Multiline = true, - ReadOnly = true, - ScrollBars = ScrollBars.Vertical, - Text = ex.StackTrace - }; + var exTextBox1 = new TextBox + { + Dock = DockStyle.Fill, + Multiline = true, + ReadOnly = true, + ScrollBars = ScrollBars.Vertical, + Text = ex.StackTrace + }; - exForm.Controls.Add(exTextBox1); - exForm.Controls.Add(exLabel3); - exForm.Controls.Add(exLabel2); - exForm.Controls.Add(exLabel1); - exForm.ShowDialog(); + exForm.Controls.Add(exTextBox1); + exForm.Controls.Add(exLabel3); + exForm.Controls.Add(exLabel2); + exForm.Controls.Add(exLabel1); + exForm.ShowDialog(); #endif - } } } \ No newline at end of file diff --git a/EndlessClient/HUD/AStarPathFinder.cs b/EndlessClient/HUD/AStarPathFinder.cs index c3902916c..99a214a14 100644 --- a/EndlessClient/HUD/AStarPathFinder.cs +++ b/EndlessClient/HUD/AStarPathFinder.cs @@ -5,107 +5,106 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +// Implemented from https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode +[AutoMappedType] +public class AStarPathFinder : IPathFinder { - // Implemented from https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode - [AutoMappedType] - public class AStarPathFinder : IPathFinder + private readonly IWalkValidationActions _walkValidationActions; + + public AStarPathFinder(IWalkValidationActions walkValidationActions) { - private readonly IWalkValidationActions _walkValidationActions; + _walkValidationActions = walkValidationActions; + } - public AStarPathFinder(IWalkValidationActions walkValidationActions) - { - _walkValidationActions = walkValidationActions; - } + public Queue FindPath(MapCoordinate start, MapCoordinate finish) + { + var openSet = new HashSet(new[] { start }); + var cameFrom = new Dictionary(); - public Queue FindPath(MapCoordinate start, MapCoordinate finish) + var scores = new Dictionary { - var openSet = new HashSet(new[] { start }); - var cameFrom = new Dictionary(); - - var scores = new Dictionary - { - { start, 0 } - }; + { start, 0 } + }; - var guessScores = new Dictionary - { - { start, heuristic(start, finish) } - }; + var guessScores = new Dictionary + { + { start, heuristic(start, finish) } + }; - while (openSet.Any()) + while (openSet.Any()) + { + MapCoordinate current = new MapCoordinate(0, 0); + var lowest = int.MaxValue; + foreach (var n in openSet) { - MapCoordinate current = new MapCoordinate(0, 0); - var lowest = int.MaxValue; - foreach (var n in openSet) + if (guessScores[n] < lowest) { - if (guessScores[n] < lowest) - { - current = n; - lowest = guessScores[n]; - } + current = n; + lowest = guessScores[n]; } + } - if (current.Equals(finish)) - return reconstructPath(start, cameFrom, current); + if (current.Equals(finish)) + return reconstructPath(start, cameFrom, current); - openSet.Remove(current); - foreach (var neighbor in getNeighbors(current)) + openSet.Remove(current); + foreach (var neighbor in getNeighbors(current)) + { + var tentativeScore = scores[current] + 1; + if (!scores.TryGetValue(neighbor, out var _)) + scores.Add(neighbor, int.MaxValue); + + if (tentativeScore < scores[neighbor]) { - var tentativeScore = scores[current] + 1; - if (!scores.TryGetValue(neighbor, out var _)) - scores.Add(neighbor, int.MaxValue); - - if (tentativeScore < scores[neighbor]) - { - cameFrom[neighbor] = current; - scores[neighbor] = tentativeScore; - guessScores[neighbor] = tentativeScore + heuristic(neighbor, finish); - - if (!openSet.Contains(neighbor)) - openSet.Add(neighbor); - } + cameFrom[neighbor] = current; + scores[neighbor] = tentativeScore; + guessScores[neighbor] = tentativeScore + heuristic(neighbor, finish); + + if (!openSet.Contains(neighbor)) + openSet.Add(neighbor); } } - - return new Queue(); } - private static int heuristic(MapCoordinate current, MapCoordinate goal) - => Math.Abs(current.X - goal.X) + Math.Abs(current.Y - goal.Y); + return new Queue(); + } + + private static int heuristic(MapCoordinate current, MapCoordinate goal) + => Math.Abs(current.X - goal.X) + Math.Abs(current.Y - goal.Y); - private Queue reconstructPath(MapCoordinate start, Dictionary cameFrom, MapCoordinate current) + private Queue reconstructPath(MapCoordinate start, Dictionary cameFrom, MapCoordinate current) + { + var retList = new List { current }; + while (cameFrom.ContainsKey(current)) { - var retList = new List { current }; - while (cameFrom.ContainsKey(current)) - { - current = cameFrom[current]; - if (current != start) - retList.Insert(0, current); - } - return new Queue(retList); + current = cameFrom[current]; + if (current != start) + retList.Insert(0, current); } + return new Queue(retList); + } - private IEnumerable getNeighbors(MapCoordinate current) + private IEnumerable getNeighbors(MapCoordinate current) + { + var points = new MapCoordinate[] { - var points = new MapCoordinate[] - { - new MapCoordinate(-1, 0), - new MapCoordinate(1, 0), - new MapCoordinate(0, -1), - new MapCoordinate(0, 1) - }; + new MapCoordinate(-1, 0), + new MapCoordinate(1, 0), + new MapCoordinate(0, -1), + new MapCoordinate(0, 1) + }; - foreach (var coordinateOffset in points) - { - if (_walkValidationActions.CanMoveToCoordinates(current.X + coordinateOffset.X, current.Y + coordinateOffset.Y) == WalkValidationResult.Walkable) - yield return new MapCoordinate(current.X + coordinateOffset.X, current.Y + coordinateOffset.Y); - } + foreach (var coordinateOffset in points) + { + if (_walkValidationActions.CanMoveToCoordinates(current.X + coordinateOffset.X, current.Y + coordinateOffset.Y) == WalkValidationResult.Walkable) + yield return new MapCoordinate(current.X + coordinateOffset.X, current.Y + coordinateOffset.Y); } } +} - public interface IPathFinder - { - Queue FindPath(MapCoordinate start, MapCoordinate finish); - } +public interface IPathFinder +{ + Queue FindPath(MapCoordinate start, MapCoordinate finish); } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatBubbleActions.cs b/EndlessClient/HUD/Chat/ChatBubbleActions.cs index 2bfa991a7..dcdd6eaa6 100644 --- a/EndlessClient/HUD/Chat/ChatBubbleActions.cs +++ b/EndlessClient/HUD/Chat/ChatBubbleActions.cs @@ -7,48 +7,47 @@ using Optional; using System.Linq; -namespace EndlessClient.HUD.Chat -{ - [AutoMappedType] - public class ChatBubbleActions : IChatBubbleActions - { - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly INPCRendererProvider _npcRendererProvider; - private readonly IPartyDataProvider _partyDataProvider; - - public ChatBubbleActions(ICharacterRendererProvider characterRendererProvider, - INPCRendererProvider npcRendererProvider, - IPartyDataProvider partyDataProvider) - { - _characterRendererProvider = characterRendererProvider; - _npcRendererProvider = npcRendererProvider; - _partyDataProvider = partyDataProvider; - } +namespace EndlessClient.HUD.Chat; - public void ShowChatBubbleForMainCharacter(string text, bool isPartyChat = false) - { - _characterRendererProvider.MainCharacterRenderer.MatchSome(r => - { - if (!_partyDataProvider.Members.Any() && isPartyChat) - return; +[AutoMappedType] +public class ChatBubbleActions : IChatBubbleActions +{ + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly INPCRendererProvider _npcRendererProvider; + private readonly IPartyDataProvider _partyDataProvider; - r.ShowChatBubble(text, isPartyChat); - }); - } + public ChatBubbleActions(ICharacterRendererProvider characterRendererProvider, + INPCRendererProvider npcRendererProvider, + IPartyDataProvider partyDataProvider) + { + _characterRendererProvider = characterRendererProvider; + _npcRendererProvider = npcRendererProvider; + _partyDataProvider = partyDataProvider; + } - public void ShowChatBubbleForNPC(int index, string input) + public void ShowChatBubbleForMainCharacter(string text, bool isPartyChat = false) + { + _characterRendererProvider.MainCharacterRenderer.MatchSome(r => { - if (!_npcRendererProvider.NPCRenderers.ContainsKey(index)) + if (!_partyDataProvider.Members.Any() && isPartyChat) return; - _npcRendererProvider.NPCRenderers[index].ShowChatBubble(input); - } + r.ShowChatBubble(text, isPartyChat); + }); } - public interface IChatBubbleActions + public void ShowChatBubbleForNPC(int index, string input) { - void ShowChatBubbleForMainCharacter(string input, bool isPartyChat = false); + if (!_npcRendererProvider.NPCRenderers.ContainsKey(index)) + return; - void ShowChatBubbleForNPC(int index, string input); + _npcRendererProvider.NPCRenderers[index].ShowChatBubble(input); } +} + +public interface IChatBubbleActions +{ + void ShowChatBubbleForMainCharacter(string input, bool isPartyChat = false); + + void ShowChatBubbleForNPC(int index, string input); } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatModeCalculator.cs b/EndlessClient/HUD/Chat/ChatModeCalculator.cs index 39dde4b17..f71759509 100644 --- a/EndlessClient/HUD/Chat/ChatModeCalculator.cs +++ b/EndlessClient/HUD/Chat/ChatModeCalculator.cs @@ -3,40 +3,39 @@ using EOLib.Domain.Character; using Moffat.EndlessOnline.SDK.Protocol; -namespace EndlessClient.HUD.Chat +namespace EndlessClient.HUD.Chat; + +[MappedType(BaseType = typeof(IChatModeCalculator))] +public class ChatModeCalculator : IChatModeCalculator { - [MappedType(BaseType = typeof(IChatModeCalculator))] - public class ChatModeCalculator : IChatModeCalculator - { - private readonly ICharacterProvider _characterProvider; + private readonly ICharacterProvider _characterProvider; - public ChatModeCalculator(ICharacterProvider characterProvider) - { - _characterProvider = characterProvider; - } + public ChatModeCalculator(ICharacterProvider characterProvider) + { + _characterProvider = characterProvider; + } - public ChatModePictureBox.ChatMode CalculateMode(string fullTextString) - { - if (string.IsNullOrEmpty(fullTextString)) - return ChatModePictureBox.ChatMode.NoText; + public ChatModePictureBox.ChatMode CalculateMode(string fullTextString) + { + if (string.IsNullOrEmpty(fullTextString)) + return ChatModePictureBox.ChatMode.NoText; - var playerIsAdmin = _characterProvider.MainCharacter.AdminLevel != AdminLevel.Player; - var playerIsInGuild = !string.IsNullOrEmpty(_characterProvider.MainCharacter.GuildName); + var playerIsAdmin = _characterProvider.MainCharacter.AdminLevel != AdminLevel.Player; + var playerIsInGuild = !string.IsNullOrEmpty(_characterProvider.MainCharacter.GuildName); - if (((fullTextString[0] == '@' || fullTextString[0] == '+') && !playerIsAdmin) || - (fullTextString[0] == '&' && !playerIsInGuild)) - return ChatModePictureBox.ChatMode.Public; + if (((fullTextString[0] == '@' || fullTextString[0] == '+') && !playerIsAdmin) || + (fullTextString[0] == '&' && !playerIsInGuild)) + return ChatModePictureBox.ChatMode.Public; - switch (fullTextString[0]) - { - case '!': return ChatModePictureBox.ChatMode.Private; - case '@': - case '~': return ChatModePictureBox.ChatMode.Global; - case '+': return ChatModePictureBox.ChatMode.Admin; - case '\'': return ChatModePictureBox.ChatMode.Group; - case '&': return ChatModePictureBox.ChatMode.Guild; - default: return ChatModePictureBox.ChatMode.Public; - } + switch (fullTextString[0]) + { + case '!': return ChatModePictureBox.ChatMode.Private; + case '@': + case '~': return ChatModePictureBox.ChatMode.Global; + case '+': return ChatModePictureBox.ChatMode.Admin; + case '\'': return ChatModePictureBox.ChatMode.Group; + case '&': return ChatModePictureBox.ChatMode.Guild; + default: return ChatModePictureBox.ChatMode.Public; } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatNotificationActions.cs b/EndlessClient/HUD/Chat/ChatNotificationActions.cs index ab8d4d06b..b719b3d1b 100644 --- a/EndlessClient/HUD/Chat/ChatNotificationActions.cs +++ b/EndlessClient/HUD/Chat/ChatNotificationActions.cs @@ -13,99 +13,98 @@ using System.Globalization; using System.Windows; -namespace EndlessClient.HUD.Chat +namespace EndlessClient.HUD.Chat; + +[AutoMappedType] +public class ChatNotificationActions : IChatEventNotifier { - [AutoMappedType] - public class ChatNotificationActions : IChatEventNotifier + private readonly IChatRepository _chatRepository; + private readonly IHudControlProvider _hudControlProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IServerMessageHandler _serverMessageHandler; + private readonly ISfxPlayer _sfxPlayer; + + public ChatNotificationActions(IChatRepository chatRepository, + IHudControlProvider hudControlProvider, + ILocalizedStringFinder localizedStringFinder, + IStatusLabelSetter statusLabelSetter, + IServerMessageHandler serverMessageHandler, + ISfxPlayer sfxPlayer) { - private readonly IChatRepository _chatRepository; - private readonly IHudControlProvider _hudControlProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IServerMessageHandler _serverMessageHandler; - private readonly ISfxPlayer _sfxPlayer; + _chatRepository = chatRepository; + _hudControlProvider = hudControlProvider; + _localizedStringFinder = localizedStringFinder; + _statusLabelSetter = statusLabelSetter; + _serverMessageHandler = serverMessageHandler; + _sfxPlayer = sfxPlayer; + } - public ChatNotificationActions(IChatRepository chatRepository, - IHudControlProvider hudControlProvider, - ILocalizedStringFinder localizedStringFinder, - IStatusLabelSetter statusLabelSetter, - IServerMessageHandler serverMessageHandler, - ISfxPlayer sfxPlayer) + public void NotifyChatReceived(ChatEventType eventType) + { + _sfxPlayer.PlaySfx(eventType switch { - _chatRepository = chatRepository; - _hudControlProvider = hudControlProvider; - _localizedStringFinder = localizedStringFinder; - _statusLabelSetter = statusLabelSetter; - _serverMessageHandler = serverMessageHandler; - _sfxPlayer = sfxPlayer; - } + ChatEventType.PrivateMessage => SoundEffectID.PrivateMessageReceived, + ChatEventType.AdminChat => SoundEffectID.AdminChatReceived, + ChatEventType.AdminAnnounce => SoundEffectID.AdminAnnounceReceived, + ChatEventType.Group => SoundEffectID.GroupChatReceived, + _ => SoundEffectID.LayeredTechIntro, // this will be funny if it ever gets hit + }); + } - public void NotifyChatReceived(ChatEventType eventType) - { - _sfxPlayer.PlaySfx(eventType switch - { - ChatEventType.PrivateMessage => SoundEffectID.PrivateMessageReceived, - ChatEventType.AdminChat => SoundEffectID.AdminChatReceived, - ChatEventType.AdminAnnounce => SoundEffectID.AdminAnnounceReceived, - ChatEventType.Group => SoundEffectID.GroupChatReceived, - _ => SoundEffectID.LayeredTechIntro, // this will be funny if it ever gets hit - }); - } + public void NotifyPrivateMessageRecipientNotFound(string recipientName) + { + var whichTab = _chatRepository.PMTarget1.ToLower() == recipientName.ToLower() + ? Option.Some(ChatTab.Private1) + : _chatRepository.PMTarget2.ToLower() == recipientName.ToLower() + ? Option.Some(ChatTab.Private2) + : Option.None(); - public void NotifyPrivateMessageRecipientNotFound(string recipientName) + whichTab.MatchSome(tab => { - var whichTab = _chatRepository.PMTarget1.ToLower() == recipientName.ToLower() - ? Option.Some(ChatTab.Private1) - : _chatRepository.PMTarget2.ToLower() == recipientName.ToLower() - ? Option.Some(ChatTab.Private2) - : Option.None(); + if (tab == ChatTab.Private1) + _chatRepository.PMTarget1 = null; + else if (tab == ChatTab.Private2) + _chatRepository.PMTarget2 = null; - whichTab.MatchSome(tab => - { - if (tab == ChatTab.Private1) - _chatRepository.PMTarget1 = null; - else if (tab == ChatTab.Private2) - _chatRepository.PMTarget2 = null; + _chatRepository.AllChat[tab].Clear(); - _chatRepository.AllChat[tab].Clear(); - - var chatPanel = _hudControlProvider.GetComponent(HudControlIdentifier.ChatPanel); - chatPanel.ClosePMTab(tab); - }); - } + var chatPanel = _hudControlProvider.GetComponent(HudControlIdentifier.ChatPanel); + chatPanel.ClosePMTab(tab); + }); + } - public void NotifyPlayerMutedByAdmin(string adminName) - { - var chatTextBox = _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); - var chatMode = _hudControlProvider.GetComponent(HudControlIdentifier.ChatModePictureBox); + public void NotifyPlayerMutedByAdmin(string adminName) + { + var chatTextBox = _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); + var chatMode = _hudControlProvider.GetComponent(HudControlIdentifier.ChatModePictureBox); - var endMuteTime = DateTime.Now.AddMinutes(Constants.MuteDefaultTimeMinutes); - chatTextBox.SetMuted(endMuteTime); - chatMode.SetMuted(endMuteTime); + var endMuteTime = DateTime.Now.AddMinutes(Constants.MuteDefaultTimeMinutes); + chatTextBox.SetMuted(endMuteTime); + chatMode.SetMuted(endMuteTime); - chatTextBox.Text = string.Empty; + chatTextBox.Text = string.Empty; - var chatData = new ChatData(ChatTab.Local, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), - _localizedStringFinder.GetString(EOResourceID.CHAT_MESSAGE_MUTED_BY) + " " + adminName, - ChatIcon.Exclamation, - ChatColor.Server); - _chatRepository.AllChat[ChatTab.Local].Add(chatData); + var chatData = new ChatData(ChatTab.Local, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), + _localizedStringFinder.GetString(EOResourceID.CHAT_MESSAGE_MUTED_BY) + " " + adminName, + ChatIcon.Exclamation, + ChatColor.Server); + _chatRepository.AllChat[ChatTab.Local].Add(chatData); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - Constants.MuteDefaultTimeMinutes.ToString(CultureInfo.InvariantCulture) + " ", - EOResourceID.STATUS_LABEL_MINUTES_MUTED); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + Constants.MuteDefaultTimeMinutes.ToString(CultureInfo.InvariantCulture) + " ", + EOResourceID.STATUS_LABEL_MINUTES_MUTED); + } - public void NotifyServerMessage(string serverMessage) - { - _serverMessageHandler.AddServerMessage(serverMessage); - } + public void NotifyServerMessage(string serverMessage) + { + _serverMessageHandler.AddServerMessage(serverMessage); + } - public void NotifyServerPing(int timeInMS) - { - var message = $"[x] Current ping to the server is: {timeInMS} ms."; - var chatData = new ChatData(ChatTab.Local, "System", message, ChatIcon.LookingDude); - _chatRepository.AllChat[ChatTab.Local].Add(chatData); - } + public void NotifyServerPing(int timeInMS) + { + var message = $"[x] Current ping to the server is: {timeInMS} ms."; + var chatData = new ChatData(ChatTab.Local, "System", message, ChatIcon.LookingDude); + _chatRepository.AllChat[ChatTab.Local].Add(chatData); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatPanelTab.cs b/EndlessClient/HUD/Chat/ChatPanelTab.cs index 382c57040..95473541f 100644 --- a/EndlessClient/HUD/Chat/ChatPanelTab.cs +++ b/EndlessClient/HUD/Chat/ChatPanelTab.cs @@ -16,232 +16,231 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Chat +namespace EndlessClient.HUD.Chat; + +public class ChatPanelTab : XNAControl { - public class ChatPanelTab : XNAControl - { - private readonly IChatProvider _chatProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly IChatRenderableGenerator _chatRenderableGenerator; + private readonly IChatProvider _chatProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly IChatRenderableGenerator _chatRenderableGenerator; - private readonly ChatPanel _parentPanel; - private readonly ScrollBar _scrollBar; - private readonly ISpriteSheet _tabSheetSelected, _tabSheetUnselected; - private readonly BitmapFont _chatFont; + private readonly ChatPanel _parentPanel; + private readonly ScrollBar _scrollBar; + private readonly ISpriteSheet _tabSheetSelected, _tabSheetUnselected; + private readonly BitmapFont _chatFont; - private readonly IXNAButton _closeButton, _tab; - private readonly IXNALabel _label; + private readonly IXNAButton _closeButton, _tab; + private readonly IXNALabel _label; - private bool _active; - private int _cachedScrollOffset; - private HashSet _cachedChat; - private List _renderables; - private bool _closeButtonClicked; + private bool _active; + private int _cachedScrollOffset; + private HashSet _cachedChat; + private List _renderables; + private bool _closeButtonClicked; - public ChatTab Tab { get; } + public ChatTab Tab { get; } - public string Text { get => _label.Text; set => _label.Text = value; } + public string Text { get => _label.Text; set => _label.Text = value; } - public bool Active + public bool Active + { + get => _active; + set { - get => _active; - set + if (_active = value) + { + _scrollBar.SetScrollOffset(_cachedScrollOffset); + _label.ForeColor = Color.White; + } + else { - if (_active = value) - { - _scrollBar.SetScrollOffset(_cachedScrollOffset); - _label.ForeColor = Color.White; - } - else - { - _cachedScrollOffset = _scrollBar.ScrollOffset; - _label.ForeColor = Color.Black; - } + _cachedScrollOffset = _scrollBar.ScrollOffset; + _label.ForeColor = Color.Black; } } + } - public event EventHandler OnClosed; - - public ChatPanelTab(IChatProvider chatProvider, - IHudControlProvider hudControlProvider, - IChatRenderableGenerator chatRenderableGenerator, - ChatPanel parentPanel, - ScrollBar scrollBar, - ChatTab whichTab, - ISpriteSheet tabSheetSelected, - ISpriteSheet tabSheetUnselected, - BitmapFont chatFont) - { - _chatProvider = chatProvider; - _hudControlProvider = hudControlProvider; - _chatRenderableGenerator = chatRenderableGenerator; + public event EventHandler OnClosed; + + public ChatPanelTab(IChatProvider chatProvider, + IHudControlProvider hudControlProvider, + IChatRenderableGenerator chatRenderableGenerator, + ChatPanel parentPanel, + ScrollBar scrollBar, + ChatTab whichTab, + ISpriteSheet tabSheetSelected, + ISpriteSheet tabSheetUnselected, + BitmapFont chatFont) + { + _chatProvider = chatProvider; + _hudControlProvider = hudControlProvider; + _chatRenderableGenerator = chatRenderableGenerator; - _parentPanel = parentPanel; - _scrollBar = scrollBar; - Tab = whichTab; - _tabSheetSelected = tabSheetSelected; - _tabSheetUnselected = tabSheetUnselected; - _chatFont = chatFont; + _parentPanel = parentPanel; + _scrollBar = scrollBar; + Tab = whichTab; + _tabSheetSelected = tabSheetSelected; + _tabSheetUnselected = tabSheetUnselected; + _chatFont = chatFont; - DrawArea = new Rectangle(0, 0, _parentPanel.DrawArea.Width, _parentPanel.DrawArea.Height); + DrawArea = new Rectangle(0, 0, _parentPanel.DrawArea.Width, _parentPanel.DrawArea.Height); - if (Tab == ChatTab.Private1) - { - _closeButton = new ClickableArea(new Rectangle(23, 102, 11, 11)); - _closeButton.OnClick += (_, _) => CloseTab(); - _closeButton.SetParentControl(this); - } - else if (Tab == ChatTab.Private2) - { - _closeButton = new ClickableArea(new Rectangle(156, 102, 11, 11)); - _closeButton.OnClick += (_, _) => CloseTab(); - _closeButton.SetParentControl(this); - } + if (Tab == ChatTab.Private1) + { + _closeButton = new ClickableArea(new Rectangle(23, 102, 11, 11)); + _closeButton.OnClick += (_, _) => CloseTab(); + _closeButton.SetParentControl(this); + } + else if (Tab == ChatTab.Private2) + { + _closeButton = new ClickableArea(new Rectangle(156, 102, 11, 11)); + _closeButton.OnClick += (_, _) => CloseTab(); + _closeButton.SetParentControl(this); + } - _tab = new ClickableArea(GetTabClickableArea()); - _tab.OnClick += (_, _) => SelectThisTab(); - _tab.SetParentControl(this); + _tab = new ClickableArea(GetTabClickableArea()); + _tab.OnClick += (_, _) => SelectThisTab(); + _tab.SetParentControl(this); - _label = new XNALabel(Constants.FontSize08) - { - Text = GetTabTextLabel(), - DrawPosition = GetTabClickableArea().Location.ToVector2() + new Vector2(16, 2) - }; - _label.SetParentControl(this); + _label = new XNALabel(Constants.FontSize08) + { + Text = GetTabTextLabel(), + DrawPosition = GetTabClickableArea().Location.ToVector2() + new Vector2(16, 2) + }; + _label.SetParentControl(this); - _cachedChat = new HashSet(); - _renderables = new List(); - } + _cachedChat = new HashSet(); + _renderables = new List(); + } - public override void Initialize() - { - _tab.Initialize(); - _closeButton?.Initialize(); - _label.Initialize(); + public override void Initialize() + { + _tab.Initialize(); + _closeButton?.Initialize(); + _label.Initialize(); - base.Initialize(); - } + base.Initialize(); + } - public void CloseTab() - { - if (Tab != ChatTab.Private1 && Tab != ChatTab.Private2) - throw new InvalidOperationException("Unable to close chat tab that isn't a PM tab"); + public void CloseTab() + { + if (Tab != ChatTab.Private1 && Tab != ChatTab.Private2) + throw new InvalidOperationException("Unable to close chat tab that isn't a PM tab"); - _closeButtonClicked = true; + _closeButtonClicked = true; - _parentPanel.SelectTab(ChatTab.Local); + _parentPanel.SelectTab(ChatTab.Local); - Visible = false; + Visible = false; - _cachedChat.Clear(); - _label.Text = string.Empty; - _cachedScrollOffset = 0; + _cachedChat.Clear(); + _label.Text = string.Empty; + _cachedScrollOffset = 0; - OnClosed?.Invoke(this, EventArgs.Empty); - } + OnClosed?.Invoke(this, EventArgs.Empty); + } + + protected override void OnUnconditionalUpdateControl(GameTime gameTime) + { + if (!Visible) + return; - protected override void OnUnconditionalUpdateControl(GameTime gameTime) + if (!_cachedChat.SetEquals(_chatProvider.AllChat[Tab])) { - if (!Visible) - return; + _cachedChat = _chatProvider.AllChat[Tab].ToHashSet(); + _renderables = _chatRenderableGenerator.GenerateChatRenderables(_cachedChat).ToList(); - if (!_cachedChat.SetEquals(_chatProvider.AllChat[Tab])) + if (Active) { - _cachedChat = _chatProvider.AllChat[Tab].ToHashSet(); - _renderables = _chatRenderableGenerator.GenerateChatRenderables(_cachedChat).ToList(); - - if (Active) - { - _scrollBar.UpdateDimensions(_renderables.Count); - _scrollBar.ScrollToEnd(); - } - else - { - _cachedScrollOffset = Math.Max(0, _renderables.Count - 7); - _label.ForeColor = Color.White; - } + _scrollBar.UpdateDimensions(_renderables.Count); + _scrollBar.ScrollToEnd(); + } + else + { + _cachedScrollOffset = Math.Max(0, _renderables.Count - 7); + _label.ForeColor = Color.White; } - - base.OnUnconditionalUpdateControl(gameTime); } - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); + base.OnUnconditionalUpdateControl(gameTime); + } - var sheet = Active ? _tabSheetSelected : _tabSheetUnselected; - _spriteBatch.Draw(sheet.SheetTexture, _tab.ClickArea.Location.ToVector2() + ImmediateParent.DrawPositionWithParentOffset, sheet.SourceRectangle, Color.White); + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); - if (Active) - { - _spriteBatch.End(); + var sheet = Active ? _tabSheetSelected : _tabSheetUnselected; + _spriteBatch.Draw(sheet.SheetTexture, _tab.ClickArea.Location.ToVector2() + ImmediateParent.DrawPositionWithParentOffset, sheet.SourceRectangle, Color.White); - foreach (var (ndx, renderable) in _renderables.Skip(_scrollBar.ScrollOffset).Take(_scrollBar.LinesToRender).Select((r, i) => (i, r))) - { - renderable.DisplayIndex = ndx; - renderable.Render(_parentPanel, _spriteBatch, _chatFont); - } + if (Active) + { + _spriteBatch.End(); - _spriteBatch.Begin(); + foreach (var (ndx, renderable) in _renderables.Skip(_scrollBar.ScrollOffset).Take(_scrollBar.LinesToRender).Select((r, i) => (i, r))) + { + renderable.DisplayIndex = ndx; + renderable.Render(_parentPanel, _spriteBatch, _chatFont); } - _spriteBatch.End(); - - base.OnDrawControl(gameTime); + _spriteBatch.Begin(); } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (eventArgs.Button == MouseButton.Right) - { - var clickedYRelativeToTopOfPanel = eventArgs.Position.Y - DrawAreaWithParentOffset.Y; - var clickedChatRow = (int)Math.Round(clickedYRelativeToTopOfPanel / 13.0) - 1; + _spriteBatch.End(); - if (clickedChatRow >= 0 && _scrollBar.ScrollOffset + clickedChatRow < _cachedChat.Count) - { - var who = _chatProvider.AllChat[Tab][_scrollBar.ScrollOffset + clickedChatRow].Who; - _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{who} "; - } + base.OnDrawControl(gameTime); + } - return true; + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (eventArgs.Button == MouseButton.Right) + { + var clickedYRelativeToTopOfPanel = eventArgs.Position.Y - DrawAreaWithParentOffset.Y; + var clickedChatRow = (int)Math.Round(clickedYRelativeToTopOfPanel / 13.0) - 1; + + if (clickedChatRow >= 0 && _scrollBar.ScrollOffset + clickedChatRow < _cachedChat.Count) + { + var who = _chatProvider.AllChat[Tab][_scrollBar.ScrollOffset + clickedChatRow].Who; + _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{who} "; } - return false; + return true; } - private void SelectThisTab() - { - if (!_closeButtonClicked) - _parentPanel.SelectTab(Tab); - _closeButtonClicked = false; - } + return false; + } + + private void SelectThisTab() + { + if (!_closeButtonClicked) + _parentPanel.SelectTab(Tab); + _closeButtonClicked = false; + } - private Rectangle GetTabClickableArea() + private Rectangle GetTabClickableArea() + { + return Tab switch { - return Tab switch - { - ChatTab.Private1 => new Rectangle(23, 102, 132, 16), - ChatTab.Private2 => new Rectangle(156, 102, 132, 16), - ChatTab.Local or - ChatTab.Global or - ChatTab.Group or - ChatTab.System => new Rectangle(289 + 44 * ((int)Tab - 2), 102, 43, 16), - _ => throw new ArgumentOutOfRangeException(nameof(Tab), Tab, null), - }; - } + ChatTab.Private1 => new Rectangle(23, 102, 132, 16), + ChatTab.Private2 => new Rectangle(156, 102, 132, 16), + ChatTab.Local or + ChatTab.Global or + ChatTab.Group or + ChatTab.System => new Rectangle(289 + 44 * ((int)Tab - 2), 102, 43, 16), + _ => throw new ArgumentOutOfRangeException(nameof(Tab), Tab, null), + }; + } - private string GetTabTextLabel() + private string GetTabTextLabel() + { + return Tab switch { - return Tab switch - { - ChatTab.Private1 or - ChatTab.Private2 => string.Empty, - ChatTab.Local => "scr", - ChatTab.Global => "glb", - ChatTab.Group => "grp", - ChatTab.System => "sys", - _ => throw new ArgumentOutOfRangeException(nameof(Tab), Tab, null), - }; - } + ChatTab.Private1 or + ChatTab.Private2 => string.Empty, + ChatTab.Local => "scr", + ChatTab.Global => "glb", + ChatTab.Group => "grp", + ChatTab.System => "sys", + _ => throw new ArgumentOutOfRangeException(nameof(Tab), Tab, null), + }; } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatTextBoxActions.cs b/EndlessClient/HUD/Chat/ChatTextBoxActions.cs index 3a18f863a..15d2fcf44 100644 --- a/EndlessClient/HUD/Chat/ChatTextBoxActions.cs +++ b/EndlessClient/HUD/Chat/ChatTextBoxActions.cs @@ -3,32 +3,31 @@ using EndlessClient.HUD.Controls; using EndlessClient.UIControls; -namespace EndlessClient.HUD.Chat +namespace EndlessClient.HUD.Chat; + +[AutoMappedType] +public class ChatTextBoxActions : IChatTextBoxActions { - [AutoMappedType] - public class ChatTextBoxActions : IChatTextBoxActions - { - private readonly IHudControlProvider _hudControlProvider; + private readonly IHudControlProvider _hudControlProvider; - public ChatTextBoxActions(IHudControlProvider hudControlProvider) - { - _hudControlProvider = hudControlProvider; - } + public ChatTextBoxActions(IHudControlProvider hudControlProvider) + { + _hudControlProvider = hudControlProvider; + } - public void ClearChatText() - { - var chatTextBox = GetChatTextBox(); - chatTextBox.Text = ""; - } + public void ClearChatText() + { + var chatTextBox = GetChatTextBox(); + chatTextBox.Text = ""; + } - public void FocusChatTextBox() - { - GetChatTextBox().Selected = true; - } + public void FocusChatTextBox() + { + GetChatTextBox().Selected = true; + } - private ChatTextBox GetChatTextBox() - { - return _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); - } + private ChatTextBox GetChatTextBox() + { + return _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/IChatModeCalculator.cs b/EndlessClient/HUD/Chat/IChatModeCalculator.cs index 5ae7f3286..e7cacaec9 100644 --- a/EndlessClient/HUD/Chat/IChatModeCalculator.cs +++ b/EndlessClient/HUD/Chat/IChatModeCalculator.cs @@ -1,9 +1,8 @@ using EndlessClient.UIControls; -namespace EndlessClient.HUD.Chat +namespace EndlessClient.HUD.Chat; + +public interface IChatModeCalculator { - public interface IChatModeCalculator - { - ChatModePictureBox.ChatMode CalculateMode(string fullTextString); - } + ChatModePictureBox.ChatMode CalculateMode(string fullTextString); } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/IChatTextBoxActions.cs b/EndlessClient/HUD/Chat/IChatTextBoxActions.cs index e5c61e4ec..4dcbe52cf 100644 --- a/EndlessClient/HUD/Chat/IChatTextBoxActions.cs +++ b/EndlessClient/HUD/Chat/IChatTextBoxActions.cs @@ -1,9 +1,8 @@ -namespace EndlessClient.HUD.Chat +namespace EndlessClient.HUD.Chat; + +public interface IChatTextBoxActions { - public interface IChatTextBoxActions - { - void ClearChatText(); + void ClearChatText(); - void FocusChatTextBox(); - } + void FocusChatTextBox(); } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/PrivateMessageActions.cs b/EndlessClient/HUD/Chat/PrivateMessageActions.cs index 6b57fe969..be60ea47b 100644 --- a/EndlessClient/HUD/Chat/PrivateMessageActions.cs +++ b/EndlessClient/HUD/Chat/PrivateMessageActions.cs @@ -7,73 +7,72 @@ using EOLib.Localization; using System; -namespace EndlessClient.HUD.Chat +namespace EndlessClient.HUD.Chat; + +[MappedType(BaseType = typeof(IPrivateMessageActions))] +public class PrivateMessageActions : IPrivateMessageActions { - [MappedType(BaseType = typeof(IPrivateMessageActions))] - public class PrivateMessageActions : IPrivateMessageActions + private readonly IHudControlProvider _hudControlProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IChatProvider _chatProvider; + private readonly IChatTypeCalculator _chatTypeCalculator; + private readonly IStatusLabelSetter _statusLabelSetter; + + public PrivateMessageActions(IHudControlProvider hudControlProvider, + ICharacterProvider characterProvider, + IChatProvider chatProvider, + IChatTypeCalculator chatTypeCalculator, + IStatusLabelSetter statusLabelSetter) { - private readonly IHudControlProvider _hudControlProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IChatProvider _chatProvider; - private readonly IChatTypeCalculator _chatTypeCalculator; - private readonly IStatusLabelSetter _statusLabelSetter; + _hudControlProvider = hudControlProvider; + _characterProvider = characterProvider; + _chatProvider = chatProvider; + _chatTypeCalculator = chatTypeCalculator; + _statusLabelSetter = statusLabelSetter; + } - public PrivateMessageActions(IHudControlProvider hudControlProvider, - ICharacterProvider characterProvider, - IChatProvider chatProvider, - IChatTypeCalculator chatTypeCalculator, - IStatusLabelSetter statusLabelSetter) + public (bool, string) GetTargetCharacter(string localTypedText) + { + if (_chatTypeCalculator.CalculateChatType(localTypedText) != ChatType.PM) { - _hudControlProvider = hudControlProvider; - _characterProvider = characterProvider; - _chatProvider = chatProvider; - _chatTypeCalculator = chatTypeCalculator; - _statusLabelSetter = statusLabelSetter; + return (true, string.Empty); } - public (bool, string) GetTargetCharacter(string localTypedText) + if (localTypedText.Length < 2 || localTypedText[1] == ' ') { - if (_chatTypeCalculator.CalculateChatType(localTypedText) != ChatType.PM) - { - return (true, string.Empty); - } - - if (localTypedText.Length < 2 || localTypedText[1] == ' ') - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_INVALID_INPUT_TRY); - return (false, string.Empty); - } - - if (CurrentTab == ChatTab.Private1) - { - return (true, _chatProvider.PMTarget1); - } - else if (CurrentTab == ChatTab.Private2) - { - return (true, _chatProvider.PMTarget2); - } - - var messageParts = localTypedText[1..].Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - if (messageParts.Length <= 1) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_INVALID_INPUT_TRY); - return (false, string.Empty); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_INVALID_INPUT_TRY); + return (false, string.Empty); + } - if (string.Equals(messageParts[0], _characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase)) - return (false, string.Empty); + if (CurrentTab == ChatTab.Private1) + { + return (true, _chatProvider.PMTarget1); + } + else if (CurrentTab == ChatTab.Private2) + { + return (true, _chatProvider.PMTarget2); + } - ChatPanel.TryStartNewPrivateChat(messageParts[0]); - return (true, messageParts[0]); + var messageParts = localTypedText[1..].Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (messageParts.Length <= 1) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_INVALID_INPUT_TRY); + return (false, string.Empty); } - private ChatPanel ChatPanel => _hudControlProvider.GetComponent(HudControlIdentifier.ChatPanel); + if (string.Equals(messageParts[0], _characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase)) + return (false, string.Empty); - private ChatTab CurrentTab => ChatPanel.CurrentTab; + ChatPanel.TryStartNewPrivateChat(messageParts[0]); + return (true, messageParts[0]); } - public interface IPrivateMessageActions - { - (bool Ok, string TargetCharacter) GetTargetCharacter(string localTypedText); - } + private ChatPanel ChatPanel => _hudControlProvider.GetComponent(HudControlIdentifier.ChatPanel); + + private ChatTab CurrentTab => ChatPanel.CurrentTab; +} + +public interface IPrivateMessageActions +{ + (bool Ok, string TargetCharacter) GetTargetCharacter(string localTypedText); } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ServerMessageHandler.cs b/EndlessClient/HUD/Chat/ServerMessageHandler.cs index 89e66123c..7fc337348 100644 --- a/EndlessClient/HUD/Chat/ServerMessageHandler.cs +++ b/EndlessClient/HUD/Chat/ServerMessageHandler.cs @@ -3,42 +3,41 @@ using EOLib.Domain.Chat; using EOLib.Localization; -namespace EndlessClient.HUD.Chat +namespace EndlessClient.HUD.Chat; + +[AutoMappedType] +public class ServerMessageHandler : IServerMessageHandler { - [AutoMappedType] - public class ServerMessageHandler : IServerMessageHandler + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ISfxPlayer _sfxPlayer; + + public ServerMessageHandler(IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + ISfxPlayer sfxPlayer) { - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ISfxPlayer _sfxPlayer; - - public ServerMessageHandler(IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - ISfxPlayer sfxPlayer) - { - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _sfxPlayer = sfxPlayer; - } - - public void AddServerMessage(string serverMessage, SoundEffectID soundEffect = SoundEffectID.Login, ChatIcon icon = ChatIcon.Exclamation) - { - var server = _localizedStringFinder.GetString(EOResourceID.STRING_SERVER); - - var localData = new ChatData(ChatTab.Local, server, serverMessage, icon, ChatColor.Server, log: false, filter: false); - var globalData = new ChatData(ChatTab.Global, server, serverMessage, icon, ChatColor.ServerGlobal, log: false, filter: false); - var systemData = new ChatData(ChatTab.System, string.Empty, serverMessage, icon, ChatColor.Server, filter: false); - - _chatRepository.AllChat[ChatTab.Local].Add(localData); - _chatRepository.AllChat[ChatTab.Global].Add(globalData); - _chatRepository.AllChat[ChatTab.System].Add(systemData); - - _sfxPlayer.PlaySfx(soundEffect); - } + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _sfxPlayer = sfxPlayer; } - public interface IServerMessageHandler + public void AddServerMessage(string serverMessage, SoundEffectID soundEffect = SoundEffectID.Login, ChatIcon icon = ChatIcon.Exclamation) { - void AddServerMessage(string message, SoundEffectID soundEffect = SoundEffectID.ServerMessage, ChatIcon icon = ChatIcon.Exclamation); + var server = _localizedStringFinder.GetString(EOResourceID.STRING_SERVER); + + var localData = new ChatData(ChatTab.Local, server, serverMessage, icon, ChatColor.Server, log: false, filter: false); + var globalData = new ChatData(ChatTab.Global, server, serverMessage, icon, ChatColor.ServerGlobal, log: false, filter: false); + var systemData = new ChatData(ChatTab.System, string.Empty, serverMessage, icon, ChatColor.Server, filter: false); + + _chatRepository.AllChat[ChatTab.Local].Add(localData); + _chatRepository.AllChat[ChatTab.Global].Add(globalData); + _chatRepository.AllChat[ChatTab.System].Add(systemData); + + _sfxPlayer.PlaySfx(soundEffect); } +} + +public interface IServerMessageHandler +{ + void AddServerMessage(string message, SoundEffectID soundEffect = SoundEffectID.ServerMessage, ChatIcon icon = ChatIcon.Exclamation); } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs b/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs index 741bbb32f..fc7da93ed 100644 --- a/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs +++ b/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs @@ -1,23 +1,22 @@ using EOLib.IO.Pub; -namespace EndlessClient.HUD.Controls +namespace EndlessClient.HUD.Controls; + +public class DragCompletedEventArgs { - public class DragCompletedEventArgs - { - public bool ContinueDrag { get; set; } = false; + public bool ContinueDrag { get; set; } = false; - public bool RestoreOriginalSlot { get; set; } = false; + public bool RestoreOriginalSlot { get; set; } = false; - public bool DragOutOfBounds { get; set; } = false; + public bool DragOutOfBounds { get; set; } = false; - public TRecord Data { get; } + public TRecord Data { get; } - public bool IsChainedDrag { get; } + public bool IsChainedDrag { get; } - public DragCompletedEventArgs(TRecord data, bool isChainedDrag) - { - Data = data; - IsChainedDrag = isChainedDrag; - } + public DragCompletedEventArgs(TRecord data, bool isChainedDrag) + { + Data = data; + IsChainedDrag = isChainedDrag; } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/DraggablePanelItem.cs b/EndlessClient/HUD/Controls/DraggablePanelItem.cs index 7632e5fce..dcc587f14 100644 --- a/EndlessClient/HUD/Controls/DraggablePanelItem.cs +++ b/EndlessClient/HUD/Controls/DraggablePanelItem.cs @@ -4,132 +4,131 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Controls +namespace EndlessClient.HUD.Controls; + +public abstract class DraggablePanelItem : XNAControl { - public abstract class DraggablePanelItem : XNAControl - { - protected readonly IDraggableItemContainer _parentContainer; + protected readonly IDraggableItemContainer _parentContainer; - // true when a single-click drag is in progress and the icon should follow the mouse - // otherwise, drag event handles following the mouse - private bool _followMouse; + // true when a single-click drag is in progress and the icon should follow the mouse + // otherwise, drag event handles following the mouse + private bool _followMouse; - // true when dragging and the drag was chained from another item - private bool _isChainedDrag; + // true when dragging and the drag was chained from another item + private bool _isChainedDrag; - // the top-left of the parent inventory panel when the drag started - protected Vector2 OldOffset { get; private set; } + // the top-left of the parent inventory panel when the drag started + protected Vector2 OldOffset { get; private set; } - // true when a drag is in progress (either single click or click + drag) - public bool IsDragging { get; private set; } + // true when a drag is in progress (either single click or click + drag) + public bool IsDragging { get; private set; } - public TRecord Data { get; protected set; } + public TRecord Data { get; protected set; } - public event EventHandler DraggingStarted; - public event EventHandler> DraggingFinishing; - public event EventHandler> DraggingFinished; + public event EventHandler DraggingStarted; + public event EventHandler> DraggingFinishing; + public event EventHandler> DraggingFinished; - // assumes absolute coordinates (not based on parent position) - protected abstract Rectangle GridArea { get; } + // assumes absolute coordinates (not based on parent position) + protected abstract Rectangle GridArea { get; } - protected DraggablePanelItem(IDraggableItemContainer parentContainer) - { - _parentContainer = parentContainer; - } + protected DraggablePanelItem(IDraggableItemContainer parentContainer) + { + _parentContainer = parentContainer; + } - public void StartDragging(bool isChainedDrag) - { - if (!isChainedDrag && !_parentContainer.NoItemsDragging()) - return; + public void StartDragging(bool isChainedDrag) + { + if (!isChainedDrag && !_parentContainer.NoItemsDragging()) + return; - IsDragging = true; - _followMouse = _isChainedDrag = isChainedDrag; + IsDragging = true; + _followMouse = _isChainedDrag = isChainedDrag; - OldOffset = ImmediateParent.DrawPositionWithParentOffset; - DrawPosition = MouseExtended.GetState().Position.ToVector2(); + OldOffset = ImmediateParent.DrawPositionWithParentOffset; + DrawPosition = MouseExtended.GetState().Position.ToVector2(); - SetControlUnparented(); - Game.Components.Add(this); - DrawOrder = 1000; + SetControlUnparented(); + Game.Components.Add(this); + DrawOrder = 1000; - DraggingStarted?.Invoke(this, EventArgs.Empty); - } + DraggingStarted?.Invoke(this, EventArgs.Empty); + } - protected override void OnUpdateControl(GameTime gameTime) + protected override void OnUpdateControl(GameTime gameTime) + { + if (_followMouse) { - if (_followMouse) - { - DrawPosition = MouseExtended.GetState().Position.ToVector2() - new Vector2(DrawArea.Width / 2, DrawArea.Height / 2); - } - - base.OnUpdateControl(gameTime); + DrawPosition = MouseExtended.GetState().Position.ToVector2() - new Vector2(DrawArea.Width / 2, DrawArea.Height / 2); } - protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) - { - StartDragging(isChainedDrag: false); - return true; - } + base.OnUpdateControl(gameTime); + } - protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) - { - DrawPosition = eventArgs.Position.ToVector2() - new Vector2(DrawArea.Width / 2, DrawArea.Height / 2); - return true; - } + protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) + { + StartDragging(isChainedDrag: false); + return true; + } - protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) + protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) + { + DrawPosition = eventArgs.Position.ToVector2() - new Vector2(DrawArea.Width / 2, DrawArea.Height / 2); + return true; + } + + protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) + { + StopDragging(eventArgs); + return true; + } + + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (_followMouse) { StopDragging(eventArgs); - return true; } - - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + else { - if (_followMouse) - { - StopDragging(eventArgs); - } - else - { - StartDragging(isChainedDrag: false); - _followMouse = true; - } - - return true; + StartDragging(isChainedDrag: false); + _followMouse = true; } - /// - /// Called when dragging is finished after the DraggingFinished event has been invoked - /// - protected virtual void OnDraggingFinished(DragCompletedEventArgs args) + return true; + } + + /// + /// Called when dragging is finished after the DraggingFinished event has been invoked + /// + protected virtual void OnDraggingFinished(DragCompletedEventArgs args) + { + } + + private void StopDragging(MouseEventArgs mouseEventArgs) + { + var args = new DragCompletedEventArgs(Data, _isChainedDrag) { - } + DragOutOfBounds = !GridArea.Contains(mouseEventArgs.Position) + }; - private void StopDragging(MouseEventArgs mouseEventArgs) + DraggingFinishing?.Invoke(this, args); + OnDraggingFinished(args); + + if (!args.ContinueDrag) + { + IsDragging = false; + OldOffset = Vector2.Zero; + _followMouse = false; + + Game.Components.Remove(this); + SetParentControl(_parentContainer); + + DraggingFinished?.Invoke(this, args); + } + else { - var args = new DragCompletedEventArgs(Data, _isChainedDrag) - { - DragOutOfBounds = !GridArea.Contains(mouseEventArgs.Position) - }; - - DraggingFinishing?.Invoke(this, args); - OnDraggingFinished(args); - - if (!args.ContinueDrag) - { - IsDragging = false; - OldOffset = Vector2.Zero; - _followMouse = false; - - Game.Components.Remove(this); - SetParentControl(_parentContainer); - - DraggingFinished?.Invoke(this, args); - } - else - { - _followMouse = true; - } + _followMouse = true; } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/HudBackgroundFrame.cs b/EndlessClient/HUD/Controls/HudBackgroundFrame.cs index c9dde9fd6..1d021a622 100644 --- a/EndlessClient/HUD/Controls/HudBackgroundFrame.cs +++ b/EndlessClient/HUD/Controls/HudBackgroundFrame.cs @@ -3,69 +3,68 @@ using Microsoft.Xna.Framework.Graphics; using XNAControls; -namespace EndlessClient.HUD.Controls +namespace EndlessClient.HUD.Controls; + +public class HudBackgroundFrame : XNAControl { - public class HudBackgroundFrame : XNAControl - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; - private Texture2D _mainFrame; - private Texture2D _topLeft; - private Texture2D _sidebar; - private Texture2D _topBar; - private Texture2D _filler; + private Texture2D _mainFrame; + private Texture2D _topLeft; + private Texture2D _sidebar; + private Texture2D _topBar; + private Texture2D _filler; - public HudBackgroundFrame(INativeGraphicsManager nativeGraphicsManager, - IGraphicsDeviceProvider graphicsDeviceProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _graphicsDeviceProvider = graphicsDeviceProvider; - } + public HudBackgroundFrame(INativeGraphicsManager nativeGraphicsManager, + IGraphicsDeviceProvider graphicsDeviceProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _graphicsDeviceProvider = graphicsDeviceProvider; + } - protected override void LoadContent() - { - _mainFrame = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, true); - _topLeft = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 21, true); - _sidebar = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 22, true); - _topBar = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 23, true); + protected override void LoadContent() + { + _mainFrame = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, true); + _topLeft = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 21, true); + _sidebar = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 22, true); + _topBar = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 23, true); - _filler = new Texture2D(_graphicsDeviceProvider.GraphicsDevice, 1, 1); - _filler.SetData(new[] { Color.FromNonPremultiplied(8, 8, 8, 255) }); + _filler = new Texture2D(_graphicsDeviceProvider.GraphicsDevice, 1, 1); + _filler.SetData(new[] { Color.FromNonPremultiplied(8, 8, 8, 255) }); - base.LoadContent(); - } + base.LoadContent(); + } - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); - _spriteBatch.Draw(_filler, new Rectangle(0, 400, 640, 80), Color.White); + _spriteBatch.Draw(_filler, new Rectangle(0, 400, 640, 80), Color.White); - _spriteBatch.Draw(_topBar, new Vector2(49, 7), Color.White); - _spriteBatch.Draw(_mainFrame, Vector2.Zero, Color.White); - _spriteBatch.Draw(_topLeft, Vector2.Zero, Color.White); - _spriteBatch.Draw(_sidebar, new Vector2(7, 53), Color.White); - _spriteBatch.Draw(_sidebar, new Vector2(629, 53), new Rectangle(3, 0, 1, _sidebar.Height), Color.White); + _spriteBatch.Draw(_topBar, new Vector2(49, 7), Color.White); + _spriteBatch.Draw(_mainFrame, Vector2.Zero, Color.White); + _spriteBatch.Draw(_topLeft, Vector2.Zero, Color.White); + _spriteBatch.Draw(_sidebar, new Vector2(7, 53), Color.White); + _spriteBatch.Draw(_sidebar, new Vector2(629, 53), new Rectangle(3, 0, 1, _sidebar.Height), Color.White); - //fill in some extra holes with black lines - _spriteBatch.Draw(_filler, new Rectangle(542, 0, 1, 8), Color.White); - _spriteBatch.Draw(_filler, new Rectangle(14, 329, 1, 142), Color.White); - _spriteBatch.Draw(_filler, new Rectangle(98, 479, 445, 1), Color.White); + //fill in some extra holes with black lines + _spriteBatch.Draw(_filler, new Rectangle(542, 0, 1, 8), Color.White); + _spriteBatch.Draw(_filler, new Rectangle(14, 329, 1, 142), Color.White); + _spriteBatch.Draw(_filler, new Rectangle(98, 479, 445, 1), Color.White); - _spriteBatch.End(); + _spriteBatch.End(); - base.OnDrawControl(gameTime); - } + base.OnDrawControl(gameTime); + } - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - _filler.Dispose(); - } - - base.Dispose(disposing); + _filler.Dispose(); } + + base.Dispose(disposing); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/HudControlIdentifier.cs b/EndlessClient/HUD/Controls/HudControlIdentifier.cs index 19824f396..35b646a2a 100644 --- a/EndlessClient/HUD/Controls/HudControlIdentifier.cs +++ b/EndlessClient/HUD/Controls/HudControlIdentifier.cs @@ -1,81 +1,80 @@ using System; -namespace EndlessClient.HUD.Controls +namespace EndlessClient.HUD.Controls; + +public enum HudControlIdentifier { - public enum HudControlIdentifier - { - CurrentUserInputTracker = int.MinValue, //this should always be first! + CurrentUserInputTracker = int.MinValue, //this should always be first! - MapRenderer = 0, - StatusIcons, - MiniMapRenderer, + MapRenderer = 0, + StatusIcons, + MiniMapRenderer, - ClickDispatcher, + ClickDispatcher, - HudBackground, + HudBackground, - //buttons and panels - InventoryButton, - InventoryPanel, + //buttons and panels + InventoryButton, + InventoryPanel, - ViewMapButton, + ViewMapButton, - ActiveSpellsButton, - ActiveSpellsPanel, + ActiveSpellsButton, + ActiveSpellsPanel, - PassiveSpellsButton, - PassiveSpellsPanel, + PassiveSpellsButton, + PassiveSpellsPanel, - ChatButton, - ChatPanel, + ChatButton, + ChatPanel, - StatsButton, - StatsPanel, + StatsButton, + StatsPanel, - OnlineListButton, - OnlineListPanel, + OnlineListButton, + OnlineListPanel, - PartyButton, - PartyPanel, + PartyButton, + PartyPanel, - MacroButton, + MacroButton, - SettingsButton, - SettingsPanel, + SettingsButton, + SettingsPanel, - HelpButton, - HelpPanel, + HelpButton, + HelpPanel, - NewsPanel, + NewsPanel, - //top bar - SessionExpButton, - QuestsButton, + //top bar + SessionExpButton, + QuestsButton, - HPStatusBar, - TPStatusBar, - SPStatusBar, - TNLStatusBar, + HPStatusBar, + TPStatusBar, + SPStatusBar, + TNLStatusBar, - //mid stuff - ChatModePictureBox, - ChatTextBox, + //mid stuff + ChatModePictureBox, + ChatTextBox, - FriendList, - IgnoreList, + FriendList, + IgnoreList, - //lower stuff - StatusLabel, - ClockLabel, + //lower stuff + StatusLabel, + ClockLabel, - //not displayed - PeriodicStatUpdater, - UserInputHandler, - CharacterAnimator, - NPCAnimator, - UnknownEntitiesRequester, - PeriodicEmoteHandler, + //not displayed + PeriodicStatUpdater, + UserInputHandler, + CharacterAnimator, + NPCAnimator, + UnknownEntitiesRequester, + PeriodicEmoteHandler, - PreviousUserInputTracker = Int32.MaxValue, //this should always be last! - } + PreviousUserInputTracker = Int32.MaxValue, //this should always be last! } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/HudControlsFactory.cs b/EndlessClient/HUD/Controls/HudControlsFactory.cs index 793f450de..38d9f6c18 100644 --- a/EndlessClient/HUD/Controls/HudControlsFactory.cs +++ b/EndlessClient/HUD/Controls/HudControlsFactory.cs @@ -31,576 +31,575 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Controls +namespace EndlessClient.HUD.Controls; + +[AutoMappedType(IsSingleton = true)] +public class HudControlsFactory : IHudControlsFactory { - [AutoMappedType(IsSingleton = true)] - public class HudControlsFactory : IHudControlsFactory + private const int HUD_BASE_LAYER = 100; + private const int HUD_CONTROL_LAYER = 130; + + private readonly IHudButtonController _hudButtonController; + private readonly IHudPanelFactory _hudPanelFactory; + private readonly IMapRendererFactory _mapRendererFactory; + private readonly IUserInputHandlerFactory _userInputHandlerFactory; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly ICharacterRepository _characterRepository; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IUserInputRepository _userInputRepository; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IStatusLabelTextProvider _statusLabelTextProvider; + private readonly IContentProvider _contentProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IChatModeCalculator _chatModeCalculator; + private readonly IExperienceTableProvider _experienceTableProvider; + private readonly IPathFinder _pathFinder; + private readonly ICharacterActions _characterActions; + private readonly IWalkValidationActions _walkValidationActions; + private readonly IChatBubbleActions _chatBubbleActions; + private readonly IUnknownEntitiesRequestActions _unknownEntitiesRequestActions; + private readonly IUserInputTimeProvider _userInputTimeProvider; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly ISfxPlayer _sfxPlayer; + private readonly IMiniMapRendererFactory _miniMapRendererFactory; + private readonly INewsProvider _newsProvider; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + private readonly IClickDispatcherFactory _clickDispatcherFactory; + private readonly IMetadataProvider _weaponMetadataProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly INPCRendererProvider _npcRendererProvider; + private IChatController _chatController; + private IMainButtonController _mainButtonController; + + public HudControlsFactory(IHudButtonController hudButtonController, + IHudPanelFactory hudPanelFactory, + IMapRendererFactory mapRendererFactory, + IUserInputHandlerFactory userInputHandlerFactory, + INativeGraphicsManager nativeGraphicsManager, + IGraphicsDeviceProvider graphicsDeviceProvider, + IClientWindowSizeRepository clientWindowSizeRepository, + IEndlessGameProvider endlessGameProvider, + ICharacterRepository characterRepository, + ICurrentMapStateRepository currentMapStateRepository, + IUserInputRepository userInputRepository, + IStatusLabelSetter statusLabelSetter, + IStatusLabelTextProvider statusLabelTextProvider, + IContentProvider contentProvider, + IHudControlProvider hudControlProvider, + ICurrentMapProvider currentMapProvider, + IChatModeCalculator chatModeCalculator, + IExperienceTableProvider experienceTableProvider, + IPathFinder pathFinder, + ICharacterActions characterActions, + IWalkValidationActions walkValidationActions, + IChatBubbleActions chatBubbleActions, + IUnknownEntitiesRequestActions unknownEntitiesRequestActions, + IUserInputTimeProvider userInputTimeProvider, + ISpellSlotDataRepository spellSlotDataRepository, + ISfxPlayer sfxPlayer, + IMiniMapRendererFactory miniMapRendererFactory, + INewsProvider newsProvider, + IFixedTimeStepRepository fixedTimeStepRepository, + IClickDispatcherFactory clickDispatcherFactory, + IMetadataProvider weaponMetadataProvider, + ILocalizedStringFinder localizedStringFinder, + ICharacterRendererProvider characterRendererProvider, + INPCRendererProvider npcRendererProvider) { - private const int HUD_BASE_LAYER = 100; - private const int HUD_CONTROL_LAYER = 130; - - private readonly IHudButtonController _hudButtonController; - private readonly IHudPanelFactory _hudPanelFactory; - private readonly IMapRendererFactory _mapRendererFactory; - private readonly IUserInputHandlerFactory _userInputHandlerFactory; - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly ICharacterRepository _characterRepository; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IUserInputRepository _userInputRepository; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IStatusLabelTextProvider _statusLabelTextProvider; - private readonly IContentProvider _contentProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IChatModeCalculator _chatModeCalculator; - private readonly IExperienceTableProvider _experienceTableProvider; - private readonly IPathFinder _pathFinder; - private readonly ICharacterActions _characterActions; - private readonly IWalkValidationActions _walkValidationActions; - private readonly IChatBubbleActions _chatBubbleActions; - private readonly IUnknownEntitiesRequestActions _unknownEntitiesRequestActions; - private readonly IUserInputTimeProvider _userInputTimeProvider; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly ISfxPlayer _sfxPlayer; - private readonly IMiniMapRendererFactory _miniMapRendererFactory; - private readonly INewsProvider _newsProvider; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - private readonly IClickDispatcherFactory _clickDispatcherFactory; - private readonly IMetadataProvider _weaponMetadataProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly INPCRendererProvider _npcRendererProvider; - private IChatController _chatController; - private IMainButtonController _mainButtonController; - - public HudControlsFactory(IHudButtonController hudButtonController, - IHudPanelFactory hudPanelFactory, - IMapRendererFactory mapRendererFactory, - IUserInputHandlerFactory userInputHandlerFactory, - INativeGraphicsManager nativeGraphicsManager, - IGraphicsDeviceProvider graphicsDeviceProvider, - IClientWindowSizeRepository clientWindowSizeRepository, - IEndlessGameProvider endlessGameProvider, - ICharacterRepository characterRepository, - ICurrentMapStateRepository currentMapStateRepository, - IUserInputRepository userInputRepository, - IStatusLabelSetter statusLabelSetter, - IStatusLabelTextProvider statusLabelTextProvider, - IContentProvider contentProvider, - IHudControlProvider hudControlProvider, - ICurrentMapProvider currentMapProvider, - IChatModeCalculator chatModeCalculator, - IExperienceTableProvider experienceTableProvider, - IPathFinder pathFinder, - ICharacterActions characterActions, - IWalkValidationActions walkValidationActions, - IChatBubbleActions chatBubbleActions, - IUnknownEntitiesRequestActions unknownEntitiesRequestActions, - IUserInputTimeProvider userInputTimeProvider, - ISpellSlotDataRepository spellSlotDataRepository, - ISfxPlayer sfxPlayer, - IMiniMapRendererFactory miniMapRendererFactory, - INewsProvider newsProvider, - IFixedTimeStepRepository fixedTimeStepRepository, - IClickDispatcherFactory clickDispatcherFactory, - IMetadataProvider weaponMetadataProvider, - ILocalizedStringFinder localizedStringFinder, - ICharacterRendererProvider characterRendererProvider, - INPCRendererProvider npcRendererProvider) - { - _hudButtonController = hudButtonController; - _hudPanelFactory = hudPanelFactory; - _mapRendererFactory = mapRendererFactory; - _userInputHandlerFactory = userInputHandlerFactory; - _nativeGraphicsManager = nativeGraphicsManager; - _graphicsDeviceProvider = graphicsDeviceProvider; - _clientWindowSizeRepository = clientWindowSizeRepository; - _endlessGameProvider = endlessGameProvider; - _characterRepository = characterRepository; - _currentMapStateRepository = currentMapStateRepository; - _userInputRepository = userInputRepository; - _statusLabelSetter = statusLabelSetter; - _statusLabelTextProvider = statusLabelTextProvider; - _contentProvider = contentProvider; - _hudControlProvider = hudControlProvider; - _currentMapProvider = currentMapProvider; - _chatModeCalculator = chatModeCalculator; - _experienceTableProvider = experienceTableProvider; - _pathFinder = pathFinder; - _characterActions = characterActions; - _walkValidationActions = walkValidationActions; - _chatBubbleActions = chatBubbleActions; - _unknownEntitiesRequestActions = unknownEntitiesRequestActions; - _userInputTimeProvider = userInputTimeProvider; - _spellSlotDataRepository = spellSlotDataRepository; - _sfxPlayer = sfxPlayer; - _miniMapRendererFactory = miniMapRendererFactory; - _newsProvider = newsProvider; - _fixedTimeStepRepository = fixedTimeStepRepository; - _clickDispatcherFactory = clickDispatcherFactory; - _weaponMetadataProvider = weaponMetadataProvider; - _localizedStringFinder = localizedStringFinder; - _characterRendererProvider = characterRendererProvider; - _npcRendererProvider = npcRendererProvider; - } + _hudButtonController = hudButtonController; + _hudPanelFactory = hudPanelFactory; + _mapRendererFactory = mapRendererFactory; + _userInputHandlerFactory = userInputHandlerFactory; + _nativeGraphicsManager = nativeGraphicsManager; + _graphicsDeviceProvider = graphicsDeviceProvider; + _clientWindowSizeRepository = clientWindowSizeRepository; + _endlessGameProvider = endlessGameProvider; + _characterRepository = characterRepository; + _currentMapStateRepository = currentMapStateRepository; + _userInputRepository = userInputRepository; + _statusLabelSetter = statusLabelSetter; + _statusLabelTextProvider = statusLabelTextProvider; + _contentProvider = contentProvider; + _hudControlProvider = hudControlProvider; + _currentMapProvider = currentMapProvider; + _chatModeCalculator = chatModeCalculator; + _experienceTableProvider = experienceTableProvider; + _pathFinder = pathFinder; + _characterActions = characterActions; + _walkValidationActions = walkValidationActions; + _chatBubbleActions = chatBubbleActions; + _unknownEntitiesRequestActions = unknownEntitiesRequestActions; + _userInputTimeProvider = userInputTimeProvider; + _spellSlotDataRepository = spellSlotDataRepository; + _sfxPlayer = sfxPlayer; + _miniMapRendererFactory = miniMapRendererFactory; + _newsProvider = newsProvider; + _fixedTimeStepRepository = fixedTimeStepRepository; + _clickDispatcherFactory = clickDispatcherFactory; + _weaponMetadataProvider = weaponMetadataProvider; + _localizedStringFinder = localizedStringFinder; + _characterRendererProvider = characterRendererProvider; + _npcRendererProvider = npcRendererProvider; + } - public void InjectChatController(IChatController chatController, - IMainButtonController mainButtonController) - { - _chatController = chatController; - _mainButtonController = mainButtonController; - } + public void InjectChatController(IChatController chatController, + IMainButtonController mainButtonController) + { + _chatController = chatController; + _mainButtonController = mainButtonController; + } + + public IReadOnlyDictionary CreateHud() + { + var characterAnimator = CreateCharacterAnimator(); + var mapRenderer = _mapRendererFactory.CreateMapRenderer(); - public IReadOnlyDictionary CreateHud() + var controls = new Dictionary { - var characterAnimator = CreateCharacterAnimator(); - var mapRenderer = _mapRendererFactory.CreateMapRenderer(); + {HudControlIdentifier.CurrentUserInputTracker, CreateCurrentUserInputTracker()}, + + {HudControlIdentifier.CharacterAnimator, characterAnimator}, + {HudControlIdentifier.NPCAnimator, CreateNPCAnimator()}, + {HudControlIdentifier.MapRenderer, mapRenderer}, + {HudControlIdentifier.StatusIcons, CreatePlayerStatusIconRenderer()}, + {HudControlIdentifier.MiniMapRenderer, _miniMapRendererFactory.Create()}, + + {HudControlIdentifier.ClickDispatcher, CreateClickDispatcher(mapRenderer)}, + + {HudControlIdentifier.HudBackground, CreateHudBackground()}, + + {HudControlIdentifier.InventoryButton, CreateStateChangeButton(InGameStates.Inventory)}, + {HudControlIdentifier.ViewMapButton, CreateStateChangeButton(InGameStates.ViewMapToggle)}, + {HudControlIdentifier.ActiveSpellsButton, CreateStateChangeButton(InGameStates.ActiveSpells)}, + {HudControlIdentifier.PassiveSpellsButton, CreateStateChangeButton(InGameStates.PassiveSpells)}, + {HudControlIdentifier.ChatButton, CreateStateChangeButton(InGameStates.Chat)}, + {HudControlIdentifier.StatsButton, CreateStateChangeButton(InGameStates.Stats)}, + {HudControlIdentifier.OnlineListButton, CreateStateChangeButton(InGameStates.OnlineList)}, + {HudControlIdentifier.PartyButton, CreateStateChangeButton(InGameStates.Party)}, + {HudControlIdentifier.MacroButton, CreateStateChangeButton(InGameStates.Macro)}, + {HudControlIdentifier.SettingsButton, CreateStateChangeButton(InGameStates.Settings)}, + {HudControlIdentifier.HelpButton, CreateStateChangeButton(InGameStates.Help)}, + + {HudControlIdentifier.FriendList, CreateFriendListButton()}, + {HudControlIdentifier.IgnoreList, CreateIgnoreListButton()}, + + {HudControlIdentifier.NewsPanel, CreateStatePanel(InGameStates.News)}, + {HudControlIdentifier.InventoryPanel, CreateStatePanel(InGameStates.Inventory)}, + {HudControlIdentifier.ActiveSpellsPanel, CreateStatePanel(InGameStates.ActiveSpells)}, + {HudControlIdentifier.PassiveSpellsPanel, CreateStatePanel(InGameStates.PassiveSpells)}, + {HudControlIdentifier.ChatPanel, CreateStatePanel(InGameStates.Chat)}, + {HudControlIdentifier.StatsPanel, CreateStatePanel(InGameStates.Stats)}, + {HudControlIdentifier.OnlineListPanel, CreateStatePanel(InGameStates.OnlineList)}, + {HudControlIdentifier.PartyPanel, CreateStatePanel(InGameStates.Party)}, + //macro panel + {HudControlIdentifier.SettingsPanel, CreateStatePanel(InGameStates.Settings)}, + {HudControlIdentifier.HelpPanel, CreateStatePanel(InGameStates.Help)}, + + {HudControlIdentifier.SessionExpButton, CreateSessionExpButton()}, + {HudControlIdentifier.QuestsButton, CreateQuestButton()}, + + {HudControlIdentifier.HPStatusBar, CreateHPStatusBar()}, + {HudControlIdentifier.TPStatusBar, CreateTPStatusBar()}, + {HudControlIdentifier.SPStatusBar, CreateSPStatusBar()}, + {HudControlIdentifier.TNLStatusBar, CreateTNLStatusBar()}, + + {HudControlIdentifier.ChatModePictureBox, CreateChatModePictureBox()}, + {HudControlIdentifier.ChatTextBox, CreateChatTextBox()}, + {HudControlIdentifier.ClockLabel, CreateClockLabel()}, + {HudControlIdentifier.StatusLabel, CreateStatusLabel()}, + + {HudControlIdentifier.PeriodicStatUpdater, CreatePeriodicStatUpdater()}, + {HudControlIdentifier.UserInputHandler, CreateUserInputHandler()}, + {HudControlIdentifier.UnknownEntitiesRequester, CreateUnknownEntitiesRequester()}, + {HudControlIdentifier.PeriodicEmoteHandler, CreatePeriodicEmoteHandler(characterAnimator)}, + + {HudControlIdentifier.PreviousUserInputTracker, CreatePreviousUserInputTracker()} + }; + + return controls; + } - var controls = new Dictionary - { - {HudControlIdentifier.CurrentUserInputTracker, CreateCurrentUserInputTracker()}, - - {HudControlIdentifier.CharacterAnimator, characterAnimator}, - {HudControlIdentifier.NPCAnimator, CreateNPCAnimator()}, - {HudControlIdentifier.MapRenderer, mapRenderer}, - {HudControlIdentifier.StatusIcons, CreatePlayerStatusIconRenderer()}, - {HudControlIdentifier.MiniMapRenderer, _miniMapRendererFactory.Create()}, - - {HudControlIdentifier.ClickDispatcher, CreateClickDispatcher(mapRenderer)}, - - {HudControlIdentifier.HudBackground, CreateHudBackground()}, - - {HudControlIdentifier.InventoryButton, CreateStateChangeButton(InGameStates.Inventory)}, - {HudControlIdentifier.ViewMapButton, CreateStateChangeButton(InGameStates.ViewMapToggle)}, - {HudControlIdentifier.ActiveSpellsButton, CreateStateChangeButton(InGameStates.ActiveSpells)}, - {HudControlIdentifier.PassiveSpellsButton, CreateStateChangeButton(InGameStates.PassiveSpells)}, - {HudControlIdentifier.ChatButton, CreateStateChangeButton(InGameStates.Chat)}, - {HudControlIdentifier.StatsButton, CreateStateChangeButton(InGameStates.Stats)}, - {HudControlIdentifier.OnlineListButton, CreateStateChangeButton(InGameStates.OnlineList)}, - {HudControlIdentifier.PartyButton, CreateStateChangeButton(InGameStates.Party)}, - {HudControlIdentifier.MacroButton, CreateStateChangeButton(InGameStates.Macro)}, - {HudControlIdentifier.SettingsButton, CreateStateChangeButton(InGameStates.Settings)}, - {HudControlIdentifier.HelpButton, CreateStateChangeButton(InGameStates.Help)}, - - {HudControlIdentifier.FriendList, CreateFriendListButton()}, - {HudControlIdentifier.IgnoreList, CreateIgnoreListButton()}, - - {HudControlIdentifier.NewsPanel, CreateStatePanel(InGameStates.News)}, - {HudControlIdentifier.InventoryPanel, CreateStatePanel(InGameStates.Inventory)}, - {HudControlIdentifier.ActiveSpellsPanel, CreateStatePanel(InGameStates.ActiveSpells)}, - {HudControlIdentifier.PassiveSpellsPanel, CreateStatePanel(InGameStates.PassiveSpells)}, - {HudControlIdentifier.ChatPanel, CreateStatePanel(InGameStates.Chat)}, - {HudControlIdentifier.StatsPanel, CreateStatePanel(InGameStates.Stats)}, - {HudControlIdentifier.OnlineListPanel, CreateStatePanel(InGameStates.OnlineList)}, - {HudControlIdentifier.PartyPanel, CreateStatePanel(InGameStates.Party)}, - //macro panel - {HudControlIdentifier.SettingsPanel, CreateStatePanel(InGameStates.Settings)}, - {HudControlIdentifier.HelpPanel, CreateStatePanel(InGameStates.Help)}, - - {HudControlIdentifier.SessionExpButton, CreateSessionExpButton()}, - {HudControlIdentifier.QuestsButton, CreateQuestButton()}, - - {HudControlIdentifier.HPStatusBar, CreateHPStatusBar()}, - {HudControlIdentifier.TPStatusBar, CreateTPStatusBar()}, - {HudControlIdentifier.SPStatusBar, CreateSPStatusBar()}, - {HudControlIdentifier.TNLStatusBar, CreateTNLStatusBar()}, - - {HudControlIdentifier.ChatModePictureBox, CreateChatModePictureBox()}, - {HudControlIdentifier.ChatTextBox, CreateChatTextBox()}, - {HudControlIdentifier.ClockLabel, CreateClockLabel()}, - {HudControlIdentifier.StatusLabel, CreateStatusLabel()}, - - {HudControlIdentifier.PeriodicStatUpdater, CreatePeriodicStatUpdater()}, - {HudControlIdentifier.UserInputHandler, CreateUserInputHandler()}, - {HudControlIdentifier.UnknownEntitiesRequester, CreateUnknownEntitiesRequester()}, - {HudControlIdentifier.PeriodicEmoteHandler, CreatePeriodicEmoteHandler(characterAnimator)}, - - {HudControlIdentifier.PreviousUserInputTracker, CreatePreviousUserInputTracker()} - }; + private PlayerStatusIconRenderer CreatePlayerStatusIconRenderer() + { + return new PlayerStatusIconRenderer( + _nativeGraphicsManager, + (ICharacterProvider)_characterRepository, + (ISpellSlotDataProvider)_spellSlotDataRepository, + _currentMapProvider, _clientWindowSizeRepository); + } - return controls; - } + private IClickDispatcher CreateClickDispatcher(IMapRenderer mapRenderer) + { + var dispatcher = _clickDispatcherFactory.Create(); + dispatcher.DrawOrder = mapRenderer.DrawOrder; + return dispatcher; + } - private PlayerStatusIconRenderer CreatePlayerStatusIconRenderer() + private HudBackgroundFrame CreateHudBackground() + { + return new HudBackgroundFrame(_nativeGraphicsManager, _graphicsDeviceProvider) { - return new PlayerStatusIconRenderer( - _nativeGraphicsManager, - (ICharacterProvider)_characterRepository, - (ISpellSlotDataProvider)_spellSlotDataRepository, - _currentMapProvider, _clientWindowSizeRepository); - } + DrawOrder = HUD_BASE_LAYER, + Visible = !_clientWindowSizeRepository.Resizable, + }; + } - private IClickDispatcher CreateClickDispatcher(IMapRenderer mapRenderer) - { - var dispatcher = _clickDispatcherFactory.Create(); - dispatcher.DrawOrder = mapRenderer.DrawOrder; - return dispatcher; - } + private IXNAButton CreateStateChangeButton(InGameStates whichState) + { + if (whichState == InGameStates.News) + throw new ArgumentOutOfRangeException(nameof(whichState), "News state does not have a button associated with it"); + var buttonIndex = (int)whichState; + + var mainButtonTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 25); + var widthDelta = mainButtonTexture.Width / 2; + var heightDelta = mainButtonTexture.Height / 11; - private HudBackgroundFrame CreateHudBackground() + IXNAButton retButton; + if (!_clientWindowSizeRepository.Resizable) { - return new HudBackgroundFrame(_nativeGraphicsManager, _graphicsDeviceProvider) + var xPosition = buttonIndex < 6 ? 62 : 590; + var yPosition = (buttonIndex < 6 ? 330 : 350) + (buttonIndex < 6 ? buttonIndex : buttonIndex - 6) * 20; + + retButton = new XNAButton( + mainButtonTexture, + new Vector2(xPosition, yPosition), + new Rectangle(0, heightDelta * buttonIndex, widthDelta, heightDelta), + new Rectangle(widthDelta, heightDelta * buttonIndex, widthDelta, heightDelta)) { - DrawOrder = HUD_BASE_LAYER, - Visible = !_clientWindowSizeRepository.Resizable, + DrawOrder = HUD_CONTROL_LAYER }; } - - private IXNAButton CreateStateChangeButton(InGameStates whichState) + else { - if (whichState == InGameStates.News) - throw new ArgumentOutOfRangeException(nameof(whichState), "News state does not have a button associated with it"); - var buttonIndex = (int)whichState; + var yIndex = buttonIndex % 6 - 3; - var mainButtonTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 25); - var widthDelta = mainButtonTexture.Width / 2; - var heightDelta = mainButtonTexture.Height / 11; + var xPosition = buttonIndex < 6 ? 0 : _clientWindowSizeRepository.Width - widthDelta; + var yPosition = (_clientWindowSizeRepository.Height / 2 + heightDelta * yIndex); - IXNAButton retButton; - if (!_clientWindowSizeRepository.Resizable) - { - var xPosition = buttonIndex < 6 ? 62 : 590; - var yPosition = (buttonIndex < 6 ? 330 : 350) + (buttonIndex < 6 ? buttonIndex : buttonIndex - 6) * 20; - - retButton = new XNAButton( - mainButtonTexture, - new Vector2(xPosition, yPosition), - new Rectangle(0, heightDelta * buttonIndex, widthDelta, heightDelta), - new Rectangle(widthDelta, heightDelta * buttonIndex, widthDelta, heightDelta)) - { - DrawOrder = HUD_CONTROL_LAYER - }; - } - else + retButton = new XNAButton( + mainButtonTexture, + new Vector2(xPosition, yPosition), + new Rectangle(0, heightDelta * buttonIndex, widthDelta, heightDelta), + new Rectangle(widthDelta, heightDelta * buttonIndex, widthDelta, heightDelta)) { - var yIndex = buttonIndex % 6 - 3; + DrawOrder = HUD_CONTROL_LAYER + }; - var xPosition = buttonIndex < 6 ? 0 : _clientWindowSizeRepository.Width - widthDelta; - var yPosition = (_clientWindowSizeRepository.Height / 2 + heightDelta * yIndex); + _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => + { + var capturedXPos = buttonIndex < 6 ? 0 : _clientWindowSizeRepository.Width - widthDelta; + var capturedYPos = (_clientWindowSizeRepository.Height / 2 + heightDelta * yIndex); + retButton.DrawPosition = new Vector2(capturedXPos, capturedYPos); + }; + } - retButton = new XNAButton( - mainButtonTexture, - new Vector2(xPosition, yPosition), - new Rectangle(0, heightDelta * buttonIndex, widthDelta, heightDelta), - new Rectangle(widthDelta, heightDelta * buttonIndex, widthDelta, heightDelta)) - { - DrawOrder = HUD_CONTROL_LAYER - }; + retButton.OnClick += (_, _) => DoHudStateChangeClick(whichState); + retButton.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel( + EOResourceID.STATUS_LABEL_TYPE_BUTTON, + EOResourceID.STATUS_LABEL_HUD_BUTTON_HOVER_FIRST + buttonIndex); + return retButton; + } - _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => - { - var capturedXPos = buttonIndex < 6 ? 0 : _clientWindowSizeRepository.Width - widthDelta; - var capturedYPos = (_clientWindowSizeRepository.Height / 2 + heightDelta * yIndex); - retButton.DrawPosition = new Vector2(capturedXPos, capturedYPos); - }; - } + private IXNAButton CreateFriendListButton() + { + Func getFriendListDrawPosition = () => new Vector2(_clientWindowSizeRepository.Width - 48, _clientWindowSizeRepository.Height - 37); + var button = new XNAButton( + _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, false), + _clientWindowSizeRepository.Resizable ? getFriendListDrawPosition() : new Vector2(592, 312), + new Rectangle(0, 260, 17, 15), + new Rectangle(0, 276, 17, 15)) + { + DrawOrder = HUD_CONTROL_LAYER + 10 + }; + button.OnClick += (_, _) => _hudButtonController.ClickFriendList(); + button.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + button.OnMouseOver += (o, e) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_FRIEND_LIST); - retButton.OnClick += (_, _) => DoHudStateChangeClick(whichState); - retButton.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel( - EOResourceID.STATUS_LABEL_TYPE_BUTTON, - EOResourceID.STATUS_LABEL_HUD_BUTTON_HOVER_FIRST + buttonIndex); - return retButton; + if (_clientWindowSizeRepository.Resizable) + { + _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => button.DrawPosition = getFriendListDrawPosition(); } - private IXNAButton CreateFriendListButton() - { - Func getFriendListDrawPosition = () => new Vector2(_clientWindowSizeRepository.Width - 48, _clientWindowSizeRepository.Height - 37); - var button = new XNAButton( - _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, false), - _clientWindowSizeRepository.Resizable ? getFriendListDrawPosition() : new Vector2(592, 312), - new Rectangle(0, 260, 17, 15), - new Rectangle(0, 276, 17, 15)) - { - DrawOrder = HUD_CONTROL_LAYER + 10 - }; - button.OnClick += (_, _) => _hudButtonController.ClickFriendList(); - button.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); - button.OnMouseOver += (o, e) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_FRIEND_LIST); + return button; + } - if (_clientWindowSizeRepository.Resizable) - { - _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => button.DrawPosition = getFriendListDrawPosition(); - } + private IXNAButton CreateIgnoreListButton() + { + Func getIgnoreListDrawPosition = () => new Vector2(_clientWindowSizeRepository.Width - 31, _clientWindowSizeRepository.Height - 37); + var button = new XNAButton( + _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, false), + _clientWindowSizeRepository.Resizable ? getIgnoreListDrawPosition() : new Vector2(609, 312), + new Rectangle(17, 260, 17, 15), + new Rectangle(17, 276, 17, 15)) + { + DrawOrder = HUD_CONTROL_LAYER + 10 + }; + button.OnClick += (_, _) => _hudButtonController.ClickIgnoreList(); + button.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + button.OnMouseOver += (o, e) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_IGNORE_LIST); - return button; + if (_clientWindowSizeRepository.Resizable) + { + _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => button.DrawPosition = getIgnoreListDrawPosition(); } - private IXNAButton CreateIgnoreListButton() + return button; + } + + private void DoHudStateChangeClick(InGameStates whichState) + { + switch (whichState) { - Func getIgnoreListDrawPosition = () => new Vector2(_clientWindowSizeRepository.Width - 31, _clientWindowSizeRepository.Height - 37); - var button = new XNAButton( - _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, false), - _clientWindowSizeRepository.Resizable ? getIgnoreListDrawPosition() : new Vector2(609, 312), - new Rectangle(17, 260, 17, 15), - new Rectangle(17, 276, 17, 15)) - { - DrawOrder = HUD_CONTROL_LAYER + 10 - }; - button.OnClick += (_, _) => _hudButtonController.ClickIgnoreList(); - button.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); - button.OnMouseOver += (o, e) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_IGNORE_LIST); + case InGameStates.Inventory: _hudButtonController.ClickInventory(); break; + case InGameStates.ViewMapToggle: _hudButtonController.ClickViewMapToggle(); break; + case InGameStates.ActiveSpells: _hudButtonController.ClickActiveSpells(); break; + case InGameStates.PassiveSpells: _hudButtonController.ClickPassiveSpells(); break; + case InGameStates.Chat: + _hudButtonController.ClickChat(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_CHAT_PANEL_NOW_VIEWED); + break; + case InGameStates.Stats: + _hudButtonController.ClickStats(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_STATS_PANEL_NOW_VIEWED); + break; + case InGameStates.OnlineList: + _hudButtonController.ClickOnlineList(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_ONLINE_PLAYERS_NOW_VIEWED); + break; + case InGameStates.Party: _hudButtonController.ClickParty(); break; + case InGameStates.Macro: break; + case InGameStates.Settings: _hudButtonController.ClickSettings(); break; + case InGameStates.Help: + _hudButtonController.ClickHelp(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_HUD_BUTTON_HOVER_LAST); + break; + default: throw new ArgumentOutOfRangeException(nameof(whichState), whichState, null); + } - if (_clientWindowSizeRepository.Resizable) - { - _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => button.DrawPosition = getIgnoreListDrawPosition(); - } + _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + } - return button; - } + private IGameComponent CreateStatePanel(InGameStates whichState) + { + DraggableHudPanel retPanel; - private void DoHudStateChangeClick(InGameStates whichState) + switch (whichState) { - switch (whichState) - { - case InGameStates.Inventory: _hudButtonController.ClickInventory(); break; - case InGameStates.ViewMapToggle: _hudButtonController.ClickViewMapToggle(); break; - case InGameStates.ActiveSpells: _hudButtonController.ClickActiveSpells(); break; - case InGameStates.PassiveSpells: _hudButtonController.ClickPassiveSpells(); break; - case InGameStates.Chat: - _hudButtonController.ClickChat(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_CHAT_PANEL_NOW_VIEWED); - break; - case InGameStates.Stats: - _hudButtonController.ClickStats(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_STATS_PANEL_NOW_VIEWED); - break; - case InGameStates.OnlineList: - _hudButtonController.ClickOnlineList(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_ONLINE_PLAYERS_NOW_VIEWED); - break; - case InGameStates.Party: _hudButtonController.ClickParty(); break; - case InGameStates.Macro: break; - case InGameStates.Settings: _hudButtonController.ClickSettings(); break; - case InGameStates.Help: - _hudButtonController.ClickHelp(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_HUD_BUTTON_HOVER_LAST); - break; - default: throw new ArgumentOutOfRangeException(nameof(whichState), whichState, null); - } - - _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + case InGameStates.Inventory: retPanel = _hudPanelFactory.CreateInventoryPanel(); break; + case InGameStates.ActiveSpells: retPanel = _hudPanelFactory.CreateActiveSpellsPanel(); break; + case InGameStates.PassiveSpells: retPanel = _hudPanelFactory.CreatePassiveSpellsPanel(); break; + case InGameStates.Chat: retPanel = _hudPanelFactory.CreateChatPanel(); break; + case InGameStates.Stats: retPanel = _hudPanelFactory.CreateStatsPanel(); break; + case InGameStates.OnlineList: retPanel = _hudPanelFactory.CreateOnlineListPanel(); break; + case InGameStates.Party: retPanel = _hudPanelFactory.CreatePartyPanel(); break; + case InGameStates.Settings: retPanel = _hudPanelFactory.CreateSettingsPanel(); break; + case InGameStates.Help: retPanel = _hudPanelFactory.CreateHelpPanel(); break; + case InGameStates.News: retPanel = _hudPanelFactory.CreateNewsPanel(); break; + default: throw new ArgumentOutOfRangeException(nameof(whichState), whichState, "Panel specification is out of range."); } - private IGameComponent CreateStatePanel(InGameStates whichState) - { - DraggableHudPanel retPanel; + retPanel.Activated += () => retPanel.DrawOrder = _hudControlProvider.HudPanels.Select(x => x.DrawOrder).Max() + 1; - switch (whichState) - { - case InGameStates.Inventory: retPanel = _hudPanelFactory.CreateInventoryPanel(); break; - case InGameStates.ActiveSpells: retPanel = _hudPanelFactory.CreateActiveSpellsPanel(); break; - case InGameStates.PassiveSpells: retPanel = _hudPanelFactory.CreatePassiveSpellsPanel(); break; - case InGameStates.Chat: retPanel = _hudPanelFactory.CreateChatPanel(); break; - case InGameStates.Stats: retPanel = _hudPanelFactory.CreateStatsPanel(); break; - case InGameStates.OnlineList: retPanel = _hudPanelFactory.CreateOnlineListPanel(); break; - case InGameStates.Party: retPanel = _hudPanelFactory.CreatePartyPanel(); break; - case InGameStates.Settings: retPanel = _hudPanelFactory.CreateSettingsPanel(); break; - case InGameStates.Help: retPanel = _hudPanelFactory.CreateHelpPanel(); break; - case InGameStates.News: retPanel = _hudPanelFactory.CreateNewsPanel(); break; - default: throw new ArgumentOutOfRangeException(nameof(whichState), whichState, "Panel specification is out of range."); - } + //news is visible by default when loading the game if news text is set + retPanel.Visible = (_newsProvider.NewsText.Any() && whichState == InGameStates.News) || + (!_newsProvider.NewsText.Any() && whichState == InGameStates.Chat); - retPanel.Activated += () => retPanel.DrawOrder = _hudControlProvider.HudPanels.Select(x => x.DrawOrder).Max() + 1; + if (_clientWindowSizeRepository.Resizable) + { + retPanel.UpdateOrder = -1; - //news is visible by default when loading the game if news text is set - retPanel.Visible = (_newsProvider.NewsText.Any() && whichState == InGameStates.News) || - (!_newsProvider.NewsText.Any() && whichState == InGameStates.Chat); + UpdatePanelDrawPosition(initialPosition: true); + _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => UpdatePanelDrawPosition(initialPosition: false); - if (_clientWindowSizeRepository.Resizable) + var panelConfig = new IniReader(Constants.PanelLayoutFile); + if (panelConfig.Load()) { - retPanel.UpdateOrder = -1; - - UpdatePanelDrawPosition(initialPosition: true); - _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => UpdatePanelDrawPosition(initialPosition: false); - - var panelConfig = new IniReader(Constants.PanelLayoutFile); - if (panelConfig.Load()) + if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:X", out int x) && + panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:Y", out int y)) { - if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:X", out int x) && - panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:Y", out int y)) - { - retPanel.DrawPosition = new Vector2(x, y); - } - - if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:Visible", out bool visible)) - { - retPanel.Visible = visible; - } - - if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:DrawOrder", out int drawOrder)) - { - retPanel.DrawOrder = drawOrder; - } + retPanel.DrawPosition = new Vector2(x, y); } - } - return retPanel; - - void UpdatePanelDrawPosition(bool initialPosition) - { - if (initialPosition) + if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:Visible", out bool visible)) { - retPanel.DrawArea = retPanel.DrawArea.WithPosition(new Vector2( - (_clientWindowSizeRepository.Width - retPanel.DrawArea.Width) / 2, - _clientWindowSizeRepository.Height - 45 - retPanel.DrawArea.Height)); + retPanel.Visible = visible; } - else - { - if (_clientWindowSizeRepository.Width < retPanel.DrawPosition.X + retPanel.DrawArea.Width) - retPanel.DrawPosition = new Vector2(_clientWindowSizeRepository.Width - retPanel.DrawArea.Width, retPanel.DrawPosition.Y); - if (_clientWindowSizeRepository.Height < retPanel.DrawPosition.Y + retPanel.DrawArea.Height) - retPanel.DrawPosition = new Vector2(retPanel.DrawPosition.X, _clientWindowSizeRepository.Height - retPanel.DrawArea.Height); + if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:DrawOrder", out int drawOrder)) + { + retPanel.DrawOrder = drawOrder; } } } - private IGameComponent CreateSessionExpButton() - { - var btn = new XNAButton( - _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, transparent: true), - new Vector2(55, 0), - new Rectangle(331, 30, 22, 14), - new Rectangle(331, 30, 22, 14)) - { - DrawOrder = HUD_CONTROL_LAYER - }; - btn.OnClick += (_, _) => _hudButtonController.ClickSessionExp(); - btn.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return btn; - } + return retPanel; - private IGameComponent CreateQuestButton() + void UpdatePanelDrawPosition(bool initialPosition) { - var btn = new XNAButton( - _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, transparent: true), - new Vector2(77, 0), - new Rectangle(353, 30, 22, 14), - new Rectangle(353, 30, 22, 14)) + if (initialPosition) { - DrawOrder = HUD_CONTROL_LAYER - }; - btn.OnClick += (_, _) => _hudButtonController.ClickQuestStatus(); - btn.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return btn; - } + retPanel.DrawArea = retPanel.DrawArea.WithPosition(new Vector2( + (_clientWindowSizeRepository.Width - retPanel.DrawArea.Width) / 2, + _clientWindowSizeRepository.Height - 45 - retPanel.DrawArea.Height)); + } + else + { + if (_clientWindowSizeRepository.Width < retPanel.DrawPosition.X + retPanel.DrawArea.Width) + retPanel.DrawPosition = new Vector2(_clientWindowSizeRepository.Width - retPanel.DrawArea.Width, retPanel.DrawPosition.Y); - private IGameComponent CreateHPStatusBar() - { - var statusBar = new HPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; - statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return statusBar; + if (_clientWindowSizeRepository.Height < retPanel.DrawPosition.Y + retPanel.DrawArea.Height) + retPanel.DrawPosition = new Vector2(retPanel.DrawPosition.X, _clientWindowSizeRepository.Height - retPanel.DrawArea.Height); + } } + } - private IGameComponent CreateTPStatusBar() + private IGameComponent CreateSessionExpButton() + { + var btn = new XNAButton( + _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, transparent: true), + new Vector2(55, 0), + new Rectangle(331, 30, 22, 14), + new Rectangle(331, 30, 22, 14)) { - var statusBar = new TPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; - statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return statusBar; - } + DrawOrder = HUD_CONTROL_LAYER + }; + btn.OnClick += (_, _) => _hudButtonController.ClickSessionExp(); + btn.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return btn; + } - private IGameComponent CreateSPStatusBar() + private IGameComponent CreateQuestButton() + { + var btn = new XNAButton( + _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, transparent: true), + new Vector2(77, 0), + new Rectangle(353, 30, 22, 14), + new Rectangle(353, 30, 22, 14)) { - var statusBar = new SPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; - statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return statusBar; - } + DrawOrder = HUD_CONTROL_LAYER + }; + btn.OnClick += (_, _) => _hudButtonController.ClickQuestStatus(); + btn.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return btn; + } - private IGameComponent CreateTNLStatusBar() - { - var statusBar = new TNLStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository, _experienceTableProvider) { DrawOrder = HUD_CONTROL_LAYER }; - statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return statusBar; - } + private IGameComponent CreateHPStatusBar() + { + var statusBar = new HPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; + statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return statusBar; + } - private ChatModePictureBox CreateChatModePictureBox() - { - return new ChatModePictureBox(_nativeGraphicsManager, _clientWindowSizeRepository, _chatModeCalculator, _hudControlProvider) - { - DrawOrder = HUD_CONTROL_LAYER + 1 - }; - } + private IGameComponent CreateTPStatusBar() + { + var statusBar = new TPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; + statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return statusBar; + } - private ChatTextBox CreateChatTextBox() - { - var chatTextBox = new ChatTextBox(_nativeGraphicsManager, _clientWindowSizeRepository, _contentProvider) - { - Text = "", - Selected = true, - Visible = true, - DrawOrder = HUD_CONTROL_LAYER, - }; - chatTextBox.OnEnterPressed += (_, _) => _chatController.SendChatAndClearTextBox(); - chatTextBox.OnClicked += (_, _) => _chatController.SelectChatTextBox(); - chatTextBox.OnTextChanged += (_, _) => _chatController.ClearAndWarnIfJailAndGlobal(); + private IGameComponent CreateSPStatusBar() + { + var statusBar = new SPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; + statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return statusBar; + } - return chatTextBox; - } + private IGameComponent CreateTNLStatusBar() + { + var statusBar = new TNLStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository, _experienceTableProvider) { DrawOrder = HUD_CONTROL_LAYER }; + statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return statusBar; + } - private TimeLabel CreateClockLabel() + private ChatModePictureBox CreateChatModePictureBox() + { + return new ChatModePictureBox(_nativeGraphicsManager, _clientWindowSizeRepository, _chatModeCalculator, _hudControlProvider) { - return new TimeLabel(_clientWindowSizeRepository) { DrawOrder = HUD_CONTROL_LAYER + 1 }; - } + DrawOrder = HUD_CONTROL_LAYER + 1 + }; + } - private PeriodicStatUpdaterComponent CreatePeriodicStatUpdater() + private ChatTextBox CreateChatTextBox() + { + var chatTextBox = new ChatTextBox(_nativeGraphicsManager, _clientWindowSizeRepository, _contentProvider) { - return new PeriodicStatUpdaterComponent(_endlessGameProvider, _characterRepository); - } + Text = "", + Selected = true, + Visible = true, + DrawOrder = HUD_CONTROL_LAYER, + }; + chatTextBox.OnEnterPressed += (_, _) => _chatController.SendChatAndClearTextBox(); + chatTextBox.OnClicked += (_, _) => _chatController.SelectChatTextBox(); + chatTextBox.OnTextChanged += (_, _) => _chatController.ClearAndWarnIfJailAndGlobal(); + + return chatTextBox; + } - private UnknownEntitiesRequester CreateUnknownEntitiesRequester() - { - return new UnknownEntitiesRequester(_endlessGameProvider, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository, _currentMapStateRepository, - _npcRendererProvider, _characterRendererProvider, _unknownEntitiesRequestActions); - } + private TimeLabel CreateClockLabel() + { + return new TimeLabel(_clientWindowSizeRepository) { DrawOrder = HUD_CONTROL_LAYER + 1 }; + } - private StatusBarLabel CreateStatusLabel() - { - return new StatusBarLabel(_nativeGraphicsManager, _clientWindowSizeRepository, _statusLabelTextProvider) - { - Visible = true, - DrawOrder = HUD_CONTROL_LAYER, - }; - } + private PeriodicStatUpdaterComponent CreatePeriodicStatUpdater() + { + return new PeriodicStatUpdaterComponent(_endlessGameProvider, _characterRepository); + } - private CurrentUserInputTracker CreateCurrentUserInputTracker() - { - return new CurrentUserInputTracker(_endlessGameProvider, _userInputRepository); - } + private UnknownEntitiesRequester CreateUnknownEntitiesRequester() + { + return new UnknownEntitiesRequester(_endlessGameProvider, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository, _currentMapStateRepository, + _npcRendererProvider, _characterRendererProvider, _unknownEntitiesRequestActions); + } - private IUserInputHandler CreateUserInputHandler() + private StatusBarLabel CreateStatusLabel() + { + return new StatusBarLabel(_nativeGraphicsManager, _clientWindowSizeRepository, _statusLabelTextProvider) { - return _userInputHandlerFactory.CreateUserInputHandler(); - } + Visible = true, + DrawOrder = HUD_CONTROL_LAYER, + }; + } - private ICharacterAnimator CreateCharacterAnimator() - { - return new CharacterAnimator( - _endlessGameProvider, _characterRepository, _currentMapStateRepository, - _currentMapProvider, _spellSlotDataRepository, _characterActions, - _walkValidationActions, _pathFinder, _fixedTimeStepRepository, - _weaponMetadataProvider); - } + private CurrentUserInputTracker CreateCurrentUserInputTracker() + { + return new CurrentUserInputTracker(_endlessGameProvider, _userInputRepository); + } - private INPCAnimator CreateNPCAnimator() - { - return new NPCAnimator(_endlessGameProvider, _currentMapStateRepository, _fixedTimeStepRepository); - } + private IUserInputHandler CreateUserInputHandler() + { + return _userInputHandlerFactory.CreateUserInputHandler(); + } - private IPeriodicEmoteHandler CreatePeriodicEmoteHandler(ICharacterAnimator characterAnimator) - { - return new PeriodicEmoteHandler( - _endlessGameProvider, _characterActions, _chatBubbleActions, - _userInputTimeProvider, _characterRepository, characterAnimator, - _statusLabelSetter, _mainButtonController, _localizedStringFinder, - _sfxPlayer); - } + private ICharacterAnimator CreateCharacterAnimator() + { + return new CharacterAnimator( + _endlessGameProvider, _characterRepository, _currentMapStateRepository, + _currentMapProvider, _spellSlotDataRepository, _characterActions, + _walkValidationActions, _pathFinder, _fixedTimeStepRepository, + _weaponMetadataProvider); + } - private PreviousUserInputTracker CreatePreviousUserInputTracker() - { - return new PreviousUserInputTracker(_endlessGameProvider, _userInputRepository); - } + private INPCAnimator CreateNPCAnimator() + { + return new NPCAnimator(_endlessGameProvider, _currentMapStateRepository, _fixedTimeStepRepository); + } + + private IPeriodicEmoteHandler CreatePeriodicEmoteHandler(ICharacterAnimator characterAnimator) + { + return new PeriodicEmoteHandler( + _endlessGameProvider, _characterActions, _chatBubbleActions, + _userInputTimeProvider, _characterRepository, characterAnimator, + _statusLabelSetter, _mainButtonController, _localizedStringFinder, + _sfxPlayer); + } + + private PreviousUserInputTracker CreatePreviousUserInputTracker() + { + return new PreviousUserInputTracker(_endlessGameProvider, _userInputRepository); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/IDraggableItemContainer.cs b/EndlessClient/HUD/Controls/IDraggableItemContainer.cs index 39713bef4..b5df38b41 100644 --- a/EndlessClient/HUD/Controls/IDraggableItemContainer.cs +++ b/EndlessClient/HUD/Controls/IDraggableItemContainer.cs @@ -1,9 +1,8 @@ using XNAControls; -namespace EndlessClient.HUD.Controls +namespace EndlessClient.HUD.Controls; + +public interface IDraggableItemContainer : IXNAControl { - public interface IDraggableItemContainer : IXNAControl - { - bool NoItemsDragging(); - } + bool NoItemsDragging(); } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/IHudControlsFactory.cs b/EndlessClient/HUD/Controls/IHudControlsFactory.cs index dc788bcdb..ba6938641 100644 --- a/EndlessClient/HUD/Controls/IHudControlsFactory.cs +++ b/EndlessClient/HUD/Controls/IHudControlsFactory.cs @@ -2,12 +2,11 @@ using Microsoft.Xna.Framework; using System.Collections.Generic; -namespace EndlessClient.HUD.Controls +namespace EndlessClient.HUD.Controls; + +public interface IHudControlsFactory { - public interface IHudControlsFactory - { - void InjectChatController(IChatController chatController, IMainButtonController mainButtonController); + void InjectChatController(IChatController chatController, IMainButtonController mainButtonController); - IReadOnlyDictionary CreateHud(); - } + IReadOnlyDictionary CreateHud(); } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs b/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs index 02baaf161..70e13b2fa 100644 --- a/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs +++ b/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs @@ -5,68 +5,67 @@ using System; using System.Diagnostics; -namespace EndlessClient.HUD.Controls +namespace EndlessClient.HUD.Controls; + +public class PeriodicStatUpdaterComponent : GameComponent { - public class PeriodicStatUpdaterComponent : GameComponent + private readonly IEndlessGameProvider _gameProvider; + private readonly ICharacterRepository _characterRepository; + + private DateTime _lastUsageUpdateTime; + private Option _lastSpUpdateTime; + + public PeriodicStatUpdaterComponent(IEndlessGameProvider gameProvider, + ICharacterRepository characterRepository) + : base((Game)gameProvider.Game) { - private readonly IEndlessGameProvider _gameProvider; - private readonly ICharacterRepository _characterRepository; + _gameProvider = gameProvider; + _characterRepository = characterRepository; + _lastUsageUpdateTime = DateTime.Now; + _lastSpUpdateTime = Option.None(); + } - private DateTime _lastUsageUpdateTime; - private Option _lastSpUpdateTime; + public override void Initialize() + { + if (!_gameProvider.Game.Components.Contains(this)) + _gameProvider.Game.Components.Add(this); - public PeriodicStatUpdaterComponent(IEndlessGameProvider gameProvider, - ICharacterRepository characterRepository) - : base((Game)gameProvider.Game) - { - _gameProvider = gameProvider; - _characterRepository = characterRepository; - _lastUsageUpdateTime = DateTime.Now; - _lastSpUpdateTime = Option.None(); - } + base.Initialize(); + } - public override void Initialize() - { - if (!_gameProvider.Game.Components.Contains(this)) - _gameProvider.Game.Components.Add(this); + public override void Update(GameTime gameTime) + { + var stats = _characterRepository.MainCharacter.Stats; - base.Initialize(); + if ((DateTime.Now - _lastUsageUpdateTime).TotalMinutes >= 1) + { + stats = stats.WithNewStat(CharacterStat.Usage, stats.Stats[CharacterStat.Usage] + 1); + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithStats(stats); + _lastUsageUpdateTime = DateTime.Now; } - public override void Update(GameTime gameTime) + if (stats[CharacterStat.SP] < stats[CharacterStat.MaxSP] - 1) { - var stats = _characterRepository.MainCharacter.Stats; - - if ((DateTime.Now - _lastUsageUpdateTime).TotalMinutes >= 1) - { - stats = stats.WithNewStat(CharacterStat.Usage, stats.Stats[CharacterStat.Usage] + 1); - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithStats(stats); - _lastUsageUpdateTime = DateTime.Now; - } - - if (stats[CharacterStat.SP] < stats[CharacterStat.MaxSP] - 1) - { - _lastSpUpdateTime.Match( - some: t => + _lastSpUpdateTime.Match( + some: t => + { + // this seems close to 2 but is probably based on level and/or one of the stats + if (t.ElapsedMilliseconds > 2000 - Math.Max(800, _characterRepository.MainCharacter.Stats[CharacterStat.Level] * 80)) { - // this seems close to 2 but is probably based on level and/or one of the stats - if (t.ElapsedMilliseconds > 2000 - Math.Max(800, _characterRepository.MainCharacter.Stats[CharacterStat.Level] * 80)) - { - var spUpdate = _characterRepository.MainCharacter.RenderProperties.SitState != SitState.Standing ? 4 : 2; - var sp = Math.Min(stats[CharacterStat.SP] + spUpdate, stats[CharacterStat.MaxSP]); - stats = stats.WithNewStat(CharacterStat.SP, sp); - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithStats(stats); + var spUpdate = _characterRepository.MainCharacter.RenderProperties.SitState != SitState.Standing ? 4 : 2; + var sp = Math.Min(stats[CharacterStat.SP] + spUpdate, stats[CharacterStat.MaxSP]); + stats = stats.WithNewStat(CharacterStat.SP, sp); + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithStats(stats); - if (stats[CharacterStat.SP] == stats[CharacterStat.MaxSP]) - _lastSpUpdateTime = Option.None(); - else - _lastSpUpdateTime = Option.Some(Stopwatch.StartNew()); - } - }, - none: () => _lastSpUpdateTime = Option.Some(Stopwatch.StartNew())); - } - - base.Update(gameTime); + if (stats[CharacterStat.SP] == stats[CharacterStat.MaxSP]) + _lastSpUpdateTime = Option.None(); + else + _lastSpUpdateTime = Option.Some(Stopwatch.StartNew()); + } + }, + none: () => _lastSpUpdateTime = Option.Some(Stopwatch.StartNew())); } + + base.Update(gameTime); } } \ No newline at end of file diff --git a/EndlessClient/HUD/HudButtonController.cs b/EndlessClient/HUD/HudButtonController.cs index bc7947a3a..7c4d45808 100644 --- a/EndlessClient/HUD/HudButtonController.cs +++ b/EndlessClient/HUD/HudButtonController.cs @@ -5,120 +5,119 @@ using EOLib.Localization; using Moffat.EndlessOnline.SDK.Protocol.Net; -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +[AutoMappedType] +public class HudButtonController : IHudButtonController { - [AutoMappedType] - public class HudButtonController : IHudButtonController - { - private readonly IHudStateActions _hudStateActions; - private readonly IOnlinePlayerActions _onlinePlayerActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IQuestActions _questActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - - public HudButtonController(IHudStateActions hudStateActions, - IOnlinePlayerActions onlinePlayerActions, - IInGameDialogActions inGameDialogActions, - IQuestActions questActions, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder) - { - _hudStateActions = hudStateActions; - _onlinePlayerActions = onlinePlayerActions; - _inGameDialogActions = inGameDialogActions; - _questActions = questActions; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - } - - public void ShowNews() - { - _hudStateActions.SwitchToState(InGameStates.News); - } - - public void ClickInventory() - { - _hudStateActions.SwitchToState(InGameStates.Inventory); - } - - public void ClickViewMapToggle() - { - _hudStateActions.ToggleMapView(); - } - - public void ClickActiveSpells() - { - _hudStateActions.SwitchToState(InGameStates.ActiveSpells); - } - - public void ClickPassiveSpells() - { - _hudStateActions.SwitchToState(InGameStates.PassiveSpells); - } - - public void ClickChat() - { - _hudStateActions.SwitchToState(InGameStates.Chat); - } - - public void ClickStats() - { - _hudStateActions.SwitchToState(InGameStates.Stats); - } - - public void ClickOnlineList() - { - _onlinePlayerActions.RequestOnlinePlayers(fullList: true); - _hudStateActions.SwitchToState(InGameStates.OnlineList); - } - - public void ClickParty() - { - _hudStateActions.SwitchToState(InGameStates.Party); - } - - public void ClickSettings() - { - _hudStateActions.SwitchToState(InGameStates.Settings); - } - - public void ClickHelp() - { - _hudStateActions.SwitchToState(InGameStates.Help); - _inGameDialogActions.ShowHelpDialog(); - } - - public void ClickFriendList() - { - _inGameDialogActions.ShowFriendListDialog(); - _onlinePlayerActions.RequestOnlinePlayers(fullList: false); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - EOResourceID.STATUS_LABEL_FRIEND_LIST, - _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_USE_RIGHT_MOUSE_CLICK_DELETE)); - } - - public void ClickIgnoreList() - { - _inGameDialogActions.ShowIgnoreListDialog(); - _onlinePlayerActions.RequestOnlinePlayers(fullList: false); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - EOResourceID.STATUS_LABEL_IGNORE_LIST, - _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_USE_RIGHT_MOUSE_CLICK_DELETE)); - } - - public void ClickSessionExp() - { - _inGameDialogActions.ShowSessionExpDialog(); - } - - public void ClickQuestStatus() - { - _questActions.RequestQuestHistory(QuestPage.Progress); - _questActions.RequestQuestHistory(QuestPage.History); - _inGameDialogActions.ShowQuestStatusDialog(); - } + private readonly IHudStateActions _hudStateActions; + private readonly IOnlinePlayerActions _onlinePlayerActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IQuestActions _questActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + + public HudButtonController(IHudStateActions hudStateActions, + IOnlinePlayerActions onlinePlayerActions, + IInGameDialogActions inGameDialogActions, + IQuestActions questActions, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder) + { + _hudStateActions = hudStateActions; + _onlinePlayerActions = onlinePlayerActions; + _inGameDialogActions = inGameDialogActions; + _questActions = questActions; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + } + + public void ShowNews() + { + _hudStateActions.SwitchToState(InGameStates.News); + } + + public void ClickInventory() + { + _hudStateActions.SwitchToState(InGameStates.Inventory); + } + + public void ClickViewMapToggle() + { + _hudStateActions.ToggleMapView(); + } + + public void ClickActiveSpells() + { + _hudStateActions.SwitchToState(InGameStates.ActiveSpells); + } + + public void ClickPassiveSpells() + { + _hudStateActions.SwitchToState(InGameStates.PassiveSpells); + } + + public void ClickChat() + { + _hudStateActions.SwitchToState(InGameStates.Chat); + } + + public void ClickStats() + { + _hudStateActions.SwitchToState(InGameStates.Stats); + } + + public void ClickOnlineList() + { + _onlinePlayerActions.RequestOnlinePlayers(fullList: true); + _hudStateActions.SwitchToState(InGameStates.OnlineList); + } + + public void ClickParty() + { + _hudStateActions.SwitchToState(InGameStates.Party); + } + + public void ClickSettings() + { + _hudStateActions.SwitchToState(InGameStates.Settings); + } + + public void ClickHelp() + { + _hudStateActions.SwitchToState(InGameStates.Help); + _inGameDialogActions.ShowHelpDialog(); + } + + public void ClickFriendList() + { + _inGameDialogActions.ShowFriendListDialog(); + _onlinePlayerActions.RequestOnlinePlayers(fullList: false); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + EOResourceID.STATUS_LABEL_FRIEND_LIST, + _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_USE_RIGHT_MOUSE_CLICK_DELETE)); + } + + public void ClickIgnoreList() + { + _inGameDialogActions.ShowIgnoreListDialog(); + _onlinePlayerActions.RequestOnlinePlayers(fullList: false); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + EOResourceID.STATUS_LABEL_IGNORE_LIST, + _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_USE_RIGHT_MOUSE_CLICK_DELETE)); + } + + public void ClickSessionExp() + { + _inGameDialogActions.ShowSessionExpDialog(); + } + + public void ClickQuestStatus() + { + _questActions.RequestQuestHistory(QuestPage.Progress); + _questActions.RequestQuestHistory(QuestPage.History); + _inGameDialogActions.ShowQuestStatusDialog(); } } \ No newline at end of file diff --git a/EndlessClient/HUD/HudStateActions.cs b/EndlessClient/HUD/HudStateActions.cs index 1b2d78473..73c9466a8 100644 --- a/EndlessClient/HUD/HudStateActions.cs +++ b/EndlessClient/HUD/HudStateActions.cs @@ -8,78 +8,77 @@ using System; using System.Linq; -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +[AutoMappedType] +public class HudStateActions : IHudStateActions { - [AutoMappedType] - public class HudStateActions : IHudStateActions - { - private const int HUD_CONTROL_LAYER = 130; + private const int HUD_CONTROL_LAYER = 130; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IHudControlProvider _hudControlProvider; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IMapFileProvider _mapFileProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IHudControlProvider _hudControlProvider; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IMapFileProvider _mapFileProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - public HudStateActions(IStatusLabelSetter statusLabelSetter, - IHudControlProvider hudControlProvider, - ICurrentMapStateRepository currentMapStateRepository, - IMapFileProvider mapFileProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _statusLabelSetter = statusLabelSetter; - _hudControlProvider = hudControlProvider; - _currentMapStateRepository = currentMapStateRepository; - _mapFileProvider = mapFileProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - } + public HudStateActions(IStatusLabelSetter statusLabelSetter, + IHudControlProvider hudControlProvider, + ICurrentMapStateRepository currentMapStateRepository, + IMapFileProvider mapFileProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _statusLabelSetter = statusLabelSetter; + _hudControlProvider = hudControlProvider; + _currentMapStateRepository = currentMapStateRepository; + _mapFileProvider = mapFileProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + } - public void SwitchToState(InGameStates newState) - { - if (!_hudControlProvider.IsInGame) - return; + public void SwitchToState(InGameStates newState) + { + if (!_hudControlProvider.IsInGame) + return; - if (newState != InGameStates.News) - _hudControlProvider.GetComponent(Controls.HudControlIdentifier.NewsPanel).Visible = false; + if (newState != InGameStates.News) + _hudControlProvider.GetComponent(Controls.HudControlIdentifier.NewsPanel).Visible = false; - foreach (var panel in _hudControlProvider.HudPanels.Where(x => x.Visible)) - panel.Visible = _clientWindowSizeProvider.Resizable; + foreach (var panel in _hudControlProvider.HudPanels.Where(x => x.Visible)) + panel.Visible = _clientWindowSizeProvider.Resizable; - var targetPanel = _hudControlProvider.HudPanels.Single(x => IsPanelForRequestedState(x, newState)); - targetPanel.Visible = !targetPanel.Visible; + var targetPanel = _hudControlProvider.HudPanels.Single(x => IsPanelForRequestedState(x, newState)); + targetPanel.Visible = !targetPanel.Visible; - if (targetPanel.Visible && _clientWindowSizeProvider.Resizable) - targetPanel.DrawOrder = _hudControlProvider.HudPanels.Select(x => x.DrawOrder).Max() + 1; - } + if (targetPanel.Visible && _clientWindowSizeProvider.Resizable) + targetPanel.DrawOrder = _hudControlProvider.HudPanels.Select(x => x.DrawOrder).Max() + 1; + } - public void ToggleMapView() + public void ToggleMapView() + { + var mapFile = _mapFileProvider.MapFiles[_currentMapStateRepository.CurrentMapID]; + if (!mapFile.Properties.MapAvailable) { - var mapFile = _mapFileProvider.MapFiles[_currentMapStateRepository.CurrentMapID]; - if (!mapFile.Properties.MapAvailable) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_NO_MAP_OF_AREA); - return; - } - - _currentMapStateRepository.ShowMiniMap = !_currentMapStateRepository.ShowMiniMap; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_NO_MAP_OF_AREA); + return; } - private bool IsPanelForRequestedState(IHudPanel hudPanel, InGameStates newState) + _currentMapStateRepository.ShowMiniMap = !_currentMapStateRepository.ShowMiniMap; + } + + private bool IsPanelForRequestedState(IHudPanel hudPanel, InGameStates newState) + { + switch (newState) { - switch (newState) - { - case InGameStates.News: return hudPanel is NewsPanel; - case InGameStates.Inventory: return hudPanel is InventoryPanel; - case InGameStates.ActiveSpells: return hudPanel is ActiveSpellsPanel; - case InGameStates.PassiveSpells: return hudPanel is PassiveSpellsPanel; - case InGameStates.Chat: return hudPanel is ChatPanel; - case InGameStates.Stats: return hudPanel is StatsPanel; - case InGameStates.OnlineList: return hudPanel is OnlineListPanel; - case InGameStates.Party: return hudPanel is PartyPanel; - case InGameStates.Settings: return hudPanel is SettingsPanel; - case InGameStates.Help: return hudPanel is HelpPanel; - default: throw new ArgumentOutOfRangeException(nameof(newState), newState, null); - } + case InGameStates.News: return hudPanel is NewsPanel; + case InGameStates.Inventory: return hudPanel is InventoryPanel; + case InGameStates.ActiveSpells: return hudPanel is ActiveSpellsPanel; + case InGameStates.PassiveSpells: return hudPanel is PassiveSpellsPanel; + case InGameStates.Chat: return hudPanel is ChatPanel; + case InGameStates.Stats: return hudPanel is StatsPanel; + case InGameStates.OnlineList: return hudPanel is OnlineListPanel; + case InGameStates.Party: return hudPanel is PartyPanel; + case InGameStates.Settings: return hudPanel is SettingsPanel; + case InGameStates.Help: return hudPanel is HelpPanel; + default: throw new ArgumentOutOfRangeException(nameof(newState), newState, null); } } } \ No newline at end of file diff --git a/EndlessClient/HUD/IHudButtonController.cs b/EndlessClient/HUD/IHudButtonController.cs index 47a5e8ad8..bba953064 100644 --- a/EndlessClient/HUD/IHudButtonController.cs +++ b/EndlessClient/HUD/IHudButtonController.cs @@ -1,35 +1,34 @@ -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +public interface IHudButtonController { - public interface IHudButtonController - { - void ShowNews(); + void ShowNews(); - void ClickInventory(); + void ClickInventory(); - void ClickViewMapToggle(); + void ClickViewMapToggle(); - void ClickActiveSpells(); + void ClickActiveSpells(); - void ClickPassiveSpells(); + void ClickPassiveSpells(); - void ClickChat(); + void ClickChat(); - void ClickStats(); + void ClickStats(); - void ClickOnlineList(); + void ClickOnlineList(); - void ClickParty(); + void ClickParty(); - void ClickSettings(); + void ClickSettings(); - void ClickHelp(); + void ClickHelp(); - void ClickFriendList(); + void ClickFriendList(); - void ClickIgnoreList(); + void ClickIgnoreList(); - void ClickSessionExp(); + void ClickSessionExp(); - void ClickQuestStatus(); - } + void ClickQuestStatus(); } \ No newline at end of file diff --git a/EndlessClient/HUD/IHudStateActions.cs b/EndlessClient/HUD/IHudStateActions.cs index 83e06dba3..e7e7906c5 100644 --- a/EndlessClient/HUD/IHudStateActions.cs +++ b/EndlessClient/HUD/IHudStateActions.cs @@ -1,9 +1,8 @@ -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +public interface IHudStateActions { - public interface IHudStateActions - { - void SwitchToState(InGameStates newState); + void SwitchToState(InGameStates newState); - void ToggleMapView(); - } + void ToggleMapView(); } \ No newline at end of file diff --git a/EndlessClient/HUD/IStatusLabelSetter.cs b/EndlessClient/HUD/IStatusLabelSetter.cs index b28839090..a65bb682b 100644 --- a/EndlessClient/HUD/IStatusLabelSetter.cs +++ b/EndlessClient/HUD/IStatusLabelSetter.cs @@ -1,16 +1,15 @@ using EOLib.Domain.Interact.Quest; using EOLib.Localization; -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +public interface IStatusLabelSetter : IStatusLabelNotifier { - public interface IStatusLabelSetter : IStatusLabelNotifier - { - void SetStatusLabel(EOResourceID type, EOResourceID text, string appended = "", bool showChatError = false); + void SetStatusLabel(EOResourceID type, EOResourceID text, string appended = "", bool showChatError = false); - void SetStatusLabel(EOResourceID type, string prepended, EOResourceID text, bool showChatError = false); + void SetStatusLabel(EOResourceID type, string prepended, EOResourceID text, bool showChatError = false); - void SetStatusLabel(EOResourceID type, string text); + void SetStatusLabel(EOResourceID type, string text); - void SetStatusLabel(string text); - } + void SetStatusLabel(string text); } \ No newline at end of file diff --git a/EndlessClient/HUD/IStatusLabelTextRepository.cs b/EndlessClient/HUD/IStatusLabelTextRepository.cs index 59eb2d9ca..f8b7dd2de 100644 --- a/EndlessClient/HUD/IStatusLabelTextRepository.cs +++ b/EndlessClient/HUD/IStatusLabelTextRepository.cs @@ -1,34 +1,33 @@ using AutomaticTypeMapper; using System; -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +public interface IStatusLabelTextRepository { - public interface IStatusLabelTextRepository - { - string StatusText { get; set; } + string StatusText { get; set; } - DateTime SetTime { get; set; } - } + DateTime SetTime { get; set; } +} - public interface IStatusLabelTextProvider - { - string StatusText { get; } +public interface IStatusLabelTextProvider +{ + string StatusText { get; } - DateTime SetTime { get; } - } + DateTime SetTime { get; } +} - [MappedType(BaseType = typeof(IStatusLabelTextRepository), IsSingleton = true)] - [MappedType(BaseType = typeof(IStatusLabelTextProvider), IsSingleton = true)] - public class StatusLabelTextRepository : IStatusLabelTextRepository, IStatusLabelTextProvider - { - public string StatusText { get; set; } +[MappedType(BaseType = typeof(IStatusLabelTextRepository), IsSingleton = true)] +[MappedType(BaseType = typeof(IStatusLabelTextProvider), IsSingleton = true)] +public class StatusLabelTextRepository : IStatusLabelTextRepository, IStatusLabelTextProvider +{ + public string StatusText { get; set; } - public DateTime SetTime { get; set; } + public DateTime SetTime { get; set; } - public StatusLabelTextRepository() - { - StatusText = ""; - SetTime = DateTime.Now; - } + public StatusLabelTextRepository() + { + StatusText = ""; + SetTime = DateTime.Now; } } \ No newline at end of file diff --git a/EndlessClient/HUD/InGameStates.cs b/EndlessClient/HUD/InGameStates.cs index 22d67676f..20573374e 100644 --- a/EndlessClient/HUD/InGameStates.cs +++ b/EndlessClient/HUD/InGameStates.cs @@ -1,18 +1,17 @@ -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +public enum InGameStates { - public enum InGameStates - { - Inventory, - ViewMapToggle, - ActiveSpells, - PassiveSpells, - Chat, - Stats, - OnlineList, - Party, - Macro, - Settings, - Help, - News - } + Inventory, + ViewMapToggle, + ActiveSpells, + PassiveSpells, + Chat, + Stats, + OnlineList, + Party, + Macro, + Settings, + Help, + News } \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventoryPanelItem.cs b/EndlessClient/HUD/Inventory/InventoryPanelItem.cs index 10400ca73..ef9745c31 100644 --- a/EndlessClient/HUD/Inventory/InventoryPanelItem.cs +++ b/EndlessClient/HUD/Inventory/InventoryPanelItem.cs @@ -15,221 +15,220 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Inventory +namespace EndlessClient.HUD.Inventory; + +public class InventoryPanelItem : DraggablePanelItem { - public class InventoryPanelItem : DraggablePanelItem - { - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly Texture2D _itemGraphic; - private readonly Texture2D _highlightBackground; - private readonly XNALabel _nameLabel; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly Texture2D _itemGraphic; + private readonly Texture2D _highlightBackground; + private readonly XNALabel _nameLabel; - private int _slot; + private int _slot; - private Option _highlightDrawPosition; + private Option _highlightDrawPosition; - public int Slot + public int Slot + { + get => _slot; + set { - get => _slot; - set - { - _slot = value; - DrawPosition = GetPosition(_slot); - UpdateNameLabelPosition(); - } + _slot = value; + DrawPosition = GetPosition(_slot); + UpdateNameLabelPosition(); } + } - public InventoryItem InventoryItem { get; set; } + public InventoryItem InventoryItem { get; set; } - public string Text + public string Text + { + get => _nameLabel.Text; + set { - get => _nameLabel.Text; - set - { - _nameLabel.Text = value; - _nameLabel.ResizeBasedOnText(16, 9); - UpdateNameLabelPosition(); - } + _nameLabel.Text = value; + _nameLabel.ResizeBasedOnText(16, 9); + UpdateNameLabelPosition(); } + } + + public event EventHandler DoubleClick; + + public override Rectangle EventArea => IsDragging ? DrawArea : DrawAreaWithParentOffset; + + // uses absolute coordinates + protected override Rectangle GridArea => new Rectangle( + _parentContainer.DrawPositionWithParentOffset.ToPoint() + new Point(12, 8), + new Point(363, 102)); - public event EventHandler DoubleClick; + public InventoryPanelItem(IItemNameColorService itemNameColorService, + InventoryPanel inventoryPanel, + IActiveDialogProvider activeDialogProvider, + ISfxPlayer sfxPlayer, + int slot, + InventoryItem inventoryItem, + EIFRecord data) + : base(inventoryPanel) + { + _activeDialogProvider = activeDialogProvider; + _sfxPlayer = sfxPlayer; - public override Rectangle EventArea => IsDragging ? DrawArea : DrawAreaWithParentOffset; + Slot = slot; + InventoryItem = inventoryItem; + Data = data; - // uses absolute coordinates - protected override Rectangle GridArea => new Rectangle( - _parentContainer.DrawPositionWithParentOffset.ToPoint() + new Point(12, 8), - new Point(363, 102)); + _itemGraphic = inventoryPanel.NativeGraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic, transparent: true); + _highlightBackground = new Texture2D(Game.GraphicsDevice, 1, 1); + _highlightBackground.SetData(new[] { Color.FromNonPremultiplied(200, 200, 200, 60) }); - public InventoryPanelItem(IItemNameColorService itemNameColorService, - InventoryPanel inventoryPanel, - IActiveDialogProvider activeDialogProvider, - ISfxPlayer sfxPlayer, - int slot, - InventoryItem inventoryItem, - EIFRecord data) - : base(inventoryPanel) + _nameLabel = new XNALabel(Constants.FontSize08) { - _activeDialogProvider = activeDialogProvider; - _sfxPlayer = sfxPlayer; - - Slot = slot; - InventoryItem = inventoryItem; - Data = data; - - _itemGraphic = inventoryPanel.NativeGraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic, transparent: true); - _highlightBackground = new Texture2D(Game.GraphicsDevice, 1, 1); - _highlightBackground.SetData(new[] { Color.FromNonPremultiplied(200, 200, 200, 60) }); - - _nameLabel = new XNALabel(Constants.FontSize08) - { - Visible = false, - AutoSize = false, - TextAlign = LabelAlignment.MiddleCenter, - ForeColor = itemNameColorService.GetColorForInventoryDisplay(Data), - BackColor = Color.FromNonPremultiplied(30, 30, 30, 160), - Text = string.Empty - }; - - OnMouseEnter += (_, _) => _nameLabel.Visible = _parentContainer.NoItemsDragging() && _activeDialogProvider.PaperdollDialog.Match(d => d.NoItemsDragging(), () => true); - OnMouseOver += InventoryPanelItem_OnMouseOver; - OnMouseLeave += (_, _) => - { - _nameLabel.Visible = false; - _highlightDrawPosition = Option.None(); - }; - - DraggingStarted += (_, _) => - { - _nameLabel.Visible = false; - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - }; - - var (slotWidth, slotHeight) = Data.Size.GetDimensions(); - SetSize(slotWidth * 26 - 3, slotHeight * 26 - 3); - } + Visible = false, + AutoSize = false, + TextAlign = LabelAlignment.MiddleCenter, + ForeColor = itemNameColorService.GetColorForInventoryDisplay(Data), + BackColor = Color.FromNonPremultiplied(30, 30, 30, 160), + Text = string.Empty + }; + + OnMouseEnter += (_, _) => _nameLabel.Visible = _parentContainer.NoItemsDragging() && _activeDialogProvider.PaperdollDialog.Match(d => d.NoItemsDragging(), () => true); + OnMouseOver += InventoryPanelItem_OnMouseOver; + OnMouseLeave += (_, _) => + { + _nameLabel.Visible = false; + _highlightDrawPosition = Option.None(); + }; - public int GetCurrentSlotBasedOnPosition() + DraggingStarted += (_, _) => { - if (!IsDragging) - return Slot; + _nameLabel.Visible = false; + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + }; - return (int)((DrawPosition.X - OldOffset.X) / 26) + InventoryPanel.InventoryRowSlots * (int)((DrawPosition.Y - OldOffset.Y) / 26); - } + var (slotWidth, slotHeight) = Data.Size.GetDimensions(); + SetSize(slotWidth * 26 - 3, slotHeight * 26 - 3); + } + + public int GetCurrentSlotBasedOnPosition() + { + if (!IsDragging) + return Slot; + + return (int)((DrawPosition.X - OldOffset.X) / 26) + InventoryPanel.InventoryRowSlots * (int)((DrawPosition.Y - OldOffset.Y) / 26); + } - public override void Initialize() + public override void Initialize() + { + _nameLabel.Initialize(); + _nameLabel.SetParentControl(_parentContainer); + _nameLabel.ResizeBasedOnText(16, 9); + //_nameLabel.DrawOrderChanged += (_, e) => + //{ + // _nameLabel.DrawOrder = _parentContainer.DrawOrder + 200 + //}; + + base.Initialize(); + } + + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); + + _highlightDrawPosition.MatchSome(drawPosition => { - _nameLabel.Initialize(); - _nameLabel.SetParentControl(_parentContainer); - _nameLabel.ResizeBasedOnText(16, 9); - //_nameLabel.DrawOrderChanged += (_, e) => - //{ - // _nameLabel.DrawOrder = _parentContainer.DrawOrder + 200 - //}; + if (GridArea.Contains(DrawArea.WithPosition(drawPosition))) + _spriteBatch.Draw(_highlightBackground, DrawArea.WithPosition(drawPosition), Color.White); + }); - base.Initialize(); + if (IsDragging) + { + _spriteBatch.Draw(_itemGraphic, DrawPosition, Color.FromNonPremultiplied(255, 255, 255, 128)); } - - protected override void OnDrawControl(GameTime gameTime) + else { - _spriteBatch.Begin(); - - _highlightDrawPosition.MatchSome(drawPosition => - { - if (GridArea.Contains(DrawArea.WithPosition(drawPosition))) - _spriteBatch.Draw(_highlightBackground, DrawArea.WithPosition(drawPosition), Color.White); - }); - - if (IsDragging) - { - _spriteBatch.Draw(_itemGraphic, DrawPosition, Color.FromNonPremultiplied(255, 255, 255, 128)); - } - else - { - _spriteBatch.Draw(_itemGraphic, DrawPositionWithParentOffset, Color.FromNonPremultiplied(255, 255, 255, 255)); - } - - _spriteBatch.End(); - base.OnDrawControl(gameTime); + _spriteBatch.Draw(_itemGraphic, DrawPositionWithParentOffset, Color.FromNonPremultiplied(255, 255, 255, 255)); } - private void InventoryPanelItem_OnMouseOver(object sender, MouseStateExtended e) - { - if (!GridArea.Contains(e.Position)) - return; + _spriteBatch.End(); + base.OnDrawControl(gameTime); + } - var currentSlot = GetCurrentSlotBasedOnPosition(); - _highlightDrawPosition = Option.Some(GetPosition(currentSlot) + (IsDragging ? OldOffset : ImmediateParent.DrawPositionWithParentOffset)); - } + private void InventoryPanelItem_OnMouseOver(object sender, MouseStateExtended e) + { + if (!GridArea.Contains(e.Position)) + return; - protected override bool HandleDoubleClick(IXNAControl control, MouseEventArgs eventArgs) + var currentSlot = GetCurrentSlotBasedOnPosition(); + _highlightDrawPosition = Option.Some(GetPosition(currentSlot) + (IsDragging ? OldOffset : ImmediateParent.DrawPositionWithParentOffset)); + } + + protected override bool HandleDoubleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (IsDragging) { - if (IsDragging) - { - // roll back the first click in the double click - base.HandleClick(control, eventArgs); - } + // roll back the first click in the double click + base.HandleClick(control, eventArgs); + } - DoubleClick?.Invoke(control, Data); + DoubleClick?.Invoke(control, Data); - return true; - } + return true; + } - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - _nameLabel.Dispose(); - _highlightBackground.Dispose(); - } - - base.Dispose(disposing); + _nameLabel.Dispose(); + _highlightBackground.Dispose(); } - private void UpdateNameLabelPosition() + base.Dispose(disposing); + } + + private void UpdateNameLabelPosition() + { + if (_nameLabel == null) + return; + + // the name label is parented to the inventory panel so that all name labels draw over all items (see draw orders below) + // the actual position of the name label needs to be set to this control's draw position + var actualPosition = DrawPosition; + + if (actualPosition.X + _nameLabel.DrawAreaWithParentOffset.Width + DrawArea.Width > GridArea.Width) { - if (_nameLabel == null) - return; - - // the name label is parented to the inventory panel so that all name labels draw over all items (see draw orders below) - // the actual position of the name label needs to be set to this control's draw position - var actualPosition = DrawPosition; - - if (actualPosition.X + _nameLabel.DrawAreaWithParentOffset.Width + DrawArea.Width > GridArea.Width) - { - _nameLabel.DrawPosition = new Vector2(actualPosition.X - _nameLabel.DrawArea.Width, actualPosition.Y); - } - else - { - _nameLabel.DrawPosition = new Vector2(actualPosition.X + DrawArea.Width, actualPosition.Y); - } - - DrawOrder = _parentContainer.DrawOrder + 2; - _nameLabel.DrawOrder = _parentContainer.DrawOrder + 200; + _nameLabel.DrawPosition = new Vector2(actualPosition.X - _nameLabel.DrawArea.Width, actualPosition.Y); } - - protected override void OnDraggingFinished(DragCompletedEventArgs args) + else { - base.OnDraggingFinished(args); + _nameLabel.DrawPosition = new Vector2(actualPosition.X + DrawArea.Width, actualPosition.Y); + } - if (args.ContinueDrag) - return; + DrawOrder = _parentContainer.DrawOrder + 2; + _nameLabel.DrawOrder = _parentContainer.DrawOrder + 200; + } - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + protected override void OnDraggingFinished(DragCompletedEventArgs args) + { + base.OnDraggingFinished(args); - if (!args.RestoreOriginalSlot) - Slot = GetCurrentSlotBasedOnPosition(); - else - DrawPosition = GetPosition(Slot); + if (args.ContinueDrag) + return; - _nameLabel.Visible = false; - UpdateNameLabelPosition(); - } + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - private static Vector2 GetPosition(int slot) - { - return new Vector2(13 + 26 * (slot % InventoryPanel.InventoryRowSlots), 9 + 26 * (slot / InventoryPanel.InventoryRowSlots)); - } + if (!args.RestoreOriginalSlot) + Slot = GetCurrentSlotBasedOnPosition(); + else + DrawPosition = GetPosition(Slot); + + _nameLabel.Visible = false; + UpdateNameLabelPosition(); + } + + private static Vector2 GetPosition(int slot) + { + return new Vector2(13 + 26 * (slot % InventoryPanel.InventoryRowSlots), 9 + 26 * (slot / InventoryPanel.InventoryRowSlots)); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventoryService.cs b/EndlessClient/HUD/Inventory/InventoryService.cs index c1b43937a..8bf113bee 100644 --- a/EndlessClient/HUD/Inventory/InventoryService.cs +++ b/EndlessClient/HUD/Inventory/InventoryService.cs @@ -5,109 +5,108 @@ using Optional; using System.Collections.Generic; -namespace EndlessClient.HUD.Inventory +namespace EndlessClient.HUD.Inventory; + +[AutoMappedType] +public class InventoryService : IInventoryService { - [AutoMappedType] - public class InventoryService : IInventoryService + public Option GetNextOpenSlot(bool[,] usedSlots, ItemSize size, Option preferredSlot) { - public Option GetNextOpenSlot(bool[,] usedSlots, ItemSize size, Option preferredSlot) - { - var (sizeWidth, sizeHeight) = size.GetDimensions(); + var (sizeWidth, sizeHeight) = size.GetDimensions(); - var preferredSlotIsValid = preferredSlot.Match( - some: slot => IsSlotOpen(usedSlots, Option.None(), slot, size), - none: () => false); + var preferredSlotIsValid = preferredSlot.Match( + some: slot => IsSlotOpen(usedSlots, Option.None(), slot, size), + none: () => false); - if (preferredSlotIsValid) - return preferredSlot; + if (preferredSlotIsValid) + return preferredSlot; - for (int r = 0; r < usedSlots.GetLength(0); r++) + for (int r = 0; r < usedSlots.GetLength(0); r++) + { + for (int c = 0; c < usedSlots.GetLength(1); c++) { - for (int c = 0; c < usedSlots.GetLength(1); c++) - { - var slot = r * InventoryPanel.InventoryRowSlots + c; - if (!usedSlots[r, c] && IsSlotOpen(usedSlots, Option.None(), slot, size)) - return Option.Some(slot); - } + var slot = r * InventoryPanel.InventoryRowSlots + c; + if (!usedSlots[r, c] && IsSlotOpen(usedSlots, Option.None(), slot, size)) + return Option.Some(slot); } - - return Option.None(); } - public void SetSlots(bool[,] usedSlots, int slot, ItemSize size) - { - SetSlotValue(usedSlots, slot, size, value: true); - } + return Option.None(); + } - public void ClearSlots(bool[,] usedSlots, int slot, ItemSize size) - { - SetSlotValue(usedSlots, slot, size, value: false); - } + public void SetSlots(bool[,] usedSlots, int slot, ItemSize size) + { + SetSlotValue(usedSlots, slot, size, value: true); + } - public bool FitsInSlot(bool[,] usedSlots, int oldSlot, int newSlot, ItemSize size) => - IsSlotOpen(usedSlots, Option.Some(oldSlot), newSlot, size); + public void ClearSlots(bool[,] usedSlots, int slot, ItemSize size) + { + SetSlotValue(usedSlots, slot, size, value: false); + } - public bool FitsInSlot(bool[,] usedSlots, int newSlot, ItemSize size) => - IsSlotOpen(usedSlots, Option.None(), newSlot, size); + public bool FitsInSlot(bool[,] usedSlots, int oldSlot, int newSlot, ItemSize size) => + IsSlotOpen(usedSlots, Option.Some(oldSlot), newSlot, size); - private bool IsSlotOpen(bool[,] usedSlots, Option oldSlot, int slot, ItemSize size) - { - var (sizeWidth, sizeHeight) = size.GetDimensions(); + public bool FitsInSlot(bool[,] usedSlots, int newSlot, ItemSize size) => + IsSlotOpen(usedSlots, Option.None(), newSlot, size); - var ignorePoints = new List<(int X, int Y)>(); - oldSlot.MatchSome(s => - { - var oldCol = s % InventoryPanel.InventoryRowSlots; - var oldRow = s / InventoryPanel.InventoryRowSlots; + private bool IsSlotOpen(bool[,] usedSlots, Option oldSlot, int slot, ItemSize size) + { + var (sizeWidth, sizeHeight) = size.GetDimensions(); + + var ignorePoints = new List<(int X, int Y)>(); + oldSlot.MatchSome(s => + { + var oldCol = s % InventoryPanel.InventoryRowSlots; + var oldRow = s / InventoryPanel.InventoryRowSlots; - for (int r = oldRow; r < oldRow + sizeHeight; r++) - for (int c = oldCol; c < oldCol + sizeWidth; c++) - ignorePoints.Add((c, r)); - }); + for (int r = oldRow; r < oldRow + sizeHeight; r++) + for (int c = oldCol; c < oldCol + sizeWidth; c++) + ignorePoints.Add((c, r)); + }); - var col = slot % InventoryPanel.InventoryRowSlots; - var row = slot / InventoryPanel.InventoryRowSlots; - for (int r = row; r < row + sizeHeight; r++) + var col = slot % InventoryPanel.InventoryRowSlots; + var row = slot / InventoryPanel.InventoryRowSlots; + for (int r = row; r < row + sizeHeight; r++) + { + for (int c = col; c < col + sizeWidth; c++) { - for (int c = col; c < col + sizeWidth; c++) - { - if (r >= usedSlots.GetLength(0) || c >= usedSlots.GetLength(1) || - r < 0 || c < 0 || - (!ignorePoints.Contains((c, r)) && usedSlots[r, c])) - return false; - } + if (r >= usedSlots.GetLength(0) || c >= usedSlots.GetLength(1) || + r < 0 || c < 0 || + (!ignorePoints.Contains((c, r)) && usedSlots[r, c])) + return false; } - - return true; } - private void SetSlotValue(bool[,] usedSlots, int slot, ItemSize size, bool value) - { - var (sizeWidth, sizeHeight) = size.GetDimensions(); + return true; + } + + private void SetSlotValue(bool[,] usedSlots, int slot, ItemSize size, bool value) + { + var (sizeWidth, sizeHeight) = size.GetDimensions(); - var slotCol = slot % InventoryPanel.InventoryRowSlots; - var slotRow = slot / InventoryPanel.InventoryRowSlots; + var slotCol = slot % InventoryPanel.InventoryRowSlots; + var slotRow = slot / InventoryPanel.InventoryRowSlots; - for (int r = slotRow; r < slotRow + sizeHeight; r++) + for (int r = slotRow; r < slotRow + sizeHeight; r++) + { + for (int c = slotCol; c < slotCol + sizeWidth; c++) { - for (int c = slotCol; c < slotCol + sizeWidth; c++) - { - if (r < usedSlots.GetLength(0) && c < usedSlots.GetLength(1)) - usedSlots[r, c] = value; - } + if (r < usedSlots.GetLength(0) && c < usedSlots.GetLength(1)) + usedSlots[r, c] = value; } } } +} - public interface IInventoryService - { - Option GetNextOpenSlot(bool[,] usedSlots, ItemSize size, Option preferredSlot); - void SetSlots(bool[,] usedSlots, int slot, ItemSize size); +public interface IInventoryService +{ + Option GetNextOpenSlot(bool[,] usedSlots, ItemSize size, Option preferredSlot); + void SetSlots(bool[,] usedSlots, int slot, ItemSize size); - void ClearSlots(bool[,] usedSlots, int slot, ItemSize size); + void ClearSlots(bool[,] usedSlots, int slot, ItemSize size); - bool FitsInSlot(bool[,] usedSlots, int oldSlot, int newSlot, ItemSize size); + bool FitsInSlot(bool[,] usedSlots, int oldSlot, int newSlot, ItemSize size); - bool FitsInSlot(bool[,] usedSlots, int newSlot, ItemSize size); - } + bool FitsInSlot(bool[,] usedSlots, int newSlot, ItemSize size); } \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventorySlotRepository.cs b/EndlessClient/HUD/Inventory/InventorySlotRepository.cs index aa4be9371..5cf65074a 100644 --- a/EndlessClient/HUD/Inventory/InventorySlotRepository.cs +++ b/EndlessClient/HUD/Inventory/InventorySlotRepository.cs @@ -4,42 +4,41 @@ using EOLib.IO.Map; using System.Collections.Generic; -namespace EndlessClient.HUD.Inventory +namespace EndlessClient.HUD.Inventory; + +public interface IInventorySlotRepository { - public interface IInventorySlotRepository - { - Matrix FilledSlots { get; set; } + Matrix FilledSlots { get; set; } - Dictionary SlotMap { get; set; } - } + Dictionary SlotMap { get; set; } +} - public interface IInventorySlotProvider - { - IReadOnlyMatrix FilledSlots { get; } +public interface IInventorySlotProvider +{ + IReadOnlyMatrix FilledSlots { get; } - IReadOnlyDictionary SlotMap { get; } - } + IReadOnlyDictionary SlotMap { get; } +} - [AutoMappedType(IsSingleton = true)] - public class InventorySlotRepository : IInventorySlotProvider, IInventorySlotRepository, IResettable - { - public Matrix FilledSlots { get; set; } +[AutoMappedType(IsSingleton = true)] +public class InventorySlotRepository : IInventorySlotProvider, IInventorySlotRepository, IResettable +{ + public Matrix FilledSlots { get; set; } - public Dictionary SlotMap { get; set; } + public Dictionary SlotMap { get; set; } - IReadOnlyMatrix IInventorySlotProvider.FilledSlots => FilledSlots; + IReadOnlyMatrix IInventorySlotProvider.FilledSlots => FilledSlots; - IReadOnlyDictionary IInventorySlotProvider.SlotMap => SlotMap; + IReadOnlyDictionary IInventorySlotProvider.SlotMap => SlotMap; - public InventorySlotRepository() - { - ResetState(); - } + public InventorySlotRepository() + { + ResetState(); + } - public void ResetState() - { - FilledSlots = new Matrix(InventoryPanel.InventoryRows, InventoryPanel.InventoryRowSlots, false); - SlotMap = new Dictionary(); - } + public void ResetState() + { + FilledSlots = new Matrix(InventoryPanel.InventoryRows, InventoryPanel.InventoryRowSlots, false); + SlotMap = new Dictionary(); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs b/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs index 4cbeac495..4eec02bdd 100644 --- a/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs +++ b/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs @@ -9,81 +9,80 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.HUD.Inventory +namespace EndlessClient.HUD.Inventory; + +[AutoMappedType] +public class InventorySpaceValidator : IInventorySpaceValidator { - [AutoMappedType] - public class InventorySpaceValidator : IInventorySpaceValidator + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IInventorySlotProvider _inventorySlotProvider; + private readonly IInventoryService _inventoryService; + + public InventorySpaceValidator(IEIFFileProvider eifFileProvider, + ICharacterInventoryProvider characterInventoryProvider, + IInventorySlotProvider inventorySlotProvider, + IInventoryService inventoryService) { - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IInventorySlotProvider _inventorySlotProvider; - private readonly IInventoryService _inventoryService; + _eifFileProvider = eifFileProvider; + _characterInventoryProvider = characterInventoryProvider; + _inventorySlotProvider = inventorySlotProvider; + _inventoryService = inventoryService; + } - public InventorySpaceValidator(IEIFFileProvider eifFileProvider, - ICharacterInventoryProvider characterInventoryProvider, - IInventorySlotProvider inventorySlotProvider, - IInventoryService inventoryService) - { - _eifFileProvider = eifFileProvider; - _characterInventoryProvider = characterInventoryProvider; - _inventorySlotProvider = inventorySlotProvider; - _inventoryService = inventoryService; - } + public bool ItemFits(MapItem item) + { + return _characterInventoryProvider.ItemInventory.Any(x => x.ItemID == item.ItemID) || ItemFits(item.ItemID); + } - public bool ItemFits(MapItem item) - { - return _characterInventoryProvider.ItemInventory.Any(x => x.ItemID == item.ItemID) || ItemFits(item.ItemID); - } + public bool ItemFits(int itemId) + { + return _characterInventoryProvider.ItemInventory.Any(x => x.ItemID == itemId) || ItemFits(_eifFileProvider.EIFFile[itemId].Size); + } - public bool ItemFits(int itemId) - { - return _characterInventoryProvider.ItemInventory.Any(x => x.ItemID == itemId) || ItemFits(_eifFileProvider.EIFFile[itemId].Size); - } + public bool ItemsFit(IReadOnlyList outItems, IReadOnlyList inItems) + { + var slotsCopy = new Matrix(_inventorySlotProvider.FilledSlots); - public bool ItemsFit(IReadOnlyList outItems, IReadOnlyList inItems) + foreach (var item in outItems) { - var slotsCopy = new Matrix(_inventorySlotProvider.FilledSlots); - - foreach (var item in outItems) - { - var itemData = _eifFileProvider.EIFFile[item.ItemID]; - _inventorySlotProvider.SlotMap.SingleOrNone(x => x.Value == item.ItemID) - .Map(x => x.Key) - .MatchSome(x => _inventoryService.ClearSlots(slotsCopy, x, itemData.Size)); - } - - foreach (var item in inItems) - { - var itemData = _eifFileProvider.EIFFile[item.ItemID]; - var itemFits = _inventoryService - .GetNextOpenSlot(slotsCopy, itemData.Size, Option.None()) - .Match(some: slot => - { - _inventoryService.SetSlots(slotsCopy, slot, itemData.Size); - return true; - }, - none: () => false); - if (!itemFits) - return false; - } - - return true; + var itemData = _eifFileProvider.EIFFile[item.ItemID]; + _inventorySlotProvider.SlotMap.SingleOrNone(x => x.Value == item.ItemID) + .Map(x => x.Key) + .MatchSome(x => _inventoryService.ClearSlots(slotsCopy, x, itemData.Size)); } - private bool ItemFits(ItemSize itemSize) + foreach (var item in inItems) { - return _inventoryService - .GetNextOpenSlot((Matrix)_inventorySlotProvider.FilledSlots, itemSize, Option.None()) - .HasValue; + var itemData = _eifFileProvider.EIFFile[item.ItemID]; + var itemFits = _inventoryService + .GetNextOpenSlot(slotsCopy, itemData.Size, Option.None()) + .Match(some: slot => + { + _inventoryService.SetSlots(slotsCopy, slot, itemData.Size); + return true; + }, + none: () => false); + if (!itemFits) + return false; } + + return true; } - public interface IInventorySpaceValidator + private bool ItemFits(ItemSize itemSize) { - bool ItemFits(MapItem item); + return _inventoryService + .GetNextOpenSlot((Matrix)_inventorySlotProvider.FilledSlots, itemSize, Option.None()) + .HasValue; + } +} - bool ItemFits(int itemId); +public interface IInventorySpaceValidator +{ + bool ItemFits(MapItem item); - bool ItemsFit(IReadOnlyList outItems, IReadOnlyList inItems); - } + bool ItemFits(int itemId); + + bool ItemsFit(IReadOnlyList outItems, IReadOnlyList inItems); } \ No newline at end of file diff --git a/EndlessClient/HUD/ItemNameColorService.cs b/EndlessClient/HUD/ItemNameColorService.cs index c41fe4a20..371951261 100644 --- a/EndlessClient/HUD/ItemNameColorService.cs +++ b/EndlessClient/HUD/ItemNameColorService.cs @@ -4,34 +4,33 @@ using EOLib.IO.Pub; using Microsoft.Xna.Framework; -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +[AutoMappedType] +public class ItemNameColorService : IItemNameColorService { - [AutoMappedType] - public class ItemNameColorService : IItemNameColorService - { - public Color GetColorForInventoryDisplay(EIFRecord itemData) => GetColor(itemData, ColorConstants.LightGrayText); + public Color GetColorForInventoryDisplay(EIFRecord itemData) => GetColor(itemData, ColorConstants.LightGrayText); - public Color GetColorForMapDisplay(EIFRecord itemData) => GetColor(itemData, Color.White); + public Color GetColorForMapDisplay(EIFRecord itemData) => GetColor(itemData, Color.White); - private static Color GetColor(EIFRecord itemData, Color defaultColor) + private static Color GetColor(EIFRecord itemData, Color defaultColor) + { + switch (itemData.Special) { - switch (itemData.Special) - { - case ItemSpecial.Lore: - case ItemSpecial.Unique: - return Color.FromNonPremultiplied(0xff, 0xf0, 0xa5, 0xff); - case ItemSpecial.Rare: - return Color.FromNonPremultiplied(0xf5, 0xc8, 0x9c, 0xff); - } - - return defaultColor; + case ItemSpecial.Lore: + case ItemSpecial.Unique: + return Color.FromNonPremultiplied(0xff, 0xf0, 0xa5, 0xff); + case ItemSpecial.Rare: + return Color.FromNonPremultiplied(0xf5, 0xc8, 0x9c, 0xff); } + + return defaultColor; } +} - public interface IItemNameColorService - { - Color GetColorForMapDisplay(EIFRecord itemData); +public interface IItemNameColorService +{ + Color GetColorForMapDisplay(EIFRecord itemData); - Color GetColorForInventoryDisplay(EIFRecord itemData); - } + Color GetColorForInventoryDisplay(EIFRecord itemData); } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs b/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs index 0178d79ef..44e4c340e 100644 --- a/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs +++ b/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs @@ -32,594 +32,593 @@ using static EndlessClient.HUD.Spells.SpellPanelItem; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class ActiveSpellsPanel : DraggableHudPanel, IHudPanel, IDraggableItemContainer { - public class ActiveSpellsPanel : DraggableHudPanel, IHudPanel, IDraggableItemContainer + public const int SpellRows = 4; + public const int SpellRowLength = 8; + + private readonly ITrainingController _trainingController; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IESFFileProvider _esfFileProvider; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly IHudControlProvider _hudControlProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IConfigurationProvider _configProvider; + + private readonly Dictionary _spellSlotMap; + private readonly List _childItems; + + private readonly Texture2D _functionKeyLabelSheet; + private Rectangle _functionKeyRow1Source, _functionKeyRow2Source; + + private readonly XNALabel _selectedSpellName, _selectedSpellLevel, _totalSkillPoints; + private readonly XNAButton _levelUpButton1, _levelUpButton2; + private readonly ScrollBar _scrollBar; + + private HashSet _cachedSpells; + private CharacterStats _cachedStats; + private Option _cachedSelectedSpell; + + private bool _confirmedTraining; + private int _lastScrollOffset; + private Texture2D _activeSpellIcon; + + public INativeGraphicsManager NativeGraphicsManager { get; } + + public ActiveSpellsPanel(INativeGraphicsManager nativeGraphicsManager, + ITrainingController trainingController, + IEOMessageBoxFactory messageBoxFactory, + IStatusLabelSetter statusLabelSetter, + IPlayerInfoProvider playerInfoProvider, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IESFFileProvider esfFileProvider, + ISpellSlotDataRepository spellSlotDataRepository, + IHudControlProvider hudControlProvider, + ISfxPlayer sfxPlayer, + IConfigurationProvider configProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - public const int SpellRows = 4; - public const int SpellRowLength = 8; - - private readonly ITrainingController _trainingController; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IESFFileProvider _esfFileProvider; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly IHudControlProvider _hudControlProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IConfigurationProvider _configProvider; - - private readonly Dictionary _spellSlotMap; - private readonly List _childItems; - - private readonly Texture2D _functionKeyLabelSheet; - private Rectangle _functionKeyRow1Source, _functionKeyRow2Source; - - private readonly XNALabel _selectedSpellName, _selectedSpellLevel, _totalSkillPoints; - private readonly XNAButton _levelUpButton1, _levelUpButton2; - private readonly ScrollBar _scrollBar; - - private HashSet _cachedSpells; - private CharacterStats _cachedStats; - private Option _cachedSelectedSpell; - - private bool _confirmedTraining; - private int _lastScrollOffset; - private Texture2D _activeSpellIcon; - - public INativeGraphicsManager NativeGraphicsManager { get; } - - public ActiveSpellsPanel(INativeGraphicsManager nativeGraphicsManager, - ITrainingController trainingController, - IEOMessageBoxFactory messageBoxFactory, - IStatusLabelSetter statusLabelSetter, - IPlayerInfoProvider playerInfoProvider, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IESFFileProvider esfFileProvider, - ISpellSlotDataRepository spellSlotDataRepository, - IHudControlProvider hudControlProvider, - ISfxPlayer sfxPlayer, - IConfigurationProvider configProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + NativeGraphicsManager = nativeGraphicsManager; + _trainingController = trainingController; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _playerInfoProvider = playerInfoProvider; + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _esfFileProvider = esfFileProvider; + _spellSlotDataRepository = spellSlotDataRepository; + _hudControlProvider = hudControlProvider; + _sfxPlayer = sfxPlayer; + _configProvider = configProvider; + + _spellSlotMap = GetSpellSlotMap(_playerInfoProvider.LoggedInAccountName, _characterProvider.MainCharacter.Name, _configProvider.Host); + _childItems = new List(); + + _cachedSpells = new HashSet(); + + _functionKeyLabelSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); + _functionKeyRow1Source = new Rectangle(148, 51, 18, 13); + _functionKeyRow2Source = new Rectangle(148 + 18 * 8, 51, 18, 13); + + _selectedSpellName = new XNALabel(Constants.FontSize08pt5) { - NativeGraphicsManager = nativeGraphicsManager; - _trainingController = trainingController; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _playerInfoProvider = playerInfoProvider; - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _esfFileProvider = esfFileProvider; - _spellSlotDataRepository = spellSlotDataRepository; - _hudControlProvider = hudControlProvider; - _sfxPlayer = sfxPlayer; - _configProvider = configProvider; - - _spellSlotMap = GetSpellSlotMap(_playerInfoProvider.LoggedInAccountName, _characterProvider.MainCharacter.Name, _configProvider.Host); - _childItems = new List(); - - _cachedSpells = new HashSet(); - - _functionKeyLabelSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); - _functionKeyRow1Source = new Rectangle(148, 51, 18, 13); - _functionKeyRow2Source = new Rectangle(148 + 18 * 8, 51, 18, 13); - - _selectedSpellName = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(9, 50, 81, 13), - Visible = false, - Text = "", - AutoSize = false, - TextAlign = LabelAlignment.MiddleCenter, - ForeColor = ColorConstants.LightGrayText, - }; - - _selectedSpellLevel = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(32, 78, 42, 15), - Visible = true, - Text = "0", - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText, - }; - - _totalSkillPoints = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(32, 96, 42, 15), - Visible = true, - Text = _characterProvider.MainCharacter.Stats[CharacterStat.SkillPoints].ToString(), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText, - }; - - var buttonSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); - _levelUpButton1 = new XNAButton(buttonSheet, new Vector2(71, 77), new Rectangle(215, 386, 19, 15), new Rectangle(234, 386, 19, 15)) - { - FlashSpeed = 500, - Visible = false - }; - _levelUpButton1.OnClick += LevelUp_Click; + DrawArea = new Rectangle(9, 50, 81, 13), + Visible = false, + Text = "", + AutoSize = false, + TextAlign = LabelAlignment.MiddleCenter, + ForeColor = ColorConstants.LightGrayText, + }; + + _selectedSpellLevel = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(32, 78, 42, 15), + Visible = true, + Text = "0", + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText, + }; + + _totalSkillPoints = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(32, 96, 42, 15), + Visible = true, + Text = _characterProvider.MainCharacter.Stats[CharacterStat.SkillPoints].ToString(), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText, + }; + + var buttonSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); + _levelUpButton1 = new XNAButton(buttonSheet, new Vector2(71, 77), new Rectangle(215, 386, 19, 15), new Rectangle(234, 386, 19, 15)) + { + FlashSpeed = 500, + Visible = false + }; + _levelUpButton1.OnClick += LevelUp_Click; - _levelUpButton2 = new XNAButton(buttonSheet, new Vector2(71, 95), new Rectangle(215, 386, 19, 15), new Rectangle(234, 386, 19, 15)) - { - FlashSpeed = 500, - Visible = false - }; - _levelUpButton2.OnClick += LevelUp_Click; + _levelUpButton2 = new XNAButton(buttonSheet, new Vector2(71, 95), new Rectangle(215, 386, 19, 15), new Rectangle(234, 386, 19, 15)) + { + FlashSpeed = 500, + Visible = false + }; + _levelUpButton2.OnClick += LevelUp_Click; - _scrollBar = new ScrollBar(new Vector2(467, 2), new Vector2(16, 115), ScrollBarColors.LightOnMed, NativeGraphicsManager) - { - LinesToRender = 2 - }; - _scrollBar.UpdateDimensions(4); - SetScrollWheelHandler(_scrollBar); + _scrollBar = new ScrollBar(new Vector2(467, 2), new Vector2(16, 115), ScrollBarColors.LightOnMed, NativeGraphicsManager) + { + LinesToRender = 2 + }; + _scrollBar.UpdateDimensions(4); + SetScrollWheelHandler(_scrollBar); - BackgroundImage = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 62); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + BackgroundImage = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 62); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - Game.Exiting += SaveSpellsFile; - } + Game.Exiting += SaveSpellsFile; + } - public bool NoItemsDragging() => _childItems.All(x => !x.IsDragging); + public bool NoItemsDragging() => _childItems.All(x => !x.IsDragging); - public override void Initialize() - { - _selectedSpellName.Initialize(); - _selectedSpellName.SetParentControl(this); + public override void Initialize() + { + _selectedSpellName.Initialize(); + _selectedSpellName.SetParentControl(this); - _selectedSpellLevel.Initialize(); - _selectedSpellLevel.SetParentControl(this); + _selectedSpellLevel.Initialize(); + _selectedSpellLevel.SetParentControl(this); - _totalSkillPoints.Initialize(); - _totalSkillPoints.SetParentControl(this); + _totalSkillPoints.Initialize(); + _totalSkillPoints.SetParentControl(this); - _levelUpButton1.Initialize(); - _levelUpButton1.SetParentControl(this); + _levelUpButton1.Initialize(); + _levelUpButton1.SetParentControl(this); - _levelUpButton2.Initialize(); - _levelUpButton2.SetParentControl(this); + _levelUpButton2.Initialize(); + _levelUpButton2.SetParentControl(this); - _scrollBar.Initialize(); - _scrollBar.SetParentControl(this); + _scrollBar.Initialize(); + _scrollBar.SetParentControl(this); - base.Initialize(); - } + base.Initialize(); + } - protected override void OnUnconditionalUpdateControl(GameTime gameTime) + protected override void OnUnconditionalUpdateControl(GameTime gameTime) + { + if (!_cachedSpells.SetEquals(_characterInventoryProvider.SpellInventory)) { - if (!_cachedSpells.SetEquals(_characterInventoryProvider.SpellInventory)) - { - var added = _characterInventoryProvider.SpellInventory.Where(i => !_cachedSpells.Any(j => i.ID == j.ID)); - var removed = _cachedSpells.Where(i => !_characterInventoryProvider.SpellInventory.Any(j => i.ID == j.ID)); - var updated = _characterInventoryProvider.SpellInventory.Except(added) - .Where(i => _cachedSpells.Any(j => i.ID == j.ID && i.Level != j.Level)); + var added = _characterInventoryProvider.SpellInventory.Where(i => !_cachedSpells.Any(j => i.ID == j.ID)); + var removed = _cachedSpells.Where(i => !_characterInventoryProvider.SpellInventory.Any(j => i.ID == j.ID)); + var updated = _characterInventoryProvider.SpellInventory.Except(added) + .Where(i => _cachedSpells.Any(j => i.ID == j.ID && i.Level != j.Level)); - foreach (var spell in removed) + foreach (var spell in removed) + { + var matchedSpell = _childItems.SingleOrNone(x => x.InventorySpell.ID == spell.ID); + matchedSpell.MatchSome(childControl => { - var matchedSpell = _childItems.SingleOrNone(x => x.InventorySpell.ID == spell.ID); - matchedSpell.MatchSome(childControl => - { - childControl.SetControlUnparented(); - childControl.Dispose(); - _childItems.Remove(childControl); + childControl.SetControlUnparented(); + childControl.Dispose(); + _childItems.Remove(childControl); - _spellSlotDataRepository.SpellSlots[childControl.Slot] = Option.None(); - }); - } + _spellSlotDataRepository.SpellSlots[childControl.Slot] = Option.None(); + }); + } - foreach (var spell in updated) + foreach (var spell in updated) + { + var matchedSpell = _childItems.SingleOrNone(x => x.InventorySpell.ID == spell.ID); + matchedSpell.MatchSome(childControl => { - var matchedSpell = _childItems.SingleOrNone(x => x.InventorySpell.ID == spell.ID); - matchedSpell.MatchSome(childControl => + childControl.InventorySpell = spell; + _spellSlotDataRepository.SelectedSpellSlot.MatchSome(s => { - childControl.InventorySpell = spell; - _spellSlotDataRepository.SelectedSpellSlot.MatchSome(s => - { - if (childControl.Slot == s) - _selectedSpellLevel.Text = spell.Level.ToString(); - }); + if (childControl.Slot == s) + _selectedSpellLevel.Text = spell.Level.ToString(); }); - } + }); + } - foreach (var spell in added) - { - var spellData = _esfFileProvider.ESFFile[spell.ID]; - - var preferredSlot = _spellSlotMap.SingleOrNone(x => x.Value == spell.ID).Map(x => x.Key); - var actualSlot = preferredSlot.Match( - some: x => - { - return _childItems.OfType().Any(ci => ci.Slot == x) - ? GetNextOpenSlot(_childItems) - : Option.Some(x); - }, - none: () => GetNextOpenSlot(_childItems)); - - actualSlot.MatchSome(slot => - { - var newChild = new SpellPanelItem(this, _sfxPlayer, slot, spell, spellData); - newChild.Initialize(); - newChild.SetParentControl(this); + foreach (var spell in added) + { + var spellData = _esfFileProvider.ESFFile[spell.ID]; - // this is required so scroll works while click+dragging when the control becomes unparented - newChild.SetScrollWheelHandler(_scrollBar); + var preferredSlot = _spellSlotMap.SingleOrNone(x => x.Value == spell.ID).Map(x => x.Key); + var actualSlot = preferredSlot.Match( + some: x => + { + return _childItems.OfType().Any(ci => ci.Slot == x) + ? GetNextOpenSlot(_childItems) + : Option.Some(x); + }, + none: () => GetNextOpenSlot(_childItems)); - newChild.Click += (sender, _) => _spellSlotDataRepository.SelectedSpellSlot = Option.Some(((SpellPanelItem)sender).Slot); - newChild.OnMouseOver += SetSpellStatusLabelHover; - newChild.DraggingFinishing += HandleItemDoneDragging; + actualSlot.MatchSome(slot => + { + var newChild = new SpellPanelItem(this, _sfxPlayer, slot, spell, spellData); + newChild.Initialize(); + newChild.SetParentControl(this); - _childItems.Add(newChild); - _spellSlotDataRepository.SpellSlots[slot] = Option.Some(spell); - }); - } + // this is required so scroll works while click+dragging when the control becomes unparented + newChild.SetScrollWheelHandler(_scrollBar); - if (added.Any()) - UpdateSpellItemsForScroll(); + newChild.Click += (sender, _) => _spellSlotDataRepository.SelectedSpellSlot = Option.Some(((SpellPanelItem)sender).Slot); + newChild.OnMouseOver += SetSpellStatusLabelHover; + newChild.DraggingFinishing += HandleItemDoneDragging; - _cachedSpells = _characterInventoryProvider.SpellInventory.ToHashSet(); + _childItems.Add(newChild); + _spellSlotDataRepository.SpellSlots[slot] = Option.Some(spell); + }); } - base.OnUnconditionalUpdateControl(gameTime); + if (added.Any()) + UpdateSpellItemsForScroll(); + + _cachedSpells = _characterInventoryProvider.SpellInventory.ToHashSet(); } - protected override void OnUpdateControl(GameTime gameTime) + base.OnUnconditionalUpdateControl(gameTime); + } + + protected override void OnUpdateControl(GameTime gameTime) + { + var kbd = KeyboardExtended.GetState(); + if (kbd.WasKeyJustUp(Keys.RightShift) || kbd.WasKeyJustDown(Keys.RightShift) || + kbd.WasKeyJustUp(Keys.LeftShift) || kbd.WasKeyJustDown(Keys.LeftShift)) { - var kbd = KeyboardExtended.GetState(); - if (kbd.WasKeyJustUp(Keys.RightShift) || kbd.WasKeyJustDown(Keys.RightShift) || - kbd.WasKeyJustUp(Keys.LeftShift) || kbd.WasKeyJustDown(Keys.LeftShift)) - { - SwapFunctionKeySourceRectangles(); - } + SwapFunctionKeySourceRectangles(); + } - if (_lastScrollOffset != _scrollBar.ScrollOffset) - { - UpdateSpellItemsForScroll(); - } + if (_lastScrollOffset != _scrollBar.ScrollOffset) + { + UpdateSpellItemsForScroll(); + } - if (_cachedStats != _characterProvider.MainCharacter.Stats && _activeSpellIcon != null) - { - _cachedStats = _characterProvider.MainCharacter.Stats; - var skillPoints = _cachedStats[CharacterStat.SkillPoints]; - _totalSkillPoints.Text = skillPoints.ToString(); + if (_cachedStats != _characterProvider.MainCharacter.Stats && _activeSpellIcon != null) + { + _cachedStats = _characterProvider.MainCharacter.Stats; + var skillPoints = _cachedStats[CharacterStat.SkillPoints]; + _totalSkillPoints.Text = skillPoints.ToString(); - _levelUpButton1.Visible = skillPoints > 0; - _levelUpButton2.Visible = skillPoints > 0; - } + _levelUpButton1.Visible = skillPoints > 0; + _levelUpButton2.Visible = skillPoints > 0; + } - _cachedSelectedSpell.Match( - some: cached => _spellSlotDataRepository.SelectedSpellSlot.Match( - some: repoSlot => - { - if (cached != repoSlot) - { - SetSelectedSpell(repoSlot); - _cachedSelectedSpell = _spellSlotDataRepository.SelectedSpellSlot; - } - }, - none: () => - { - ClearSelectedSpell(); - _cachedSelectedSpell = Option.None(); - }), - none: () => _spellSlotDataRepository.SelectedSpellSlot.MatchSome( - some: repoSlot => + _cachedSelectedSpell.Match( + some: cached => _spellSlotDataRepository.SelectedSpellSlot.Match( + some: repoSlot => + { + if (cached != repoSlot) { SetSelectedSpell(repoSlot); _cachedSelectedSpell = _spellSlotDataRepository.SelectedSpellSlot; - })); + } + }, + none: () => + { + ClearSelectedSpell(); + _cachedSelectedSpell = Option.None(); + }), + none: () => _spellSlotDataRepository.SelectedSpellSlot.MatchSome( + some: repoSlot => + { + SetSelectedSpell(repoSlot); + _cachedSelectedSpell = _spellSlotDataRepository.SelectedSpellSlot; + })); - base.OnUpdateControl(gameTime); - } + base.OnUpdateControl(gameTime); + } - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - _spriteBatch.Begin(); + _spriteBatch.Begin(); - DrawFunctionKeyLabels(); - DrawActiveSpell(); + DrawFunctionKeyLabels(); + DrawActiveSpell(); - _spriteBatch.End(); - } + _spriteBatch.End(); + } + + private void DrawFunctionKeyLabels() + { + if (_scrollBar.ScrollOffset >= 2) + return; - private void DrawFunctionKeyLabels() + for (int i = 0; i < 8; ++i) { - if (_scrollBar.ScrollOffset >= 2) - return; + var offset = _functionKeyRow1Source.Width * i; - for (int i = 0; i < 8; ++i) + if (_scrollBar.ScrollOffset == 0) { - var offset = _functionKeyRow1Source.Width * i; - - if (_scrollBar.ScrollOffset == 0) - { - _spriteBatch.Draw(_functionKeyLabelSheet, - DrawPosition + new Vector2(100 + 45 * i, 8), - _functionKeyRow1Source.WithPosition((_functionKeyRow1Source.Location + new Point(offset, 0)).ToVector2()), - Color.White); - } + _spriteBatch.Draw(_functionKeyLabelSheet, + DrawPosition + new Vector2(100 + 45 * i, 8), + _functionKeyRow1Source.WithPosition((_functionKeyRow1Source.Location + new Point(offset, 0)).ToVector2()), + Color.White); + } - if (_scrollBar.ScrollOffset < 2) - { - var yCoord = _scrollBar.ScrollOffset == 0 ? 90 : 38; - _spriteBatch.Draw(_functionKeyLabelSheet, - DrawPosition + new Vector2(100 + 45 * i, yCoord), - _functionKeyRow2Source.WithPosition((_functionKeyRow2Source.Location + new Point(offset, 0)).ToVector2()), - Color.White); - } + if (_scrollBar.ScrollOffset < 2) + { + var yCoord = _scrollBar.ScrollOffset == 0 ? 90 : 38; + _spriteBatch.Draw(_functionKeyLabelSheet, + DrawPosition + new Vector2(100 + 45 * i, yCoord), + _functionKeyRow2Source.WithPosition((_functionKeyRow2Source.Location + new Point(offset, 0)).ToVector2()), + Color.White); } } + } - private void DrawActiveSpell() - { - if (_activeSpellIcon == null) - return; + private void DrawActiveSpell() + { + if (_activeSpellIcon == null) + return; - var srcRect = new Rectangle(0, 0, _activeSpellIcon.Width / 2, _activeSpellIcon.Height); - var dstRect = new Rectangle(DrawAreaWithParentOffset.X + 32, DrawAreaWithParentOffset.Y + 14, srcRect.Width, srcRect.Height); - _spriteBatch.Draw(_activeSpellIcon, dstRect, srcRect, Color.White); - } + var srcRect = new Rectangle(0, 0, _activeSpellIcon.Width / 2, _activeSpellIcon.Height); + var dstRect = new Rectangle(DrawAreaWithParentOffset.X + 32, DrawAreaWithParentOffset.Y + 14, srcRect.Width, srcRect.Height); + _spriteBatch.Draw(_activeSpellIcon, dstRect, srcRect, Color.White); + } - private void LevelUp_Click(object sender, EventArgs args) + private void LevelUp_Click(object sender, EventArgs args) + { + if (!_confirmedTraining) { - if (!_confirmedTraining) + //apparently this is NOT stored in the edf files... + //NOTE: copy-pasted from EOCharacterStats button event handler. Should probably be in some shared function somewhere. + var dialog = _messageBoxFactory.CreateMessageBox("Do you want to train?", + "Skill training", + EODialogButtons.OkCancel); + dialog.DialogClosing += (_, e) => { - //apparently this is NOT stored in the edf files... - //NOTE: copy-pasted from EOCharacterStats button event handler. Should probably be in some shared function somewhere. - var dialog = _messageBoxFactory.CreateMessageBox("Do you want to train?", - "Skill training", - EODialogButtons.OkCancel); - dialog.DialogClosing += (_, e) => - { - if (e.Result == XNADialogResult.OK) - _confirmedTraining = true; - }; - dialog.ShowDialog(); - } - else + if (e.Result == XNADialogResult.OK) + _confirmedTraining = true; + }; + dialog.ShowDialog(); + } + else + { + _cachedSelectedSpell.MatchSome(slot => { - _cachedSelectedSpell.MatchSome(slot => - { - _childItems.SingleOrNone(x => x.Slot == slot) - .MatchSome(x => _trainingController.AddSkillPoint(x.Data.ID)); - }); - } + _childItems.SingleOrNone(x => x.Slot == slot) + .MatchSome(x => _trainingController.AddSkillPoint(x.Data.ID)); + }); } + } - private void SetSelectedSpell(int slot) - { - _childItems.OfType().SingleOrNone(x => x.Slot == slot) - .MatchSome(spell => - { - var spellData = spell.Data; + private void SetSelectedSpell(int slot) + { + _childItems.OfType().SingleOrNone(x => x.Slot == slot) + .MatchSome(spell => + { + var spellData = spell.Data; - _activeSpellIcon = NativeGraphicsManager.TextureFromResource(GFXTypes.SpellIcons, spellData.Icon); + _activeSpellIcon = NativeGraphicsManager.TextureFromResource(GFXTypes.SpellIcons, spellData.Icon); - _selectedSpellName.Text = spellData.Name; - _selectedSpellName.Visible = true; + _selectedSpellName.Text = spellData.Name; + _selectedSpellName.Visible = true; - _selectedSpellLevel.Text = spell.InventorySpell.Level.ToString(); + _selectedSpellLevel.Text = spell.InventorySpell.Level.ToString(); - _levelUpButton1.Visible = _levelUpButton2.Visible = _characterProvider.MainCharacter.Stats[CharacterStat.SkillPoints] > 0; - }); - } + _levelUpButton1.Visible = _levelUpButton2.Visible = _characterProvider.MainCharacter.Stats[CharacterStat.SkillPoints] > 0; + }); + } - private void ClearSelectedSpell() - { - _activeSpellIcon = null; + private void ClearSelectedSpell() + { + _activeSpellIcon = null; - _selectedSpellName.Text = string.Empty; - _selectedSpellName.Visible = false; + _selectedSpellName.Text = string.Empty; + _selectedSpellName.Visible = false; - _selectedSpellLevel.Text = "0"; + _selectedSpellLevel.Text = "0"; - _levelUpButton1.Visible = _levelUpButton2.Visible = false; - } + _levelUpButton1.Visible = _levelUpButton2.Visible = false; + } - private void SetSpellStatusLabelHover(object sender, MouseStateExtended e) - { - var spellPanelItem = sender as SpellPanelItem; - if (spellPanelItem == null || spellPanelItem.IsDragging) - return; + private void SetSpellStatusLabelHover(object sender, MouseStateExtended e) + { + var spellPanelItem = sender as SpellPanelItem; + if (spellPanelItem == null || spellPanelItem.IsDragging) + return; + + _statusLabelSetter.SetStatusLabel(EOResourceID.SKILLMASTER_WORD_SPELL, spellPanelItem.Data.Name); + } + + private void HandleItemDoneDragging(object sender, DragCompletedEventArgs e) + { + var item = sender as SpellPanelItem; + if (item == null) + return; - _statusLabelSetter.SetStatusLabel(EOResourceID.SKILLMASTER_WORD_SPELL, spellPanelItem.Data.Name); + if (e.DragOutOfBounds) + { + e.RestoreOriginalSlot = true; + return; } - private void HandleItemDoneDragging(object sender, DragCompletedEventArgs e) + var oldSlot = item.Slot; + var newSlot = item.GetCurrentSlotBasedOnPosition(_scrollBar.ScrollOffset); + + if (oldSlot != newSlot && + newSlot < (_scrollBar.ScrollOffset + _scrollBar.LinesToRender) * SpellRowLength && + newSlot >= _scrollBar.ScrollOffset * SpellRowLength) { - var item = sender as SpellPanelItem; - if (item == null) - return; + _childItems.SingleOrNone(x => x.Slot == newSlot) + .Match(child => + { + var oldDisplaySlot = item.DisplaySlot; + var newDisplaySlot = child.DisplaySlot; - if (e.DragOutOfBounds) - { - e.RestoreOriginalSlot = true; - return; - } + item.Slot = newSlot; + item.DisplaySlot = newDisplaySlot; - var oldSlot = item.Slot; - var newSlot = item.GetCurrentSlotBasedOnPosition(_scrollBar.ScrollOffset); + child.Slot = oldSlot; + child.DisplaySlot = oldDisplaySlot; - if (oldSlot != newSlot && - newSlot < (_scrollBar.ScrollOffset + _scrollBar.LinesToRender) * SpellRowLength && - newSlot >= _scrollBar.ScrollOffset * SpellRowLength) - { - _childItems.SingleOrNone(x => x.Slot == newSlot) - .Match(child => - { - var oldDisplaySlot = item.DisplaySlot; - var newDisplaySlot = child.DisplaySlot; + _spellSlotDataRepository.SpellSlots[oldSlot] = Option.Some(child.InventorySpell); + _spellSlotDataRepository.SpellSlots[newSlot] = Option.Some(item.InventorySpell); + _spellSlotDataRepository.SelectedSpellSlot = Option.Some(newSlot); + _spellSlotDataRepository.SpellIsPrepared = false; + }, + () => + { + item.Slot = newSlot; + item.DisplaySlot = newSlot - (SpellRowLength * _scrollBar.ScrollOffset); - item.Slot = newSlot; - item.DisplaySlot = newDisplaySlot; + _spellSlotDataRepository.SpellSlots[oldSlot] = Option.None(); + _spellSlotDataRepository.SpellSlots[newSlot] = Option.Some(item.InventorySpell); + _spellSlotDataRepository.SelectedSpellSlot = Option.Some(newSlot); + _spellSlotDataRepository.SpellIsPrepared = false; + }); - child.Slot = oldSlot; - child.DisplaySlot = oldDisplaySlot; + UpdateSpellItemsForScroll(); + } + } - _spellSlotDataRepository.SpellSlots[oldSlot] = Option.Some(child.InventorySpell); - _spellSlotDataRepository.SpellSlots[newSlot] = Option.Some(item.InventorySpell); - _spellSlotDataRepository.SelectedSpellSlot = Option.Some(newSlot); - _spellSlotDataRepository.SpellIsPrepared = false; - }, - () => - { - item.Slot = newSlot; - item.DisplaySlot = newSlot - (SpellRowLength * _scrollBar.ScrollOffset); + private Option GetNextOpenSlot(IEnumerable childItems) + { + return _spellSlotDataRepository.SpellSlots + .Select((spellItem, slot) => (SpellItem: spellItem, Slot: slot)) + .Where(pair => !pair.SpellItem.HasValue && childItems.All(x => x.Slot != pair.Slot)) + .FirstOrNone() + .Map(x => x.Slot); + } - _spellSlotDataRepository.SpellSlots[oldSlot] = Option.None(); - _spellSlotDataRepository.SpellSlots[newSlot] = Option.Some(item.InventorySpell); - _spellSlotDataRepository.SelectedSpellSlot = Option.Some(newSlot); - _spellSlotDataRepository.SpellIsPrepared = false; - }); + private void SwapFunctionKeySourceRectangles() + { + var tmpRect = _functionKeyRow2Source; + _functionKeyRow2Source = _functionKeyRow1Source; + _functionKeyRow1Source = tmpRect; + } - UpdateSpellItemsForScroll(); - } - } + private void UpdateSpellItemsForScroll() + { + var firstValidSlot = _scrollBar.ScrollOffset * SpellRowLength; + var lastValidSlot = firstValidSlot + 2 * SpellRowLength; - private Option GetNextOpenSlot(IEnumerable childItems) + var itemsToHide = _childItems.Where(x => x.Slot < firstValidSlot || x.Slot >= lastValidSlot).ToList(); + foreach (var item in itemsToHide) { - return _spellSlotDataRepository.SpellSlots - .Select((spellItem, slot) => (SpellItem: spellItem, Slot: slot)) - .Where(pair => !pair.SpellItem.HasValue && childItems.All(x => x.Slot != pair.Slot)) - .FirstOrNone() - .Map(x => x.Slot); - } + if (!item.IsDragging) + item.Visible = false; - private void SwapFunctionKeySourceRectangles() - { - var tmpRect = _functionKeyRow2Source; - _functionKeyRow2Source = _functionKeyRow1Source; - _functionKeyRow1Source = tmpRect; + item.DisplaySlot = GetDisplaySlotFromSlot(item.Slot); } - private void UpdateSpellItemsForScroll() + foreach (var item in _childItems.Except(itemsToHide)) { - var firstValidSlot = _scrollBar.ScrollOffset * SpellRowLength; - var lastValidSlot = firstValidSlot + 2 * SpellRowLength; - - var itemsToHide = _childItems.Where(x => x.Slot < firstValidSlot || x.Slot >= lastValidSlot).ToList(); - foreach (var item in itemsToHide) - { - if (!item.IsDragging) - item.Visible = false; - - item.DisplaySlot = GetDisplaySlotFromSlot(item.Slot); - } + item.Visible = true; + item.DisplaySlot = item.Slot - firstValidSlot; + } - foreach (var item in _childItems.Except(itemsToHide)) - { - item.Visible = true; - item.DisplaySlot = item.Slot - firstValidSlot; - } + _lastScrollOffset = _scrollBar.ScrollOffset; + } - _lastScrollOffset = _scrollBar.ScrollOffset; - } + private int GetDisplaySlotFromSlot(int newSlot) + { + var offset = _scrollBar.ScrollOffset; + return newSlot - SpellRowLength * offset; + } - private int GetDisplaySlotFromSlot(int newSlot) + protected override void Dispose(bool disposing) + { + if (disposing) { - var offset = _scrollBar.ScrollOffset; - return newSlot - SpellRowLength * offset; + Game.Exiting -= SaveSpellsFile; + SaveSpellsFile(null, EventArgs.Empty); } - protected override void Dispose(bool disposing) - { - if (disposing) - { - Game.Exiting -= SaveSpellsFile; - SaveSpellsFile(null, EventArgs.Empty); - } + base.Dispose(disposing); + } - base.Dispose(disposing); - } + #region Slot loading - #region Slot loading + private static Dictionary GetSpellSlotMap(string accountName, string characterName, string host) + { + var map = new Dictionary(); - private static Dictionary GetSpellSlotMap(string accountName, string characterName, string host) + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !File.Exists(Constants.SpellsFile)) { - var map = new Dictionary(); - - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !File.Exists(Constants.SpellsFile)) + using var registrySpellsKey = TryGetCharacterRegistryKey(accountName, characterName); + if (registrySpellsKey != null) { - using var registrySpellsKey = TryGetCharacterRegistryKey(accountName, characterName); - if (registrySpellsKey != null) + for (int i = 0; i < SpellRowLength * SpellRows; ++i) { - for (int i = 0; i < SpellRowLength * SpellRows; ++i) - { - if (int.TryParse(registrySpellsKey.GetValue($"item{i}")?.ToString() ?? string.Empty, out var id)) - map[i] = id; - } + if (int.TryParse(registrySpellsKey.GetValue($"item{i}")?.ToString() ?? string.Empty, out var id)) + map[i] = id; } } + } - var spells = new IniReader(Constants.SpellsFile); - var spellsKey = $"{host}:{accountName}"; - if (spells.Load() && spells.Sections.ContainsKey(spellsKey)) + var spells = new IniReader(Constants.SpellsFile); + var spellsKey = $"{host}:{accountName}"; + if (spells.Load() && spells.Sections.ContainsKey(spellsKey)) + { + var section = spells.Sections[spellsKey]; + foreach (var key in section.Keys.Where(x => x.Contains(characterName, StringComparison.OrdinalIgnoreCase))) { - var section = spells.Sections[spellsKey]; - foreach (var key in section.Keys.Where(x => x.Contains(characterName, StringComparison.OrdinalIgnoreCase))) - { - if (!key.Contains(".")) - continue; + if (!key.Contains(".")) + continue; - var slot = key.Split(".")[1]; - if (!int.TryParse(slot, out var slotIndex)) - continue; + var slot = key.Split(".")[1]; + if (!int.TryParse(slot, out var slotIndex)) + continue; - if (int.TryParse(section[key], out var id)) - map[slotIndex] = id; - } + if (int.TryParse(section[key], out var id)) + map[slotIndex] = id; } - - return map; } - [SupportedOSPlatform("Windows")] - private static RegistryKey TryGetCharacterRegistryKey(string accountName, string characterName) - { - using RegistryKey currentUser = Registry.CurrentUser; + return map; + } - var pathSegments = $"Software\\EndlessClient\\{accountName}\\{characterName}\\spells".Split('\\'); - var currentPath = string.Empty; + [SupportedOSPlatform("Windows")] + private static RegistryKey TryGetCharacterRegistryKey(string accountName, string characterName) + { + using RegistryKey currentUser = Registry.CurrentUser; - RegistryKey retKey = null; - foreach (var segment in pathSegments) - { - retKey?.Dispose(); + var pathSegments = $"Software\\EndlessClient\\{accountName}\\{characterName}\\spells".Split('\\'); + var currentPath = string.Empty; - currentPath = Path.Combine(currentPath, segment); - retKey = currentUser.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadSubTree); - } + RegistryKey retKey = null; + foreach (var segment in pathSegments) + { + retKey?.Dispose(); - return retKey; + currentPath = Path.Combine(currentPath, segment); + retKey = currentUser.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadSubTree); } - private void SaveSpellsFile(object sender, EventArgs e) - { - var spells = new IniReader(Constants.SpellsFile); + return retKey; + } - var section = spells.Load() && spells.Sections.ContainsKey(_playerInfoProvider.LoggedInAccountName) - ? spells.Sections[_playerInfoProvider.LoggedInAccountName] - : new SortedList(); + private void SaveSpellsFile(object sender, EventArgs e) + { + var spells = new IniReader(Constants.SpellsFile); - var existing = section.Where(x => x.Key.Contains(_characterProvider.MainCharacter.Name)).Select(x => x.Key).ToList(); - foreach (var key in existing) - section.Remove(key); + var section = spells.Load() && spells.Sections.ContainsKey(_playerInfoProvider.LoggedInAccountName) + ? spells.Sections[_playerInfoProvider.LoggedInAccountName] + : new SortedList(); - foreach (var item in _childItems.OfType()) - section[$"{_characterProvider.MainCharacter.Name}.{item.Slot}"] = $"{item.InventorySpell.ID}"; + var existing = section.Where(x => x.Key.Contains(_characterProvider.MainCharacter.Name)).Select(x => x.Key).ToList(); + foreach (var key in existing) + section.Remove(key); - spells.Sections[_playerInfoProvider.LoggedInAccountName] = section; + foreach (var item in _childItems.OfType()) + section[$"{_characterProvider.MainCharacter.Name}.{item.Slot}"] = $"{item.InventorySpell.ID}"; - spells.Save(); - } + spells.Sections[_playerInfoProvider.LoggedInAccountName] = section; - #endregion + spells.Save(); } + + #endregion } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/ChatPanel.cs b/EndlessClient/HUD/Panels/ChatPanel.cs index 856db4f09..7747c7cf5 100644 --- a/EndlessClient/HUD/Panels/ChatPanel.cs +++ b/EndlessClient/HUD/Panels/ChatPanel.cs @@ -13,124 +13,123 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class ChatPanel : DraggableHudPanel { - public class ChatPanel : DraggableHudPanel + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatActions _chatActions; + private readonly IChatRenderableGenerator _chatRenderableGenerator; + private readonly IChatProvider _chatProvider; + private readonly IHudControlProvider _hudControlProvider; + + private readonly ScrollBar _scrollBar; + private readonly Dictionary _tabs; + + public ChatTab CurrentTab => _tabs.Single(x => x.Value.Active).Key; + + public ChatPanel(INativeGraphicsManager nativeGraphicsManager, + IChatActions chatActions, + IChatRenderableGenerator chatRenderableGenerator, + IChatProvider chatProvider, + IHudControlProvider hudControlProvider, + BitmapFont chatFont, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatActions _chatActions; - private readonly IChatRenderableGenerator _chatRenderableGenerator; - private readonly IChatProvider _chatProvider; - private readonly IHudControlProvider _hudControlProvider; - - private readonly ScrollBar _scrollBar; - private readonly Dictionary _tabs; - - public ChatTab CurrentTab => _tabs.Single(x => x.Value.Active).Key; - - public ChatPanel(INativeGraphicsManager nativeGraphicsManager, - IChatActions chatActions, - IChatRenderableGenerator chatRenderableGenerator, - IChatProvider chatProvider, - IHudControlProvider hudControlProvider, - BitmapFont chatFont, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + _nativeGraphicsManager = nativeGraphicsManager; + _chatActions = chatActions; + _chatRenderableGenerator = chatRenderableGenerator; + _chatProvider = chatProvider; + _hudControlProvider = hudControlProvider; + + //abs coordiantes: 568 309 + _scrollBar = new ScrollBar(new Vector2(467, 2), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) { - _nativeGraphicsManager = nativeGraphicsManager; - _chatActions = chatActions; - _chatRenderableGenerator = chatRenderableGenerator; - _chatProvider = chatProvider; - _hudControlProvider = hudControlProvider; - - //abs coordiantes: 568 309 - _scrollBar = new ScrollBar(new Vector2(467, 2), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) - { - LinesToRender = 7, - Visible = true - }; - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); - - var tabTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 35); - var smallSelected = new SpriteSheet(tabTexture, new Rectangle(307, 16, 43, 16)); - var smallUnselected = new SpriteSheet(tabTexture, new Rectangle(264, 16, 43, 16)); - var largeSelected = new SpriteSheet(tabTexture, new Rectangle(132, 16, 132, 16)); - var largeUnselected = new SpriteSheet(tabTexture, new Rectangle(0, 16, 132, 16)); - - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 28); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - - _tabs = new Dictionary - { - {ChatTab.Local, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Local, smallSelected, smallUnselected, chatFont) { Visible = true, Active = true } }, - {ChatTab.Global, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Global, smallSelected, smallUnselected, chatFont) { Visible = true, } }, - {ChatTab.Group, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Group, smallSelected, smallUnselected, chatFont) { Visible = true, } }, - {ChatTab.System, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.System, smallSelected, smallUnselected, chatFont) { Visible = true, } }, - {ChatTab.Private1, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Private1, largeSelected, largeUnselected, chatFont) {Visible = false} }, - {ChatTab.Private2, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Private2, largeSelected, largeUnselected, chatFont) {Visible = false } }, - }; - - foreach (var tab in _tabs.Values) - { - tab.SetParentControl(this); - tab.OnClosed += (s, _) => _chatActions.ClosePMTab(((ChatPanelTab)s).Tab); - } - } - - public override void Initialize() + LinesToRender = 7, + Visible = true + }; + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); + + var tabTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 35); + var smallSelected = new SpriteSheet(tabTexture, new Rectangle(307, 16, 43, 16)); + var smallUnselected = new SpriteSheet(tabTexture, new Rectangle(264, 16, 43, 16)); + var largeSelected = new SpriteSheet(tabTexture, new Rectangle(132, 16, 132, 16)); + var largeUnselected = new SpriteSheet(tabTexture, new Rectangle(0, 16, 132, 16)); + + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 28); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + + _tabs = new Dictionary + { + {ChatTab.Local, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Local, smallSelected, smallUnselected, chatFont) { Visible = true, Active = true } }, + {ChatTab.Global, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Global, smallSelected, smallUnselected, chatFont) { Visible = true, } }, + {ChatTab.Group, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Group, smallSelected, smallUnselected, chatFont) { Visible = true, } }, + {ChatTab.System, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.System, smallSelected, smallUnselected, chatFont) { Visible = true, } }, + {ChatTab.Private1, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Private1, largeSelected, largeUnselected, chatFont) {Visible = false} }, + {ChatTab.Private2, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Private2, largeSelected, largeUnselected, chatFont) {Visible = false } }, + }; + + foreach (var tab in _tabs.Values) { - _scrollBar.Initialize(); + tab.SetParentControl(this); + tab.OnClosed += (s, _) => _chatActions.ClosePMTab(((ChatPanelTab)s).Tab); + } + } - foreach (var tab in _tabs.Values) - tab.Initialize(); + public override void Initialize() + { + _scrollBar.Initialize(); - base.Initialize(); - } + foreach (var tab in _tabs.Values) + tab.Initialize(); - public void TryStartNewPrivateChat(string targetCharacter) - { - if (_tabs[ChatTab.Private1].Visible && _tabs[ChatTab.Private2].Visible) - return; + base.Initialize(); + } - if (!string.Equals(_chatProvider.PMTarget1, targetCharacter, StringComparison.OrdinalIgnoreCase) && - !string.Equals(_chatProvider.PMTarget2, targetCharacter, StringComparison.OrdinalIgnoreCase)) - { - if (_tabs[ChatTab.Private1].Visible) - { - SelectTab(ChatTab.Private2); - _tabs[ChatTab.Private2].Text = char.ToUpper(targetCharacter[0]) + targetCharacter[1..]; - } - else - { - SelectTab(ChatTab.Private1); - _tabs[ChatTab.Private1].Text = char.ToUpper(targetCharacter[0]) + targetCharacter[1..]; - } - } - } + public void TryStartNewPrivateChat(string targetCharacter) + { + if (_tabs[ChatTab.Private1].Visible && _tabs[ChatTab.Private2].Visible) + return; - public void SelectTab(ChatTab clickedTab) + if (!string.Equals(_chatProvider.PMTarget1, targetCharacter, StringComparison.OrdinalIgnoreCase) && + !string.Equals(_chatProvider.PMTarget2, targetCharacter, StringComparison.OrdinalIgnoreCase)) { - if (CurrentTab == ChatTab.Global && clickedTab != ChatTab.Global) + if (_tabs[ChatTab.Private1].Visible) { - _chatActions.SetGlobalActive(false); + SelectTab(ChatTab.Private2); + _tabs[ChatTab.Private2].Text = char.ToUpper(targetCharacter[0]) + targetCharacter[1..]; } - else if (CurrentTab != ChatTab.Global && clickedTab == ChatTab.Global) + else { - _chatActions.SetGlobalActive(true); + SelectTab(ChatTab.Private1); + _tabs[ChatTab.Private1].Text = char.ToUpper(targetCharacter[0]) + targetCharacter[1..]; } - - _tabs[CurrentTab].Active = false; - - _tabs[clickedTab].Visible = true; - _tabs[clickedTab].Active = true; - - _scrollBar.UpdateDimensions(_chatProvider.AllChat[clickedTab].Count); } + } - public void ClosePMTab(ChatTab whichTab) + public void SelectTab(ChatTab clickedTab) + { + if (CurrentTab == ChatTab.Global && clickedTab != ChatTab.Global) { - _tabs[whichTab].CloseTab(); + _chatActions.SetGlobalActive(false); } + else if (CurrentTab != ChatTab.Global && clickedTab == ChatTab.Global) + { + _chatActions.SetGlobalActive(true); + } + + _tabs[CurrentTab].Active = false; + + _tabs[clickedTab].Visible = true; + _tabs[clickedTab].Active = true; + + _scrollBar.UpdateDimensions(_chatProvider.AllChat[clickedTab].Count); + } + + public void ClosePMTab(ChatTab whichTab) + { + _tabs[whichTab].CloseTab(); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/DraggableHudPanel.cs b/EndlessClient/HUD/Panels/DraggableHudPanel.cs index 3a3316c3e..e7ee305b6 100644 --- a/EndlessClient/HUD/Panels/DraggableHudPanel.cs +++ b/EndlessClient/HUD/Panels/DraggableHudPanel.cs @@ -4,63 +4,62 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class DraggableHudPanel : XNAPanel, IHudPanel { - public class DraggableHudPanel : XNAPanel, IHudPanel - { - public event Action Activated; - public event Action DragCompleted; + public event Action Activated; + public event Action DragCompleted; - private static Option _dragging; - private bool _enableDragging; + private static Option _dragging; + private bool _enableDragging; - public bool IsBeingDragged => _dragging.HasValue; + public bool IsBeingDragged => _dragging.HasValue; - public DraggableHudPanel(bool enableDragging) - { - _enableDragging = enableDragging; - } + public DraggableHudPanel(bool enableDragging) + { + _enableDragging = enableDragging; + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - Activated?.Invoke(); - return true; - } + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + Activated?.Invoke(); + return true; + } - protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_enableDragging) - return false; + protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_enableDragging) + return false; - Activated?.Invoke(); - return true; - } + Activated?.Invoke(); + return true; + } - protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_enableDragging) - return false; + protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_enableDragging) + return false; - _dragging - .FlatMap(p => p.NoneWhen(q => p == this)) - .MatchNone(() => - { - _dragging = Option.Some(this); - DrawPosition = DrawPositionWithParentOffset + eventArgs.DistanceMoved; - }); + _dragging + .FlatMap(p => p.NoneWhen(q => p == this)) + .MatchNone(() => + { + _dragging = Option.Some(this); + DrawPosition = DrawPositionWithParentOffset + eventArgs.DistanceMoved; + }); - return true; - } + return true; + } - protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_enableDragging) - return false; + protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_enableDragging) + return false; - _dragging = Option.None(); - DragCompleted?.Invoke(); + _dragging = Option.None(); + DragCompleted?.Invoke(); - return true; - } + return true; } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/HelpPanel.cs b/EndlessClient/HUD/Panels/HelpPanel.cs index 3ac20c7cb..4f05576da 100644 --- a/EndlessClient/HUD/Panels/HelpPanel.cs +++ b/EndlessClient/HUD/Panels/HelpPanel.cs @@ -3,20 +3,19 @@ using Microsoft.Xna.Framework; using XNAControls; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class HelpPanel : DraggableHudPanel { - public class HelpPanel : DraggableHudPanel - { - private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly INativeGraphicsManager _nativeGraphicsManager; - public HelpPanel(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) - { - _nativeGraphicsManager = nativeGraphicsManager; + public HelpPanel(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) + { + _nativeGraphicsManager = nativeGraphicsManager; - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 63); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - } + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 63); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/HudPanelFactory.cs b/EndlessClient/HUD/Panels/HudPanelFactory.cs index 0a1f045de..e3f10ed35 100644 --- a/EndlessClient/HUD/Panels/HudPanelFactory.cs +++ b/EndlessClient/HUD/Panels/HudPanelFactory.cs @@ -22,220 +22,219 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +[MappedType(BaseType = typeof(IHudPanelFactory))] +public class HudPanelFactory : IHudPanelFactory { - [MappedType(BaseType = typeof(IHudPanelFactory))] - public class HudPanelFactory : IHudPanelFactory + private const int HUD_CONTROL_LAYER = 130; + + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IInventoryController _inventoryController; + private readonly IChatActions _chatActions; + private readonly IContentProvider _contentProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly INewsProvider _newsProvider; + private readonly IChatProvider _chatProvider; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IExperienceTableProvider _experienceTableProvider; + private readonly IPubFileProvider _pubFileProvider; + private readonly IInventorySlotRepository _inventorySlotRepository; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITrainingController _trainingController; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IItemStringService _itemStringService; + private readonly IItemNameColorService _itemNameColorService; + private readonly IInventoryService _inventoryService; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly IConfigurationRepository _configurationRepository; + private readonly IOnlinePlayerProvider _onlinePlayerProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IAudioActions _audioActions; + private readonly ISfxPlayer _sfxPlayer; + private readonly IPartyActions _partyActions; + private readonly IPartyDataProvider _partyDataProvider; + private readonly IConfigurationProvider _configurationProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + + public HudPanelFactory(INativeGraphicsManager nativeGraphicsManager, + IInventoryController inventoryController, + IChatActions chatActions, + IContentProvider contentProvider, + IHudControlProvider hudControlProvider, + INewsProvider newsProvider, + IChatProvider chatProvider, + IPlayerInfoProvider playerInfoProvider, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IExperienceTableProvider experienceTableProvider, + IPubFileProvider pubFileProvider, + IInventorySlotRepository inventorySlotRepository, + IEOMessageBoxFactory messageBoxFactory, + ITrainingController trainingController, + IFriendIgnoreListService friendIgnoreListService, + IStatusLabelSetter statusLabelSetter, + IItemStringService itemStringService, + IItemNameColorService itemNameColorService, + IInventoryService inventoryService, + IActiveDialogProvider activeDialogProvider, + ISpellSlotDataRepository spellSlotDataRepository, + IConfigurationRepository configurationRepository, + IOnlinePlayerProvider onlinePlayerProvider, + ILocalizedStringFinder localizedStringFinder, + IAudioActions audioActions, + ISfxPlayer sfxPlayer, + IPartyActions partyActions, + IPartyDataProvider partyDataProvider, + IConfigurationProvider configurationProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _inventoryController = inventoryController; + _chatActions = chatActions; + _contentProvider = contentProvider; + _hudControlProvider = hudControlProvider; + _newsProvider = newsProvider; + _chatProvider = chatProvider; + _playerInfoProvider = playerInfoProvider; + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _experienceTableProvider = experienceTableProvider; + _pubFileProvider = pubFileProvider; + _inventorySlotRepository = inventorySlotRepository; + _messageBoxFactory = messageBoxFactory; + _trainingController = trainingController; + _friendIgnoreListService = friendIgnoreListService; + _statusLabelSetter = statusLabelSetter; + _itemStringService = itemStringService; + _itemNameColorService = itemNameColorService; + _inventoryService = inventoryService; + _activeDialogProvider = activeDialogProvider; + _spellSlotDataRepository = spellSlotDataRepository; + _configurationRepository = configurationRepository; + _onlinePlayerProvider = onlinePlayerProvider; + _localizedStringFinder = localizedStringFinder; + _audioActions = audioActions; + _sfxPlayer = sfxPlayer; + _partyActions = partyActions; + _partyDataProvider = partyDataProvider; + _configurationProvider = configurationProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + } + + public NewsPanel CreateNewsPanel() + { + var chatFont = _contentProvider.Fonts[Constants.FontSize08]; + + return new NewsPanel(_nativeGraphicsManager, + new ChatRenderableGenerator(_nativeGraphicsManager, _friendIgnoreListService, chatFont), + _newsProvider, + chatFont, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public InventoryPanel CreateInventoryPanel() + { + return new InventoryPanel(_nativeGraphicsManager, + _inventoryController, + _statusLabelSetter, + _itemStringService, + _itemNameColorService, + _inventoryService, + _inventorySlotRepository, + _playerInfoProvider, + _characterProvider, + _characterInventoryProvider, + _pubFileProvider, + _hudControlProvider, + _activeDialogProvider, + _sfxPlayer, + _configurationProvider, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public ActiveSpellsPanel CreateActiveSpellsPanel() + { + return new ActiveSpellsPanel(_nativeGraphicsManager, + _trainingController, + _messageBoxFactory, + _statusLabelSetter, + _playerInfoProvider, + _characterProvider, + _characterInventoryProvider, + _pubFileProvider, + _spellSlotDataRepository, + _hudControlProvider, + _sfxPlayer, + _configurationProvider, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public PassiveSpellsPanel CreatePassiveSpellsPanel() + { + return new PassiveSpellsPanel(_nativeGraphicsManager, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + } + + public ChatPanel CreateChatPanel() + { + var chatFont = _contentProvider.Fonts[Constants.FontSize08]; + + return new ChatPanel(_nativeGraphicsManager, + _chatActions, + new ChatRenderableGenerator(_nativeGraphicsManager, _friendIgnoreListService, chatFont), + _chatProvider, + _hudControlProvider, + chatFont, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public StatsPanel CreateStatsPanel() + { + return new StatsPanel(_nativeGraphicsManager, + _characterProvider, + _characterInventoryProvider, + _experienceTableProvider, + _messageBoxFactory, + _trainingController, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public OnlineListPanel CreateOnlineListPanel() + { + var chatFont = _contentProvider.Fonts[Constants.FontSize08]; + return new OnlineListPanel(_nativeGraphicsManager, _hudControlProvider, _onlinePlayerProvider, _partyDataProvider, _friendIgnoreListService, _sfxPlayer, chatFont, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + } + + public PartyPanel CreatePartyPanel() + { + return new PartyPanel(_nativeGraphicsManager, _partyActions, _contentProvider, _partyDataProvider, _characterProvider, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + } + + public SettingsPanel CreateSettingsPanel() + { + return new SettingsPanel(_nativeGraphicsManager, + _chatActions, + _audioActions, + _statusLabelSetter, + _localizedStringFinder, + _messageBoxFactory, + _configurationRepository, + _sfxPlayer, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public HelpPanel CreateHelpPanel() { - private const int HUD_CONTROL_LAYER = 130; - - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IInventoryController _inventoryController; - private readonly IChatActions _chatActions; - private readonly IContentProvider _contentProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly INewsProvider _newsProvider; - private readonly IChatProvider _chatProvider; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IExperienceTableProvider _experienceTableProvider; - private readonly IPubFileProvider _pubFileProvider; - private readonly IInventorySlotRepository _inventorySlotRepository; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITrainingController _trainingController; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IItemStringService _itemStringService; - private readonly IItemNameColorService _itemNameColorService; - private readonly IInventoryService _inventoryService; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly IConfigurationRepository _configurationRepository; - private readonly IOnlinePlayerProvider _onlinePlayerProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IAudioActions _audioActions; - private readonly ISfxPlayer _sfxPlayer; - private readonly IPartyActions _partyActions; - private readonly IPartyDataProvider _partyDataProvider; - private readonly IConfigurationProvider _configurationProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - - public HudPanelFactory(INativeGraphicsManager nativeGraphicsManager, - IInventoryController inventoryController, - IChatActions chatActions, - IContentProvider contentProvider, - IHudControlProvider hudControlProvider, - INewsProvider newsProvider, - IChatProvider chatProvider, - IPlayerInfoProvider playerInfoProvider, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IExperienceTableProvider experienceTableProvider, - IPubFileProvider pubFileProvider, - IInventorySlotRepository inventorySlotRepository, - IEOMessageBoxFactory messageBoxFactory, - ITrainingController trainingController, - IFriendIgnoreListService friendIgnoreListService, - IStatusLabelSetter statusLabelSetter, - IItemStringService itemStringService, - IItemNameColorService itemNameColorService, - IInventoryService inventoryService, - IActiveDialogProvider activeDialogProvider, - ISpellSlotDataRepository spellSlotDataRepository, - IConfigurationRepository configurationRepository, - IOnlinePlayerProvider onlinePlayerProvider, - ILocalizedStringFinder localizedStringFinder, - IAudioActions audioActions, - ISfxPlayer sfxPlayer, - IPartyActions partyActions, - IPartyDataProvider partyDataProvider, - IConfigurationProvider configurationProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _inventoryController = inventoryController; - _chatActions = chatActions; - _contentProvider = contentProvider; - _hudControlProvider = hudControlProvider; - _newsProvider = newsProvider; - _chatProvider = chatProvider; - _playerInfoProvider = playerInfoProvider; - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _experienceTableProvider = experienceTableProvider; - _pubFileProvider = pubFileProvider; - _inventorySlotRepository = inventorySlotRepository; - _messageBoxFactory = messageBoxFactory; - _trainingController = trainingController; - _friendIgnoreListService = friendIgnoreListService; - _statusLabelSetter = statusLabelSetter; - _itemStringService = itemStringService; - _itemNameColorService = itemNameColorService; - _inventoryService = inventoryService; - _activeDialogProvider = activeDialogProvider; - _spellSlotDataRepository = spellSlotDataRepository; - _configurationRepository = configurationRepository; - _onlinePlayerProvider = onlinePlayerProvider; - _localizedStringFinder = localizedStringFinder; - _audioActions = audioActions; - _sfxPlayer = sfxPlayer; - _partyActions = partyActions; - _partyDataProvider = partyDataProvider; - _configurationProvider = configurationProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - } - - public NewsPanel CreateNewsPanel() - { - var chatFont = _contentProvider.Fonts[Constants.FontSize08]; - - return new NewsPanel(_nativeGraphicsManager, - new ChatRenderableGenerator(_nativeGraphicsManager, _friendIgnoreListService, chatFont), - _newsProvider, - chatFont, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public InventoryPanel CreateInventoryPanel() - { - return new InventoryPanel(_nativeGraphicsManager, - _inventoryController, - _statusLabelSetter, - _itemStringService, - _itemNameColorService, - _inventoryService, - _inventorySlotRepository, - _playerInfoProvider, - _characterProvider, - _characterInventoryProvider, - _pubFileProvider, - _hudControlProvider, - _activeDialogProvider, - _sfxPlayer, - _configurationProvider, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public ActiveSpellsPanel CreateActiveSpellsPanel() - { - return new ActiveSpellsPanel(_nativeGraphicsManager, - _trainingController, - _messageBoxFactory, - _statusLabelSetter, - _playerInfoProvider, - _characterProvider, - _characterInventoryProvider, - _pubFileProvider, - _spellSlotDataRepository, - _hudControlProvider, - _sfxPlayer, - _configurationProvider, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public PassiveSpellsPanel CreatePassiveSpellsPanel() - { - return new PassiveSpellsPanel(_nativeGraphicsManager, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; - } - - public ChatPanel CreateChatPanel() - { - var chatFont = _contentProvider.Fonts[Constants.FontSize08]; - - return new ChatPanel(_nativeGraphicsManager, - _chatActions, - new ChatRenderableGenerator(_nativeGraphicsManager, _friendIgnoreListService, chatFont), - _chatProvider, - _hudControlProvider, - chatFont, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public StatsPanel CreateStatsPanel() - { - return new StatsPanel(_nativeGraphicsManager, - _characterProvider, - _characterInventoryProvider, - _experienceTableProvider, - _messageBoxFactory, - _trainingController, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public OnlineListPanel CreateOnlineListPanel() - { - var chatFont = _contentProvider.Fonts[Constants.FontSize08]; - return new OnlineListPanel(_nativeGraphicsManager, _hudControlProvider, _onlinePlayerProvider, _partyDataProvider, _friendIgnoreListService, _sfxPlayer, chatFont, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; - } - - public PartyPanel CreatePartyPanel() - { - return new PartyPanel(_nativeGraphicsManager, _partyActions, _contentProvider, _partyDataProvider, _characterProvider, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; - } - - public SettingsPanel CreateSettingsPanel() - { - return new SettingsPanel(_nativeGraphicsManager, - _chatActions, - _audioActions, - _statusLabelSetter, - _localizedStringFinder, - _messageBoxFactory, - _configurationRepository, - _sfxPlayer, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public HelpPanel CreateHelpPanel() - { - return new HelpPanel(_nativeGraphicsManager, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; - } + return new HelpPanel(_nativeGraphicsManager, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/IHudPanel.cs b/EndlessClient/HUD/Panels/IHudPanel.cs index e380c4618..be4cdb34b 100644 --- a/EndlessClient/HUD/Panels/IHudPanel.cs +++ b/EndlessClient/HUD/Panels/IHudPanel.cs @@ -2,22 +2,21 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public interface IHudPanel : IGameComponent { - public interface IHudPanel : IGameComponent - { - bool Visible { get; set; } + bool Visible { get; set; } - int UpdateOrder { get; set; } + int UpdateOrder { get; set; } - int DrawOrder { get; set; } + int DrawOrder { get; set; } - Vector2 DrawPosition { get; set; } + Vector2 DrawPosition { get; set; } - Rectangle DrawArea { get; set; } + Rectangle DrawArea { get; set; } - bool IsBeingDragged { get; } + bool IsBeingDragged { get; } - event Action DragCompleted; - } + event Action DragCompleted; } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/IHudPanelFactory.cs b/EndlessClient/HUD/Panels/IHudPanelFactory.cs index eec471e9d..bc7208317 100644 --- a/EndlessClient/HUD/Panels/IHudPanelFactory.cs +++ b/EndlessClient/HUD/Panels/IHudPanelFactory.cs @@ -1,25 +1,24 @@ -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public interface IHudPanelFactory { - public interface IHudPanelFactory - { - NewsPanel CreateNewsPanel(); + NewsPanel CreateNewsPanel(); - InventoryPanel CreateInventoryPanel(); + InventoryPanel CreateInventoryPanel(); - ActiveSpellsPanel CreateActiveSpellsPanel(); + ActiveSpellsPanel CreateActiveSpellsPanel(); - PassiveSpellsPanel CreatePassiveSpellsPanel(); + PassiveSpellsPanel CreatePassiveSpellsPanel(); - ChatPanel CreateChatPanel(); + ChatPanel CreateChatPanel(); - StatsPanel CreateStatsPanel(); + StatsPanel CreateStatsPanel(); - OnlineListPanel CreateOnlineListPanel(); + OnlineListPanel CreateOnlineListPanel(); - PartyPanel CreatePartyPanel(); + PartyPanel CreatePartyPanel(); - SettingsPanel CreateSettingsPanel(); + SettingsPanel CreateSettingsPanel(); - HelpPanel CreateHelpPanel(); - } + HelpPanel CreateHelpPanel(); } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/InventoryPanel.cs b/EndlessClient/HUD/Panels/InventoryPanel.cs index aa3abf31d..45fe1b3e7 100644 --- a/EndlessClient/HUD/Panels/InventoryPanel.cs +++ b/EndlessClient/HUD/Panels/InventoryPanel.cs @@ -32,534 +32,533 @@ using System.Runtime.Versioning; using XNAControls; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class InventoryPanel : DraggableHudPanel, IHudPanel, IDraggableItemContainer { - public class InventoryPanel : DraggableHudPanel, IHudPanel, IDraggableItemContainer + public const int InventoryRows = 4; + public const int InventoryRowSlots = 14; + + private readonly IInventoryController _inventoryController; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IItemStringService _itemStringService; + private readonly IItemNameColorService _itemNameColorService; + private readonly IInventoryService _inventoryService; + private readonly IInventorySlotRepository _inventorySlotRepository; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IPubFileProvider _pubFileProvider; // todo: this can probably become EIFFileProvider + private readonly IHudControlProvider _hudControlProvider; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IConfigurationProvider _configProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly List _childItems = new List(); + + private readonly IXNALabel _weightLabel; + private readonly IXNAButton _drop, _junk, _paperdoll; + //private readonly ScrollBar _scrollBar; + + private Option _cachedStats; + private HashSet _cachedInventory; + + public INativeGraphicsManager NativeGraphicsManager { get; } + + public InventoryPanel(INativeGraphicsManager nativeGraphicsManager, + IInventoryController inventoryController, + IStatusLabelSetter statusLabelSetter, + IItemStringService itemStringService, + IItemNameColorService itemNameColorService, + IInventoryService inventoryService, + IInventorySlotRepository inventorySlotRepository, + IPlayerInfoProvider playerInfoProvider, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IPubFileProvider pubFileProvider, + IHudControlProvider hudControlProvider, + IActiveDialogProvider activeDialogProvider, + ISfxPlayer sfxPlayer, + IConfigurationProvider configProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - public const int InventoryRows = 4; - public const int InventoryRowSlots = 14; - - private readonly IInventoryController _inventoryController; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IItemStringService _itemStringService; - private readonly IItemNameColorService _itemNameColorService; - private readonly IInventoryService _inventoryService; - private readonly IInventorySlotRepository _inventorySlotRepository; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IPubFileProvider _pubFileProvider; // todo: this can probably become EIFFileProvider - private readonly IHudControlProvider _hudControlProvider; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IConfigurationProvider _configProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly List _childItems = new List(); - - private readonly IXNALabel _weightLabel; - private readonly IXNAButton _drop, _junk, _paperdoll; - //private readonly ScrollBar _scrollBar; - - private Option _cachedStats; - private HashSet _cachedInventory; - - public INativeGraphicsManager NativeGraphicsManager { get; } - - public InventoryPanel(INativeGraphicsManager nativeGraphicsManager, - IInventoryController inventoryController, - IStatusLabelSetter statusLabelSetter, - IItemStringService itemStringService, - IItemNameColorService itemNameColorService, - IInventoryService inventoryService, - IInventorySlotRepository inventorySlotRepository, - IPlayerInfoProvider playerInfoProvider, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IPubFileProvider pubFileProvider, - IHudControlProvider hudControlProvider, - IActiveDialogProvider activeDialogProvider, - ISfxPlayer sfxPlayer, - IConfigurationProvider configProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + NativeGraphicsManager = nativeGraphicsManager; + _inventoryController = inventoryController; + _statusLabelSetter = statusLabelSetter; + _itemStringService = itemStringService; + _itemNameColorService = itemNameColorService; + _inventoryService = inventoryService; + _inventorySlotRepository = inventorySlotRepository; + _playerInfoProvider = playerInfoProvider; + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _pubFileProvider = pubFileProvider; + _hudControlProvider = hudControlProvider; + _activeDialogProvider = activeDialogProvider; + _sfxPlayer = sfxPlayer; + _configProvider = configProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + + _weightLabel = new XNALabel(Constants.FontSize08pt5) { - NativeGraphicsManager = nativeGraphicsManager; - _inventoryController = inventoryController; - _statusLabelSetter = statusLabelSetter; - _itemStringService = itemStringService; - _itemNameColorService = itemNameColorService; - _inventoryService = inventoryService; - _inventorySlotRepository = inventorySlotRepository; - _playerInfoProvider = playerInfoProvider; - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _pubFileProvider = pubFileProvider; - _hudControlProvider = hudControlProvider; - _activeDialogProvider = activeDialogProvider; - _sfxPlayer = sfxPlayer; - _configProvider = configProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - - _weightLabel = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(385, 37, 88, 18), - ForeColor = ColorConstants.LightGrayText, - TextAlign = LabelAlignment.MiddleCenter, - Visible = true, - AutoSize = false - }; + DrawArea = new Rectangle(385, 37, 88, 18), + ForeColor = ColorConstants.LightGrayText, + TextAlign = LabelAlignment.MiddleCenter, + Visible = true, + AutoSize = false + }; - _inventorySlotRepository.SlotMap = GetItemSlotMap(_playerInfoProvider.LoggedInAccountName, _characterProvider.MainCharacter.Name, _configProvider.Host); + _inventorySlotRepository.SlotMap = GetItemSlotMap(_playerInfoProvider.LoggedInAccountName, _characterProvider.MainCharacter.Name, _configProvider.Host); - var weirdOffsetSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); + var weirdOffsetSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); - _paperdoll = new XNAButton(weirdOffsetSheet, new Vector2(385, 9), new Rectangle(39, 385, 88, 19), new Rectangle(126, 385, 88, 19)); - _paperdoll.OnMouseEnter += MouseOverButton; - _paperdoll.OnClick += (_, _) => - { - _inventoryController.ShowPaperdollDialog(); - _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); - }; + _paperdoll = new XNAButton(weirdOffsetSheet, new Vector2(385, 9), new Rectangle(39, 385, 88, 19), new Rectangle(126, 385, 88, 19)); + _paperdoll.OnMouseEnter += MouseOverButton; + _paperdoll.OnClick += (_, _) => + { + _inventoryController.ShowPaperdollDialog(); + _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + }; - _drop = new XNAButton(weirdOffsetSheet, new Vector2(389, 68), new Rectangle(0, 15, 38, 37), new Rectangle(0, 52, 38, 37)); - _drop.OnMouseEnter += MouseOverButton; - _drop.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + _drop = new XNAButton(weirdOffsetSheet, new Vector2(389, 68), new Rectangle(0, 15, 38, 37), new Rectangle(0, 52, 38, 37)); + _drop.OnMouseEnter += MouseOverButton; + _drop.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - _junk = new XNAButton(weirdOffsetSheet, new Vector2(431, 68), new Rectangle(0, 89, 38, 37), new Rectangle(0, 126, 38, 37)); - _junk.OnMouseEnter += MouseOverButton; - _junk.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + _junk = new XNAButton(weirdOffsetSheet, new Vector2(431, 68), new Rectangle(0, 89, 38, 37), new Rectangle(0, 126, 38, 37)); + _junk.OnMouseEnter += MouseOverButton; + _junk.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - _cachedStats = Option.None(); - _cachedInventory = new HashSet(); + _cachedStats = Option.None(); + _cachedInventory = new HashSet(); - BackgroundImage = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 44); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + BackgroundImage = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 44); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - Game.Exiting += SaveInventoryFile; - } + Game.Exiting += SaveInventoryFile; + } - public bool NoItemsDragging() => _childItems.All(x => !x.IsDragging); + public bool NoItemsDragging() => _childItems.All(x => !x.IsDragging); - public override void Initialize() - { - _weightLabel.Initialize(); - _weightLabel.SetParentControl(this); + public override void Initialize() + { + _weightLabel.Initialize(); + _weightLabel.SetParentControl(this); - _paperdoll.Initialize(); - _paperdoll.SetParentControl(this); + _paperdoll.Initialize(); + _paperdoll.SetParentControl(this); - _drop.Initialize(); - _drop.SetParentControl(this); + _drop.Initialize(); + _drop.SetParentControl(this); - _junk.Initialize(); - _junk.SetParentControl(this); + _junk.Initialize(); + _junk.SetParentControl(this); - OnUpdateControl(new GameTime()); - _inventorySlotRepository.SlotMap.Clear(); + OnUpdateControl(new GameTime()); + _inventorySlotRepository.SlotMap.Clear(); - base.Initialize(); - } + base.Initialize(); + } - protected override void OnDrawOrderChanged(object sender, EventArgs args) + protected override void OnDrawOrderChanged(object sender, EventArgs args) + { + base.OnDrawOrderChanged(sender, args); + + if (_clientWindowSizeProvider.Resizable) { - base.OnDrawOrderChanged(sender, args); + // ensure labels have a high enough draw order when in resizable mode + // this is because draw order is updated when panels are opened in resizable mode + foreach (var label in ChildControls.OfType()) + label.DrawOrder = DrawOrder + 70; + } + } - if (_clientWindowSizeProvider.Resizable) + protected override void OnUnconditionalUpdateControl(GameTime gameTime) + { + _cachedStats.Match( + some: stats => { - // ensure labels have a high enough draw order when in resizable mode - // this is because draw order is updated when panels are opened in resizable mode - foreach (var label in ChildControls.OfType()) - label.DrawOrder = DrawOrder + 70; - } - } + stats.SomeWhen(s => s != _characterProvider.MainCharacter.Stats) + .MatchSome(_ => + { + var newStats = _characterProvider.MainCharacter.Stats; + _cachedStats = Option.Some(newStats); + _weightLabel.Text = $"{newStats[CharacterStat.Weight]} / {newStats[CharacterStat.MaxWeight]}"; + }); + }, + none: () => + { + var stats = _characterProvider.MainCharacter.Stats; + _cachedStats = Option.Some(stats); + _weightLabel.Text = $"{stats[CharacterStat.Weight]} / {stats[CharacterStat.MaxWeight]}"; + }); - protected override void OnUnconditionalUpdateControl(GameTime gameTime) + if (!_cachedInventory.SetEquals(_characterInventoryProvider.ItemInventory)) { - _cachedStats.Match( - some: stats => - { - stats.SomeWhen(s => s != _characterProvider.MainCharacter.Stats) - .MatchSome(_ => - { - var newStats = _characterProvider.MainCharacter.Stats; - _cachedStats = Option.Some(newStats); - _weightLabel.Text = $"{newStats[CharacterStat.Weight]} / {newStats[CharacterStat.MaxWeight]}"; - }); - }, - none: () => - { - var stats = _characterProvider.MainCharacter.Stats; - _cachedStats = Option.Some(stats); - _weightLabel.Text = $"{stats[CharacterStat.Weight]} / {stats[CharacterStat.MaxWeight]}"; - }); + var added = _characterInventoryProvider.ItemInventory.Where(i => !_cachedInventory.Any(j => i.ItemID == j.ItemID)); + var removed = _cachedInventory.Where(i => !_characterInventoryProvider.ItemInventory.Any(j => i.ItemID == j.ItemID)); + var updated = _characterInventoryProvider.ItemInventory.Except(added) + .Where(i => _cachedInventory.Any(j => i.ItemID == j.ItemID && i.Amount != j.Amount)); - if (!_cachedInventory.SetEquals(_characterInventoryProvider.ItemInventory)) + foreach (var item in removed) { - var added = _characterInventoryProvider.ItemInventory.Where(i => !_cachedInventory.Any(j => i.ItemID == j.ItemID)); - var removed = _cachedInventory.Where(i => !_characterInventoryProvider.ItemInventory.Any(j => i.ItemID == j.ItemID)); - var updated = _characterInventoryProvider.ItemInventory.Except(added) - .Where(i => _cachedInventory.Any(j => i.ItemID == j.ItemID && i.Amount != j.Amount)); - - foreach (var item in removed) + var matchedItem = _childItems.SingleOrNone(x => x.InventoryItem.ItemID == item.ItemID); + matchedItem.MatchSome(childItem => { - var matchedItem = _childItems.SingleOrNone(x => x.InventoryItem.ItemID == item.ItemID); - matchedItem.MatchSome(childItem => - { - childItem.SetControlUnparented(); - childItem.Dispose(); - _childItems.Remove(childItem); + childItem.SetControlUnparented(); + childItem.Dispose(); + _childItems.Remove(childItem); - var itemData = _pubFileProvider.EIFFile[item.ItemID]; - _inventoryService.ClearSlots(_inventorySlotRepository.FilledSlots, childItem.Slot, itemData.Size); - }); - } - - foreach (var item in updated) - { var itemData = _pubFileProvider.EIFFile[item.ItemID]; + _inventoryService.ClearSlots(_inventorySlotRepository.FilledSlots, childItem.Slot, itemData.Size); + }); + } - var matchedItem = _childItems.SingleOrNone(x => x.InventoryItem.ItemID == item.ItemID); - matchedItem.MatchSome(childItem => - { - childItem.InventoryItem = item; - childItem.Text = _itemStringService.GetStringForInventoryDisplay(itemData, item.Amount); - }); - } + foreach (var item in updated) + { + var itemData = _pubFileProvider.EIFFile[item.ItemID]; - foreach (var item in added) + var matchedItem = _childItems.SingleOrNone(x => x.InventoryItem.ItemID == item.ItemID); + matchedItem.MatchSome(childItem => { - var itemData = _pubFileProvider.EIFFile[item.ItemID]; - - var preferredSlot = _inventorySlotRepository.SlotMap.SingleOrNone(x => x.Value == item.ItemID).Map(x => x.Key); - var actualSlot = _inventoryService.GetNextOpenSlot(_inventorySlotRepository.FilledSlots, itemData.Size, preferredSlot); + childItem.InventoryItem = item; + childItem.Text = _itemStringService.GetStringForInventoryDisplay(itemData, item.Amount); + }); + } - actualSlot.MatchSome(slot => - { - _inventoryService.SetSlots(_inventorySlotRepository.FilledSlots, slot, itemData.Size); + foreach (var item in added) + { + var itemData = _pubFileProvider.EIFFile[item.ItemID]; - var newItem = new InventoryPanelItem(_itemNameColorService, this, _activeDialogProvider, _sfxPlayer, slot, item, itemData); - newItem.Initialize(); - newItem.SetParentControl(this); - newItem.Text = _itemStringService.GetStringForInventoryDisplay(itemData, item.Amount); + var preferredSlot = _inventorySlotRepository.SlotMap.SingleOrNone(x => x.Value == item.ItemID).Map(x => x.Key); + var actualSlot = _inventoryService.GetNextOpenSlot(_inventorySlotRepository.FilledSlots, itemData.Size, preferredSlot); - newItem.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ITEM, newItem.Text); - newItem.DoubleClick += HandleItemDoubleClick; - newItem.DraggingFinishing += HandleItemDoneDragging; - newItem.DraggingFinished += (_, _) => ResetSlotMap(_childItems.Where(x => !x.IsDragging)); + actualSlot.MatchSome(slot => + { + _inventoryService.SetSlots(_inventorySlotRepository.FilledSlots, slot, itemData.Size); - // side-effect of calling newItem.SetParentControl(this) is that the draw order gets reset - // setting the slot manually here resets it so the item labels render appropriately - newItem.Slot = slot; + var newItem = new InventoryPanelItem(_itemNameColorService, this, _activeDialogProvider, _sfxPlayer, slot, item, itemData); + newItem.Initialize(); + newItem.SetParentControl(this); + newItem.Text = _itemStringService.GetStringForInventoryDisplay(itemData, item.Amount); - _childItems.Add(newItem); - }); - } + newItem.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ITEM, newItem.Text); + newItem.DoubleClick += HandleItemDoubleClick; + newItem.DraggingFinishing += HandleItemDoneDragging; + newItem.DraggingFinished += (_, _) => ResetSlotMap(_childItems.Where(x => !x.IsDragging)); - _cachedInventory = _characterInventoryProvider.ItemInventory.ToHashSet(); + // side-effect of calling newItem.SetParentControl(this) is that the draw order gets reset + // setting the slot manually here resets it so the item labels render appropriately + newItem.Slot = slot; - if (removed.Any()) - { - RemoveHiddenItemsFromCachedInventory(); - } + _childItems.Add(newItem); + }); } - base.OnUpdateControl(gameTime); - } + _cachedInventory = _characterInventoryProvider.ItemInventory.ToHashSet(); - protected override void Dispose(bool disposing) - { - if (disposing) + if (removed.Any()) { - _paperdoll.OnMouseEnter -= MouseOverButton; - _drop.OnMouseEnter -= MouseOverButton; - _junk.OnMouseEnter -= MouseOverButton; - Game.Exiting -= SaveInventoryFile; - - // todo: IResettable should work but it doesn't - _inventorySlotRepository.FilledSlots = new Matrix(InventoryRows, InventoryRowSlots, false); - - SaveInventoryFile(null, EventArgs.Empty); + RemoveHiddenItemsFromCachedInventory(); } - - base.Dispose(disposing); } - private void MouseOverButton(object sender, MouseStateExtended e) + base.OnUpdateControl(gameTime); + } + + protected override void Dispose(bool disposing) + { + if (disposing) { - var id = sender == _paperdoll - ? EOResourceID.STATUS_LABEL_INVENTORY_SHOW_YOUR_PAPERDOLL - : sender == _drop - ? EOResourceID.STATUS_LABEL_INVENTORY_DROP_BUTTON - : EOResourceID.STATUS_LABEL_INVENTORY_JUNK_BUTTON; - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, id); + _paperdoll.OnMouseEnter -= MouseOverButton; + _drop.OnMouseEnter -= MouseOverButton; + _junk.OnMouseEnter -= MouseOverButton; + Game.Exiting -= SaveInventoryFile; + + // todo: IResettable should work but it doesn't + _inventorySlotRepository.FilledSlots = new Matrix(InventoryRows, InventoryRowSlots, false); + + SaveInventoryFile(null, EventArgs.Empty); } - private static Dictionary GetItemSlotMap(string accountName, string characterName, string host) - { - var map = new Dictionary(); + base.Dispose(disposing); + } + + private void MouseOverButton(object sender, MouseStateExtended e) + { + var id = sender == _paperdoll + ? EOResourceID.STATUS_LABEL_INVENTORY_SHOW_YOUR_PAPERDOLL + : sender == _drop + ? EOResourceID.STATUS_LABEL_INVENTORY_DROP_BUTTON + : EOResourceID.STATUS_LABEL_INVENTORY_JUNK_BUTTON; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, id); + } - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !File.Exists(Constants.InventoryFile)) + private static Dictionary GetItemSlotMap(string accountName, string characterName, string host) + { + var map = new Dictionary(); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !File.Exists(Constants.InventoryFile)) + { + using var registryInventoryKey = TryGetCharacterRegistryKey(accountName, characterName); + if (registryInventoryKey != null) { - using var registryInventoryKey = TryGetCharacterRegistryKey(accountName, characterName); - if (registryInventoryKey != null) + for (int i = 0; i < InventoryRowSlots * 4; ++i) { - for (int i = 0; i < InventoryRowSlots * 4; ++i) - { - if (int.TryParse(registryInventoryKey.GetValue($"item{i}")?.ToString() ?? string.Empty, out var id)) - map[i] = id; - } + if (int.TryParse(registryInventoryKey.GetValue($"item{i}")?.ToString() ?? string.Empty, out var id)) + map[i] = id; } } + } - var inventory = new IniReader(Constants.InventoryFile); - var inventoryKey = $"{host}:{accountName}"; - if (inventory.Load() && inventory.Sections.ContainsKey(inventoryKey)) + var inventory = new IniReader(Constants.InventoryFile); + var inventoryKey = $"{host}:{accountName}"; + if (inventory.Load() && inventory.Sections.ContainsKey(inventoryKey)) + { + var section = inventory.Sections[inventoryKey]; + foreach (var key in section.Keys.Where(x => x.Contains(characterName, StringComparison.OrdinalIgnoreCase))) { - var section = inventory.Sections[inventoryKey]; - foreach (var key in section.Keys.Where(x => x.Contains(characterName, StringComparison.OrdinalIgnoreCase))) - { - if (!key.Contains(".")) - continue; + if (!key.Contains(".")) + continue; - var slot = key.Split(".")[1]; - if (!int.TryParse(slot, out var slotIndex)) - continue; + var slot = key.Split(".")[1]; + if (!int.TryParse(slot, out var slotIndex)) + continue; - if (int.TryParse(section[key], out var id)) - map[slotIndex] = id; - } + if (int.TryParse(section[key], out var id)) + map[slotIndex] = id; } - - return map; } - [SupportedOSPlatform("Windows")] - private static RegistryKey TryGetCharacterRegistryKey(string accountName, string characterName) - { - using RegistryKey currentUser = Registry.CurrentUser; + return map; + } - var pathSegments = $"Software\\EndlessClient\\{accountName}\\{characterName}\\inventory".Split('\\'); - var currentPath = string.Empty; + [SupportedOSPlatform("Windows")] + private static RegistryKey TryGetCharacterRegistryKey(string accountName, string characterName) + { + using RegistryKey currentUser = Registry.CurrentUser; - RegistryKey retKey = null; - foreach (var segment in pathSegments) - { - retKey?.Dispose(); + var pathSegments = $"Software\\EndlessClient\\{accountName}\\{characterName}\\inventory".Split('\\'); + var currentPath = string.Empty; - currentPath = Path.Combine(currentPath, segment); - retKey = currentUser.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadSubTree); - } + RegistryKey retKey = null; + foreach (var segment in pathSegments) + { + retKey?.Dispose(); - return retKey; + currentPath = Path.Combine(currentPath, segment); + retKey = currentUser.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadSubTree); } - private void SaveInventoryFile(object sender, EventArgs e) - { - var inventory = new IniReader(Constants.InventoryFile); - var inventoryKey = $"{_configProvider.Host}:{_playerInfoProvider.LoggedInAccountName}"; + return retKey; + } - var section = inventory.Load() && inventory.Sections.ContainsKey(inventoryKey) - ? inventory.Sections[inventoryKey] - : new SortedList(); + private void SaveInventoryFile(object sender, EventArgs e) + { + var inventory = new IniReader(Constants.InventoryFile); + var inventoryKey = $"{_configProvider.Host}:{_playerInfoProvider.LoggedInAccountName}"; - var existing = section.Where(x => x.Key.Contains(_characterProvider.MainCharacter.Name)).Select(x => x.Key).ToList(); - foreach (var key in existing) - section.Remove(key); + var section = inventory.Load() && inventory.Sections.ContainsKey(inventoryKey) + ? inventory.Sections[inventoryKey] + : new SortedList(); - foreach (var item in _childItems) - section[$"{_characterProvider.MainCharacter.Name}.{item.Slot}"] = $"{item.InventoryItem.ItemID}"; + var existing = section.Where(x => x.Key.Contains(_characterProvider.MainCharacter.Name)).Select(x => x.Key).ToList(); + foreach (var key in existing) + section.Remove(key); - inventory.Sections[inventoryKey] = section; + foreach (var item in _childItems) + section[$"{_characterProvider.MainCharacter.Name}.{item.Slot}"] = $"{item.InventoryItem.ItemID}"; - inventory.Save(); - } + inventory.Sections[inventoryKey] = section; - private void HandleItemDoubleClick(object sender, EIFRecord itemData) - { - if (itemData.Type >= ItemType.Weapon && itemData.Type <= ItemType.Bracer) - { - _inventoryController.EquipItem(itemData); - } - else - { - _inventoryController.UseItem(itemData); - } + inventory.Save(); + } - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + private void HandleItemDoubleClick(object sender, EIFRecord itemData) + { + if (itemData.Type >= ItemType.Weapon && itemData.Type <= ItemType.Bracer) + { + _inventoryController.EquipItem(itemData); } - - private void HandleItemDoneDragging(object sender, DragCompletedEventArgs e) + else { - var item = sender as InventoryPanelItem; - if (item == null) - return; + _inventoryController.UseItem(itemData); + } - ResetSlotMap(_childItems.Where(x => !x.IsDragging)); + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + } - var oldSlot = item.Slot; - var fitsInOldSlot = _inventoryService.FitsInSlot(_inventorySlotRepository.FilledSlots, oldSlot, e.Data.Size); + private void HandleItemDoneDragging(object sender, DragCompletedEventArgs e) + { + var item = sender as InventoryPanelItem; + if (item == null) + return; - if (_activeDialogProvider.ActiveDialogs.All(x => !x.HasValue)) - { - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - if (mapRenderer.MouseOver && !MouseOver) - { - e.ContinueDrag = !fitsInOldSlot; - e.RestoreOriginalSlot = fitsInOldSlot; + ResetSlotMap(_childItems.Where(x => !x.IsDragging)); - _inventoryController.DropItem(item.Data, item.InventoryItem, mapRenderer.GridCoordinates); - return; - } - } + var oldSlot = item.Slot; + var fitsInOldSlot = _inventoryService.FitsInSlot(_inventorySlotRepository.FilledSlots, oldSlot, e.Data.Size); - if (_drop.MouseOver) + if (_activeDialogProvider.ActiveDialogs.All(x => !x.HasValue)) + { + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + if (mapRenderer.MouseOver && !MouseOver) { e.ContinueDrag = !fitsInOldSlot; e.RestoreOriginalSlot = fitsInOldSlot; - _inventoryController.DropItem(item.Data, item.InventoryItem, MapCoordinate.Max); + _inventoryController.DropItem(item.Data, item.InventoryItem, mapRenderer.GridCoordinates); return; } - else if (_junk.MouseOver) - { - e.ContinueDrag = !fitsInOldSlot; - e.RestoreOriginalSlot = fitsInOldSlot; + } - _inventoryController.JunkItem(item.Data, item.InventoryItem); - return; - } + if (_drop.MouseOver) + { + e.ContinueDrag = !fitsInOldSlot; + e.RestoreOriginalSlot = fitsInOldSlot; - var dialogDrop = false; - foreach (var dlg in _activeDialogProvider.ActiveDialogs) - { - dialogDrop |= dlg.Match( - activeDialog => + _inventoryController.DropItem(item.Data, item.InventoryItem, MapCoordinate.Max); + return; + } + else if (_junk.MouseOver) + { + e.ContinueDrag = !fitsInOldSlot; + e.RestoreOriginalSlot = fitsInOldSlot; + + _inventoryController.JunkItem(item.Data, item.InventoryItem); + return; + } + + var dialogDrop = false; + foreach (var dlg in _activeDialogProvider.ActiveDialogs) + { + dialogDrop |= dlg.Match( + activeDialog => + { + if (!activeDialog.MouseOver && !activeDialog.MouseOverPreviously) + return false; + + switch (activeDialog) { - if (!activeDialog.MouseOver && !activeDialog.MouseOverPreviously) - return false; - - switch (activeDialog) - { - case PaperdollDialog: - if (item.Data.GetEquipLocation() != EquipLocation.PAPERDOLL_MAX) - _inventoryController.EquipItem(item.Data); - break; - case ChestDialog: _inventoryController.DropItemInChest(item.Data, item.InventoryItem); break; - case LockerDialog: _inventoryController.DropItemInLocker(item.Data, item.InventoryItem); break; - case BankAccountDialog: - if (item.Data.ID == 1) - _inventoryController.DropItemInBank(item.Data, item.InventoryItem); - break; - case TradeDialog: _inventoryController.TradeItem(item.Data, item.InventoryItem); break; - default: return false; - }; - - return true; - }, - () => false); - } + case PaperdollDialog: + if (item.Data.GetEquipLocation() != EquipLocation.PAPERDOLL_MAX) + _inventoryController.EquipItem(item.Data); + break; + case ChestDialog: _inventoryController.DropItemInChest(item.Data, item.InventoryItem); break; + case LockerDialog: _inventoryController.DropItemInLocker(item.Data, item.InventoryItem); break; + case BankAccountDialog: + if (item.Data.ID == 1) + _inventoryController.DropItemInBank(item.Data, item.InventoryItem); + break; + case TradeDialog: _inventoryController.TradeItem(item.Data, item.InventoryItem); break; + default: return false; + }; - if (e.DragOutOfBounds || dialogDrop) - { - e.ContinueDrag = !fitsInOldSlot; - e.RestoreOriginalSlot = fitsInOldSlot; - return; - } + return true; + }, + () => false); + } - var newSlot = item.GetCurrentSlotBasedOnPosition(); + if (e.DragOutOfBounds || dialogDrop) + { + e.ContinueDrag = !fitsInOldSlot; + e.RestoreOriginalSlot = fitsInOldSlot; + return; + } - // check overlapping items: - // 1. If there's multiple items under it, snap it back to the original slot if iti fits, otherwise continue dragging - // 2. If there's only one item under it, "chain" the drag operation to that item - // 3. If there's nothing under it, make sure it fits in the inventory, otherwise snap back to original slot + var newSlot = item.GetCurrentSlotBasedOnPosition(); - var overlapped = GetOverlappingTakenSlots(newSlot, e.Data.Size, _childItems.Except(new[] { item }).Select(x => (x.Slot, x.Data.Size))) - .ToList(); + // check overlapping items: + // 1. If there's multiple items under it, snap it back to the original slot if iti fits, otherwise continue dragging + // 2. If there's only one item under it, "chain" the drag operation to that item + // 3. If there's nothing under it, make sure it fits in the inventory, otherwise snap back to original slot - if (overlapped.Count > 1) - { - e.RestoreOriginalSlot = true; + var overlapped = GetOverlappingTakenSlots(newSlot, e.Data.Size, _childItems.Except(new[] { item }).Select(x => (x.Slot, x.Data.Size))) + .ToList(); - if (!fitsInOldSlot) - e.ContinueDrag = true; - } - else if (overlapped.Count == 1) - { - var nextItem = _childItems.Single(x => x.Slot == overlapped[0] && !x.IsDragging); - nextItem.Slot = oldSlot; - nextItem.StartDragging(isChainedDrag: true); - } - else if (oldSlot != newSlot) + if (overlapped.Count > 1) + { + e.RestoreOriginalSlot = true; + + if (!fitsInOldSlot) + e.ContinueDrag = true; + } + else if (overlapped.Count == 1) + { + var nextItem = _childItems.Single(x => x.Slot == overlapped[0] && !x.IsDragging); + nextItem.Slot = oldSlot; + nextItem.StartDragging(isChainedDrag: true); + } + else if (oldSlot != newSlot) + { + if (!_inventoryService.FitsInSlot(_inventorySlotRepository.FilledSlots, oldSlot, newSlot, e.Data.Size)) { - if (!_inventoryService.FitsInSlot(_inventorySlotRepository.FilledSlots, oldSlot, newSlot, e.Data.Size)) + // if the original slot no longer fits (because this is a chained drag), don't stop dragging this item + if (!fitsInOldSlot) { - // if the original slot no longer fits (because this is a chained drag), don't stop dragging this item - if (!fitsInOldSlot) - { - e.ContinueDrag = true; - } - else - { - e.RestoreOriginalSlot = true; - } + e.ContinueDrag = true; } else { - RemoveHiddenItemsFromCachedInventory(); + e.RestoreOriginalSlot = true; } } + else + { + RemoveHiddenItemsFromCachedInventory(); + } } + } - private void ResetSlotMap(IEnumerable childItems) - { - // reset the slot map based on the current state of the inventory - // avoids issues due to chained drags + variable item sizes - _inventorySlotRepository.FilledSlots.Fill(false); - foreach (var childItem in childItems) - _inventoryService.SetSlots(_inventorySlotRepository.FilledSlots, childItem.Slot, childItem.Data.Size); - } + private void ResetSlotMap(IEnumerable childItems) + { + // reset the slot map based on the current state of the inventory + // avoids issues due to chained drags + variable item sizes + _inventorySlotRepository.FilledSlots.Fill(false); + foreach (var childItem in childItems) + _inventoryService.SetSlots(_inventorySlotRepository.FilledSlots, childItem.Slot, childItem.Data.Size); + } - private void RemoveHiddenItemsFromCachedInventory() - { - // the item fits in the new slot, and there is no chained drag, snapback, or continued drag - // under these conditions, check if there are any items that don't have a matching childItem and remove them from the cached list - // the next update loop will detect these items as 'added' and attempt to show them in the empty space + private void RemoveHiddenItemsFromCachedInventory() + { + // the item fits in the new slot, and there is no chained drag, snapback, or continued drag + // under these conditions, check if there are any items that don't have a matching childItem and remove them from the cached list + // the next update loop will detect these items as 'added' and attempt to show them in the empty space - var notDisplayedItems = _cachedInventory.Where(x => _childItems.All(ci => x != ci.InventoryItem)); - _cachedInventory.RemoveWhere(notDisplayedItems.Contains); - } + var notDisplayedItems = _cachedInventory.Where(x => _childItems.All(ci => x != ci.InventoryItem)); + _cachedInventory.RemoveWhere(notDisplayedItems.Contains); + } - private static IEnumerable GetOverlappingTakenSlots(int newSlot, ItemSize size, IEnumerable<(int Slot, ItemSize Size)> items) - { - var slotX = newSlot % InventoryRowSlots; - var slotY = newSlot / InventoryRowSlots; - var slotItemDim = size.GetDimensions(); + private static IEnumerable GetOverlappingTakenSlots(int newSlot, ItemSize size, IEnumerable<(int Slot, ItemSize Size)> items) + { + var slotX = newSlot % InventoryRowSlots; + var slotY = newSlot / InventoryRowSlots; + var slotItemDim = size.GetDimensions(); + + var newSlotCoords = new List<(int X, int Y)>(); + for (int r = slotY; r < slotY + slotItemDim.Height; r++) + for (int c = slotX; c < slotX + slotItemDim.Width; c++) + newSlotCoords.Add((c, r)); - var newSlotCoords = new List<(int X, int Y)>(); - for (int r = slotY; r < slotY + slotItemDim.Height; r++) - for (int c = slotX; c < slotX + slotItemDim.Width; c++) - newSlotCoords.Add((c, r)); + foreach (var item in items) + { + var itemX = item.Slot % InventoryRowSlots; + var itemY = item.Slot / InventoryRowSlots; + var itemDim = item.Size.GetDimensions(); - foreach (var item in items) + var @break = false; + for (int r = itemY; r < itemY + itemDim.Height; r++) { - var itemX = item.Slot % InventoryRowSlots; - var itemY = item.Slot / InventoryRowSlots; - var itemDim = item.Size.GetDimensions(); + if (@break) + break; - var @break = false; - for (int r = itemY; r < itemY + itemDim.Height; r++) + for (int c = itemX; c < itemX + itemDim.Width; c++) { - if (@break) - break; - - for (int c = itemX; c < itemX + itemDim.Width; c++) + if (newSlotCoords.Contains((c, r))) { - if (newSlotCoords.Contains((c, r))) - { - yield return item.Slot; - @break = true; - break; - } + yield return item.Slot; + @break = true; + break; } } } diff --git a/EndlessClient/HUD/Panels/NewsPanel.cs b/EndlessClient/HUD/Panels/NewsPanel.cs index ad983b417..dc5976243 100644 --- a/EndlessClient/HUD/Panels/NewsPanel.cs +++ b/EndlessClient/HUD/Panels/NewsPanel.cs @@ -10,123 +10,122 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class NewsPanel : DraggableHudPanel { - public class NewsPanel : DraggableHudPanel + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatRenderableGenerator _chatRenderableGenerator; + private readonly INewsProvider _newsProvider; + private readonly ScrollBar _scrollBar; + private readonly List _chatRenderables; + private readonly BitmapFont _chatFont; + + //cached data fields + private readonly List _cachedNewsStrings; + private int _cachedScrollOffset; + private int _cachedLinesToRender; + + private bool _firstTime = true; + + public NewsPanel(INativeGraphicsManager nativeGraphicsManager, + IChatRenderableGenerator chatRenderableGenerator, + INewsProvider newsProvider, + BitmapFont chatFont, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatRenderableGenerator _chatRenderableGenerator; - private readonly INewsProvider _newsProvider; - private readonly ScrollBar _scrollBar; - private readonly List _chatRenderables; - private readonly BitmapFont _chatFont; - - //cached data fields - private readonly List _cachedNewsStrings; - private int _cachedScrollOffset; - private int _cachedLinesToRender; - - private bool _firstTime = true; - - public NewsPanel(INativeGraphicsManager nativeGraphicsManager, - IChatRenderableGenerator chatRenderableGenerator, - INewsProvider newsProvider, - BitmapFont chatFont, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + _nativeGraphicsManager = nativeGraphicsManager; + _chatRenderableGenerator = chatRenderableGenerator; + _newsProvider = newsProvider; + + //abs coordiantes: 568 331 + _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) { - _nativeGraphicsManager = nativeGraphicsManager; - _chatRenderableGenerator = chatRenderableGenerator; - _newsProvider = newsProvider; + LinesToRender = 7, + Visible = true + }; + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); - //abs coordiantes: 568 331 - _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) - { - LinesToRender = 7, - Visible = true - }; - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); + _chatRenderables = new List(); + _chatFont = chatFont; - _chatRenderables = new List(); - _chatFont = chatFont; + _cachedNewsStrings = new List(); + _cachedScrollOffset = -1; + _cachedLinesToRender = -1; - _cachedNewsStrings = new List(); - _cachedScrollOffset = -1; - _cachedLinesToRender = -1; + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 48); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + } - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 48); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - } + public override void Initialize() + { + _scrollBar.Initialize(); + base.Initialize(); + } - public override void Initialize() + protected override void OnUpdateControl(GameTime gameTime) + { + var newsChanged = false; + if (!_cachedNewsStrings.SequenceEqual(_newsProvider.NewsText)) { - _scrollBar.Initialize(); - base.Initialize(); + UpdateCachedNewsStrings(); + newsChanged = true; } - protected override void OnUpdateControl(GameTime gameTime) + if (newsChanged || + _cachedScrollOffset != _scrollBar.ScrollOffset || + _cachedLinesToRender != _scrollBar.LinesToRender) { - var newsChanged = false; - if (!_cachedNewsStrings.SequenceEqual(_newsProvider.NewsText)) - { - UpdateCachedNewsStrings(); - newsChanged = true; - } - - if (newsChanged || - _cachedScrollOffset != _scrollBar.ScrollOffset || - _cachedLinesToRender != _scrollBar.LinesToRender) - { - var renderables = _chatRenderableGenerator.GenerateNewsRenderables(_cachedNewsStrings); + var renderables = _chatRenderableGenerator.GenerateNewsRenderables(_cachedNewsStrings); - UpdateCachedScrollProperties(); - SetupRenderablesFromCachedValues(renderables); + UpdateCachedScrollProperties(); + SetupRenderablesFromCachedValues(renderables); - if (_firstTime && renderables.Count > _scrollBar.LinesToRender) - { - _scrollBar.SetDownArrowFlashSpeed(500); - _firstTime = false; - } + if (_firstTime && renderables.Count > _scrollBar.LinesToRender) + { + _scrollBar.SetDownArrowFlashSpeed(500); + _firstTime = false; } - - base.OnUpdateControl(gameTime); } - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + base.OnUpdateControl(gameTime); + } - if (_chatRenderables == null) - return; + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - foreach (var renderable in _chatRenderables) - renderable.Render(this, _spriteBatch, _chatFont); - } + if (_chatRenderables == null) + return; - private void UpdateCachedNewsStrings() - { - _cachedNewsStrings.Clear(); - _cachedNewsStrings.AddRange(_newsProvider.NewsText); - } + foreach (var renderable in _chatRenderables) + renderable.Render(this, _spriteBatch, _chatFont); + } - private void UpdateCachedScrollProperties() - { - _cachedScrollOffset = _scrollBar.ScrollOffset; - _cachedLinesToRender = _scrollBar.LinesToRender; - } + private void UpdateCachedNewsStrings() + { + _cachedNewsStrings.Clear(); + _cachedNewsStrings.AddRange(_newsProvider.NewsText); + } - private void SetupRenderablesFromCachedValues(IReadOnlyList renderables) - { - _chatRenderables.Clear(); + private void UpdateCachedScrollProperties() + { + _cachedScrollOffset = _scrollBar.ScrollOffset; + _cachedLinesToRender = _scrollBar.LinesToRender; + } - //only render based on what the scroll bar's position is - _chatRenderables.AddRange(renderables.Skip(_cachedScrollOffset).Take(_cachedLinesToRender)); - for (int i = 0; i < _chatRenderables.Count; ++i) - _chatRenderables[i].DisplayIndex = i; + private void SetupRenderablesFromCachedValues(IReadOnlyList renderables) + { + _chatRenderables.Clear(); - //update scrollbar with total number of renderables - _scrollBar.UpdateDimensions(renderables.Count); - } + //only render based on what the scroll bar's position is + _chatRenderables.AddRange(renderables.Skip(_cachedScrollOffset).Take(_cachedLinesToRender)); + for (int i = 0; i < _chatRenderables.Count; ++i) + _chatRenderables[i].DisplayIndex = i; + + //update scrollbar with total number of renderables + _scrollBar.UpdateDimensions(renderables.Count); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/OnlineListPanel.cs b/EndlessClient/HUD/Panels/OnlineListPanel.cs index 6f892ebb2..2a9b50f00 100644 --- a/EndlessClient/HUD/Panels/OnlineListPanel.cs +++ b/EndlessClient/HUD/Panels/OnlineListPanel.cs @@ -21,223 +21,222 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class OnlineListPanel : DraggableHudPanel { - public class OnlineListPanel : DraggableHudPanel + private enum Filter { - private enum Filter - { - All, - Friends, - Admins, - Party, - Max - } + All, + Friends, + Admins, + Party, + Max + } - private const int DRAW_NAME_X = 18, - DRAW_OFFSET_Y = 23; - - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IHudControlProvider _hudControlProvider; - private readonly IOnlinePlayerProvider _onlinePlayerProvider; - private readonly IPartyDataProvider _partyDataProvider; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly ISfxPlayer _sfxPlayer; - - private readonly BitmapFont _chatFont; - - private readonly List _onlineList; - private readonly IXNALabel _totalNumberOfPlayers; - private readonly ScrollBar _scrollBar; - private readonly ClickableArea _filterClickArea; - - private readonly Texture2D _weirdOffsetTextureSheet, _chatIconsTexture; - private readonly Rectangle[] _filterTextureSources; - - private HashSet _cachedList; - - private Filter _filter; - private List _filteredList; - private IReadOnlyList _friendList; - - public OnlineListPanel(INativeGraphicsManager nativeGraphicsManager, - IHudControlProvider hudControlProvider, - IOnlinePlayerProvider onlinePlayerProvider, - IPartyDataProvider partyDataProvider, - IFriendIgnoreListService friendIgnoreListService, - ISfxPlayer sfxPlayer, - BitmapFont chatFont, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + private const int DRAW_NAME_X = 18, + DRAW_OFFSET_Y = 23; + + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IHudControlProvider _hudControlProvider; + private readonly IOnlinePlayerProvider _onlinePlayerProvider; + private readonly IPartyDataProvider _partyDataProvider; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly ISfxPlayer _sfxPlayer; + + private readonly BitmapFont _chatFont; + + private readonly List _onlineList; + private readonly IXNALabel _totalNumberOfPlayers; + private readonly ScrollBar _scrollBar; + private readonly ClickableArea _filterClickArea; + + private readonly Texture2D _weirdOffsetTextureSheet, _chatIconsTexture; + private readonly Rectangle[] _filterTextureSources; + + private HashSet _cachedList; + + private Filter _filter; + private List _filteredList; + private IReadOnlyList _friendList; + + public OnlineListPanel(INativeGraphicsManager nativeGraphicsManager, + IHudControlProvider hudControlProvider, + IOnlinePlayerProvider onlinePlayerProvider, + IPartyDataProvider partyDataProvider, + IFriendIgnoreListService friendIgnoreListService, + ISfxPlayer sfxPlayer, + BitmapFont chatFont, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) + { + _nativeGraphicsManager = nativeGraphicsManager; + _hudControlProvider = hudControlProvider; + _onlinePlayerProvider = onlinePlayerProvider; + _partyDataProvider = partyDataProvider; + _friendIgnoreListService = friendIgnoreListService; + _sfxPlayer = sfxPlayer; + _chatFont = chatFont; + _onlineList = new List(); + + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 36); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + + _totalNumberOfPlayers = new XNALabel(Constants.FontSize09) { - _nativeGraphicsManager = nativeGraphicsManager; - _hudControlProvider = hudControlProvider; - _onlinePlayerProvider = onlinePlayerProvider; - _partyDataProvider = partyDataProvider; - _friendIgnoreListService = friendIgnoreListService; - _sfxPlayer = sfxPlayer; - _chatFont = chatFont; - _onlineList = new List(); - - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 36); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - - _totalNumberOfPlayers = new XNALabel(Constants.FontSize09) - { - AutoSize = false, - ForeColor = ColorConstants.LightGrayText, - TextAlign = LabelAlignment.MiddleRight, - DrawArea = new Rectangle(454, 1, 27, 14), - BackColor = Color.Transparent, - }; - _totalNumberOfPlayers.SetParentControl(this); - - _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) - { - LinesToRender = 7, - Visible = true - }; - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); - - _filterClickArea = new ClickableArea(new Rectangle(2, 2, 14, 14)); - _filterClickArea.SetParentControl(this); - _filterClickArea.OnClick += FilterClickArea_Click; - - _weirdOffsetTextureSheet = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); - _chatIconsTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); - - _filterTextureSources = new Rectangle[4]; - for (int i = 0; i < _filterTextureSources.Length; ++i) - _filterTextureSources[i] = new Rectangle(i % 2 == 0 ? 0 : 12, i >= 2 ? 246 : 233, 12, 13); - - _cachedList = new HashSet(); - _filter = Filter.All; - _filteredList = new List(); - } - - public override void Initialize() + AutoSize = false, + ForeColor = ColorConstants.LightGrayText, + TextAlign = LabelAlignment.MiddleRight, + DrawArea = new Rectangle(454, 1, 27, 14), + BackColor = Color.Transparent, + }; + _totalNumberOfPlayers.SetParentControl(this); + + _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) { - _totalNumberOfPlayers.Initialize(); - _scrollBar.Initialize(); - _filterClickArea.Initialize(); + LinesToRender = 7, + Visible = true + }; + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); + + _filterClickArea = new ClickableArea(new Rectangle(2, 2, 14, 14)); + _filterClickArea.SetParentControl(this); + _filterClickArea.OnClick += FilterClickArea_Click; + + _weirdOffsetTextureSheet = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); + _chatIconsTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); + + _filterTextureSources = new Rectangle[4]; + for (int i = 0; i < _filterTextureSources.Length; ++i) + _filterTextureSources[i] = new Rectangle(i % 2 == 0 ? 0 : 12, i >= 2 ? 246 : 233, 12, 13); + + _cachedList = new HashSet(); + _filter = Filter.All; + _filteredList = new List(); + } - base.Initialize(); - } + public override void Initialize() + { + _totalNumberOfPlayers.Initialize(); + _scrollBar.Initialize(); + _filterClickArea.Initialize(); - protected override void OnUpdateControl(GameTime gameTime) + base.Initialize(); + } + + protected override void OnUpdateControl(GameTime gameTime) + { + if (!_cachedList.SetEquals(_onlinePlayerProvider.OnlinePlayers)) { - if (!_cachedList.SetEquals(_onlinePlayerProvider.OnlinePlayers)) - { - _cachedList = _onlinePlayerProvider.OnlinePlayers.ToHashSet(); + _cachedList = _onlinePlayerProvider.OnlinePlayers.ToHashSet(); - // keep the friends list data from overriding the displayed data in this panel - // it will be friends list data if all titles (or any field other than name) are empty - if (!_cachedList.All(x => x.Title == string.Empty)) - { - _onlineList.Clear(); - _onlineList.AddRange(_cachedList); + // keep the friends list data from overriding the displayed data in this panel + // it will be friends list data if all titles (or any field other than name) are empty + if (!_cachedList.All(x => x.Title == string.Empty)) + { + _onlineList.Clear(); + _onlineList.AddRange(_cachedList); - _onlineList.Sort((a, b) => a.Name.CompareTo(b.Name)); - _filteredList = new List(_onlineList); + _onlineList.Sort((a, b) => a.Name.CompareTo(b.Name)); + _filteredList = new List(_onlineList); - _totalNumberOfPlayers.Text = $"{_onlineList.Count}"; - _scrollBar.UpdateDimensions(_onlineList.Count); - _scrollBar.ScrollToTop(); + _totalNumberOfPlayers.Text = $"{_onlineList.Count}"; + _scrollBar.UpdateDimensions(_onlineList.Count); + _scrollBar.ScrollToTop(); - _friendList = _friendIgnoreListService.LoadList(Constants.FriendListFile); + _friendList = _friendIgnoreListService.LoadList(Constants.FriendListFile); - ApplyFilter(); - } + ApplyFilter(); } - - base.OnUpdateControl(gameTime); } - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); - - const int DRAW_ICON_X = 4, - DRAW_TITLE_X = 133, - DRAW_GUILD_X = 245, - DRAW_CLASS_X = 359; + base.OnUpdateControl(gameTime); + } + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - _spriteBatch.Begin(); + const int DRAW_ICON_X = 4, + DRAW_TITLE_X = 133, + DRAW_GUILD_X = 245, + DRAW_CLASS_X = 359; - _spriteBatch.Draw(_weirdOffsetTextureSheet, new Vector2(DrawAreaWithParentOffset.X + 4, DrawAreaWithParentOffset.Y + 2), _filterTextureSources[(int)_filter], Color.White); - // todo: either a) use renderable approach like Chat/News or b) remove renderable approach in favor of this simpler method - for (int i = _scrollBar.ScrollOffset; i < _scrollBar.ScrollOffset + _scrollBar.LinesToRender && i < _filteredList.Count; ++i) - { - int yCoord = DRAW_OFFSET_Y + DrawAreaWithParentOffset.Y + (i - _scrollBar.ScrollOffset) * 13; - _spriteBatch.Draw(_chatIconsTexture, new Vector2(DrawAreaWithParentOffset.X + DRAW_ICON_X, yCoord), GetChatIconSourceRectangle(_filteredList[i].Icon), Color.White); - _spriteBatch.DrawString(_chatFont, _filteredList[i].Name, new Vector2(DrawAreaWithParentOffset.X + DRAW_NAME_X, yCoord), Color.Black); - _spriteBatch.DrawString(_chatFont, _filteredList[i].Title, new Vector2(DrawAreaWithParentOffset.X + DRAW_TITLE_X, yCoord), Color.Black); - _spriteBatch.DrawString(_chatFont, _filteredList[i].Guild, new Vector2(DrawAreaWithParentOffset.X + DRAW_GUILD_X, yCoord), Color.Black); - _spriteBatch.DrawString(_chatFont, _filteredList[i].Class, new Vector2(DrawAreaWithParentOffset.X + DRAW_CLASS_X, yCoord), Color.Black); - } + _spriteBatch.Begin(); - _spriteBatch.End(); - } + _spriteBatch.Draw(_weirdOffsetTextureSheet, new Vector2(DrawAreaWithParentOffset.X + 4, DrawAreaWithParentOffset.Y + 2), _filterTextureSources[(int)_filter], Color.White); - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + // todo: either a) use renderable approach like Chat/News or b) remove renderable approach in favor of this simpler method + for (int i = _scrollBar.ScrollOffset; i < _scrollBar.ScrollOffset + _scrollBar.LinesToRender && i < _filteredList.Count; ++i) { - if (eventArgs.Button != MouseButton.Right) - return false; - - var mousePos = eventArgs.Position; - if (mousePos.X >= DrawAreaWithParentOffset.X + DRAW_NAME_X && mousePos.X <= _scrollBar.DrawAreaWithParentOffset.X && - mousePos.Y >= DrawAreaWithParentOffset.Y + DRAW_OFFSET_Y && mousePos.Y <= DrawAreaWithParentOffset.Y + DrawAreaWithParentOffset.Height) - { - var index = (mousePos.Y - (DrawAreaWithParentOffset.Y + DRAW_OFFSET_Y)) / 13; - if (index >= 0 && index <= _filteredList.Count) - { - var name = _filteredList[_scrollBar.ScrollOffset + index].Name; - _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{name} "; - } - } - - return true; + int yCoord = DRAW_OFFSET_Y + DrawAreaWithParentOffset.Y + (i - _scrollBar.ScrollOffset) * 13; + _spriteBatch.Draw(_chatIconsTexture, new Vector2(DrawAreaWithParentOffset.X + DRAW_ICON_X, yCoord), GetChatIconSourceRectangle(_filteredList[i].Icon), Color.White); + _spriteBatch.DrawString(_chatFont, _filteredList[i].Name, new Vector2(DrawAreaWithParentOffset.X + DRAW_NAME_X, yCoord), Color.Black); + _spriteBatch.DrawString(_chatFont, _filteredList[i].Title, new Vector2(DrawAreaWithParentOffset.X + DRAW_TITLE_X, yCoord), Color.Black); + _spriteBatch.DrawString(_chatFont, _filteredList[i].Guild, new Vector2(DrawAreaWithParentOffset.X + DRAW_GUILD_X, yCoord), Color.Black); + _spriteBatch.DrawString(_chatFont, _filteredList[i].Class, new Vector2(DrawAreaWithParentOffset.X + DRAW_CLASS_X, yCoord), Color.Black); } - private void FilterClickArea_Click(object sender, EventArgs e) - { - _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - _filter = (Filter)(((int)_filter + 1) % (int)Filter.Max); - _scrollBar.ScrollToTop(); + _spriteBatch.End(); + } - ApplyFilter(); - } + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (eventArgs.Button != MouseButton.Right) + return false; - private void ApplyFilter() + var mousePos = eventArgs.Position; + if (mousePos.X >= DrawAreaWithParentOffset.X + DRAW_NAME_X && mousePos.X <= _scrollBar.DrawAreaWithParentOffset.X && + mousePos.Y >= DrawAreaWithParentOffset.Y + DRAW_OFFSET_Y && mousePos.Y <= DrawAreaWithParentOffset.Y + DrawAreaWithParentOffset.Height) { - switch (_filter) + var index = (mousePos.Y - (DrawAreaWithParentOffset.Y + DRAW_OFFSET_Y)) / 13; + if (index >= 0 && index <= _filteredList.Count) { - case Filter.Friends: _filteredList = _onlineList.Where(x => _friendList.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase)).ToList(); break; - case Filter.Admins: _filteredList = _onlineList.Where(IsAdminIcon).ToList(); break; - case Filter.Party: _filteredList = _onlineList.Where(x => _partyDataProvider.Members.Any(y => string.Equals(y.Name, x.Name, StringComparison.InvariantCultureIgnoreCase))).ToList(); break; - case Filter.All: - default: _filteredList = new List(_onlineList); break; + var name = _filteredList[_scrollBar.ScrollOffset + index].Name; + _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{name} "; } - - _scrollBar.UpdateDimensions(_filteredList.Count); } - private static bool IsAdminIcon(OnlinePlayerInfo onlineInfo) + return true; + } + + private void FilterClickArea_Click(object sender, EventArgs e) + { + _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + _filter = (Filter)(((int)_filter + 1) % (int)Filter.Max); + _scrollBar.ScrollToTop(); + + ApplyFilter(); + } + + private void ApplyFilter() + { + switch (_filter) { - return onlineInfo.Icon switch - { - CharacterIcon.Gm or CharacterIcon.Hgm or CharacterIcon.GmParty or CharacterIcon.HgmParty => true, - _ => false, - }; + case Filter.Friends: _filteredList = _onlineList.Where(x => _friendList.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase)).ToList(); break; + case Filter.Admins: _filteredList = _onlineList.Where(IsAdminIcon).ToList(); break; + case Filter.Party: _filteredList = _onlineList.Where(x => _partyDataProvider.Members.Any(y => string.Equals(y.Name, x.Name, StringComparison.InvariantCultureIgnoreCase))).ToList(); break; + case Filter.All: + default: _filteredList = new List(_onlineList); break; } - private static Rectangle? GetChatIconSourceRectangle(CharacterIcon icon) + _scrollBar.UpdateDimensions(_filteredList.Count); + } + + private static bool IsAdminIcon(OnlinePlayerInfo onlineInfo) + { + return onlineInfo.Icon switch { - var (x, y, width, height) = icon.ToChatIcon().GetChatIconRectangleBounds().ValueOrDefault(); - return new Rectangle(x, y, width, height); - } + CharacterIcon.Gm or CharacterIcon.Hgm or CharacterIcon.GmParty or CharacterIcon.HgmParty => true, + _ => false, + }; + } + + private static Rectangle? GetChatIconSourceRectangle(CharacterIcon icon) + { + var (x, y, width, height) = icon.ToChatIcon().GetChatIconRectangleBounds().ValueOrDefault(); + return new Rectangle(x, y, width, height); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/PartyPanel.cs b/EndlessClient/HUD/Panels/PartyPanel.cs index 40bc1a4ea..e5f22a316 100644 --- a/EndlessClient/HUD/Panels/PartyPanel.cs +++ b/EndlessClient/HUD/Panels/PartyPanel.cs @@ -12,152 +12,151 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class PartyPanel : DraggableHudPanel { - public class PartyPanel : DraggableHudPanel + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IPartyActions _partyActions; + private readonly IContentProvider _contentProvider; + private readonly IPartyDataProvider _partyDataProvider; + private readonly ICharacterProvider _characterProvider; + + private readonly ScrollBar _scrollBar; + private readonly IXNALabel _numMembers; + private readonly List _children; + + private HashSet _cachedParty; + private int _cachedScrollOffset; + + public PartyPanel(INativeGraphicsManager nativeGraphicsManager, + IPartyActions partyActions, + IContentProvider contentProvider, + IPartyDataProvider partyDataProvider, + ICharacterProvider characterProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IPartyActions _partyActions; - private readonly IContentProvider _contentProvider; - private readonly IPartyDataProvider _partyDataProvider; - private readonly ICharacterProvider _characterProvider; - - private readonly ScrollBar _scrollBar; - private readonly IXNALabel _numMembers; - private readonly List _children; - - private HashSet _cachedParty; - private int _cachedScrollOffset; - - public PartyPanel(INativeGraphicsManager nativeGraphicsManager, - IPartyActions partyActions, - IContentProvider contentProvider, - IPartyDataProvider partyDataProvider, - ICharacterProvider characterProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + _nativeGraphicsManager = nativeGraphicsManager; + _partyActions = partyActions; + _contentProvider = contentProvider; + _partyDataProvider = partyDataProvider; + _characterProvider = characterProvider; + _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) { - _nativeGraphicsManager = nativeGraphicsManager; - _partyActions = partyActions; - _contentProvider = contentProvider; - _partyDataProvider = partyDataProvider; - _characterProvider = characterProvider; - _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) - { - LinesToRender = 7, - Visible = true, - }; - _scrollBar.SetParentControl(this); - _scrollBar.UpdateDimensions(0); - SetScrollWheelHandler(_scrollBar); - - _numMembers = new XNALabel(Constants.FontSize09) - { - AutoSize = false, - DrawArea = new Rectangle(455, 0, 27, 14), - ForeColor = ColorConstants.LightGrayText, - TextAlign = LabelAlignment.MiddleRight - }; - _numMembers.SetParentControl(this); + LinesToRender = 7, + Visible = true, + }; + _scrollBar.SetParentControl(this); + _scrollBar.UpdateDimensions(0); + SetScrollWheelHandler(_scrollBar); + + _numMembers = new XNALabel(Constants.FontSize09) + { + AutoSize = false, + DrawArea = new Rectangle(455, 0, 27, 14), + ForeColor = ColorConstants.LightGrayText, + TextAlign = LabelAlignment.MiddleRight + }; + _numMembers.SetParentControl(this); - _children = new List(); + _children = new List(); - _cachedParty = new HashSet(); + _cachedParty = new HashSet(); - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 42); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - } + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 42); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + } - public override void Initialize() - { - _scrollBar.Initialize(); - _numMembers.Initialize(); + public override void Initialize() + { + _scrollBar.Initialize(); + _numMembers.Initialize(); - base.Initialize(); - } + base.Initialize(); + } - protected override void OnUpdateControl(GameTime gameTime) + protected override void OnUpdateControl(GameTime gameTime) + { + if (!_cachedParty.SetEquals(_partyDataProvider.Members)) { - if (!_cachedParty.SetEquals(_partyDataProvider.Members)) - { - var added = _partyDataProvider.Members.Where(x => !_cachedParty.Any(y => y.CharacterID == x.CharacterID)).ToList(); - var removed = _cachedParty.Where(x => !_partyDataProvider.Members.Any(y => y.CharacterID == x.CharacterID)).ToList(); - var updated = _partyDataProvider.Members.Where(x => _cachedParty.Any(y => y.CharacterID == x.CharacterID && !y.Equals(x))).ToList(); - _cachedParty = _partyDataProvider.Members.ToHashSet(); + var added = _partyDataProvider.Members.Where(x => !_cachedParty.Any(y => y.CharacterID == x.CharacterID)).ToList(); + var removed = _cachedParty.Where(x => !_partyDataProvider.Members.Any(y => y.CharacterID == x.CharacterID)).ToList(); + var updated = _partyDataProvider.Members.Where(x => _cachedParty.Any(y => y.CharacterID == x.CharacterID && !y.Equals(x))).ToList(); + _cachedParty = _partyDataProvider.Members.ToHashSet(); - var mainCharacterIsLeader = _cachedParty.Any(x => x.IsLeader && x.CharacterID == _characterProvider.MainCharacter.ID); + var mainCharacterIsLeader = _cachedParty.Any(x => x.IsLeader && x.CharacterID == _characterProvider.MainCharacter.ID); - foreach (var member in added) - { - var next = new PartyPanelMember( - _nativeGraphicsManager, - _contentProvider, - mainCharacterIsLeader || member.CharacterID == _characterProvider.MainCharacter.ID) - { - PartyMember = member, - }; - next.RemoveAction += (_, _) => _partyActions.RemovePartyMember(member.CharacterID); - next.SetParentControl(this); - next.Initialize(); - - _children.Add(next); - } - - foreach (var member in removed) - { - _children.SingleOrNone(x => x.PartyMember.CharacterID == member.CharacterID) - .MatchSome(x => - { - x.SetControlUnparented(); - x.Dispose(); - _children.Remove(x); - }); - } - - foreach (var member in updated) + foreach (var member in added) + { + var next = new PartyPanelMember( + _nativeGraphicsManager, + _contentProvider, + mainCharacterIsLeader || member.CharacterID == _characterProvider.MainCharacter.ID) { - _children.SingleOrNone(x => x.PartyMember.CharacterID == member.CharacterID) - .MatchSome(x => x.PartyMember = member); - } + PartyMember = member, + }; + next.RemoveAction += (_, _) => _partyActions.RemovePartyMember(member.CharacterID); + next.SetParentControl(this); + next.Initialize(); - _numMembers.Text = $"{_cachedParty.Count}"; - _scrollBar.UpdateDimensions(_cachedParty.Count); + _children.Add(next); + } - UpdateChildMemberVisibility(); + foreach (var member in removed) + { + _children.SingleOrNone(x => x.PartyMember.CharacterID == member.CharacterID) + .MatchSome(x => + { + x.SetControlUnparented(); + x.Dispose(); + _children.Remove(x); + }); } - if (_cachedScrollOffset != _scrollBar.ScrollOffset) + foreach (var member in updated) { - _cachedScrollOffset = _scrollBar.ScrollOffset; - UpdateChildMemberVisibility(); + _children.SingleOrNone(x => x.PartyMember.CharacterID == member.CharacterID) + .MatchSome(x => x.PartyMember = member); } - base.OnUpdateControl(gameTime); + _numMembers.Text = $"{_cachedParty.Count}"; + _scrollBar.UpdateDimensions(_cachedParty.Count); + + UpdateChildMemberVisibility(); } - protected override void OnVisibleChanged(object sender, System.EventArgs args) + if (_cachedScrollOffset != _scrollBar.ScrollOffset) { - if (Visible) - { - // request party list when viewing the party panel - _partyActions.ListParty(); - } - - base.OnVisibleChanged(sender, args); + _cachedScrollOffset = _scrollBar.ScrollOffset; + UpdateChildMemberVisibility(); } - private void UpdateChildMemberVisibility() + base.OnUpdateControl(gameTime); + } + + protected override void OnVisibleChanged(object sender, System.EventArgs args) + { + if (Visible) { - foreach (var child in _children) - child.Visible = false; + // request party list when viewing the party panel + _partyActions.ListParty(); + } - for (int i = 0; i < _scrollBar.LinesToRender; i++) - { - if (_scrollBar.ScrollOffset + i >= _children.Count) - break; - _children[_scrollBar.ScrollOffset + i].DisplayIndex = i; - _children[_scrollBar.ScrollOffset + i].Visible = true; - } + base.OnVisibleChanged(sender, args); + } + + private void UpdateChildMemberVisibility() + { + foreach (var child in _children) + child.Visible = false; + + for (int i = 0; i < _scrollBar.LinesToRender; i++) + { + if (_scrollBar.ScrollOffset + i >= _children.Count) + break; + _children[_scrollBar.ScrollOffset + i].DisplayIndex = i; + _children[_scrollBar.ScrollOffset + i].Visible = true; } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/PassiveSpellsPanel.cs b/EndlessClient/HUD/Panels/PassiveSpellsPanel.cs index aeadd38a3..bcb0b765b 100644 --- a/EndlessClient/HUD/Panels/PassiveSpellsPanel.cs +++ b/EndlessClient/HUD/Panels/PassiveSpellsPanel.cs @@ -2,20 +2,19 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class PassiveSpellsPanel : DraggableHudPanel { - public class PassiveSpellsPanel : DraggableHudPanel - { - private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly INativeGraphicsManager _nativeGraphicsManager; - public PassiveSpellsPanel(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) - { - _nativeGraphicsManager = nativeGraphicsManager; + public PassiveSpellsPanel(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) + { + _nativeGraphicsManager = nativeGraphicsManager; - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 62); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - } + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 62); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/SettingsPanel.cs b/EndlessClient/HUD/Panels/SettingsPanel.cs index c459144dc..c27284a03 100644 --- a/EndlessClient/HUD/Panels/SettingsPanel.cs +++ b/EndlessClient/HUD/Panels/SettingsPanel.cs @@ -13,255 +13,254 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class SettingsPanel : DraggableHudPanel { - public class SettingsPanel : DraggableHudPanel + private enum KeyboardLayout { - private enum KeyboardLayout - { - English, - Dutch, - Swedish, - Azerty - } + English, + Dutch, + Swedish, + Azerty + } - private enum WhichSetting - { - Sfx, - Mfx, - Keyboard, - Language, - HearWhispers, - ShowBalloons, - ShowShadows, - CurseFilter, - LogChat, - Interaction, - } + private enum WhichSetting + { + Sfx, + Mfx, + Keyboard, + Language, + HearWhispers, + ShowBalloons, + ShowShadows, + CurseFilter, + LogChat, + Interaction, + } - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatActions _chatActions; - private readonly IAudioActions _audioActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IConfigurationRepository _configurationRepository; - private readonly ISfxPlayer _sfxPlayer; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatActions _chatActions; + private readonly IAudioActions _audioActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IConfigurationRepository _configurationRepository; + private readonly ISfxPlayer _sfxPlayer; - private readonly Dictionary _labels; - private readonly Dictionary _buttons; + private readonly Dictionary _labels; + private readonly Dictionary _buttons; - private bool _soundChanged, _musicChanged; - private KeyboardLayout _keyboardLayout; + private bool _soundChanged, _musicChanged; + private KeyboardLayout _keyboardLayout; - public SettingsPanel(INativeGraphicsManager nativeGraphicsManager, - IChatActions chatActions, - IAudioActions audioActions, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - IEOMessageBoxFactory messageBoxFactory, - IConfigurationRepository configurationRepository, - ISfxPlayer sfxPlayer, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) - { - _nativeGraphicsManager = nativeGraphicsManager; - _chatActions = chatActions; - _audioActions = audioActions; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _messageBoxFactory = messageBoxFactory; - _configurationRepository = configurationRepository; - _sfxPlayer = sfxPlayer; + public SettingsPanel(INativeGraphicsManager nativeGraphicsManager, + IChatActions chatActions, + IAudioActions audioActions, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + IEOMessageBoxFactory messageBoxFactory, + IConfigurationRepository configurationRepository, + ISfxPlayer sfxPlayer, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) + { + _nativeGraphicsManager = nativeGraphicsManager; + _chatActions = chatActions; + _audioActions = audioActions; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _messageBoxFactory = messageBoxFactory; + _configurationRepository = configurationRepository; + _sfxPlayer = sfxPlayer; - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 47); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 47); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - var values = Enum.GetValues(); - _labels = values.ToDictionary(k => k, - v => + var values = Enum.GetValues(); + _labels = values.ToDictionary(k => k, + v => + { + var ndx = (int)v; + return (IXNALabel)new XNALabel(Constants.FontSize09) { - var ndx = (int)v; - return (IXNALabel)new XNALabel(Constants.FontSize09) - { - DrawArea = new Rectangle(117 + (ndx / 5) * 239, 25 + 18 * (ndx % 5), 100, 15), - AutoSize = false, - ForeColor = ColorConstants.LightGrayText, - }; - }); + DrawArea = new Rectangle(117 + (ndx / 5) * 239, 25 + 18 * (ndx % 5), 100, 15), + AutoSize = false, + ForeColor = ColorConstants.LightGrayText, + }; + }); - UpdateDisplayText(); + UpdateDisplayText(); - _buttons = values.ToDictionary(k => k, - v => - { - var ndx = (int)v; - return (IXNAButton)new XNAButton( - _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true), - new Vector2(215 + (ndx / 5) * 239, 25 + 18 * (ndx % 5)), - new Rectangle(0, 0, 19, 15), - new Rectangle(19, 0, 19, 15)); - }); + _buttons = values.ToDictionary(k => k, + v => + { + var ndx = (int)v; + return (IXNAButton)new XNAButton( + _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true), + new Vector2(215 + (ndx / 5) * 239, 25 + 18 * (ndx % 5)), + new Rectangle(0, 0, 19, 15), + new Rectangle(19, 0, 19, 15)); + }); + } + + public override void Initialize() + { + foreach (var label in _labels.Values) + { + label.SetParentControl(this); + label.Initialize(); } - public override void Initialize() + foreach (var pair in _buttons) { - foreach (var label in _labels.Values) - { - label.SetParentControl(this); - label.Initialize(); - } + var button = pair.Value; + button.OnClick += (_, _) => SettingChange(pair.Key); + button.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_SETTINGS_CLICK_TO_CHANGE); + button.SetParentControl(this); + button.Initialize(); + } - foreach (var pair in _buttons) - { - var button = pair.Value; - button.OnClick += (_, _) => SettingChange(pair.Key); - button.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_SETTINGS_CLICK_TO_CHANGE); - button.SetParentControl(this); - button.Initialize(); - } + if (!_configurationRepository.HearWhispers) + _chatActions.SetHearWhispers(_configurationRepository.HearWhispers); - if (!_configurationRepository.HearWhispers) - _chatActions.SetHearWhispers(_configurationRepository.HearWhispers); + base.Initialize(); + } - base.Initialize(); - } + private void SettingChange(WhichSetting setting) + { + _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - private void SettingChange(WhichSetting setting) + switch (setting) { - _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - - switch (setting) - { - case WhichSetting.Sfx: + case WhichSetting.Sfx: + { + // this alert is emulated even though it isn't needed + if (!_soundChanged && !_configurationRepository.SoundEnabled) { - // this alert is emulated even though it isn't needed - if (!_soundChanged && !_configurationRepository.SoundEnabled) + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SETTINGS_SOUND_DISABLED, EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SETTINGS_SOUND_DISABLED, EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => - { - if (e.Result != XNADialogResult.OK) - return; - - _soundChanged = true; - _configurationRepository.SoundEnabled = !_configurationRepository.SoundEnabled; - _audioActions.ToggleSound(); + if (e.Result != XNADialogResult.OK) + return; - UpdateDisplayText(); - }; - dlg.ShowDialog(); - } - else - { _soundChanged = true; _configurationRepository.SoundEnabled = !_configurationRepository.SoundEnabled; _audioActions.ToggleSound(); - } + + UpdateDisplayText(); + }; + dlg.ShowDialog(); + } + else + { + _soundChanged = true; + _configurationRepository.SoundEnabled = !_configurationRepository.SoundEnabled; + _audioActions.ToggleSound(); } - break; - case WhichSetting.Mfx: + } + break; + case WhichSetting.Mfx: + { + // this alert is emulated even though it isn't needed + if (!_musicChanged && !_configurationRepository.MusicEnabled) { - // this alert is emulated even though it isn't needed - if (!_musicChanged && !_configurationRepository.MusicEnabled) + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SETTINGS_MUSIC_DISABLED, EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SETTINGS_MUSIC_DISABLED, EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => - { - if (e.Result != XNADialogResult.OK) - return; - - _musicChanged = true; - _configurationRepository.MusicEnabled = !_configurationRepository.MusicEnabled; - _audioActions.ToggleBackgroundMusic(); + if (e.Result != XNADialogResult.OK) + return; - UpdateDisplayText(); - }; - dlg.ShowDialog(); - } - else - { _musicChanged = true; _configurationRepository.MusicEnabled = !_configurationRepository.MusicEnabled; _audioActions.ToggleBackgroundMusic(); - } + + UpdateDisplayText(); + }; + dlg.ShowDialog(); } - break; - case WhichSetting.Keyboard: + else { - // this doesn't actually change anything... - _keyboardLayout++; - if (_keyboardLayout > KeyboardLayout.Azerty) - _keyboardLayout = 0; + _musicChanged = true; + _configurationRepository.MusicEnabled = !_configurationRepository.MusicEnabled; + _audioActions.ToggleBackgroundMusic(); } - break; - case WhichSetting.Language: + } + break; + case WhichSetting.Keyboard: + { + // this doesn't actually change anything... + _keyboardLayout++; + if (_keyboardLayout > KeyboardLayout.Azerty) + _keyboardLayout = 0; + } + break; + case WhichSetting.Language: + { + _configurationRepository.Language++; + if (_configurationRepository.Language > EOLanguage.Portuguese) + _configurationRepository.Language = 0; + } + break; + case WhichSetting.HearWhispers: + { + _configurationRepository.HearWhispers = !_configurationRepository.HearWhispers; + _chatActions.SetHearWhispers(_configurationRepository.HearWhispers); + } + break; + case WhichSetting.ShowBalloons: + _configurationRepository.ShowChatBubbles = !_configurationRepository.ShowChatBubbles; + break; + case WhichSetting.ShowShadows: + _configurationRepository.ShowShadows = !_configurationRepository.ShowShadows; + break; + case WhichSetting.CurseFilter: + { + if (_configurationRepository.StrictFilterEnabled) { - _configurationRepository.Language++; - if (_configurationRepository.Language > EOLanguage.Portuguese) - _configurationRepository.Language = 0; + _configurationRepository.StrictFilterEnabled = false; } - break; - case WhichSetting.HearWhispers: + else if (_configurationRepository.CurseFilterEnabled) { - _configurationRepository.HearWhispers = !_configurationRepository.HearWhispers; - _chatActions.SetHearWhispers(_configurationRepository.HearWhispers); + _configurationRepository.CurseFilterEnabled = false; + _configurationRepository.StrictFilterEnabled = true; } - break; - case WhichSetting.ShowBalloons: - _configurationRepository.ShowChatBubbles = !_configurationRepository.ShowChatBubbles; - break; - case WhichSetting.ShowShadows: - _configurationRepository.ShowShadows = !_configurationRepository.ShowShadows; - break; - case WhichSetting.CurseFilter: + else { - if (_configurationRepository.StrictFilterEnabled) - { - _configurationRepository.StrictFilterEnabled = false; - } - else if (_configurationRepository.CurseFilterEnabled) - { - _configurationRepository.CurseFilterEnabled = false; - _configurationRepository.StrictFilterEnabled = true; - } - else - { - _configurationRepository.CurseFilterEnabled = true; - } + _configurationRepository.CurseFilterEnabled = true; } - break; - case WhichSetting.LogChat: - _configurationRepository.LogChatToFile = !_configurationRepository.LogChatToFile; - break; - case WhichSetting.Interaction: - // todo: block trade requests when this is true - _configurationRepository.Interaction = !_configurationRepository.Interaction; - break; - } - - UpdateDisplayText(); + } + break; + case WhichSetting.LogChat: + _configurationRepository.LogChatToFile = !_configurationRepository.LogChatToFile; + break; + case WhichSetting.Interaction: + // todo: block trade requests when this is true + _configurationRepository.Interaction = !_configurationRepository.Interaction; + break; } - private void UpdateDisplayText() - { - _labels[WhichSetting.Sfx].Text = _localizedStringFinder.GetString(_configurationRepository.SoundEnabled ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.Mfx].Text = _localizedStringFinder.GetString(_configurationRepository.MusicEnabled ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.Keyboard].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_KEYBOARD_ENGLISH); - _labels[WhichSetting.Language].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_LANG_CURRENT); - _labels[WhichSetting.HearWhispers].Text = _localizedStringFinder.GetString(_configurationRepository.HearWhispers ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + UpdateDisplayText(); + } - _labels[WhichSetting.ShowBalloons].Text = _localizedStringFinder.GetString(_configurationRepository.ShowChatBubbles ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.ShowShadows].Text = _localizedStringFinder.GetString(_configurationRepository.ShowShadows ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - if (_configurationRepository.StrictFilterEnabled) - _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_EXCLUSIVE); - else if (_configurationRepository.CurseFilterEnabled) - _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_NORMAL); - else - _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_DISABLED); + private void UpdateDisplayText() + { + _labels[WhichSetting.Sfx].Text = _localizedStringFinder.GetString(_configurationRepository.SoundEnabled ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + _labels[WhichSetting.Mfx].Text = _localizedStringFinder.GetString(_configurationRepository.MusicEnabled ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + _labels[WhichSetting.Keyboard].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_KEYBOARD_ENGLISH); + _labels[WhichSetting.Language].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_LANG_CURRENT); + _labels[WhichSetting.HearWhispers].Text = _localizedStringFinder.GetString(_configurationRepository.HearWhispers ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.LogChat].Text = _localizedStringFinder.GetString(_configurationRepository.LogChatToFile ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.Interaction].Text = _localizedStringFinder.GetString(_configurationRepository.Interaction ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - } + _labels[WhichSetting.ShowBalloons].Text = _localizedStringFinder.GetString(_configurationRepository.ShowChatBubbles ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + _labels[WhichSetting.ShowShadows].Text = _localizedStringFinder.GetString(_configurationRepository.ShowShadows ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + if (_configurationRepository.StrictFilterEnabled) + _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_EXCLUSIVE); + else if (_configurationRepository.CurseFilterEnabled) + _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_NORMAL); + else + _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_DISABLED); + + _labels[WhichSetting.LogChat].Text = _localizedStringFinder.GetString(_configurationRepository.LogChatToFile ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + _labels[WhichSetting.Interaction].Text = _localizedStringFinder.GetString(_configurationRepository.Interaction ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/StatsPanel.cs b/EndlessClient/HUD/Panels/StatsPanel.cs index 9106f5563..6fb734617 100644 --- a/EndlessClient/HUD/Panels/StatsPanel.cs +++ b/EndlessClient/HUD/Panels/StatsPanel.cs @@ -11,231 +11,230 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels +namespace EndlessClient.HUD.Panels; + +public class StatsPanel : DraggableHudPanel { - public class StatsPanel : DraggableHudPanel + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IExperienceTableProvider _experienceTableProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITrainingController _trainingController; + private const int STR = 0, INT = 1, WIS = 2, AGI = 3, CON = 4, CHA = 5; + private readonly IXNALabel[] _basicStats; + private readonly IXNAButton[] _arrowButtons; + + private const int HP = 0, TP = 1, DAM = 2, ACC = 3, ARM = 4, EVA = 5; + private readonly IXNALabel[] _characterStats; + + private const int NAME = 0, LEVEL = 1, GUILD = 2; + private readonly IXNALabel[] _characterInfo; + + private const int WEIGHT = 0, STATPTS = 1, SKILLPTS = 2, ELEM = 3, + GOLD = 4, EXP = 5, TNL = 6, KARMA = 7; + private readonly IXNALabel[] _otherInfo; + + private CharacterStats _lastCharacterStats; + private InventoryItem _lastCharacterGold; + private bool _confirmedTraining; + + public StatsPanel(INativeGraphicsManager nativeGraphicsManager, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IExperienceTableProvider experienceTableProvider, + IEOMessageBoxFactory messageBoxFactory, + ITrainingController trainingController, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IExperienceTableProvider _experienceTableProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITrainingController _trainingController; - private const int STR = 0, INT = 1, WIS = 2, AGI = 3, CON = 4, CHA = 5; - private readonly IXNALabel[] _basicStats; - private readonly IXNAButton[] _arrowButtons; - - private const int HP = 0, TP = 1, DAM = 2, ACC = 3, ARM = 4, EVA = 5; - private readonly IXNALabel[] _characterStats; - - private const int NAME = 0, LEVEL = 1, GUILD = 2; - private readonly IXNALabel[] _characterInfo; - - private const int WEIGHT = 0, STATPTS = 1, SKILLPTS = 2, ELEM = 3, - GOLD = 4, EXP = 5, TNL = 6, KARMA = 7; - private readonly IXNALabel[] _otherInfo; - - private CharacterStats _lastCharacterStats; - private InventoryItem _lastCharacterGold; - private bool _confirmedTraining; - - public StatsPanel(INativeGraphicsManager nativeGraphicsManager, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IExperienceTableProvider experienceTableProvider, - IEOMessageBoxFactory messageBoxFactory, - ITrainingController trainingController, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _experienceTableProvider = experienceTableProvider; + _messageBoxFactory = messageBoxFactory; + _trainingController = trainingController; + + BackgroundImage = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 34); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + + _basicStats = new IXNALabel[6]; + _arrowButtons = new IXNAButton[6]; + _characterStats = new IXNALabel[6]; + _characterInfo = new IXNALabel[3]; + _otherInfo = new IXNALabel[8]; + + var buttonTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); + var outTextureArea = new Rectangle(215, 386, 19, 15); + var overTextureArea = new Rectangle(234, 386, 19, 15); + + for (int i = 0; i < _basicStats.Length; ++i) { - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _experienceTableProvider = experienceTableProvider; - _messageBoxFactory = messageBoxFactory; - _trainingController = trainingController; - - BackgroundImage = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 34); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - - _basicStats = new IXNALabel[6]; - _arrowButtons = new IXNAButton[6]; - _characterStats = new IXNALabel[6]; - _characterInfo = new IXNALabel[3]; - _otherInfo = new IXNALabel[8]; - - var buttonTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); - var outTextureArea = new Rectangle(215, 386, 19, 15); - var overTextureArea = new Rectangle(234, 386, 19, 15); - - for (int i = 0; i < _basicStats.Length; ++i) - { - _basicStats[i] = new XNALabel(Constants.FontSize08pt5) - { - ForeColor = ColorConstants.LightGrayText, - AutoSize = false, - Text = "", - DrawArea = new Rectangle(50, 8 + i * 18, 73, 13) - }; - - _arrowButtons[i] = new XNAButton(buttonTexture, - new Vector2(106, 7 + i * 18), - outTextureArea, - overTextureArea) - { - Visible = false, - FlashSpeed = 500 - }; - } - - for (int i = 0; i < _characterStats.Length; ++i) - { - _characterStats[i] = new XNALabel(Constants.FontSize08pt5) - { - ForeColor = ColorConstants.LightGrayText, - AutoSize = false, - Text = "", - DrawArea = new Rectangle(158, 8 + i * 18, 73, 13) - }; - } - - for (int i = 0; i < _otherInfo.Length; ++i) - { - var drawArea = i < 4 - ? new Rectangle(280, 44 + i % 4 * 18, 60, 13) - : new Rectangle(379, 44 + i % 4 * 18, 94, 13); - - _otherInfo[i] = new XNALabel(Constants.FontSize08pt5) - { - ForeColor = ColorConstants.LightGrayText, - AutoSize = false, - Text = "", - DrawArea = drawArea - }; - } - - _characterInfo[NAME] = new XNALabel(Constants.FontSize08pt5) + _basicStats[i] = new XNALabel(Constants.FontSize08pt5) { ForeColor = ColorConstants.LightGrayText, AutoSize = false, Text = "", - DrawArea = new Rectangle(280, 8, 144, 13) + DrawArea = new Rectangle(50, 8 + i * 18, 73, 13) + }; + + _arrowButtons[i] = new XNAButton(buttonTexture, + new Vector2(106, 7 + i * 18), + outTextureArea, + overTextureArea) + { + Visible = false, + FlashSpeed = 500 }; - _characterInfo[GUILD] = new XNALabel(Constants.FontSize08pt5) + } + + for (int i = 0; i < _characterStats.Length; ++i) + { + _characterStats[i] = new XNALabel(Constants.FontSize08pt5) { ForeColor = ColorConstants.LightGrayText, AutoSize = false, Text = "", - DrawArea = new Rectangle(280, 26, 193, 13) + DrawArea = new Rectangle(158, 8 + i * 18, 73, 13) }; - _characterInfo[LEVEL] = new XNALabel(Constants.FontSize08pt5) + } + + for (int i = 0; i < _otherInfo.Length; ++i) + { + var drawArea = i < 4 + ? new Rectangle(280, 44 + i % 4 * 18, 60, 13) + : new Rectangle(379, 44 + i % 4 * 18, 94, 13); + + _otherInfo[i] = new XNALabel(Constants.FontSize08pt5) { ForeColor = ColorConstants.LightGrayText, AutoSize = false, Text = "", - DrawArea = new Rectangle(453, 8, 20, 13) + DrawArea = drawArea }; } - public override void Initialize() + _characterInfo[NAME] = new XNALabel(Constants.FontSize08pt5) { - foreach (var control in _arrowButtons) - control.OnClick += HandleArrowButtonClick; - - var controls = _basicStats.Concat(_characterStats) - .Concat(_arrowButtons) - .Concat(_characterInfo) - .Concat(_otherInfo); - foreach (var control in controls) - { - control.SetParentControl(this); - control.Initialize(); - } + ForeColor = ColorConstants.LightGrayText, + AutoSize = false, + Text = "", + DrawArea = new Rectangle(280, 8, 144, 13) + }; + _characterInfo[GUILD] = new XNALabel(Constants.FontSize08pt5) + { + ForeColor = ColorConstants.LightGrayText, + AutoSize = false, + Text = "", + DrawArea = new Rectangle(280, 26, 193, 13) + }; + _characterInfo[LEVEL] = new XNALabel(Constants.FontSize08pt5) + { + ForeColor = ColorConstants.LightGrayText, + AutoSize = false, + Text = "", + DrawArea = new Rectangle(453, 8, 20, 13) + }; + } - base.Initialize(); + public override void Initialize() + { + foreach (var control in _arrowButtons) + control.OnClick += HandleArrowButtonClick; + + var controls = _basicStats.Concat(_characterStats) + .Concat(_arrowButtons) + .Concat(_characterInfo) + .Concat(_otherInfo); + foreach (var control in controls) + { + control.SetParentControl(this); + control.Initialize(); } - protected override void OnUpdateControl(GameTime gameTime) + base.Initialize(); + } + + protected override void OnUpdateControl(GameTime gameTime) + { + if (_lastCharacterStats != _characterProvider.MainCharacter.Stats || + _lastCharacterGold != CurrentCharacterGold) { - if (_lastCharacterStats != _characterProvider.MainCharacter.Stats || - _lastCharacterGold != CurrentCharacterGold) + _lastCharacterStats = _characterProvider.MainCharacter.Stats; + _lastCharacterGold = CurrentCharacterGold; + + _basicStats[STR].Text = $"{_lastCharacterStats[CharacterStat.Strength]}"; + _basicStats[INT].Text = $"{_lastCharacterStats[CharacterStat.Intelligence]}"; + _basicStats[WIS].Text = $"{_lastCharacterStats[CharacterStat.Wisdom]}"; + _basicStats[AGI].Text = $"{_lastCharacterStats[CharacterStat.Agility]}"; + _basicStats[CON].Text = $"{_lastCharacterStats[CharacterStat.Constitution]}"; + _basicStats[CHA].Text = $"{_lastCharacterStats[CharacterStat.Charisma]}"; + + _characterStats[HP].Text = $"{_lastCharacterStats[CharacterStat.HP]}"; + _characterStats[TP].Text = $"{_lastCharacterStats[CharacterStat.TP]}"; + _characterStats[DAM].Text = $"{_lastCharacterStats[CharacterStat.MinDam]} - {_lastCharacterStats[CharacterStat.MaxDam]}"; + _characterStats[ACC].Text = $"{_lastCharacterStats[CharacterStat.Accuracy]}"; + _characterStats[EVA].Text = $"{_lastCharacterStats[CharacterStat.Evade]}"; + _characterStats[ARM].Text = $"{_lastCharacterStats[CharacterStat.Armor]}"; + + _otherInfo[WEIGHT].Text = $"{_lastCharacterStats[CharacterStat.Weight]} / {_lastCharacterStats[CharacterStat.MaxWeight]}"; + _otherInfo[STATPTS].Text = $"{_lastCharacterStats[CharacterStat.StatPoints]}"; + _otherInfo[SKILLPTS].Text = $"{_lastCharacterStats[CharacterStat.SkillPoints]}"; + _otherInfo[ELEM].Text = ""; //Elements are not supported by Endless Online :( + _otherInfo[GOLD].Text = $"{CurrentCharacterGold.Amount}"; + _otherInfo[EXP].Text = $"{_lastCharacterStats[CharacterStat.Experience]}"; + _otherInfo[TNL].Text = $"{ExperienceToNextLevel}"; + _otherInfo[KARMA].Text = $"{_lastCharacterStats.GetKarmaString()}"; + + _characterInfo[NAME].Text = $"{_characterProvider.MainCharacter.Name}"; + _characterInfo[GUILD].Text = $"{_characterProvider.MainCharacter.GuildName}"; + _characterInfo[LEVEL].Text = $"{_lastCharacterStats[CharacterStat.Level]}"; + + if (_lastCharacterStats.Stats[CharacterStat.StatPoints] > 0) { - _lastCharacterStats = _characterProvider.MainCharacter.Stats; - _lastCharacterGold = CurrentCharacterGold; - - _basicStats[STR].Text = $"{_lastCharacterStats[CharacterStat.Strength]}"; - _basicStats[INT].Text = $"{_lastCharacterStats[CharacterStat.Intelligence]}"; - _basicStats[WIS].Text = $"{_lastCharacterStats[CharacterStat.Wisdom]}"; - _basicStats[AGI].Text = $"{_lastCharacterStats[CharacterStat.Agility]}"; - _basicStats[CON].Text = $"{_lastCharacterStats[CharacterStat.Constitution]}"; - _basicStats[CHA].Text = $"{_lastCharacterStats[CharacterStat.Charisma]}"; - - _characterStats[HP].Text = $"{_lastCharacterStats[CharacterStat.HP]}"; - _characterStats[TP].Text = $"{_lastCharacterStats[CharacterStat.TP]}"; - _characterStats[DAM].Text = $"{_lastCharacterStats[CharacterStat.MinDam]} - {_lastCharacterStats[CharacterStat.MaxDam]}"; - _characterStats[ACC].Text = $"{_lastCharacterStats[CharacterStat.Accuracy]}"; - _characterStats[EVA].Text = $"{_lastCharacterStats[CharacterStat.Evade]}"; - _characterStats[ARM].Text = $"{_lastCharacterStats[CharacterStat.Armor]}"; - - _otherInfo[WEIGHT].Text = $"{_lastCharacterStats[CharacterStat.Weight]} / {_lastCharacterStats[CharacterStat.MaxWeight]}"; - _otherInfo[STATPTS].Text = $"{_lastCharacterStats[CharacterStat.StatPoints]}"; - _otherInfo[SKILLPTS].Text = $"{_lastCharacterStats[CharacterStat.SkillPoints]}"; - _otherInfo[ELEM].Text = ""; //Elements are not supported by Endless Online :( - _otherInfo[GOLD].Text = $"{CurrentCharacterGold.Amount}"; - _otherInfo[EXP].Text = $"{_lastCharacterStats[CharacterStat.Experience]}"; - _otherInfo[TNL].Text = $"{ExperienceToNextLevel}"; - _otherInfo[KARMA].Text = $"{_lastCharacterStats.GetKarmaString()}"; - - _characterInfo[NAME].Text = $"{_characterProvider.MainCharacter.Name}"; - _characterInfo[GUILD].Text = $"{_characterProvider.MainCharacter.GuildName}"; - _characterInfo[LEVEL].Text = $"{_lastCharacterStats[CharacterStat.Level]}"; - - if (_lastCharacterStats.Stats[CharacterStat.StatPoints] > 0) - { - foreach (var button in _arrowButtons.OfType()) - button.Visible = true; - } - else - { - foreach (var button in _arrowButtons.OfType()) - button.Visible = false; - _confirmedTraining = false; - } + foreach (var button in _arrowButtons.OfType()) + button.Visible = true; + } + else + { + foreach (var button in _arrowButtons.OfType()) + button.Visible = false; + _confirmedTraining = false; } - - base.OnUpdateControl(gameTime); } - private void HandleArrowButtonClick(object sender, EventArgs e) + base.OnUpdateControl(gameTime); + } + + private void HandleArrowButtonClick(object sender, EventArgs e) + { + if (!_confirmedTraining) { - if (!_confirmedTraining) - { - var dialog = _messageBoxFactory.CreateMessageBox("Do you want to train?", - "Character training", - EODialogButtons.OkCancel); + var dialog = _messageBoxFactory.CreateMessageBox("Do you want to train?", + "Character training", + EODialogButtons.OkCancel); - dialog.DialogClosing += (_, e) => - { + dialog.DialogClosing += (_, e) => + { - if (e.Result == XNADialogResult.OK) - _confirmedTraining = true; - }; + if (e.Result == XNADialogResult.OK) + _confirmedTraining = true; + }; - dialog.ShowDialog(); - } - else - { - var index = _arrowButtons.Select((btn, ndx) => new { btn, ndx }) - .Single(x => x.btn == sender).ndx; - var characterStat = CharacterStat.Strength + index; - _trainingController.AddStatPoint(characterStat); - } + dialog.ShowDialog(); + } + else + { + var index = _arrowButtons.Select((btn, ndx) => new { btn, ndx }) + .Single(x => x.btn == sender).ndx; + var characterStat = CharacterStat.Strength + index; + _trainingController.AddStatPoint(characterStat); } + } - private InventoryItem CurrentCharacterGold - => _characterInventoryProvider.ItemInventory.Single(x => x.ItemID == 1); + private InventoryItem CurrentCharacterGold + => _characterInventoryProvider.ItemInventory.Single(x => x.ItemID == 1); - private int ExperienceToNextLevel => - _experienceTableProvider.ExperienceByLevel[ - _characterProvider.MainCharacter.Stats[CharacterStat.Level] + 1 - ] - _lastCharacterStats[CharacterStat.Experience]; - } + private int ExperienceToNextLevel => + _experienceTableProvider.ExperienceByLevel[ + _characterProvider.MainCharacter.Stats[CharacterStat.Level] + 1 + ] - _lastCharacterStats[CharacterStat.Experience]; } \ No newline at end of file diff --git a/EndlessClient/HUD/Party/PartyPanelMember.cs b/EndlessClient/HUD/Party/PartyPanelMember.cs index f37254f22..abf6ba5b1 100644 --- a/EndlessClient/HUD/Party/PartyPanelMember.cs +++ b/EndlessClient/HUD/Party/PartyPanelMember.cs @@ -9,127 +9,126 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Party +namespace EndlessClient.HUD.Party; + +public class PartyPanelMember : XNAControl { - public class PartyPanelMember : XNAControl - { - private readonly IContentProvider _contentProvider; - private readonly Texture2D _chatIconsTexture; + private readonly IContentProvider _contentProvider; + private readonly Texture2D _chatIconsTexture; - private readonly IXNAButton _removeButton; - private readonly IXNALabel _nameLabel, _levelLabel, _hpLabel; + private readonly IXNAButton _removeButton; + private readonly IXNALabel _nameLabel, _levelLabel, _hpLabel; - private ChatIcon _playerIcon; - private Rectangle _iconSource; + private ChatIcon _playerIcon; + private Rectangle _iconSource; - private int _displayIndex; - public int DisplayIndex + private int _displayIndex; + public int DisplayIndex + { + get => _displayIndex; + set { - get => _displayIndex; - set - { - _displayIndex = value; + _displayIndex = value; - DrawArea = new Rectangle(0, 20 + _displayIndex * 13, ImmediateParent?.DrawArea.Width ?? 0, 13); - } + DrawArea = new Rectangle(0, 20 + _displayIndex * 13, ImmediateParent?.DrawArea.Width ?? 0, 13); } + } - private PartyMember _partyMember; - public PartyMember PartyMember + private PartyMember _partyMember; + public PartyMember PartyMember + { + get => _partyMember; + set { - get => _partyMember; - set - { - _partyMember = value; - _nameLabel.Text = _partyMember.Name; - _levelLabel.Text = $"{_partyMember.Level}"; - - _playerIcon = _partyMember.IsLeader ? ChatIcon.Star : ChatIcon.Player; - var (X, Y, Width, Height) = _playerIcon.GetChatIconRectangleBounds().ValueOr((0, 0, 0, 0)); - _iconSource = new Rectangle(X, Y, Width, Height); - } + _partyMember = value; + _nameLabel.Text = _partyMember.Name; + _levelLabel.Text = $"{_partyMember.Level}"; + + _playerIcon = _partyMember.IsLeader ? ChatIcon.Star : ChatIcon.Player; + var (X, Y, Width, Height) = _playerIcon.GetChatIconRectangleBounds().ValueOr((0, 0, 0, 0)); + _iconSource = new Rectangle(X, Y, Width, Height); } + } - public event EventHandler RemoveAction; + public event EventHandler RemoveAction; - public PartyPanelMember(INativeGraphicsManager nativeGraphicsManager, - IContentProvider contentProvider, - bool isRemovable) + public PartyPanelMember(INativeGraphicsManager nativeGraphicsManager, + IContentProvider contentProvider, + bool isRemovable) + { + _contentProvider = contentProvider; + _chatIconsTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); + + var removeTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 43); + var delta = removeTexture.Height / 3; + _removeButton = new XNAButton(removeTexture, + new Vector2(337, 0), + isRemovable + ? new Rectangle(0, 0, removeTexture.Width, delta) + : new Rectangle(0, delta, removeTexture.Width, delta), + isRemovable + ? new Rectangle(0, delta * 2, removeTexture.Width, delta) + : new Rectangle(0, delta, removeTexture.Width, delta)); + + if (isRemovable) + _removeButton.OnClick += (o, e) => RemoveAction?.Invoke(o, e); + _removeButton.SetParentControl(this); + + _nameLabel = new XNALabel(Constants.FontSize08) { - _contentProvider = contentProvider; - _chatIconsTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); - - var removeTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 43); - var delta = removeTexture.Height / 3; - _removeButton = new XNAButton(removeTexture, - new Vector2(337, 0), - isRemovable - ? new Rectangle(0, 0, removeTexture.Width, delta) - : new Rectangle(0, delta, removeTexture.Width, delta), - isRemovable - ? new Rectangle(0, delta * 2, removeTexture.Width, delta) - : new Rectangle(0, delta, removeTexture.Width, delta)); - - if (isRemovable) - _removeButton.OnClick += (o, e) => RemoveAction?.Invoke(o, e); - _removeButton.SetParentControl(this); - - _nameLabel = new XNALabel(Constants.FontSize08) - { - DrawPosition = new Vector2(23, 0), - AutoSize = true, - ForeColor = Color.Black - }; - _nameLabel.SetParentControl(this); - - _levelLabel = new XNALabel(Constants.FontSize08) - { - DrawPosition = new Vector2(138, 0), - AutoSize = true, - ForeColor = Color.Black - }; - _levelLabel.SetParentControl(this); - - _hpLabel = new XNALabel(Constants.FontSize08) - { - DrawPosition = new Vector2(205, 0), - AutoSize = true, - ForeColor = Color.Black, - Text = "HP" - }; - _hpLabel.SetParentControl(this); - } + DrawPosition = new Vector2(23, 0), + AutoSize = true, + ForeColor = Color.Black + }; + _nameLabel.SetParentControl(this); - public override void Initialize() + _levelLabel = new XNALabel(Constants.FontSize08) { - _removeButton.Initialize(); - _nameLabel.Initialize(); - _levelLabel.Initialize(); - _hpLabel.Initialize(); + DrawPosition = new Vector2(138, 0), + AutoSize = true, + ForeColor = Color.Black + }; + _levelLabel.SetParentControl(this); - base.Initialize(); - } - - protected override void OnDrawControl(GameTime gameTime) + _hpLabel = new XNALabel(Constants.FontSize08) { - var iconDrawPosition = DrawPositionWithParentOffset + new Vector2(5, 1); - var healthBarDrawPosition = DrawPositionWithParentOffset + new Vector2(228, 1); + DrawPosition = new Vector2(205, 0), + AutoSize = true, + ForeColor = Color.Black, + Text = "HP" + }; + _hpLabel.SetParentControl(this); + } - var barTexture = _partyMember.PercentHealth > 50 - ? _contentProvider.Textures[ContentProvider.HPGreen] - : _partyMember.PercentHealth > 25 - ? _contentProvider.Textures[ContentProvider.HPYellow] - : _contentProvider.Textures[ContentProvider.HPRed]; + public override void Initialize() + { + _removeButton.Initialize(); + _nameLabel.Initialize(); + _levelLabel.Initialize(); + _hpLabel.Initialize(); - var barSource = new Rectangle(0, 0, (int)Math.Round(barTexture.Width * (_partyMember.PercentHealth / 100.0)), barTexture.Height); + base.Initialize(); + } - _spriteBatch.Begin(); - _spriteBatch.Draw(_chatIconsTexture, iconDrawPosition, _iconSource, Color.White); - _spriteBatch.Draw(_contentProvider.Textures[ContentProvider.HPOutline], healthBarDrawPosition, Color.White); - _spriteBatch.Draw(barTexture, healthBarDrawPosition, barSource, Color.White); - _spriteBatch.End(); + protected override void OnDrawControl(GameTime gameTime) + { + var iconDrawPosition = DrawPositionWithParentOffset + new Vector2(5, 1); + var healthBarDrawPosition = DrawPositionWithParentOffset + new Vector2(228, 1); - base.OnDrawControl(gameTime); - } + var barTexture = _partyMember.PercentHealth > 50 + ? _contentProvider.Textures[ContentProvider.HPGreen] + : _partyMember.PercentHealth > 25 + ? _contentProvider.Textures[ContentProvider.HPYellow] + : _contentProvider.Textures[ContentProvider.HPRed]; + + var barSource = new Rectangle(0, 0, (int)Math.Round(barTexture.Width * (_partyMember.PercentHealth / 100.0)), barTexture.Height); + + _spriteBatch.Begin(); + _spriteBatch.Draw(_chatIconsTexture, iconDrawPosition, _iconSource, Color.White); + _spriteBatch.Draw(_contentProvider.Textures[ContentProvider.HPOutline], healthBarDrawPosition, Color.White); + _spriteBatch.Draw(barTexture, healthBarDrawPosition, barSource, Color.White); + _spriteBatch.End(); + + base.OnDrawControl(gameTime); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Spells/SpellPanelItem.cs b/EndlessClient/HUD/Spells/SpellPanelItem.cs index ad936f914..d7c2b39b1 100644 --- a/EndlessClient/HUD/Spells/SpellPanelItem.cs +++ b/EndlessClient/HUD/Spells/SpellPanelItem.cs @@ -11,189 +11,188 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Spells +namespace EndlessClient.HUD.Spells; + +public class SpellPanelItem : DraggablePanelItem { - public class SpellPanelItem : DraggablePanelItem - { - private const int ICON_AREA_WIDTH = 42, ICON_AREA_HEIGHT = 36; + private const int ICON_AREA_WIDTH = 42, ICON_AREA_HEIGHT = 36; - private readonly ISfxPlayer _sfxPlayer; + private readonly ISfxPlayer _sfxPlayer; - private readonly Texture2D _spellGraphic; - private Rectangle _spellGraphicSourceRect; + private readonly Texture2D _spellGraphic; + private Rectangle _spellGraphicSourceRect; - private readonly Texture2D _whitePixel; + private readonly Texture2D _whitePixel; - public int Slot { get; set; } + public int Slot { get; set; } - private int _displaySlot; - public int DisplaySlot + private int _displaySlot; + public int DisplaySlot + { + get => _displaySlot; + set { - get => _displaySlot; - set - { - _displaySlot = value; - DrawPosition = GetDisplayPosition(_displaySlot); - } + _displaySlot = value; + DrawPosition = GetDisplayPosition(_displaySlot); } + } - public InventorySpell InventorySpell { get; set; } + public InventorySpell InventorySpell { get; set; } - public override Rectangle EventArea => IsDragging ? DrawArea : DrawAreaWithParentOffset; + public override Rectangle EventArea => IsDragging ? DrawArea : DrawAreaWithParentOffset; - // uses absolute coordinates - protected override Rectangle GridArea => new Rectangle( - _parentContainer.DrawPositionWithParentOffset.ToPoint() + new Point(98, 6), - new Point(363, 102)); + // uses absolute coordinates + protected override Rectangle GridArea => new Rectangle( + _parentContainer.DrawPositionWithParentOffset.ToPoint() + new Point(98, 6), + new Point(363, 102)); - public event EventHandler Click; + public event EventHandler Click; - public SpellPanelItem(ActiveSpellsPanel spellPanel, - ISfxPlayer sfxPlayer, - int slot, - InventorySpell spell, - ESFRecord data) - : base(spellPanel) - { - _sfxPlayer = sfxPlayer; + public SpellPanelItem(ActiveSpellsPanel spellPanel, + ISfxPlayer sfxPlayer, + int slot, + InventorySpell spell, + ESFRecord data) + : base(spellPanel) + { + _sfxPlayer = sfxPlayer; - Slot = DisplaySlot = slot; - InventorySpell = spell; - Data = data; + Slot = DisplaySlot = slot; + InventorySpell = spell; + Data = data; - _spellGraphic = spellPanel.NativeGraphicsManager.TextureFromResource(GFXTypes.SpellIcons, Data.Icon); - _spellGraphicSourceRect = new Rectangle(0, 0, _spellGraphic.Width / 2, _spellGraphic.Height); + _spellGraphic = spellPanel.NativeGraphicsManager.TextureFromResource(GFXTypes.SpellIcons, Data.Icon); + _spellGraphicSourceRect = new Rectangle(0, 0, _spellGraphic.Width / 2, _spellGraphic.Height); - _whitePixel = new Texture2D(Game.GraphicsDevice, 1, 1); - _whitePixel.SetData(new[] { Color.White }); + _whitePixel = new Texture2D(Game.GraphicsDevice, 1, 1); + _whitePixel.SetData(new[] { Color.White }); - SetSize(ICON_AREA_WIDTH, ICON_AREA_HEIGHT); - } + SetSize(ICON_AREA_WIDTH, ICON_AREA_HEIGHT); + } - public int GetCurrentSlotBasedOnPosition(int scrollOffset) - { - if (!IsDragging) - return Slot; + public int GetCurrentSlotBasedOnPosition(int scrollOffset) + { + if (!IsDragging) + return Slot; - // old offset X needs to be adjusted since it assumes parent coordinates are the start of the slot grid - // this works for inventory without adjustment since the grid goes all the way to the parent panel coordinate - // however, spell panel has 2 slots worth of padding for the selected slot / level up controls - var adjustedOffsetX = OldOffset.X + (ICON_AREA_WIDTH * 2); + // old offset X needs to be adjusted since it assumes parent coordinates are the start of the slot grid + // this works for inventory without adjustment since the grid goes all the way to the parent panel coordinate + // however, spell panel has 2 slots worth of padding for the selected slot / level up controls + var adjustedOffsetX = OldOffset.X + (ICON_AREA_WIDTH * 2); - return scrollOffset * ActiveSpellsPanel.SpellRowLength + - (int)((DrawPosition.X - adjustedOffsetX) / ICON_AREA_WIDTH) + - ActiveSpellsPanel.SpellRowLength * (int)((DrawPosition.Y - OldOffset.Y) / ICON_AREA_HEIGHT); - } + return scrollOffset * ActiveSpellsPanel.SpellRowLength + + (int)((DrawPosition.X - adjustedOffsetX) / ICON_AREA_WIDTH) + + ActiveSpellsPanel.SpellRowLength * (int)((DrawPosition.Y - OldOffset.Y) / ICON_AREA_HEIGHT); + } - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); - DrawLevelAndHighlight(); - DrawSpellIcon(); + DrawLevelAndHighlight(); + DrawSpellIcon(); - _spriteBatch.End(); + _spriteBatch.End(); - base.OnDrawControl(gameTime); - } + base.OnDrawControl(gameTime); + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (_parentContainer.NoItemsDragging()) - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (_parentContainer.NoItemsDragging()) + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - Click?.Invoke(control, eventArgs); - return base.HandleClick(control, eventArgs); - } + Click?.Invoke(control, eventArgs); + return base.HandleClick(control, eventArgs); + } - protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) - { - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) + { + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - return base.HandleDragStart(control, eventArgs); - } + return base.HandleDragStart(control, eventArgs); + } - protected override void OnDraggingFinished(DragCompletedEventArgs args) - { - base.OnDraggingFinished(args); + protected override void OnDraggingFinished(DragCompletedEventArgs args) + { + base.OnDraggingFinished(args); - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - DrawPosition = GetDisplayPosition(DisplaySlot); - } + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + DrawPosition = GetDisplayPosition(DisplaySlot); + } - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - _whitePixel.Dispose(); - } - - base.Dispose(disposing); + _whitePixel.Dispose(); } - private void DrawLevelAndHighlight() - { - if (!IsDragging) - { - var width = (int)(InventorySpell.Level / 100.0 * 36); - var levelDestinationRectangle = new Rectangle(DrawAreaWithParentOffset.X + 3, DrawAreaWithParentOffset.Y + 40, width, 6); - _spriteBatch.Draw(_whitePixel, levelDestinationRectangle, Color.FromNonPremultiplied(0xc9, 0xb8, 0x9b, 0xff)); - } + base.Dispose(disposing); + } - if (MouseOver) - { - if (!IsDragging) - { - _spriteBatch.Draw(_whitePixel, DrawAreaWithParentOffset, Color.FromNonPremultiplied(200, 200, 200, 60)); - } - else - { - var highlightPosition = GetDisplayPosition(DisplaySlot); - var highlightRectangle = new Rectangle((_parentContainer.DrawPositionWithParentOffset + highlightPosition).ToPoint(), DrawArea.Size); - - if (highlightRectangle.Contains(Mouse.GetState().Position)) - _spriteBatch.Draw(_whitePixel, highlightRectangle, Color.FromNonPremultiplied(200, 200, 200, 60)); - } - } + private void DrawLevelAndHighlight() + { + if (!IsDragging) + { + var width = (int)(InventorySpell.Level / 100.0 * 36); + var levelDestinationRectangle = new Rectangle(DrawAreaWithParentOffset.X + 3, DrawAreaWithParentOffset.Y + 40, width, 6); + _spriteBatch.Draw(_whitePixel, levelDestinationRectangle, Color.FromNonPremultiplied(0xc9, 0xb8, 0x9b, 0xff)); } - private void DrawSpellIcon() + if (MouseOver) { - var halfWidth = _spellGraphic.Width / 2; - _spellGraphicSourceRect = new Rectangle(MouseOver ? halfWidth : 0, 0, halfWidth, _spellGraphic.Height); - - Rectangle targetDrawArea; if (!IsDragging) { - targetDrawArea = new Rectangle( - DrawAreaWithParentOffset.X + (DrawAreaWithParentOffset.Width - _spellGraphicSourceRect.Width) / 2, - DrawAreaWithParentOffset.Y + (DrawAreaWithParentOffset.Height - _spellGraphicSourceRect.Height) / 2, - _spellGraphicSourceRect.Width, - _spellGraphicSourceRect.Height); + _spriteBatch.Draw(_whitePixel, DrawAreaWithParentOffset, Color.FromNonPremultiplied(200, 200, 200, 60)); } else { - targetDrawArea = new Rectangle( - Mouse.GetState().X - _spellGraphicSourceRect.Width / 2, - Mouse.GetState().Y - _spellGraphicSourceRect.Height / 2, - _spellGraphicSourceRect.Width, - _spellGraphicSourceRect.Height - ); - } + var highlightPosition = GetDisplayPosition(DisplaySlot); + var highlightRectangle = new Rectangle((_parentContainer.DrawPositionWithParentOffset + highlightPosition).ToPoint(), DrawArea.Size); - _spriteBatch.Draw(_spellGraphic, - targetDrawArea, - _spellGraphicSourceRect, - Color.FromNonPremultiplied(255, 255, 255, IsDragging ? 127 : 255)); + if (highlightRectangle.Contains(Mouse.GetState().Position)) + _spriteBatch.Draw(_whitePixel, highlightRectangle, Color.FromNonPremultiplied(200, 200, 200, 60)); + } } + } + + private void DrawSpellIcon() + { + var halfWidth = _spellGraphic.Width / 2; + _spellGraphicSourceRect = new Rectangle(MouseOver ? halfWidth : 0, 0, halfWidth, _spellGraphic.Height); - private static Vector2 GetDisplayPosition(int slot) + Rectangle targetDrawArea; + if (!IsDragging) + { + targetDrawArea = new Rectangle( + DrawAreaWithParentOffset.X + (DrawAreaWithParentOffset.Width - _spellGraphicSourceRect.Width) / 2, + DrawAreaWithParentOffset.Y + (DrawAreaWithParentOffset.Height - _spellGraphicSourceRect.Height) / 2, + _spellGraphicSourceRect.Width, + _spellGraphicSourceRect.Height); + } + else { - //start pos: 101, 97 - //xdelta: 45; ydelta: 52 - var row = slot / ActiveSpellsPanel.SpellRowLength; - var col = slot % ActiveSpellsPanel.SpellRowLength; - return new Vector2(101 + col * 45, 9 + row * 52); + targetDrawArea = new Rectangle( + Mouse.GetState().X - _spellGraphicSourceRect.Width / 2, + Mouse.GetState().Y - _spellGraphicSourceRect.Height / 2, + _spellGraphicSourceRect.Width, + _spellGraphicSourceRect.Height + ); } + + _spriteBatch.Draw(_spellGraphic, + targetDrawArea, + _spellGraphicSourceRect, + Color.FromNonPremultiplied(255, 255, 255, IsDragging ? 127 : 255)); + } + + private static Vector2 GetDisplayPosition(int slot) + { + //start pos: 101, 97 + //xdelta: 45; ydelta: 52 + var row = slot / ActiveSpellsPanel.SpellRowLength; + var col = slot % ActiveSpellsPanel.SpellRowLength; + return new Vector2(101 + col * 45, 9 + row * 52); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Spells/SpellSelectActions.cs b/EndlessClient/HUD/Spells/SpellSelectActions.cs index 58a3035bf..25e143f71 100644 --- a/EndlessClient/HUD/Spells/SpellSelectActions.cs +++ b/EndlessClient/HUD/Spells/SpellSelectActions.cs @@ -5,57 +5,56 @@ using Optional; using System.Linq; -namespace EndlessClient.HUD.Spells +namespace EndlessClient.HUD.Spells; + +[AutoMappedType] +public class SpellSelectActions : ISpellSelectActions { - [AutoMappedType] - public class SpellSelectActions : ISpellSelectActions + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly IPartyDataProvider _partyDataProvider; + private readonly IESFFileProvider _esfFileProvider; + + public SpellSelectActions(IStatusLabelSetter statusLabelSetter, + ISpellSlotDataRepository spellSlotDataRepository, + IPartyDataProvider partyDataProvider, + IESFFileProvider esfFileProvider) { - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly IPartyDataProvider _partyDataProvider; - private readonly IESFFileProvider _esfFileProvider; + _statusLabelSetter = statusLabelSetter; + _spellSlotDataRepository = spellSlotDataRepository; + _partyDataProvider = partyDataProvider; + _esfFileProvider = esfFileProvider; + } - public SpellSelectActions(IStatusLabelSetter statusLabelSetter, - ISpellSlotDataRepository spellSlotDataRepository, - IPartyDataProvider partyDataProvider, - IESFFileProvider esfFileProvider) - { - _statusLabelSetter = statusLabelSetter; - _spellSlotDataRepository = spellSlotDataRepository; - _partyDataProvider = partyDataProvider; - _esfFileProvider = esfFileProvider; - } + public void SelectSpellBySlot(int slot) + { + _spellSlotDataRepository.SpellSlots[slot].Match( + some: si => + { + var spellData = _esfFileProvider.ESFFile[si.ID]; - public void SelectSpellBySlot(int slot) - { - _spellSlotDataRepository.SpellSlots[slot].Match( - some: si => + if (spellData.Target == EOLib.IO.SpellTarget.Group && !_partyDataProvider.Members.Any()) { - var spellData = _esfFileProvider.ESFFile[si.ID]; - - if (spellData.Target == EOLib.IO.SpellTarget.Group && !_partyDataProvider.Members.Any()) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.SPELL_ONLY_WORKS_ON_GROUP); - } - else - { - _statusLabelSetter.SetStatusLabel(EOResourceID.SKILLMASTER_WORD_SPELL, $"{spellData.Name} ", EOResourceID.SPELL_WAS_SELECTED); - _spellSlotDataRepository.SelectedSpellSlot = Option.Some(slot); - _spellSlotDataRepository.SpellIsPrepared = true; - } - }, - none: () => + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.SPELL_ONLY_WORKS_ON_GROUP); + } + else { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.SPELL_NOTHING_WAS_SELECTED); + _statusLabelSetter.SetStatusLabel(EOResourceID.SKILLMASTER_WORD_SPELL, $"{spellData.Name} ", EOResourceID.SPELL_WAS_SELECTED); + _spellSlotDataRepository.SelectedSpellSlot = Option.Some(slot); + _spellSlotDataRepository.SpellIsPrepared = true; + } + }, + none: () => + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.SPELL_NOTHING_WAS_SELECTED); - _spellSlotDataRepository.SelectedSpellSlot = Option.None(); - _spellSlotDataRepository.SpellIsPrepared = false; - }); - } + _spellSlotDataRepository.SelectedSpellSlot = Option.None(); + _spellSlotDataRepository.SpellIsPrepared = false; + }); } +} - public interface ISpellSelectActions - { - void SelectSpellBySlot(int slot); - } +public interface ISpellSelectActions +{ + void SelectSpellBySlot(int slot); } \ No newline at end of file diff --git a/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs b/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs index e6bae1c2e..0243a224d 100644 --- a/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs +++ b/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs @@ -4,63 +4,62 @@ using Optional; using System.Collections.Generic; -namespace EndlessClient.HUD.Spells +namespace EndlessClient.HUD.Spells; + +public interface ISpellSlotDataRepository { - public interface ISpellSlotDataRepository - { - /// - /// Slot for the selected spell displayed in the UI (or none if nothing is selected). A selected spell is not necessarily prepared for cast via hotkey selection. - /// - Option SelectedSpellSlot { get; set; } + /// + /// Slot for the selected spell displayed in the UI (or none if nothing is selected). A selected spell is not necessarily prepared for cast via hotkey selection. + /// + Option SelectedSpellSlot { get; set; } - /// - /// Spell info for the selected spell (based on SelectedSpellSlot value) - /// - Option SelectedSpellInfo { get; } + /// + /// Spell info for the selected spell (based on SelectedSpellSlot value) + /// + Option SelectedSpellInfo { get; } - /// - /// True if the selected spell slot has been prepared by using a hotkey. - /// - bool SpellIsPrepared { get; set; } + /// + /// True if the selected spell slot has been prepared by using a hotkey. + /// + bool SpellIsPrepared { get; set; } - /// - /// Array of inventory spells by their slot number. - /// - Option[] SpellSlots { get; set; } - } + /// + /// Array of inventory spells by their slot number. + /// + Option[] SpellSlots { get; set; } +} - public interface ISpellSlotDataProvider - { - Option SelectedSpellSlot { get; } +public interface ISpellSlotDataProvider +{ + Option SelectedSpellSlot { get; } - Option SelectedSpellInfo { get; } + Option SelectedSpellInfo { get; } - bool SpellIsPrepared { get; } + bool SpellIsPrepared { get; } - IReadOnlyList> SpellSlots { get; } - } + IReadOnlyList> SpellSlots { get; } +} - [AutoMappedType(IsSingleton = true)] - public class SpellSlotDataRepository : ISpellSlotDataRepository, ISpellSlotDataProvider - { - public Option SelectedSpellSlot { get; set; } +[AutoMappedType(IsSingleton = true)] +public class SpellSlotDataRepository : ISpellSlotDataRepository, ISpellSlotDataProvider +{ + public Option SelectedSpellSlot { get; set; } - public Option SelectedSpellInfo => - SelectedSpellSlot.Match( - x => SpellSlots[x].Match( - y => Option.Some(y), - () => Option.None()), - () => Option.None()); + public Option SelectedSpellInfo => + SelectedSpellSlot.Match( + x => SpellSlots[x].Match( + y => Option.Some(y), + () => Option.None()), + () => Option.None()); - public bool SpellIsPrepared { get; set; } + public bool SpellIsPrepared { get; set; } - public Option[] SpellSlots { get; set; } + public Option[] SpellSlots { get; set; } - IReadOnlyList> ISpellSlotDataProvider.SpellSlots => SpellSlots; + IReadOnlyList> ISpellSlotDataProvider.SpellSlots => SpellSlots; - public SpellSlotDataRepository() - { - SpellSlots = new Option[ActiveSpellsPanel.SpellRows * ActiveSpellsPanel.SpellRowLength]; - } + public SpellSlotDataRepository() + { + SpellSlots = new Option[ActiveSpellsPanel.SpellRows * ActiveSpellsPanel.SpellRowLength]; } } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/HPStatusBar.cs b/EndlessClient/HUD/StatusBars/HPStatusBar.cs index 03150e25c..335c3171e 100644 --- a/EndlessClient/HUD/StatusBars/HPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/HPStatusBar.cs @@ -4,36 +4,35 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.HUD.StatusBars +namespace EndlessClient.HUD.StatusBars; + +public class HPStatusBar : StatusBarBase { - public class HPStatusBar : StatusBarBase - { - protected override int StatusBarIndex => -2; + protected override int StatusBarIndex => -2; - public HPStatusBar(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider) - : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) - { - DrawArea = new Rectangle(100, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); - ChangeStatusBarPosition(); - } + public HPStatusBar(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider) + : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + { + DrawArea = new Rectangle(100, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); + ChangeStatusBarPosition(); + } - protected override void UpdateLabelText() - { - _label.Text = $"{Stats[CharacterStat.HP]}/{Stats[CharacterStat.MaxHP]}"; - } + protected override void UpdateLabelText() + { + _label.Text = $"{Stats[CharacterStat.HP]}/{Stats[CharacterStat.MaxHP]}"; + } - protected override void DrawStatusBar() - { - //todo: figure out these magic numbers - var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.HP] / (double)Stats[CharacterStat.MaxHP] * 79); - var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); + protected override void DrawStatusBar() + { + //todo: figure out these magic numbers + var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.HP] / (double)Stats[CharacterStat.MaxHP] * 79); + var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); - _spriteBatch.Begin(); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); - _spriteBatch.End(); - } + _spriteBatch.Begin(); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); + _spriteBatch.End(); } } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/SPStatusBar.cs b/EndlessClient/HUD/StatusBars/SPStatusBar.cs index cf2e2916a..95d281f19 100644 --- a/EndlessClient/HUD/StatusBars/SPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/SPStatusBar.cs @@ -4,37 +4,36 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.HUD.StatusBars +namespace EndlessClient.HUD.StatusBars; + +public class SPStatusBar : StatusBarBase { - public class SPStatusBar : StatusBarBase - { - protected override int StatusBarIndex => 0; + protected override int StatusBarIndex => 0; - public SPStatusBar(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider) - : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) - { - DrawArea = new Rectangle(320, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); - _sourceRectangleArea.Offset(_sourceRectangleArea.Width * 2, 0); - ChangeStatusBarPosition(); - } + public SPStatusBar(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider) + : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + { + DrawArea = new Rectangle(320, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); + _sourceRectangleArea.Offset(_sourceRectangleArea.Width * 2, 0); + ChangeStatusBarPosition(); + } - protected override void UpdateLabelText() - { - _label.Text = $"{Stats[CharacterStat.SP]}/{Stats[CharacterStat.MaxSP]}"; - } + protected override void UpdateLabelText() + { + _label.Text = $"{Stats[CharacterStat.SP]}/{Stats[CharacterStat.MaxSP]}"; + } - protected override void DrawStatusBar() - { - //todo: figure out these magic numbers - var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.SP] / (double)Stats[CharacterStat.MaxSP] * 79); - var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); + protected override void DrawStatusBar() + { + //todo: figure out these magic numbers + var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.SP] / (double)Stats[CharacterStat.MaxSP] * 79); + var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); - _spriteBatch.Begin(); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); - _spriteBatch.End(); - } + _spriteBatch.Begin(); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); + _spriteBatch.End(); } } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/StatusBarBase.cs b/EndlessClient/HUD/StatusBars/StatusBarBase.cs index aec449222..6f731f44b 100644 --- a/EndlessClient/HUD/StatusBars/StatusBarBase.cs +++ b/EndlessClient/HUD/StatusBars/StatusBarBase.cs @@ -9,116 +9,115 @@ using System; using XNAControls; -namespace EndlessClient.HUD.StatusBars +namespace EndlessClient.HUD.StatusBars; + +public abstract class StatusBarBase : XNAControl { - public abstract class StatusBarBase : XNAControl - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICharacterProvider _characterProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICharacterProvider _characterProvider; - protected readonly XNALabel _label; - protected readonly Texture2D _texture; + protected readonly XNALabel _label; + protected readonly Texture2D _texture; - protected CharacterStats Stats => _characterProvider.MainCharacter.Stats; - protected Rectangle _sourceRectangleArea; + protected CharacterStats Stats => _characterProvider.MainCharacter.Stats; + protected Rectangle _sourceRectangleArea; - protected abstract int StatusBarIndex { get; } + protected abstract int StatusBarIndex { get; } - private Option _labelShowTime; + private Option _labelShowTime; - public event Action StatusBarClicked; - public event Action StatusBarClosed; + public event Action StatusBarClicked; + public event Action StatusBarClosed; - protected StatusBarBase(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _clientWindowSizeProvider = clientWindowSizeProvider; - _characterProvider = characterProvider; + protected StatusBarBase(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _clientWindowSizeProvider = clientWindowSizeProvider; + _characterProvider = characterProvider; - _texture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); + _texture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); - _label = new XNALabel(Constants.FontSize08) - { - AutoSize = false, - BackColor = Color.Transparent, - DrawPosition = new Vector2(6, 15), - ForeColor = ColorConstants.LightGrayText, - Visible = false - }; - _label.SetParentControl(this); - - _sourceRectangleArea = new Rectangle(0, 0, 110, 14); - - if (_clientWindowSizeProvider.Resizable) - _clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => ChangeStatusBarPosition(); - } + _label = new XNALabel(Constants.FontSize08) + { + AutoSize = false, + BackColor = Color.Transparent, + DrawPosition = new Vector2(6, 15), + ForeColor = ColorConstants.LightGrayText, + Visible = false + }; + _label.SetParentControl(this); + + _sourceRectangleArea = new Rectangle(0, 0, 110, 14); + + if (_clientWindowSizeProvider.Resizable) + _clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => ChangeStatusBarPosition(); + } - protected abstract void UpdateLabelText(); - protected abstract void DrawStatusBar(); + protected abstract void UpdateLabelText(); + protected abstract void DrawStatusBar(); - public override void Initialize() - { - _label.Initialize(); - base.Initialize(); - } + public override void Initialize() + { + _label.Initialize(); + base.Initialize(); + } - protected override void OnUpdateControl(GameTime gameTime) + protected override void OnUpdateControl(GameTime gameTime) + { + _labelShowTime.MatchSome(x => { - _labelShowTime.MatchSome(x => + UpdateLabelText(); + + if ((DateTime.Now - x).TotalSeconds >= 4) { - UpdateLabelText(); + _label.Visible = false; + _labelShowTime = Option.None(); - if ((DateTime.Now - x).TotalSeconds >= 4) - { - _label.Visible = false; - _labelShowTime = Option.None(); + StatusBarClosed?.Invoke(); + } + }); - StatusBarClosed?.Invoke(); - } - }); + base.OnUpdateControl(gameTime); + } - base.OnUpdateControl(gameTime); - } + protected override void OnDrawControl(GameTime gameTime) + { + DrawStatusBar(); - protected override void OnDrawControl(GameTime gameTime) + if (_labelShowTime.HasValue) { - DrawStatusBar(); - - if (_labelShowTime.HasValue) - { - var dest = new Vector2(DrawAreaWithParentOffset.X, - DrawAreaWithParentOffset.Y + _sourceRectangleArea.Height - 3); + var dest = new Vector2(DrawAreaWithParentOffset.X, + DrawAreaWithParentOffset.Y + _sourceRectangleArea.Height - 3); - _spriteBatch.Begin(); - _spriteBatch.Draw(_texture, dest, DropDownSourceRectangle, Color.White); - _spriteBatch.End(); - } - - base.OnDrawControl(gameTime); + _spriteBatch.Begin(); + _spriteBatch.Draw(_texture, dest, DropDownSourceRectangle, Color.White); + _spriteBatch.End(); } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - _label.Visible = !_label.Visible; - _labelShowTime = _label.SomeWhen(x => x.Visible).Map(_ => DateTime.Now); + base.OnDrawControl(gameTime); + } - StatusBarClicked?.Invoke(); + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + _label.Visible = !_label.Visible; + _labelShowTime = _label.SomeWhen(x => x.Visible).Map(_ => DateTime.Now); - return true; - } + StatusBarClicked?.Invoke(); - protected void ChangeStatusBarPosition() - { - var xCoord = (_clientWindowSizeProvider.Width / 2) + StatusBarIndex * DrawArea.Width; - DrawPosition = new Vector2(xCoord, 0); - } + return true; + } - /// - /// Source rectangle for the drop-down box in the texture sprite sheet (shown when control is clicked) - /// - private static Rectangle DropDownSourceRectangle => new Rectangle(220, 30, 110, 21); + protected void ChangeStatusBarPosition() + { + var xCoord = (_clientWindowSizeProvider.Width / 2) + StatusBarIndex * DrawArea.Width; + DrawPosition = new Vector2(xCoord, 0); } + + /// + /// Source rectangle for the drop-down box in the texture sprite sheet (shown when control is clicked) + /// + private static Rectangle DropDownSourceRectangle => new Rectangle(220, 30, 110, 21); } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/TNLStatusBar.cs b/EndlessClient/HUD/StatusBars/TNLStatusBar.cs index 9919e57a8..31382c97f 100644 --- a/EndlessClient/HUD/StatusBars/TNLStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/TNLStatusBar.cs @@ -6,49 +6,48 @@ using System; using System.Collections.Generic; -namespace EndlessClient.HUD.StatusBars +namespace EndlessClient.HUD.StatusBars; + +public class TNLStatusBar : StatusBarBase { - public class TNLStatusBar : StatusBarBase + private readonly IExperienceTableProvider _experienceTableProvider; + + protected override int StatusBarIndex => 1; + + public TNLStatusBar(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider, + IExperienceTableProvider experienceTableProvider) + : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + { + _experienceTableProvider = experienceTableProvider; + DrawArea = new Rectangle(430, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); + + _sourceRectangleArea = new Rectangle(_sourceRectangleArea.Width * 3 - 1, + 0, + _sourceRectangleArea.Width + 1, + _sourceRectangleArea.Height); + ChangeStatusBarPosition(); + } + + protected override void UpdateLabelText() { - private readonly IExperienceTableProvider _experienceTableProvider; - - protected override int StatusBarIndex => 1; - - public TNLStatusBar(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider, - IExperienceTableProvider experienceTableProvider) - : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) - { - _experienceTableProvider = experienceTableProvider; - DrawArea = new Rectangle(430, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); - - _sourceRectangleArea = new Rectangle(_sourceRectangleArea.Width * 3 - 1, - 0, - _sourceRectangleArea.Width + 1, - _sourceRectangleArea.Height); - ChangeStatusBarPosition(); - } - - protected override void UpdateLabelText() - { - _label.Text = $"{ExpTable[Stats[CharacterStat.Level] + 1] - Stats[CharacterStat.Experience]}"; - } - - protected override void DrawStatusBar() - { - //todo: figure out these magic numbers - var thisLevelExp = ExpTable[Stats[CharacterStat.Level]]; - var nextLevelExp = ExpTable[Stats[CharacterStat.Level] + 1]; - var srcWidth = 25 + (int)Math.Round((Stats[CharacterStat.Experience] - thisLevelExp) / (double)(nextLevelExp - thisLevelExp) * 79); - var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); - - _spriteBatch.Begin(); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); - _spriteBatch.End(); - } - - private IReadOnlyList ExpTable => _experienceTableProvider.ExperienceByLevel; + _label.Text = $"{ExpTable[Stats[CharacterStat.Level] + 1] - Stats[CharacterStat.Experience]}"; } + + protected override void DrawStatusBar() + { + //todo: figure out these magic numbers + var thisLevelExp = ExpTable[Stats[CharacterStat.Level]]; + var nextLevelExp = ExpTable[Stats[CharacterStat.Level] + 1]; + var srcWidth = 25 + (int)Math.Round((Stats[CharacterStat.Experience] - thisLevelExp) / (double)(nextLevelExp - thisLevelExp) * 79); + var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); + + _spriteBatch.Begin(); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); + _spriteBatch.End(); + } + + private IReadOnlyList ExpTable => _experienceTableProvider.ExperienceByLevel; } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/TPStatusBar.cs b/EndlessClient/HUD/StatusBars/TPStatusBar.cs index 0d9c2705b..4803fb420 100644 --- a/EndlessClient/HUD/StatusBars/TPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/TPStatusBar.cs @@ -5,37 +5,36 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.HUD.StatusBars +namespace EndlessClient.HUD.StatusBars; + +public class TPStatusBar : StatusBarBase { - public class TPStatusBar : StatusBarBase - { - protected override int StatusBarIndex => -1; + protected override int StatusBarIndex => -1; - public TPStatusBar(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider) - : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) - { - DrawArea = new Rectangle(210, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); - _sourceRectangleArea.Offset(_sourceRectangleArea.Width, 0); - ChangeStatusBarPosition(); - } + public TPStatusBar(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider) + : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + { + DrawArea = new Rectangle(210, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); + _sourceRectangleArea.Offset(_sourceRectangleArea.Width, 0); + ChangeStatusBarPosition(); + } - protected override void UpdateLabelText() - { - _label.Text = $"{Stats[CharacterStat.TP]}/{Stats[CharacterStat.MaxTP]}"; - } + protected override void UpdateLabelText() + { + _label.Text = $"{Stats[CharacterStat.TP]}/{Stats[CharacterStat.MaxTP]}"; + } - protected override void DrawStatusBar() - { - //todo: figure out these magic numbers - var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.TP] / (double)Stats[CharacterStat.MaxTP] * 79); - var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); + protected override void DrawStatusBar() + { + //todo: figure out these magic numbers + var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.TP] / (double)Stats[CharacterStat.MaxTP] * 79); + var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); - _spriteBatch.Begin(); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); - _spriteBatch.End(); - } + _spriteBatch.Begin(); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); + _spriteBatch.End(); } } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusLabelSetter.cs b/EndlessClient/HUD/StatusLabelSetter.cs index 547124824..22518f043 100644 --- a/EndlessClient/HUD/StatusLabelSetter.cs +++ b/EndlessClient/HUD/StatusLabelSetter.cs @@ -3,85 +3,84 @@ using EOLib.Localization; using System; -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +[AutoMappedType] +public class StatusLabelSetter : IStatusLabelSetter { - [AutoMappedType] - public class StatusLabelSetter : IStatusLabelSetter + private readonly IStatusLabelTextRepository _statusLabelTextRepository; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + + public StatusLabelSetter(IStatusLabelTextRepository statusLabelTextRepository, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder) { - private readonly IStatusLabelTextRepository _statusLabelTextRepository; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; + _statusLabelTextRepository = statusLabelTextRepository; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + } - public StatusLabelSetter(IStatusLabelTextRepository statusLabelTextRepository, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder) - { - _statusLabelTextRepository = statusLabelTextRepository; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - } + public void SetStatusLabel(EOResourceID type, EOResourceID text, string appended = "", bool showChatError = false) + { + CheckStatusLabelType(type); - public void SetStatusLabel(EOResourceID type, EOResourceID text, string appended = "", bool showChatError = false) - { - CheckStatusLabelType(type); + SetStatusLabelText(_localizedStringFinder.GetString(type), + _localizedStringFinder.GetString(text), + appended, + showChatError); + } - SetStatusLabelText(_localizedStringFinder.GetString(type), - _localizedStringFinder.GetString(text), - appended, - showChatError); - } + public void SetStatusLabel(EOResourceID type, string prepended, EOResourceID text, bool showChatError = false) + { + CheckStatusLabelType(type); + SetStatusLabelText(_localizedStringFinder.GetString(type), + prepended, + _localizedStringFinder.GetString(text), + showChatError); + } - public void SetStatusLabel(EOResourceID type, string prepended, EOResourceID text, bool showChatError = false) - { - CheckStatusLabelType(type); - SetStatusLabelText(_localizedStringFinder.GetString(type), - prepended, - _localizedStringFinder.GetString(text), - showChatError); - } + public void SetStatusLabel(EOResourceID type, string text) + { + CheckStatusLabelType(type); + SetStatusLabelText(_localizedStringFinder.GetString(type), text); + } - public void SetStatusLabel(EOResourceID type, string text) - { - CheckStatusLabelType(type); - SetStatusLabelText(_localizedStringFinder.GetString(type), text); - } + public void SetStatusLabel(string text) + { + _statusLabelTextRepository.StatusText = text; + _statusLabelTextRepository.SetTime = DateTime.Now; + } - public void SetStatusLabel(string text) - { - _statusLabelTextRepository.StatusText = text; - _statusLabelTextRepository.SetTime = DateTime.Now; - } + public void ShowWarning(string message) + { + SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, message); + } - public void ShowWarning(string message) - { - SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, message); - } + private void SetStatusLabelText(string type, string text, string extra = "", bool showChatError = false) + { + _statusLabelTextRepository.StatusText = $"[ {type} ] {text}{extra}"; + _statusLabelTextRepository.SetTime = DateTime.Now; - private void SetStatusLabelText(string type, string text, string extra = "", bool showChatError = false) + if (showChatError) { - _statusLabelTextRepository.StatusText = $"[ {type} ] {text}{extra}"; - _statusLabelTextRepository.SetTime = DateTime.Now; - - if (showChatError) - { - var chatData = new ChatData(ChatTab.System, string.Empty, $"{text}{extra}", ChatIcon.Error, ChatColor.Error); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } + var chatData = new ChatData(ChatTab.System, string.Empty, $"{text}{extra}", ChatIcon.Error, ChatColor.Error); + _chatRepository.AllChat[ChatTab.System].Add(chatData); } + } - private void CheckStatusLabelType(EOResourceID type) + private void CheckStatusLabelType(EOResourceID type) + { + switch (type) { - switch (type) - { - case EOResourceID.STATUS_LABEL_TYPE_ACTION: - case EOResourceID.STATUS_LABEL_TYPE_BUTTON: - case EOResourceID.STATUS_LABEL_TYPE_INFORMATION: - case EOResourceID.STATUS_LABEL_TYPE_WARNING: - case EOResourceID.STATUS_LABEL_TYPE_ITEM: - case EOResourceID.SKILLMASTER_WORD_SPELL: - break; - default: throw new ArgumentOutOfRangeException(nameof(type), "Use either ACTION, BUTTION, INFORMATION, WARNING, ITEM, or SPELL for this."); - } + case EOResourceID.STATUS_LABEL_TYPE_ACTION: + case EOResourceID.STATUS_LABEL_TYPE_BUTTON: + case EOResourceID.STATUS_LABEL_TYPE_INFORMATION: + case EOResourceID.STATUS_LABEL_TYPE_WARNING: + case EOResourceID.STATUS_LABEL_TYPE_ITEM: + case EOResourceID.SKILLMASTER_WORD_SPELL: + break; + default: throw new ArgumentOutOfRangeException(nameof(type), "Use either ACTION, BUTTION, INFORMATION, WARNING, ITEM, or SPELL for this."); } } } \ No newline at end of file diff --git a/EndlessClient/HUD/UserInterfaceActions.cs b/EndlessClient/HUD/UserInterfaceActions.cs index 46a0c2a3d..ad8f9110c 100644 --- a/EndlessClient/HUD/UserInterfaceActions.cs +++ b/EndlessClient/HUD/UserInterfaceActions.cs @@ -10,96 +10,95 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.HUD +namespace EndlessClient.HUD; + +[AutoMappedType] +public class UserInterfaceActions : IUserInterfaceNotifier { - [AutoMappedType] - public class UserInterfaceActions : IUserInterfaceNotifier - { - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; - public UserInterfaceActions(IInGameDialogActions inGameDialogActions, - IEIFFileProvider eifFileProvider, - ILocalizedStringFinder localizedStringFinder) - { - _inGameDialogActions = inGameDialogActions; - _eifFileProvider = eifFileProvider; - _localizedStringFinder = localizedStringFinder; - } + public UserInterfaceActions(IInGameDialogActions inGameDialogActions, + IEIFFileProvider eifFileProvider, + ILocalizedStringFinder localizedStringFinder) + { + _inGameDialogActions = inGameDialogActions; + _eifFileProvider = eifFileProvider; + _localizedStringFinder = localizedStringFinder; + } - public void NotifyPacketDialog(PacketFamily packetFamily) + public void NotifyPacketDialog(PacketFamily packetFamily) + { + switch (packetFamily) { - switch (packetFamily) - { - case PacketFamily.Locker: _inGameDialogActions.ShowLockerDialog(); break; - case PacketFamily.Chest: _inGameDialogActions.ShowChestDialog(); break; - case PacketFamily.Board: _inGameDialogActions.ShowBoardDialog(); break; - case PacketFamily.Jukebox: _inGameDialogActions.ShowJukeboxDialog(); break; - } + case PacketFamily.Locker: _inGameDialogActions.ShowLockerDialog(); break; + case PacketFamily.Chest: _inGameDialogActions.ShowChestDialog(); break; + case PacketFamily.Board: _inGameDialogActions.ShowBoardDialog(); break; + case PacketFamily.Jukebox: _inGameDialogActions.ShowJukeboxDialog(); break; } + } - public void NotifyMessageDialog(string title, IReadOnlyList messages) - { - _inGameDialogActions.ShowMessageDialog(title, messages); - } + public void NotifyMessageDialog(string title, IReadOnlyList messages) + { + _inGameDialogActions.ShowMessageDialog(title, messages); + } - public void NotifyCharacterInfo(string name, int mapId, MapCoordinate mapCoords, CharacterStats stats) + public void NotifyCharacterInfo(string name, int mapId, MapCoordinate mapCoords, CharacterStats stats) + { + var messages = new List<(string, string)> { - var messages = new List<(string, string)> - { - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEVEL), $"{stats[CharacterStat.Experience]} [{stats[CharacterStat.Level]}]"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_LOCATION), mapId.ToString()), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_COORDINATES), $"{mapCoords.X},{mapCoords.Y}"), - (string.Empty, string.Empty), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_HITPOINTS), $"{stats[CharacterStat.HP]}/{stats[CharacterStat.MaxHP]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_TECHPOINTS), $"{stats[CharacterStat.TP]}/{stats[CharacterStat.MaxTP]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WEIGHT), $"{stats[CharacterStat.Weight]}/{stats[CharacterStat.MaxWeight]}"), - (string.Empty, string.Empty), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DAMAGE), $"{stats[CharacterStat.MinDam]}-{stats[CharacterStat.MaxDam]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_HITRATE), $"{stats[CharacterStat.Accuracy]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_ARMOR), $"{stats[CharacterStat.Armor]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DODGE), $"{stats[CharacterStat.Evade]}"), - (string.Empty, string.Empty), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_STRENGTH), $"{stats[CharacterStat.Strength]}"), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_INTELLIGENCE), $"{stats[CharacterStat.Intelligence]}"), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_WISDOM), $"{stats[CharacterStat.Wisdom]}"), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_AGILITY), $"{stats[CharacterStat.Agility]}"), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CONSTITUTION), $"{stats[CharacterStat.Constitution]}"), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CHARISMA), $"{stats[CharacterStat.Charisma]}"), - (string.Empty, string.Empty), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_LIGHT), $"{stats[CharacterStat.Light]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DARK), $"{stats[CharacterStat.Dark]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_FIRE), $"{stats[CharacterStat.Fire]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WATER), $"{stats[CharacterStat.Water]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_EARTH), $"{stats[CharacterStat.Earth]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WIND), $"{stats[CharacterStat.Wind]}"), - }; + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEVEL), $"{stats[CharacterStat.Experience]} [{stats[CharacterStat.Level]}]"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_LOCATION), mapId.ToString()), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_COORDINATES), $"{mapCoords.X},{mapCoords.Y}"), + (string.Empty, string.Empty), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_HITPOINTS), $"{stats[CharacterStat.HP]}/{stats[CharacterStat.MaxHP]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_TECHPOINTS), $"{stats[CharacterStat.TP]}/{stats[CharacterStat.MaxTP]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WEIGHT), $"{stats[CharacterStat.Weight]}/{stats[CharacterStat.MaxWeight]}"), + (string.Empty, string.Empty), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DAMAGE), $"{stats[CharacterStat.MinDam]}-{stats[CharacterStat.MaxDam]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_HITRATE), $"{stats[CharacterStat.Accuracy]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_ARMOR), $"{stats[CharacterStat.Armor]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DODGE), $"{stats[CharacterStat.Evade]}"), + (string.Empty, string.Empty), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_STRENGTH), $"{stats[CharacterStat.Strength]}"), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_INTELLIGENCE), $"{stats[CharacterStat.Intelligence]}"), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_WISDOM), $"{stats[CharacterStat.Wisdom]}"), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_AGILITY), $"{stats[CharacterStat.Agility]}"), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CONSTITUTION), $"{stats[CharacterStat.Constitution]}"), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CHARISMA), $"{stats[CharacterStat.Charisma]}"), + (string.Empty, string.Empty), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_LIGHT), $"{stats[CharacterStat.Light]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DARK), $"{stats[CharacterStat.Dark]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_FIRE), $"{stats[CharacterStat.Fire]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WATER), $"{stats[CharacterStat.Water]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_EARTH), $"{stats[CharacterStat.Earth]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WIND), $"{stats[CharacterStat.Wind]}"), + }; - var title = $"{name} - {(int)Math.Floor(stats[CharacterStat.Usage] / 60.0)}h.{stats[CharacterStat.Usage] % 60}m."; - _inGameDialogActions.ShowKeyValueMessageDialog(title, messages); - } + var title = $"{name} - {(int)Math.Floor(stats[CharacterStat.Usage] / 60.0)}h.{stats[CharacterStat.Usage] % 60}m."; + _inGameDialogActions.ShowKeyValueMessageDialog(title, messages); + } - public void NotifyCharacterInventory(string name, int usage, int gold, IReadOnlyList inventory, IReadOnlyList bank) - { - var inventoryDisplay = inventory - .Select(x => ((string, string))(_eifFileProvider.EIFFile[x.ItemID].Name, x.Amount.ToString())) - .OrderBy(x => x.Item1); + public void NotifyCharacterInventory(string name, int usage, int gold, IReadOnlyList inventory, IReadOnlyList bank) + { + var inventoryDisplay = inventory + .Select(x => ((string, string))(_eifFileProvider.EIFFile[x.ItemID].Name, x.Amount.ToString())) + .OrderBy(x => x.Item1); - var bankDisplay = bank - .Select(x => ((string, string))(_eifFileProvider.EIFFile[x.ItemID].Name, x.Amount.ToString())) - .OrderBy(x => x.Item1); + var bankDisplay = bank + .Select(x => ((string, string))(_eifFileProvider.EIFFile[x.ItemID].Name, x.Amount.ToString())) + .OrderBy(x => x.Item1); - var messages = new List<(string, string)>(); - messages.AddRange(inventoryDisplay); - messages.Add((string.Empty, string.Empty)); - messages.AddRange(bankDisplay); - messages.Add((string.Empty, string.Empty)); - messages.Add((_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_BANK_ACCOUNT), gold.ToString())); - messages.Add((string.Empty, string.Empty)); + var messages = new List<(string, string)>(); + messages.AddRange(inventoryDisplay); + messages.Add((string.Empty, string.Empty)); + messages.AddRange(bankDisplay); + messages.Add((string.Empty, string.Empty)); + messages.Add((_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_BANK_ACCOUNT), gold.ToString())); + messages.Add((string.Empty, string.Empty)); - var title = $"{name} - {(int)Math.Floor(usage / 60.0)}h.{usage % 60}m."; - _inGameDialogActions.ShowKeyValueMessageDialog(title, messages); - } + var title = $"{name} - {(int)Math.Floor(usage / 60.0)}h.{usage % 60}m."; + _inGameDialogActions.ShowKeyValueMessageDialog(title, messages); } } \ No newline at end of file diff --git a/EndlessClient/Initialization/ConfigInitializer.cs b/EndlessClient/Initialization/ConfigInitializer.cs index 3610a8654..e08064992 100644 --- a/EndlessClient/Initialization/ConfigInitializer.cs +++ b/EndlessClient/Initialization/ConfigInitializer.cs @@ -1,21 +1,20 @@ using AutomaticTypeMapper; using EOLib.Config; -namespace EndlessClient.Initialization +namespace EndlessClient.Initialization; + +[MappedType(BaseType = typeof(IGameInitializer))] +public class ConfigInitializer : IGameInitializer { - [MappedType(BaseType = typeof(IGameInitializer))] - public class ConfigInitializer : IGameInitializer - { - private readonly IConfigFileLoadActions _configFileLoadActions; + private readonly IConfigFileLoadActions _configFileLoadActions; - public ConfigInitializer(IConfigFileLoadActions configFileLoadActions) - { - _configFileLoadActions = configFileLoadActions; - } + public ConfigInitializer(IConfigFileLoadActions configFileLoadActions) + { + _configFileLoadActions = configFileLoadActions; + } - public void Initialize() - { - _configFileLoadActions.LoadConfigFile(); - } + public void Initialize() + { + _configFileLoadActions.LoadConfigFile(); } } \ No newline at end of file diff --git a/EndlessClient/Initialization/EndlessClientInitializer.cs b/EndlessClient/Initialization/EndlessClientInitializer.cs index f4d90833d..1fb5e67bd 100644 --- a/EndlessClient/Initialization/EndlessClientInitializer.cs +++ b/EndlessClient/Initialization/EndlessClientInitializer.cs @@ -12,88 +12,87 @@ using XNAControls; using XNAControls.Input; -namespace EndlessClient.Initialization +namespace EndlessClient.Initialization; + +[AutoMappedType] +public class EndlessClientInitializer : IGameInitializer { - [AutoMappedType] - public class EndlessClientInitializer : IGameInitializer - { - private readonly IEndlessGame _game; - private readonly IEndlessGameRepository _endlessGameRepository; - private readonly IContentProvider _contentProvider; - private readonly List _persistentComponents; + private readonly IEndlessGame _game; + private readonly IEndlessGameRepository _endlessGameRepository; + private readonly IContentProvider _contentProvider; + private readonly List _persistentComponents; - private readonly IMainButtonController _mainButtonController; - private readonly IAccountController _accountController; - private readonly ILoginController _loginController; - private readonly ICharacterManagementController _characterManagementController; - private readonly IChatController _chatController; - private readonly IInventoryController _inventoryController; - private readonly IControlSetFactory _controlSetFactory; - private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; - private readonly IHudControlsFactory _hudControlsFactory; - private readonly IPaperdollDialogFactory _paperdollDialogFactory; + private readonly IMainButtonController _mainButtonController; + private readonly IAccountController _accountController; + private readonly ILoginController _loginController; + private readonly ICharacterManagementController _characterManagementController; + private readonly IChatController _chatController; + private readonly IInventoryController _inventoryController; + private readonly IControlSetFactory _controlSetFactory; + private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; + private readonly IHudControlsFactory _hudControlsFactory; + private readonly IPaperdollDialogFactory _paperdollDialogFactory; - public EndlessClientInitializer(IEndlessGame game, - IEndlessGameRepository endlessGameRepository, - IContentProvider contentProvider, - List persistentComponents, + public EndlessClientInitializer(IEndlessGame game, + IEndlessGameRepository endlessGameRepository, + IContentProvider contentProvider, + List persistentComponents, - //Todo: refactor method injection to something like IEnumerable - IMainButtonController mainButtonController, - IAccountController accountController, - ILoginController loginController, - ICharacterManagementController characterManagementController, - IChatController chatController, - IInventoryController inventoryController, - //factories - IControlSetFactory controlSetFactory, - ICharacterInfoPanelFactory characterInfoPanelFactory, - IHudControlsFactory hudControlsFactory, - IPaperdollDialogFactory paperdollDialogFactory) - { - _game = game; - _endlessGameRepository = endlessGameRepository; - _contentProvider = contentProvider; - _persistentComponents = persistentComponents; - _mainButtonController = mainButtonController; - _accountController = accountController; - _loginController = loginController; - _characterManagementController = characterManagementController; - _chatController = chatController; - _inventoryController = inventoryController; - _controlSetFactory = controlSetFactory; - _characterInfoPanelFactory = characterInfoPanelFactory; - _hudControlsFactory = hudControlsFactory; - _paperdollDialogFactory = paperdollDialogFactory; - } + //Todo: refactor method injection to something like IEnumerable + IMainButtonController mainButtonController, + IAccountController accountController, + ILoginController loginController, + ICharacterManagementController characterManagementController, + IChatController chatController, + IInventoryController inventoryController, + //factories + IControlSetFactory controlSetFactory, + ICharacterInfoPanelFactory characterInfoPanelFactory, + IHudControlsFactory hudControlsFactory, + IPaperdollDialogFactory paperdollDialogFactory) + { + _game = game; + _endlessGameRepository = endlessGameRepository; + _contentProvider = contentProvider; + _persistentComponents = persistentComponents; + _mainButtonController = mainButtonController; + _accountController = accountController; + _loginController = loginController; + _characterManagementController = characterManagementController; + _chatController = chatController; + _inventoryController = inventoryController; + _controlSetFactory = controlSetFactory; + _characterInfoPanelFactory = characterInfoPanelFactory; + _hudControlsFactory = hudControlsFactory; + _paperdollDialogFactory = paperdollDialogFactory; + } - public void Initialize() - { - GameRepository.SetGame(_game as Game); + public void Initialize() + { + GameRepository.SetGame(_game as Game); - foreach (var component in _persistentComponents) - _game.Components.Add(component); + foreach (var component in _persistentComponents) + _game.Components.Add(component); - var mouseListenerSettings = new MouseListenerSettings - { - DoubleClickMilliseconds = 150, - DragThreshold = 1 - }; - _game.Components.Add(new InputManager(GameRepository.GetGame(), mouseListenerSettings)); + var mouseListenerSettings = new MouseListenerSettings + { + DoubleClickMilliseconds = 150, + DragThreshold = 1 + }; + _game.Components.Add(new InputManager(GameRepository.GetGame(), mouseListenerSettings)); - _endlessGameRepository.Game = _game; + _endlessGameRepository.Game = _game; - _game.Content.RootDirectory = "ContentPipeline"; - _contentProvider.SetContentManager(_game.Content); + _game.Content.RootDirectory = "ContentPipeline"; + _contentProvider.SetContentManager(_game.Content); - _controlSetFactory.InjectControllers(_mainButtonController, - _accountController, - _loginController, - _characterManagementController); - _characterInfoPanelFactory.InjectCharacterManagementController(_characterManagementController); - _characterInfoPanelFactory.InjectLoginController(_loginController); - _hudControlsFactory.InjectChatController(_chatController, _mainButtonController); - _paperdollDialogFactory.InjectInventoryController(_inventoryController); - } + _controlSetFactory.InjectControllers(_mainButtonController, + _accountController, + _loginController, + _characterManagementController); + _characterInfoPanelFactory.InjectCharacterManagementController(_characterManagementController); + _characterInfoPanelFactory.InjectLoginController(_loginController); + _hudControlsFactory.InjectChatController(_chatController, _mainButtonController); + _paperdollDialogFactory.InjectInventoryController(_inventoryController); } } \ No newline at end of file diff --git a/EndlessClient/Initialization/GraphicsInitializer.cs b/EndlessClient/Initialization/GraphicsInitializer.cs index d39032ce5..c2bc82450 100644 --- a/EndlessClient/Initialization/GraphicsInitializer.cs +++ b/EndlessClient/Initialization/GraphicsInitializer.cs @@ -3,41 +3,40 @@ using PELoaderLib; using System.IO; -namespace EndlessClient.Initialization +namespace EndlessClient.Initialization; + +[MappedType(BaseType = typeof(IGameInitializer))] +public class GraphicsInitializer : IGameInitializer { - [MappedType(BaseType = typeof(IGameInitializer))] - public class GraphicsInitializer : IGameInitializer + private readonly IPEFileCollection _peFileCollection; + + public GraphicsInitializer(IPEFileCollection peFileCollection) { - private readonly IPEFileCollection _peFileCollection; + _peFileCollection = peFileCollection; + } - public GraphicsInitializer(IPEFileCollection peFileCollection) - { - _peFileCollection = peFileCollection; - } + public void Initialize() + { + _peFileCollection.PopulateCollectionWithStandardGFX(); - public void Initialize() - { - _peFileCollection.PopulateCollectionWithStandardGFX(); + foreach (var filePair in _peFileCollection) + TryInitializePEFiles(filePair.Key, filePair.Value); + } - foreach (var filePair in _peFileCollection) - TryInitializePEFiles(filePair.Key, filePair.Value); - } + private static void TryInitializePEFiles(GFXTypes file, IPEFile peFile) + { + var number = ((int)file).ToString("D3"); - private static void TryInitializePEFiles(GFXTypes file, IPEFile peFile) + try { - var number = ((int)file).ToString("D3"); - - try - { - peFile.Initialize(); - } - catch (IOException) - { - throw new LibraryLoadException(number, file); - } - - if (!peFile.Initialized) - throw new LibraryLoadException(number, file); + peFile.Initialize(); } + catch (IOException) + { + throw new LibraryLoadException(number, file); + } + + if (!peFile.Initialized) + throw new LibraryLoadException(number, file); } } \ No newline at end of file diff --git a/EndlessClient/Initialization/IGameInitializer.cs b/EndlessClient/Initialization/IGameInitializer.cs index 7bddf1ae9..1963b6c4c 100644 --- a/EndlessClient/Initialization/IGameInitializer.cs +++ b/EndlessClient/Initialization/IGameInitializer.cs @@ -1,7 +1,6 @@ -namespace EndlessClient.Initialization +namespace EndlessClient.Initialization; + +public interface IGameInitializer { - public interface IGameInitializer - { - void Initialize(); - } + void Initialize(); } \ No newline at end of file diff --git a/EndlessClient/Initialization/LocalizationInitializer.cs b/EndlessClient/Initialization/LocalizationInitializer.cs index 72f96ae48..6c8272b37 100644 --- a/EndlessClient/Initialization/LocalizationInitializer.cs +++ b/EndlessClient/Initialization/LocalizationInitializer.cs @@ -1,21 +1,20 @@ using AutomaticTypeMapper; using EOLib.Localization; -namespace EndlessClient.Initialization +namespace EndlessClient.Initialization; + +[MappedType(BaseType = typeof(IGameInitializer))] +public class LocalizationInitializer : IGameInitializer { - [MappedType(BaseType = typeof(IGameInitializer))] - public class LocalizationInitializer : IGameInitializer - { - private readonly IDataFileLoadActions _dataFileLoadActions; + private readonly IDataFileLoadActions _dataFileLoadActions; - public LocalizationInitializer(IDataFileLoadActions dataFileLoadActions) - { - _dataFileLoadActions = dataFileLoadActions; - } + public LocalizationInitializer(IDataFileLoadActions dataFileLoadActions) + { + _dataFileLoadActions = dataFileLoadActions; + } - public void Initialize() - { - _dataFileLoadActions.LoadDataFiles(); - } + public void Initialize() + { + _dataFileLoadActions.LoadDataFiles(); } } \ No newline at end of file diff --git a/EndlessClient/Input/ArrowKeyHandler.cs b/EndlessClient/Input/ArrowKeyHandler.cs index c4aac0903..6c5301a01 100644 --- a/EndlessClient/Input/ArrowKeyHandler.cs +++ b/EndlessClient/Input/ArrowKeyHandler.cs @@ -4,37 +4,36 @@ using Microsoft.Xna.Framework.Input; using Optional; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public class ArrowKeyHandler : InputHandlerBase { - public class ArrowKeyHandler : InputHandlerBase - { - private readonly IArrowKeyController _arrowKeyController; + private readonly IArrowKeyController _arrowKeyController; - public ArrowKeyHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - IArrowKeyController arrowKeyController, - ICurrentMapStateRepository currentMapStateRepository) - : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) - { - _arrowKeyController = arrowKeyController; - } + public ArrowKeyHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + IArrowKeyController arrowKeyController, + ICurrentMapStateRepository currentMapStateRepository) + : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + { + _arrowKeyController = arrowKeyController; + } - protected override Option HandleInput() - { - if (IsKeyHeld(Keys.Left) && _arrowKeyController.MoveLeft()) - return Option.Some(Keys.Left); - if (IsKeyHeld(Keys.Right) && _arrowKeyController.MoveRight()) - return Option.Some(Keys.Right); - if (IsKeyHeld(Keys.Up) && _arrowKeyController.MoveUp()) - return Option.Some(Keys.Up); - if (IsKeyHeld(Keys.Down) && _arrowKeyController.MoveDown()) - return Option.Some(Keys.Down); + protected override Option HandleInput() + { + if (IsKeyHeld(Keys.Left) && _arrowKeyController.MoveLeft()) + return Option.Some(Keys.Left); + if (IsKeyHeld(Keys.Right) && _arrowKeyController.MoveRight()) + return Option.Some(Keys.Right); + if (IsKeyHeld(Keys.Up) && _arrowKeyController.MoveUp()) + return Option.Some(Keys.Up); + if (IsKeyHeld(Keys.Down) && _arrowKeyController.MoveDown()) + return Option.Some(Keys.Down); - if (KeysAreUp(Keys.Left, Keys.Right, Keys.Up, Keys.Down)) - _arrowKeyController.KeysUp(); + if (KeysAreUp(Keys.Left, Keys.Right, Keys.Up, Keys.Down)) + _arrowKeyController.KeysUp(); - return Option.None(); - } + return Option.None(); } } \ No newline at end of file diff --git a/EndlessClient/Input/ControlKeyHandler.cs b/EndlessClient/Input/ControlKeyHandler.cs index d0e51f4f1..b7a21af76 100644 --- a/EndlessClient/Input/ControlKeyHandler.cs +++ b/EndlessClient/Input/ControlKeyHandler.cs @@ -4,30 +4,29 @@ using Microsoft.Xna.Framework.Input; using Optional; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public class ControlKeyHandler : InputHandlerBase { - public class ControlKeyHandler : InputHandlerBase - { - private readonly IControlKeyController _controlKeyController; + private readonly IControlKeyController _controlKeyController; - public ControlKeyHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - IControlKeyController controlKeyController, - ICurrentMapStateRepository currentMapStateRepository) - : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) - { - _controlKeyController = controlKeyController; - } + public ControlKeyHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + IControlKeyController controlKeyController, + ICurrentMapStateRepository currentMapStateRepository) + : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + { + _controlKeyController = controlKeyController; + } - protected override Option HandleInput() - { - if (IsKeyHeld(Keys.LeftControl) && _controlKeyController.Attack()) - return Option.Some(Keys.LeftControl); - if (IsKeyHeld(Keys.RightControl) && _controlKeyController.Attack()) - return Option.Some(Keys.RightControl); + protected override Option HandleInput() + { + if (IsKeyHeld(Keys.LeftControl) && _controlKeyController.Attack()) + return Option.Some(Keys.LeftControl); + if (IsKeyHeld(Keys.RightControl) && _controlKeyController.Attack()) + return Option.Some(Keys.RightControl); - return Option.None(); - } + return Option.None(); } } \ No newline at end of file diff --git a/EndlessClient/Input/CurrentUserInputTracker.cs b/EndlessClient/Input/CurrentUserInputTracker.cs index f09bb9f5e..87dcb51e7 100644 --- a/EndlessClient/Input/CurrentUserInputTracker.cs +++ b/EndlessClient/Input/CurrentUserInputTracker.cs @@ -2,28 +2,27 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public class CurrentUserInputTracker : GameComponent { - public class CurrentUserInputTracker : GameComponent - { - private readonly IUserInputRepository _userInputRepository; + private readonly IUserInputRepository _userInputRepository; - public CurrentUserInputTracker( - IEndlessGameProvider endlessGameProvider, - IUserInputRepository userInputRepository) - : base((Game)endlessGameProvider.Game) - { - _userInputRepository = userInputRepository; + public CurrentUserInputTracker( + IEndlessGameProvider endlessGameProvider, + IUserInputRepository userInputRepository) + : base((Game)endlessGameProvider.Game) + { + _userInputRepository = userInputRepository; - UpdateOrder = int.MinValue; - } + UpdateOrder = int.MinValue; + } - public override void Update(GameTime gameTime) - { - _userInputRepository.CurrentKeyState = Keyboard.GetState(); - _userInputRepository.CurrentMouseState = Mouse.GetState(); + public override void Update(GameTime gameTime) + { + _userInputRepository.CurrentKeyState = Keyboard.GetState(); + _userInputRepository.CurrentMouseState = Mouse.GetState(); - base.Update(gameTime); - } + base.Update(gameTime); } } \ No newline at end of file diff --git a/EndlessClient/Input/FunctionKeyHandler.cs b/EndlessClient/Input/FunctionKeyHandler.cs index e0a1de145..d507eec29 100644 --- a/EndlessClient/Input/FunctionKeyHandler.cs +++ b/EndlessClient/Input/FunctionKeyHandler.cs @@ -4,41 +4,40 @@ using Microsoft.Xna.Framework.Input; using Optional; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public class FunctionKeyHandler : InputHandlerBase { - public class FunctionKeyHandler : InputHandlerBase - { - private readonly IFunctionKeyController _functionKeyController; + private readonly IFunctionKeyController _functionKeyController; - public FunctionKeyHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - IFunctionKeyController functionKeyController, - ICurrentMapStateRepository currentMapStateRepository) - : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) - { - _functionKeyController = functionKeyController; - } + public FunctionKeyHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + IFunctionKeyController functionKeyController, + ICurrentMapStateRepository currentMapStateRepository) + : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + { + _functionKeyController = functionKeyController; + } - protected override Option HandleInput() + protected override Option HandleInput() + { + for (var key = Keys.F1; key <= Keys.F8; key++) { - for (var key = Keys.F1; key <= Keys.F8; key++) + if (IsKeyHeld(key)) { - if (IsKeyHeld(key)) - { - var isShiftHeld = IsKeyHeld(Keys.LeftShift) || IsKeyHeld(Keys.RightShift); - if (_functionKeyController.SelectSpell(key - Keys.F1, isShiftHeld)) - return Option.Some(key); - } + var isShiftHeld = IsKeyHeld(Keys.LeftShift) || IsKeyHeld(Keys.RightShift); + if (_functionKeyController.SelectSpell(key - Keys.F1, isShiftHeld)) + return Option.Some(key); } + } - if (IsKeyPressedOnce(Keys.F11) && _functionKeyController.Sit()) - return Option.Some(Keys.F11); + if (IsKeyPressedOnce(Keys.F11) && _functionKeyController.Sit()) + return Option.Some(Keys.F11); - if (IsKeyPressedOnce(Keys.F12) && _functionKeyController.RefreshMapState()) - return Option.Some(Keys.F12); + if (IsKeyPressedOnce(Keys.F12) && _functionKeyController.RefreshMapState()) + return Option.Some(Keys.F12); - return Option.None(); - } + return Option.None(); } } \ No newline at end of file diff --git a/EndlessClient/Input/IUserInputRepository.cs b/EndlessClient/Input/IUserInputRepository.cs index 8382d233a..1e5486ef1 100644 --- a/EndlessClient/Input/IUserInputRepository.cs +++ b/EndlessClient/Input/IUserInputRepository.cs @@ -1,40 +1,39 @@ using AutomaticTypeMapper; using Microsoft.Xna.Framework.Input; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public interface IUserInputRepository { - public interface IUserInputRepository - { - KeyboardState PreviousKeyState { get; set; } + KeyboardState PreviousKeyState { get; set; } - KeyboardState CurrentKeyState { get; set; } + KeyboardState CurrentKeyState { get; set; } - MouseState PreviousMouseState { get; set; } + MouseState PreviousMouseState { get; set; } - MouseState CurrentMouseState { get; set; } - } + MouseState CurrentMouseState { get; set; } +} - public interface IUserInputProvider - { - KeyboardState PreviousKeyState { get; } +public interface IUserInputProvider +{ + KeyboardState PreviousKeyState { get; } - KeyboardState CurrentKeyState { get; } + KeyboardState CurrentKeyState { get; } - MouseState PreviousMouseState { get; } + MouseState PreviousMouseState { get; } - MouseState CurrentMouseState { get; } - } + MouseState CurrentMouseState { get; } +} - [MappedType(BaseType = typeof(IUserInputRepository), IsSingleton = true)] - [MappedType(BaseType = typeof(IUserInputProvider), IsSingleton = true)] - public class KeyStateRepository : IUserInputRepository, IUserInputProvider - { - public KeyboardState PreviousKeyState { get; set; } +[MappedType(BaseType = typeof(IUserInputRepository), IsSingleton = true)] +[MappedType(BaseType = typeof(IUserInputProvider), IsSingleton = true)] +public class KeyStateRepository : IUserInputRepository, IUserInputProvider +{ + public KeyboardState PreviousKeyState { get; set; } - public KeyboardState CurrentKeyState { get; set; } + public KeyboardState CurrentKeyState { get; set; } - public MouseState PreviousMouseState { get; set; } + public MouseState PreviousMouseState { get; set; } - public MouseState CurrentMouseState { get; set; } - } + public MouseState CurrentMouseState { get; set; } } \ No newline at end of file diff --git a/EndlessClient/Input/IUserInputTimeRepository.cs b/EndlessClient/Input/IUserInputTimeRepository.cs index e4d074b4b..444799d09 100644 --- a/EndlessClient/Input/IUserInputTimeRepository.cs +++ b/EndlessClient/Input/IUserInputTimeRepository.cs @@ -1,26 +1,25 @@ using AutomaticTypeMapper; using System; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public interface IUserInputTimeRepository { - public interface IUserInputTimeRepository - { - DateTime LastInputTime { get; set; } - } + DateTime LastInputTime { get; set; } +} - public interface IUserInputTimeProvider - { - DateTime LastInputTime { get; } - } +public interface IUserInputTimeProvider +{ + DateTime LastInputTime { get; } +} - [AutoMappedType(IsSingleton = true)] - public class UserInputTimeRepository : IUserInputTimeRepository, IUserInputTimeProvider - { - public DateTime LastInputTime { get; set; } +[AutoMappedType(IsSingleton = true)] +public class UserInputTimeRepository : IUserInputTimeRepository, IUserInputTimeProvider +{ + public DateTime LastInputTime { get; set; } - public UserInputTimeRepository() - { - LastInputTime = DateTime.Now; - } + public UserInputTimeRepository() + { + LastInputTime = DateTime.Now; } } \ No newline at end of file diff --git a/EndlessClient/Input/InputHandlerBase.cs b/EndlessClient/Input/InputHandlerBase.cs index e93648ddd..2cb9f154d 100644 --- a/EndlessClient/Input/InputHandlerBase.cs +++ b/EndlessClient/Input/InputHandlerBase.cs @@ -5,84 +5,83 @@ using System; using System.Linq; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public abstract class InputHandlerBase : IInputHandler { - public abstract class InputHandlerBase : IInputHandler + private const int INPUT_RATE_LIMIT_MILLISECONDS = 200; + private const int WARP_BACKOFF_TIME_MILLISECONDS = 300; + private const int WARP_SLEEP_BACKOFF_TIME_MILLISECONDS = 5000; + + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IUserInputProvider _keyStateProvider; + private readonly IUserInputTimeRepository _userInputTimeRepository; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + + private KeyboardState CurrentState => _keyStateProvider.CurrentKeyState; + + private KeyboardState PreviousState => _keyStateProvider.PreviousKeyState; + + protected InputHandlerBase(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + ICurrentMapStateRepository currentMapStateRepository) + { + _endlessGameProvider = endlessGameProvider; + _keyStateProvider = userInputProvider; + _userInputTimeRepository = userInputTimeRepository; + _currentMapStateRepository = currentMapStateRepository; + } + + public void HandleKeyboardInput(DateTime timeAtBeginningOfUpdate) { - private const int INPUT_RATE_LIMIT_MILLISECONDS = 200; - private const int WARP_BACKOFF_TIME_MILLISECONDS = 300; - private const int WARP_SLEEP_BACKOFF_TIME_MILLISECONDS = 5000; - - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IUserInputProvider _keyStateProvider; - private readonly IUserInputTimeRepository _userInputTimeRepository; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - - private KeyboardState CurrentState => _keyStateProvider.CurrentKeyState; - - private KeyboardState PreviousState => _keyStateProvider.PreviousKeyState; - - protected InputHandlerBase(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - ICurrentMapStateRepository currentMapStateRepository) - { - _endlessGameProvider = endlessGameProvider; - _keyStateProvider = userInputProvider; - _userInputTimeRepository = userInputTimeRepository; - _currentMapStateRepository = currentMapStateRepository; - } - - public void HandleKeyboardInput(DateTime timeAtBeginningOfUpdate) - { - var millisecondsSinceLastUpdate = GetMillisecondsSinceLastUpdate(timeAtBeginningOfUpdate); - if (!_endlessGameProvider.Game.IsActive || - millisecondsSinceLastUpdate < INPUT_RATE_LIMIT_MILLISECONDS || - _currentMapStateRepository.MapWarpState != WarpState.None) - return; - - _currentMapStateRepository.MapWarpTime.MatchSome( - some: t => + var millisecondsSinceLastUpdate = GetMillisecondsSinceLastUpdate(timeAtBeginningOfUpdate); + if (!_endlessGameProvider.Game.IsActive || + millisecondsSinceLastUpdate < INPUT_RATE_LIMIT_MILLISECONDS || + _currentMapStateRepository.MapWarpState != WarpState.None) + return; + + _currentMapStateRepository.MapWarpTime.MatchSome( + some: t => + { + var span = (DateTime.Now - t).TotalMilliseconds; + var isSleepBackoffDone = _currentMapStateRepository.IsSleepWarp && span >= WARP_SLEEP_BACKOFF_TIME_MILLISECONDS; + var isWarpBackoffDone = !_currentMapStateRepository.IsSleepWarp && span >= WARP_BACKOFF_TIME_MILLISECONDS; + + if (isSleepBackoffDone || isWarpBackoffDone) { - var span = (DateTime.Now - t).TotalMilliseconds; - var isSleepBackoffDone = _currentMapStateRepository.IsSleepWarp && span >= WARP_SLEEP_BACKOFF_TIME_MILLISECONDS; - var isWarpBackoffDone = !_currentMapStateRepository.IsSleepWarp && span >= WARP_BACKOFF_TIME_MILLISECONDS; - - if (isSleepBackoffDone || isWarpBackoffDone) - { - _currentMapStateRepository.MapWarpTime = Option.None(); - _currentMapStateRepository.IsSleepWarp = false; - } - }); - - _currentMapStateRepository.MapWarpTime.MatchNone(() => HandleInput().MatchSome(_ => _userInputTimeRepository.LastInputTime = timeAtBeginningOfUpdate)); - } - - private double GetMillisecondsSinceLastUpdate(DateTime timeAtBeginningOfUpdate) - { - return (timeAtBeginningOfUpdate - _userInputTimeRepository.LastInputTime).TotalMilliseconds; - } - - protected abstract Option HandleInput(); - - protected bool IsKeyHeld(params Keys[] keys) - { - return keys.Any(key => CurrentState.IsKeyHeld(PreviousState, key)); - } - - protected bool IsKeyPressedOnce(params Keys[] keys) - { - return keys.Any(key => CurrentState.IsKeyPressedOnce(PreviousState, key)); - } - - protected bool KeysAreUp(params Keys[] keys) - { - return keys.All(CurrentState.IsKeyUp); - } + _currentMapStateRepository.MapWarpTime = Option.None(); + _currentMapStateRepository.IsSleepWarp = false; + } + }); + + _currentMapStateRepository.MapWarpTime.MatchNone(() => HandleInput().MatchSome(_ => _userInputTimeRepository.LastInputTime = timeAtBeginningOfUpdate)); } - public interface IInputHandler + private double GetMillisecondsSinceLastUpdate(DateTime timeAtBeginningOfUpdate) { - void HandleKeyboardInput(DateTime timeAtStart); + return (timeAtBeginningOfUpdate - _userInputTimeRepository.LastInputTime).TotalMilliseconds; } + + protected abstract Option HandleInput(); + + protected bool IsKeyHeld(params Keys[] keys) + { + return keys.Any(key => CurrentState.IsKeyHeld(PreviousState, key)); + } + + protected bool IsKeyPressedOnce(params Keys[] keys) + { + return keys.Any(key => CurrentState.IsKeyPressedOnce(PreviousState, key)); + } + + protected bool KeysAreUp(params Keys[] keys) + { + return keys.All(CurrentState.IsKeyUp); + } +} + +public interface IInputHandler +{ + void HandleKeyboardInput(DateTime timeAtStart); } \ No newline at end of file diff --git a/EndlessClient/Input/KeyboardStateExtensions.cs b/EndlessClient/Input/KeyboardStateExtensions.cs index 977060c9b..4da269423 100644 --- a/EndlessClient/Input/KeyboardStateExtensions.cs +++ b/EndlessClient/Input/KeyboardStateExtensions.cs @@ -1,31 +1,30 @@ using Microsoft.Xna.Framework.Input; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public static class KeyboardStateExtensions { - public static class KeyboardStateExtensions + /// + /// Compares the state of a single key between two KeyboardStates to determine if the key is being held down + /// + /// The current keystate + /// The previous keystate + /// The key to test + /// True if the key is held (down for both states); false otherwise + public static bool IsKeyHeld(this KeyboardState keyState, KeyboardState previousKeyState, Keys key) { - /// - /// Compares the state of a single key between two KeyboardStates to determine if the key is being held down - /// - /// The current keystate - /// The previous keystate - /// The key to test - /// True if the key is held (down for both states); false otherwise - public static bool IsKeyHeld(this KeyboardState keyState, KeyboardState previousKeyState, Keys key) - { - return previousKeyState.IsKeyDown(key) && keyState.IsKeyDown(key); - } + return previousKeyState.IsKeyDown(key) && keyState.IsKeyDown(key); + } - /// - /// Compares the state of a single key between two KeyboardStates to determine if the key was pressed once - /// - /// The current keystate - /// The previous keystate - /// The key to test - /// True if the key was pressed once (down in previous then up in current); false otherwise - public static bool IsKeyPressedOnce(this KeyboardState keyState, KeyboardState previousKeyState, Keys key) - { - return previousKeyState.IsKeyDown(key) && keyState.IsKeyUp(key); - } + /// + /// Compares the state of a single key between two KeyboardStates to determine if the key was pressed once + /// + /// The current keystate + /// The previous keystate + /// The key to test + /// True if the key was pressed once (down in previous then up in current); false otherwise + public static bool IsKeyPressedOnce(this KeyboardState keyState, KeyboardState previousKeyState, Keys key) + { + return previousKeyState.IsKeyDown(key) && keyState.IsKeyUp(key); } } \ No newline at end of file diff --git a/EndlessClient/Input/NumPadHandler.cs b/EndlessClient/Input/NumPadHandler.cs index 44c490bd6..84582705d 100644 --- a/EndlessClient/Input/NumPadHandler.cs +++ b/EndlessClient/Input/NumPadHandler.cs @@ -5,43 +5,42 @@ using Microsoft.Xna.Framework.Input; using Optional; -namespace EndlessClient.Input +namespace EndlessClient.Input; + + +public class NumPadHandler : InputHandlerBase { + private readonly INumPadController _numPadController; - public class NumPadHandler : InputHandlerBase + public NumPadHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + ICurrentMapStateRepository currentMapStateRepository, + INumPadController numPadController) + : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) { - private readonly INumPadController _numPadController; - - public NumPadHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - ICurrentMapStateRepository currentMapStateRepository, - INumPadController numPadController) - : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) - { - _numPadController = numPadController; - } + _numPadController = numPadController; + } - protected override Option HandleInput() + protected override Option HandleInput() + { + for (var key = Keys.NumPad0; key <= Keys.NumPad9; ++key) { - for (var key = Keys.NumPad0; key <= Keys.NumPad9; ++key) + if (IsKeyHeld(key)) { - if (IsKeyHeld(key)) - { - var emote = key == Keys.NumPad0 ? Emote.Playful : (Emote)(key - Keys.NumPad0); - _numPadController.Emote(emote); - return Option.Some(key); - } - } - - // Keys.Decimal == ./DEL on the num pad - if (IsKeyHeld(Keys.Decimal)) - { - _numPadController.Emote(Emote.Embarassed); - return Option.Some(Keys.Decimal); + var emote = key == Keys.NumPad0 ? Emote.Playful : (Emote)(key - Keys.NumPad0); + _numPadController.Emote(emote); + return Option.Some(key); } + } - return Option.None(); + // Keys.Decimal == ./DEL on the num pad + if (IsKeyHeld(Keys.Decimal)) + { + _numPadController.Emote(Emote.Embarassed); + return Option.Some(Keys.Decimal); } + + return Option.None(); } } \ No newline at end of file diff --git a/EndlessClient/Input/PanelShortcutHandler.cs b/EndlessClient/Input/PanelShortcutHandler.cs index 6287056b9..f6c807338 100644 --- a/EndlessClient/Input/PanelShortcutHandler.cs +++ b/EndlessClient/Input/PanelShortcutHandler.cs @@ -5,56 +5,55 @@ using Optional; using System.Linq; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public class PanelShortcutHandler : InputHandlerBase { - public class PanelShortcutHandler : InputHandlerBase + private readonly IHudButtonController _hudButtonController; + + public PanelShortcutHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + ICurrentMapStateRepository currentMapStateRepository, + IHudButtonController hudButtonController) + : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) { - private readonly IHudButtonController _hudButtonController; - - public PanelShortcutHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - ICurrentMapStateRepository currentMapStateRepository, - IHudButtonController hudButtonController) - : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) - { - _hudButtonController = hudButtonController; - } + _hudButtonController = hudButtonController; + } - protected override Option HandleInput() - { - if (!IsKeyHeld(Keys.LeftAlt) && !IsKeyHeld(Keys.RightAlt)) - return Option.None(); + protected override Option HandleInput() + { + if (!IsKeyHeld(Keys.LeftAlt) && !IsKeyHeld(Keys.RightAlt)) + return Option.None(); - var keys = Enumerable.Range((int)Keys.D0, 10).Select(i => (Keys)i).Concat(new[] { Keys.OemTilde }); + var keys = Enumerable.Range((int)Keys.D0, 10).Select(i => (Keys)i).Concat(new[] { Keys.OemTilde }); - foreach (var key in keys) + foreach (var key in keys) + { + if (IsKeyPressedOnce(key)) { - if (IsKeyPressedOnce(key)) + switch (key) { - switch (key) - { - case Keys.OemTilde: _hudButtonController.ShowNews(); break; - - case Keys.D1: _hudButtonController.ClickInventory(); break; - case Keys.D2: _hudButtonController.ClickViewMapToggle(); break; - case Keys.D3: _hudButtonController.ClickActiveSpells(); break; - case Keys.D4: _hudButtonController.ClickPassiveSpells(); break; - case Keys.D5: _hudButtonController.ClickChat(); break; - case Keys.D6: _hudButtonController.ClickStats(); break; - - case Keys.D7: _hudButtonController.ClickOnlineList(); break; - case Keys.D8: _hudButtonController.ClickParty(); break; - // macro: intentionally not implemented - case Keys.D9: _hudButtonController.ClickSettings(); break; - case Keys.D0: _hudButtonController.ClickHelp(); break; - } - - return Option.Some(key); + case Keys.OemTilde: _hudButtonController.ShowNews(); break; + + case Keys.D1: _hudButtonController.ClickInventory(); break; + case Keys.D2: _hudButtonController.ClickViewMapToggle(); break; + case Keys.D3: _hudButtonController.ClickActiveSpells(); break; + case Keys.D4: _hudButtonController.ClickPassiveSpells(); break; + case Keys.D5: _hudButtonController.ClickChat(); break; + case Keys.D6: _hudButtonController.ClickStats(); break; + + case Keys.D7: _hudButtonController.ClickOnlineList(); break; + case Keys.D8: _hudButtonController.ClickParty(); break; + // macro: intentionally not implemented + case Keys.D9: _hudButtonController.ClickSettings(); break; + case Keys.D0: _hudButtonController.ClickHelp(); break; } - } - return Option.None(); + return Option.Some(key); + } } + + return Option.None(); } } \ No newline at end of file diff --git a/EndlessClient/Input/PreviousUserInputTracker.cs b/EndlessClient/Input/PreviousUserInputTracker.cs index d157bc31c..3b9e86547 100644 --- a/EndlessClient/Input/PreviousUserInputTracker.cs +++ b/EndlessClient/Input/PreviousUserInputTracker.cs @@ -1,27 +1,26 @@ using EndlessClient.GameExecution; using Microsoft.Xna.Framework; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public class PreviousUserInputTracker : GameComponent { - public class PreviousUserInputTracker : GameComponent - { - private readonly IUserInputRepository _userInputRepository; + private readonly IUserInputRepository _userInputRepository; - public PreviousUserInputTracker( - IEndlessGameProvider endlessGameProvider, - IUserInputRepository userInputRepository) - : base((Game)endlessGameProvider.Game) - { - _userInputRepository = userInputRepository; - UpdateOrder = int.MaxValue; - } + public PreviousUserInputTracker( + IEndlessGameProvider endlessGameProvider, + IUserInputRepository userInputRepository) + : base((Game)endlessGameProvider.Game) + { + _userInputRepository = userInputRepository; + UpdateOrder = int.MaxValue; + } - public override void Update(GameTime gameTime) - { - _userInputRepository.PreviousKeyState = _userInputRepository.CurrentKeyState; - _userInputRepository.PreviousMouseState = _userInputRepository.CurrentMouseState; + public override void Update(GameTime gameTime) + { + _userInputRepository.PreviousKeyState = _userInputRepository.CurrentKeyState; + _userInputRepository.PreviousMouseState = _userInputRepository.CurrentMouseState; - base.Update(gameTime); - } + base.Update(gameTime); } } \ No newline at end of file diff --git a/EndlessClient/Input/UnwalkableTileActions.cs b/EndlessClient/Input/UnwalkableTileActions.cs index 5eeed3648..261770b27 100644 --- a/EndlessClient/Input/UnwalkableTileActions.cs +++ b/EndlessClient/Input/UnwalkableTileActions.cs @@ -9,172 +9,171 @@ using EOLib.Localization; using System.Collections.Generic; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public enum UnwalkableTileAction +{ + None, + Chair, + Chest, + Door, + Locker, + Board, + Jukebox, +} + +[AutoMappedType] +public class UnwalkableTileActions : IUnwalkableTileActions { - public enum UnwalkableTileAction + private readonly IMapCellStateProvider _mapCellStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IUnlockDoorValidator _unlockDoorValidator; + private readonly IUnlockChestValidator _unlockChestValidator; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ISfxPlayer _sfxPlayer; + + public UnwalkableTileActions(IMapCellStateProvider mapCellStateProvider, + ICharacterProvider characterProvider, + IStatusLabelSetter statusLabelSetter, + ICurrentMapStateRepository currentMapStateRepository, + IUnlockDoorValidator unlockDoorValidator, + IUnlockChestValidator unlockChestValidator, + IEOMessageBoxFactory eoMessageBoxFactory, + IEOMessageBoxFactory messageBoxFactory, + ISfxPlayer sfxPlayer) { - None, - Chair, - Chest, - Door, - Locker, - Board, - Jukebox, + _mapCellStateProvider = mapCellStateProvider; + _characterProvider = characterProvider; + _statusLabelSetter = statusLabelSetter; + _currentMapStateRepository = currentMapStateRepository; + _unlockDoorValidator = unlockDoorValidator; + _unlockChestValidator = unlockChestValidator; + _eoMessageBoxFactory = eoMessageBoxFactory; + _messageBoxFactory = messageBoxFactory; + _sfxPlayer = sfxPlayer; } - [AutoMappedType] - public class UnwalkableTileActions : IUnwalkableTileActions + public (IReadOnlyList, IMapCellState) GetUnwalkableTileActions() { - private readonly IMapCellStateProvider _mapCellStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IUnlockDoorValidator _unlockDoorValidator; - private readonly IUnlockChestValidator _unlockChestValidator; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ISfxPlayer _sfxPlayer; - - public UnwalkableTileActions(IMapCellStateProvider mapCellStateProvider, - ICharacterProvider characterProvider, - IStatusLabelSetter statusLabelSetter, - ICurrentMapStateRepository currentMapStateRepository, - IUnlockDoorValidator unlockDoorValidator, - IUnlockChestValidator unlockChestValidator, - IEOMessageBoxFactory eoMessageBoxFactory, - IEOMessageBoxFactory messageBoxFactory, - ISfxPlayer sfxPlayer) - { - _mapCellStateProvider = mapCellStateProvider; - _characterProvider = characterProvider; - _statusLabelSetter = statusLabelSetter; - _currentMapStateRepository = currentMapStateRepository; - _unlockDoorValidator = unlockDoorValidator; - _unlockChestValidator = unlockChestValidator; - _eoMessageBoxFactory = eoMessageBoxFactory; - _messageBoxFactory = messageBoxFactory; - _sfxPlayer = sfxPlayer; - } - - public (IReadOnlyList, IMapCellState) GetUnwalkableTileActions() - { - var destX = MainCharacter.RenderProperties.GetDestinationX(); - var destY = MainCharacter.RenderProperties.GetDestinationY(); - return GetUnwalkableTileActions(destX, destY); - } + var destX = MainCharacter.RenderProperties.GetDestinationX(); + var destY = MainCharacter.RenderProperties.GetDestinationY(); + return GetUnwalkableTileActions(destX, destY); + } - public (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(int x, int y) - { - var cellState = _mapCellStateProvider.GetCellStateAt(x, y); - var action = GetUnwalkableTileActions(cellState); - return (action, cellState); - } + public (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(int x, int y) + { + var cellState = _mapCellStateProvider.GetCellStateAt(x, y); + var action = GetUnwalkableTileActions(cellState); + return (action, cellState); + } - public IReadOnlyList GetUnwalkableTileActions(IMapCellState cellState) - { - if (MainCharacter.RenderProperties.SitState != SitState.Standing) - return new[] { UnwalkableTileAction.None }; + public IReadOnlyList GetUnwalkableTileActions(IMapCellState cellState) + { + if (MainCharacter.RenderProperties.SitState != SitState.Standing) + return new[] { UnwalkableTileAction.None }; - return cellState.Warp.Match( - some: w => new[] { HandleWalkToWarpTile(w), HandleWalkToTileSpec(cellState) }, - none: () => new[] { HandleWalkToTileSpec(cellState) }); - } + return cellState.Warp.Match( + some: w => new[] { HandleWalkToWarpTile(w), HandleWalkToTileSpec(cellState) }, + none: () => new[] { HandleWalkToTileSpec(cellState) }); + } - private UnwalkableTileAction HandleWalkToWarpTile(Warp warp) + private UnwalkableTileAction HandleWalkToWarpTile(Warp warp) + { + if (warp.DoorType != DoorSpec.NoDoor) { - if (warp.DoorType != DoorSpec.NoDoor) + if (!_unlockDoorValidator.CanMainCharacterOpenDoor(warp)) { - if (!_unlockDoorValidator.CanMainCharacterOpenDoor(warp)) - { - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.DOOR_LOCKED); - messageBox.ShowDialog(); - - var requiredKey = _unlockDoorValidator.GetRequiredKey(warp); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.STATUS_LABEL_THE_DOOR_IS_LOCKED_EXCLAMATION, - requiredKey.Match(x => $" - {x}", () => string.Empty)); - - _sfxPlayer.PlaySfx(SoundEffectID.DoorOrChestLocked); - } - else if (!_currentMapStateRepository.OpenDoors.Contains(warp) && - !_currentMapStateRepository.PendingDoors.Contains(warp)) - { - return UnwalkableTileAction.Door; - } + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.DOOR_LOCKED); + messageBox.ShowDialog(); + + var requiredKey = _unlockDoorValidator.GetRequiredKey(warp); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.STATUS_LABEL_THE_DOOR_IS_LOCKED_EXCLAMATION, + requiredKey.Match(x => $" - {x}", () => string.Empty)); + + _sfxPlayer.PlaySfx(SoundEffectID.DoorOrChestLocked); } - else if (warp.LevelRequirement > 0 && MainCharacter.Stats[CharacterStat.Level] < warp.LevelRequirement) + else if (!_currentMapStateRepository.OpenDoors.Contains(warp) && + !_currentMapStateRepository.PendingDoors.Contains(warp)) { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.STATUS_LABEL_NOT_READY_TO_USE_ENTRANCE, - " - LVL " + warp.LevelRequirement); + return UnwalkableTileAction.Door; } - - return UnwalkableTileAction.None; + } + else if (warp.LevelRequirement > 0 && MainCharacter.Stats[CharacterStat.Level] < warp.LevelRequirement) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.STATUS_LABEL_NOT_READY_TO_USE_ENTRANCE, + " - LVL " + warp.LevelRequirement); } - private UnwalkableTileAction HandleWalkToTileSpec(IMapCellState cellState) + return UnwalkableTileAction.None; + } + + private UnwalkableTileAction HandleWalkToTileSpec(IMapCellState cellState) + { + switch (cellState.TileSpec) { - switch (cellState.TileSpec) - { - case TileSpec.ChairDown: - case TileSpec.ChairLeft: - case TileSpec.ChairRight: - case TileSpec.ChairUp: - case TileSpec.ChairDownRight: - case TileSpec.ChairUpLeft: - case TileSpec.ChairAll: - return UnwalkableTileAction.Chair; - case TileSpec.Chest: - return cellState.ChestKey.Match( - some: key => + case TileSpec.ChairDown: + case TileSpec.ChairLeft: + case TileSpec.ChairRight: + case TileSpec.ChairUp: + case TileSpec.ChairDownRight: + case TileSpec.ChairUpLeft: + case TileSpec.ChairAll: + return UnwalkableTileAction.Chair; + case TileSpec.Chest: + return cellState.ChestKey.Match( + some: key => + { + if (!_unlockChestValidator.CanMainCharacterOpenChest(key)) { - if (!_unlockChestValidator.CanMainCharacterOpenChest(key)) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.CHEST_LOCKED); - dlg.ShowDialog(); - - var requiredKey = _unlockChestValidator.GetRequiredKeyName(key); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_THE_CHEST_IS_LOCKED_EXCLAMATION, requiredKey.Match(x => $" - {x}", () => string.Empty)); - - _sfxPlayer.PlaySfx(SoundEffectID.DoorOrChestLocked); - - return UnwalkableTileAction.None; - } - else - { - return UnwalkableTileAction.Chest; - } - }, - none: () => + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.CHEST_LOCKED); + dlg.ShowDialog(); + + var requiredKey = _unlockChestValidator.GetRequiredKeyName(key); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_THE_CHEST_IS_LOCKED_EXCLAMATION, requiredKey.Match(x => $" - {x}", () => string.Empty)); + + _sfxPlayer.PlaySfx(SoundEffectID.DoorOrChestLocked); + + return UnwalkableTileAction.None; + } + else { return UnwalkableTileAction.Chest; - }); - case TileSpec.BankVault: - return UnwalkableTileAction.Locker; - case TileSpec.Board1: - case TileSpec.Board2: - case TileSpec.Board3: - case TileSpec.Board4: - case TileSpec.Board5: - case TileSpec.Board6: - case TileSpec.Board7: - case TileSpec.Board8: - return UnwalkableTileAction.Board; - case TileSpec.Jukebox: - return UnwalkableTileAction.Jukebox; - } - - return UnwalkableTileAction.None; + } + }, + none: () => + { + return UnwalkableTileAction.Chest; + }); + case TileSpec.BankVault: + return UnwalkableTileAction.Locker; + case TileSpec.Board1: + case TileSpec.Board2: + case TileSpec.Board3: + case TileSpec.Board4: + case TileSpec.Board5: + case TileSpec.Board6: + case TileSpec.Board7: + case TileSpec.Board8: + return UnwalkableTileAction.Board; + case TileSpec.Jukebox: + return UnwalkableTileAction.Jukebox; } - private Character MainCharacter => _characterProvider.MainCharacter; + + return UnwalkableTileAction.None; } + private Character MainCharacter => _characterProvider.MainCharacter; +} - public interface IUnwalkableTileActions - { - (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(); +public interface IUnwalkableTileActions +{ + (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(); - (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(int x, int y); + (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(int x, int y); - IReadOnlyList GetUnwalkableTileActions(IMapCellState mapCellState); - } + IReadOnlyList GetUnwalkableTileActions(IMapCellState mapCellState); } \ No newline at end of file diff --git a/EndlessClient/Input/UnwalkableTileActionsHandler.cs b/EndlessClient/Input/UnwalkableTileActionsHandler.cs index c09c702eb..a3bc993ac 100644 --- a/EndlessClient/Input/UnwalkableTileActionsHandler.cs +++ b/EndlessClient/Input/UnwalkableTileActionsHandler.cs @@ -4,59 +4,58 @@ using EOLib.Domain.Map; using System.Collections.Generic; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +[AutoMappedType] +public class UnwalkableTileActionsHandler : IUnwalkableTileActionsHandler { - [AutoMappedType] - public class UnwalkableTileActionsHandler : IUnwalkableTileActionsHandler - { - private readonly IMapActions _mapActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly ICharacterActions _characterActions; + private readonly IMapActions _mapActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly ICharacterActions _characterActions; - public UnwalkableTileActionsHandler(IMapActions mapActions, - IInGameDialogActions inGameDialogActions, - ICharacterActions characterActions) - { - _mapActions = mapActions; - _inGameDialogActions = inGameDialogActions; - _characterActions = characterActions; - } + public UnwalkableTileActionsHandler(IMapActions mapActions, + IInGameDialogActions inGameDialogActions, + ICharacterActions characterActions) + { + _mapActions = mapActions; + _inGameDialogActions = inGameDialogActions; + _characterActions = characterActions; + } - public void HandleUnwalkableTileActions(IReadOnlyList unwalkableActions, IMapCellState cellState) + public void HandleUnwalkableTileActions(IReadOnlyList unwalkableActions, IMapCellState cellState) + { + foreach (var action in unwalkableActions) { - foreach (var action in unwalkableActions) + switch (action) { - switch (action) - { - case UnwalkableTileAction.Chest: - _mapActions.OpenChest(cellState.Coordinate); - _inGameDialogActions.ShowChestDialog(); - break; - case UnwalkableTileAction.Locker: - _mapActions.OpenLocker(cellState.Coordinate); - _inGameDialogActions.ShowLockerDialog(); - break; - case UnwalkableTileAction.Chair: - _characterActions.Sit(cellState.Coordinate, isChair: true); - break; - case UnwalkableTileAction.Door: - cellState.Warp.MatchSome(w => _mapActions.OpenDoor(w)); - break; - case UnwalkableTileAction.Board: - _mapActions.OpenBoard(cellState.TileSpec); - _inGameDialogActions.ShowBoardDialog(); - break; - case UnwalkableTileAction.Jukebox: - _mapActions.OpenJukebox(cellState.Coordinate); - _inGameDialogActions.ShowJukeboxDialog(); - break; - } + case UnwalkableTileAction.Chest: + _mapActions.OpenChest(cellState.Coordinate); + _inGameDialogActions.ShowChestDialog(); + break; + case UnwalkableTileAction.Locker: + _mapActions.OpenLocker(cellState.Coordinate); + _inGameDialogActions.ShowLockerDialog(); + break; + case UnwalkableTileAction.Chair: + _characterActions.Sit(cellState.Coordinate, isChair: true); + break; + case UnwalkableTileAction.Door: + cellState.Warp.MatchSome(w => _mapActions.OpenDoor(w)); + break; + case UnwalkableTileAction.Board: + _mapActions.OpenBoard(cellState.TileSpec); + _inGameDialogActions.ShowBoardDialog(); + break; + case UnwalkableTileAction.Jukebox: + _mapActions.OpenJukebox(cellState.Coordinate); + _inGameDialogActions.ShowJukeboxDialog(); + break; } } } +} - public interface IUnwalkableTileActionsHandler - { - void HandleUnwalkableTileActions(IReadOnlyList unwalkableActions, IMapCellState cellState); - } +public interface IUnwalkableTileActionsHandler +{ + void HandleUnwalkableTileActions(IReadOnlyList unwalkableActions, IMapCellState cellState); } \ No newline at end of file diff --git a/EndlessClient/Input/UserInputHandler.cs b/EndlessClient/Input/UserInputHandler.cs index 376889d2f..2eb8dd56b 100644 --- a/EndlessClient/Input/UserInputHandler.cs +++ b/EndlessClient/Input/UserInputHandler.cs @@ -10,72 +10,71 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Input +namespace EndlessClient.Input; + +public class UserInputHandler : XNAControl, IUserInputHandler { - public class UserInputHandler : XNAControl, IUserInputHandler - { - private readonly List _handlers; - private readonly IActiveDialogProvider _activeDialogProvider; + private readonly List _handlers; + private readonly IActiveDialogProvider _activeDialogProvider; - public UserInputHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - IArrowKeyController arrowKeyController, - IControlKeyController controlKeyController, - IFunctionKeyController functionKeyController, - INumPadController numPadController, - IHudButtonController hudButtonController, - ICurrentMapStateRepository currentMapStateRepository, - IActiveDialogProvider activeDialogProvider, - IClientWindowSizeProvider clientWindowSizeProvider) + public UserInputHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + IArrowKeyController arrowKeyController, + IControlKeyController controlKeyController, + IFunctionKeyController functionKeyController, + INumPadController numPadController, + IHudButtonController hudButtonController, + ICurrentMapStateRepository currentMapStateRepository, + IActiveDialogProvider activeDialogProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _handlers = new List { - _handlers = new List - { - new ArrowKeyHandler(endlessGameProvider, - userInputProvider, - userInputTimeRepository, - arrowKeyController, - currentMapStateRepository), - new ControlKeyHandler(endlessGameProvider, - userInputProvider, - userInputTimeRepository, - controlKeyController, - currentMapStateRepository), - new FunctionKeyHandler(endlessGameProvider, - userInputProvider, - userInputTimeRepository, - functionKeyController, - currentMapStateRepository), - new NumPadHandler(endlessGameProvider, - userInputProvider, - userInputTimeRepository, - currentMapStateRepository, - numPadController), - }; - - if (clientWindowSizeProvider.Resizable) - { - _handlers.Add(new PanelShortcutHandler(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository, hudButtonController)); - } + new ArrowKeyHandler(endlessGameProvider, + userInputProvider, + userInputTimeRepository, + arrowKeyController, + currentMapStateRepository), + new ControlKeyHandler(endlessGameProvider, + userInputProvider, + userInputTimeRepository, + controlKeyController, + currentMapStateRepository), + new FunctionKeyHandler(endlessGameProvider, + userInputProvider, + userInputTimeRepository, + functionKeyController, + currentMapStateRepository), + new NumPadHandler(endlessGameProvider, + userInputProvider, + userInputTimeRepository, + currentMapStateRepository, + numPadController), + }; - _activeDialogProvider = activeDialogProvider; + if (clientWindowSizeProvider.Resizable) + { + _handlers.Add(new PanelShortcutHandler(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository, hudButtonController)); } - protected override void OnUpdateControl(GameTime gameTime) - { - if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) - return; + _activeDialogProvider = activeDialogProvider; + } - var timeAtBeginningOfUpdate = DateTime.Now; + protected override void OnUpdateControl(GameTime gameTime) + { + if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) + return; - foreach (var handler in _handlers) - handler.HandleKeyboardInput(timeAtBeginningOfUpdate); + var timeAtBeginningOfUpdate = DateTime.Now; - base.OnUpdateControl(gameTime); - } - } + foreach (var handler in _handlers) + handler.HandleKeyboardInput(timeAtBeginningOfUpdate); - public interface IUserInputHandler : IGameComponent - { + base.OnUpdateControl(gameTime); } +} + +public interface IUserInputHandler : IGameComponent +{ } \ No newline at end of file diff --git a/EndlessClient/Input/UserInputHandlerFactory.cs b/EndlessClient/Input/UserInputHandlerFactory.cs index 0b7a37162..9ea3484df 100644 --- a/EndlessClient/Input/UserInputHandlerFactory.cs +++ b/EndlessClient/Input/UserInputHandlerFactory.cs @@ -6,66 +6,65 @@ using EndlessClient.Rendering; using EOLib.Domain.Map; -namespace EndlessClient.Input -{ - [MappedType(BaseType = typeof(IUserInputHandlerFactory))] - public class UserInputHandlerFactory : IUserInputHandlerFactory - { - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly IUserInputTimeRepository _userInputTimeRepository; - private readonly IArrowKeyController _arrowKeyController; - private readonly IControlKeyController _controlKeyController; - private readonly IFunctionKeyController _functionKeyController; - private readonly INumPadController _numPadController; - private readonly IHudButtonController _hudButtonController; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; +namespace EndlessClient.Input; - public UserInputHandlerFactory(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - IArrowKeyController arrowKeyController, - IControlKeyController controlKeyController, - IFunctionKeyController functionKeyController, - INumPadController numPadController, - IHudButtonController hudButtonController, - ICurrentMapStateRepository currentMapStateRepository, - IActiveDialogProvider activeDialogProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _endlessGameProvider = endlessGameProvider; - _userInputProvider = userInputProvider; - _userInputTimeRepository = userInputTimeRepository; - _arrowKeyController = arrowKeyController; - _controlKeyController = controlKeyController; - _functionKeyController = functionKeyController; - _numPadController = numPadController; - _hudButtonController = hudButtonController; - _currentMapStateRepository = currentMapStateRepository; - _activeDialogProvider = activeDialogProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - } +[MappedType(BaseType = typeof(IUserInputHandlerFactory))] +public class UserInputHandlerFactory : IUserInputHandlerFactory +{ + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly IUserInputTimeRepository _userInputTimeRepository; + private readonly IArrowKeyController _arrowKeyController; + private readonly IControlKeyController _controlKeyController; + private readonly IFunctionKeyController _functionKeyController; + private readonly INumPadController _numPadController; + private readonly IHudButtonController _hudButtonController; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - public IUserInputHandler CreateUserInputHandler() - { - return new UserInputHandler(_endlessGameProvider, - _userInputProvider, - _userInputTimeRepository, - _arrowKeyController, - _controlKeyController, - _functionKeyController, - _numPadController, - _hudButtonController, - _currentMapStateRepository, - _activeDialogProvider, - _clientWindowSizeProvider); - } + public UserInputHandlerFactory(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + IArrowKeyController arrowKeyController, + IControlKeyController controlKeyController, + IFunctionKeyController functionKeyController, + INumPadController numPadController, + IHudButtonController hudButtonController, + ICurrentMapStateRepository currentMapStateRepository, + IActiveDialogProvider activeDialogProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _endlessGameProvider = endlessGameProvider; + _userInputProvider = userInputProvider; + _userInputTimeRepository = userInputTimeRepository; + _arrowKeyController = arrowKeyController; + _controlKeyController = controlKeyController; + _functionKeyController = functionKeyController; + _numPadController = numPadController; + _hudButtonController = hudButtonController; + _currentMapStateRepository = currentMapStateRepository; + _activeDialogProvider = activeDialogProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; } - public interface IUserInputHandlerFactory + public IUserInputHandler CreateUserInputHandler() { - IUserInputHandler CreateUserInputHandler(); + return new UserInputHandler(_endlessGameProvider, + _userInputProvider, + _userInputTimeRepository, + _arrowKeyController, + _controlKeyController, + _functionKeyController, + _numPadController, + _hudButtonController, + _currentMapStateRepository, + _activeDialogProvider, + _clientWindowSizeProvider); } +} + +public interface IUserInputHandlerFactory +{ + IUserInputHandler CreateUserInputHandler(); } \ No newline at end of file diff --git a/EndlessClient/Network/PacketHandlerGameComponent.cs b/EndlessClient/Network/PacketHandlerGameComponent.cs index cce3832a4..a7f11766d 100644 --- a/EndlessClient/Network/PacketHandlerGameComponent.cs +++ b/EndlessClient/Network/PacketHandlerGameComponent.cs @@ -6,47 +6,46 @@ using EOLib.Net.Handlers; using Microsoft.Xna.Framework; -namespace EndlessClient.Network +namespace EndlessClient.Network; + +[MappedType(BaseType = typeof(IGameComponent), IsSingleton = true)] +public class PacketHandlerGameComponent : GameComponent { - [MappedType(BaseType = typeof(IGameComponent), IsSingleton = true)] - public class PacketHandlerGameComponent : GameComponent + private readonly IOutOfBandPacketHandler _packetHandler; + private readonly INetworkClientProvider _networkClientProvider; + private readonly IBackgroundReceiveTaskRepository _backgroundReceiveTaskRepository; + private readonly IMainButtonController _mainButtonController; + + public PacketHandlerGameComponent(IEndlessGame game, + IOutOfBandPacketHandler packetHandler, + INetworkClientProvider networkClientProvider, + IBackgroundReceiveTaskRepository backgroundReceiveTaskRepository, + IMainButtonController mainButtonController) + : base((Game)game) { - private readonly IOutOfBandPacketHandler _packetHandler; - private readonly INetworkClientProvider _networkClientProvider; - private readonly IBackgroundReceiveTaskRepository _backgroundReceiveTaskRepository; - private readonly IMainButtonController _mainButtonController; - - public PacketHandlerGameComponent(IEndlessGame game, - IOutOfBandPacketHandler packetHandler, - INetworkClientProvider networkClientProvider, - IBackgroundReceiveTaskRepository backgroundReceiveTaskRepository, - IMainButtonController mainButtonController) - : base((Game)game) - { - _packetHandler = packetHandler; - _networkClientProvider = networkClientProvider; - _backgroundReceiveTaskRepository = backgroundReceiveTaskRepository; - _mainButtonController = mainButtonController; + _packetHandler = packetHandler; + _networkClientProvider = networkClientProvider; + _backgroundReceiveTaskRepository = backgroundReceiveTaskRepository; + _mainButtonController = mainButtonController; - UpdateOrder = int.MinValue; - } + UpdateOrder = int.MinValue; + } - public override void Update(GameTime gameTime) + public override void Update(GameTime gameTime) + { + if (_networkClientProvider.NetworkClient != null && _networkClientProvider.NetworkClient.Started) { - if (_networkClientProvider.NetworkClient != null && _networkClientProvider.NetworkClient.Started) - { - var connected = _networkClientProvider.NetworkClient.Connected; - var receiveLoopFaulted = _backgroundReceiveTaskRepository.Task?.IsFaulted ?? false; + var connected = _networkClientProvider.NetworkClient.Connected; + var receiveLoopFaulted = _backgroundReceiveTaskRepository.Task?.IsFaulted ?? false; - if (!connected || receiveLoopFaulted) - { - _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); - } + if (!connected || receiveLoopFaulted) + { + _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); } + } - _packetHandler.PollForPacketsAndHandle(); + _packetHandler.PollForPacketsAndHandle(); - base.Update(gameTime); - } + base.Update(gameTime); } } \ No newline at end of file diff --git a/EndlessClient/Network/UnknownEntitiesRequester.cs b/EndlessClient/Network/UnknownEntitiesRequester.cs index 53446e24f..ec1694f06 100644 --- a/EndlessClient/Network/UnknownEntitiesRequester.cs +++ b/EndlessClient/Network/UnknownEntitiesRequester.cs @@ -12,104 +12,103 @@ using System.Diagnostics; using System.Linq; -namespace EndlessClient.Network +namespace EndlessClient.Network; + +public class UnknownEntitiesRequester : GameComponent { - public class UnknownEntitiesRequester : GameComponent + private const int UPPER_SEE_DISTANCE = 12; + private const int LOWER_SEE_DISTANCE = 15; + + private const int REQUEST_INTERVAL_MS = 1000; + + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly INPCRendererProvider _npcRendererProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly IUnknownEntitiesRequestActions _unknownEntitiesRequestActions; + + private readonly Stopwatch _requestTimer; + + public UnknownEntitiesRequester(IEndlessGameProvider gameProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider, + ICurrentMapStateRepository currentMapStateRepository, + INPCRendererProvider npcRendererProvider, + ICharacterRendererProvider characterRendererProvider, + IUnknownEntitiesRequestActions unknownEntitiesRequestActions) + : base((Game)gameProvider.Game) { - private const int UPPER_SEE_DISTANCE = 12; - private const int LOWER_SEE_DISTANCE = 15; - - private const int REQUEST_INTERVAL_MS = 1000; - - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly INPCRendererProvider _npcRendererProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly IUnknownEntitiesRequestActions _unknownEntitiesRequestActions; - - private readonly Stopwatch _requestTimer; - - public UnknownEntitiesRequester(IEndlessGameProvider gameProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider, - ICurrentMapStateRepository currentMapStateRepository, - INPCRendererProvider npcRendererProvider, - ICharacterRendererProvider characterRendererProvider, - IUnknownEntitiesRequestActions unknownEntitiesRequestActions) - : base((Game)gameProvider.Game) - { - _clientWindowSizeProvider = clientWindowSizeProvider; - _characterProvider = characterProvider; - _currentMapStateRepository = currentMapStateRepository; - _npcRendererProvider = npcRendererProvider; - _characterRendererProvider = characterRendererProvider; - _unknownEntitiesRequestActions = unknownEntitiesRequestActions; - _requestTimer = Stopwatch.StartNew(); - } + _clientWindowSizeProvider = clientWindowSizeProvider; + _characterProvider = characterProvider; + _currentMapStateRepository = currentMapStateRepository; + _npcRendererProvider = npcRendererProvider; + _characterRendererProvider = characterRendererProvider; + _unknownEntitiesRequestActions = unknownEntitiesRequestActions; + _requestTimer = Stopwatch.StartNew(); + } - public override void Update(GameTime gameTime) + public override void Update(GameTime gameTime) + { + if (_requestTimer.ElapsedMilliseconds >= REQUEST_INTERVAL_MS) { - if (_requestTimer.ElapsedMilliseconds >= REQUEST_INTERVAL_MS) + ClearOutOfRangeActors(); + + if (_currentMapStateRepository.UnknownNPCIndexes.Count > 0 && _currentMapStateRepository.UnknownPlayerIDs.Count > 0) + { + _unknownEntitiesRequestActions.RequestAll(); + } + else if (_currentMapStateRepository.UnknownNPCIndexes.Count > 0) { - ClearOutOfRangeActors(); - - if (_currentMapStateRepository.UnknownNPCIndexes.Count > 0 && _currentMapStateRepository.UnknownPlayerIDs.Count > 0) - { - _unknownEntitiesRequestActions.RequestAll(); - } - else if (_currentMapStateRepository.UnknownNPCIndexes.Count > 0) - { - _unknownEntitiesRequestActions.RequestUnknownNPCs(); - } - else if (_currentMapStateRepository.UnknownPlayerIDs.Count > 0) - { - _unknownEntitiesRequestActions.RequestUnknownPlayers(); - } - - _requestTimer.Restart(); + _unknownEntitiesRequestActions.RequestUnknownNPCs(); + } + else if (_currentMapStateRepository.UnknownPlayerIDs.Count > 0) + { + _unknownEntitiesRequestActions.RequestUnknownPlayers(); } - base.Update(gameTime); + _requestTimer.Restart(); } - private void ClearOutOfRangeActors() - { - var mc = _characterProvider.MainCharacter; + base.Update(gameTime); + } + + private void ClearOutOfRangeActors() + { + var mc = _characterProvider.MainCharacter; - var entities = new List(_currentMapStateRepository.Characters) - .Concat(_currentMapStateRepository.NPCs) - .Concat(_currentMapStateRepository.MapItems); + var entities = new List(_currentMapStateRepository.Characters) + .Concat(_currentMapStateRepository.NPCs) + .Concat(_currentMapStateRepository.MapItems); - var seeDistanceUpper = (int)(_clientWindowSizeProvider.Height / 480.0 * UPPER_SEE_DISTANCE); - var seeDistanceLower = (int)(_clientWindowSizeProvider.Height / 480.0 * LOWER_SEE_DISTANCE); + var seeDistanceUpper = (int)(_clientWindowSizeProvider.Height / 480.0 * UPPER_SEE_DISTANCE); + var seeDistanceLower = (int)(_clientWindowSizeProvider.Height / 480.0 * LOWER_SEE_DISTANCE); - var entitiesToRemove = new List(); - foreach (var entity in entities) + var entitiesToRemove = new List(); + foreach (var entity in entities) + { + var xDiff = Math.Abs(mc.X - entity.X); + var yDiff = Math.Abs(mc.Y - entity.Y); + + if (entity.X < mc.X || entity.Y < mc.Y) { - var xDiff = Math.Abs(mc.X - entity.X); - var yDiff = Math.Abs(mc.Y - entity.Y); - - if (entity.X < mc.X || entity.Y < mc.Y) - { - if (xDiff + yDiff > seeDistanceUpper) - entitiesToRemove.Add(entity); - } - else if (xDiff + yDiff > seeDistanceLower) - { + if (xDiff + yDiff > seeDistanceUpper) entitiesToRemove.Add(entity); - } } - - foreach (var entity in entitiesToRemove) + else if (xDiff + yDiff > seeDistanceLower) { - if (entity is Character c && _characterRendererProvider.CharacterRenderers.ContainsKey(c.ID)) - _currentMapStateRepository.Characters.Remove(c); - else if (entity is NPC n && _npcRendererProvider.NPCRenderers.ContainsKey(n.Index)) - _currentMapStateRepository.NPCs.Remove(n); - else if (entity is MapItem i) - _currentMapStateRepository.MapItems.Remove(i); + entitiesToRemove.Add(entity); } } + + foreach (var entity in entitiesToRemove) + { + if (entity is Character c && _characterRendererProvider.CharacterRenderers.ContainsKey(c.ID)) + _currentMapStateRepository.Characters.Remove(c); + else if (entity is NPC n && _npcRendererProvider.NPCRenderers.ContainsKey(n.Index)) + _currentMapStateRepository.NPCs.Remove(n); + else if (entity is MapItem i) + _currentMapStateRepository.MapItems.Remove(i); + } } } \ No newline at end of file diff --git a/EndlessClient/Program.cs b/EndlessClient/Program.cs index 3b86ced2b..47a8c09b3 100644 --- a/EndlessClient/Program.cs +++ b/EndlessClient/Program.cs @@ -3,36 +3,35 @@ using System; using System.Reflection; -namespace EndlessClient +namespace EndlessClient; + +public static class Program { - public static class Program - { - private static IGameRunner _gameRunner; + private static IGameRunner _gameRunner; - [STAThread] - public static void Main(string[] args) + [STAThread] + public static void Main(string[] args) + { + var assemblyNames = new[] { - var assemblyNames = new[] - { - Assembly.GetExecutingAssembly().FullName, - "EOLib", - "EOLib.Config", - "EOLib.Graphics", - "EOLib.IO", - "EOLib.Localization", - "EOLib.Logger" - }; + Assembly.GetExecutingAssembly().FullName, + "EOLib", + "EOLib.Config", + "EOLib.Graphics", + "EOLib.IO", + "EOLib.Localization", + "EOLib.Logger" + }; - using (ITypeRegistry registry = new UnityRegistry(assemblyNames)) - { + using (ITypeRegistry registry = new UnityRegistry(assemblyNames)) + { #if DEBUG - _gameRunner = new DebugGameRunner(registry, args); + _gameRunner = new DebugGameRunner(registry, args); #else - _gameRunner = new ReleaseGameRunner(registry, args); + _gameRunner = new ReleaseGameRunner(registry, args); #endif - if (_gameRunner.SetupDependencies()) - _gameRunner.RunGame(); - } + if (_gameRunner.SetupDependencies()) + _gameRunner.RunGame(); } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterAnimationActions.cs b/EndlessClient/Rendering/Character/CharacterAnimationActions.cs index ae352a600..6e55d1228 100644 --- a/EndlessClient/Rendering/Character/CharacterAnimationActions.cs +++ b/EndlessClient/Rendering/Character/CharacterAnimationActions.cs @@ -25,418 +25,417 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +[AutoMappedType] +public class CharacterAnimationActions : ICharacterAnimationActions, IOtherCharacterAnimationNotifier, IEffectNotifier, IEmoteNotifier { - [AutoMappedType] - public class CharacterAnimationActions : ICharacterAnimationActions, IOtherCharacterAnimationNotifier, IEffectNotifier, IEmoteNotifier + private readonly IHudControlProvider _hudControlProvider; + private readonly ICharacterRepository _characterRepository; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IPubFileProvider _pubFileProvider; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ISfxPlayer _sfxPlayer; + private readonly IMetadataProvider _weaponMetadataProvider; + + private readonly Random _random; + + public CharacterAnimationActions(IHudControlProvider hudControlProvider, + ICharacterRepository characterRepository, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterRendererProvider characterRendererProvider, + ICurrentMapProvider currentMapProvider, + IPubFileProvider pubFileProvider, + IStatusLabelSetter statusLabelSetter, + ISfxPlayer sfxPlayer, + IMetadataProvider weaponMetadataProvider) { - private readonly IHudControlProvider _hudControlProvider; - private readonly ICharacterRepository _characterRepository; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IPubFileProvider _pubFileProvider; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ISfxPlayer _sfxPlayer; - private readonly IMetadataProvider _weaponMetadataProvider; - - private readonly Random _random; - - public CharacterAnimationActions(IHudControlProvider hudControlProvider, - ICharacterRepository characterRepository, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterRendererProvider characterRendererProvider, - ICurrentMapProvider currentMapProvider, - IPubFileProvider pubFileProvider, - IStatusLabelSetter statusLabelSetter, - ISfxPlayer sfxPlayer, - IMetadataProvider weaponMetadataProvider) - { - _hudControlProvider = hudControlProvider; - _characterRepository = characterRepository; - _currentMapStateProvider = currentMapStateProvider; - _characterRendererProvider = characterRendererProvider; - _currentMapProvider = currentMapProvider; - _pubFileProvider = pubFileProvider; - _statusLabelSetter = statusLabelSetter; - _sfxPlayer = sfxPlayer; - _weaponMetadataProvider = weaponMetadataProvider; - _random = new Random(); - } + _hudControlProvider = hudControlProvider; + _characterRepository = characterRepository; + _currentMapStateProvider = currentMapStateProvider; + _characterRendererProvider = characterRendererProvider; + _currentMapProvider = currentMapProvider; + _pubFileProvider = pubFileProvider; + _statusLabelSetter = statusLabelSetter; + _sfxPlayer = sfxPlayer; + _weaponMetadataProvider = weaponMetadataProvider; + _random = new Random(); + } - public void Face(EODirection direction) - { - if (!_hudControlProvider.IsInGame) - return; + public void Face(EODirection direction) + { + if (!_hudControlProvider.IsInGame) + return; - CancelSpellPrep(); - Animator.MainCharacterFace(direction); - } + CancelSpellPrep(); + Animator.MainCharacterFace(direction); + } + + public void StartWalking(Option targetCoordinate, bool ghosted = false) + { + if (!_hudControlProvider.IsInGame) + return; - public void StartWalking(Option targetCoordinate, bool ghosted = false) + _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler).CancelArenaBlockTimer(); + + CancelSpellPrep(); + Animator.StartMainCharacterWalkAnimation(targetCoordinate, ghosted, () => { - if (!_hudControlProvider.IsInGame) - return; + PlayMainCharacterWalkSfx(); + ShowWaterSplashiesIfNeeded(CharacterActionState.Walking, _characterRepository.MainCharacter.ID); + }); + } - _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler).CancelArenaBlockTimer(); + public void CancelClickToWalk() + { + Animator.CancelClickToWalk(); + } - CancelSpellPrep(); - Animator.StartMainCharacterWalkAnimation(targetCoordinate, ghosted, () => - { - PlayMainCharacterWalkSfx(); - ShowWaterSplashiesIfNeeded(CharacterActionState.Walking, _characterRepository.MainCharacter.ID); - }); - } + public void StartAttacking(int noteIndex = -1) + { + if (!_hudControlProvider.IsInGame) + return; - public void CancelClickToWalk() - { - Animator.CancelClickToWalk(); - } + CancelSpellPrep(); - public void StartAttacking(int noteIndex = -1) - { - if (!_hudControlProvider.IsInGame) - return; + if (noteIndex >= 0 || IsInstrumentWeapon(_characterRepository.MainCharacter.RenderProperties.WeaponGraphic)) + Animator.Emote(_characterRepository.MainCharacter.ID, EOLib.Domain.Character.Emote.MusicNotes); + Animator.StartMainCharacterAttackAnimation(() => PlayWeaponSound(_characterRepository.MainCharacter, noteIndex)); + ShowWaterSplashiesIfNeeded(CharacterActionState.Attacking, _characterRepository.MainCharacter.ID); + } - CancelSpellPrep(); + public bool PrepareMainCharacterSpell(int spellId, ISpellTargetable spellTarget) + { + if (!_hudControlProvider.IsInGame) + return false; - if (noteIndex >= 0 || IsInstrumentWeapon(_characterRepository.MainCharacter.RenderProperties.WeaponGraphic)) - Animator.Emote(_characterRepository.MainCharacter.ID, EOLib.Domain.Character.Emote.MusicNotes); - Animator.StartMainCharacterAttackAnimation(() => PlayWeaponSound(_characterRepository.MainCharacter, noteIndex)); - ShowWaterSplashiesIfNeeded(CharacterActionState.Attacking, _characterRepository.MainCharacter.ID); - } + var spellData = _pubFileProvider.ESFFile[spellId]; + _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.ShoutSpellPrep(spellData.Shout)); + return Animator.MainCharacterShoutSpellPrep(spellData, spellTarget); + } - public bool PrepareMainCharacterSpell(int spellId, ISpellTargetable spellTarget) - { - if (!_hudControlProvider.IsInGame) - return false; + public void Emote(Emote whichEmote) + { + if (!_hudControlProvider.IsInGame) + return; - var spellData = _pubFileProvider.ESFFile[spellId]; - _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.ShoutSpellPrep(spellData.Shout)); - return Animator.MainCharacterShoutSpellPrep(spellData, spellTarget); - } + Animator.Emote(_characterRepository.MainCharacter.ID, whichEmote); + } - public void Emote(Emote whichEmote) - { - if (!_hudControlProvider.IsInGame) - return; + public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) + { + if (!_hudControlProvider.IsInGame || !_currentMapStateProvider.Characters.TryGetValue(characterID, out var character)) + return; - Animator.Emote(_characterRepository.MainCharacter.ID, whichEmote); - } + Animator.StartOtherCharacterWalkAnimation(characterID, destination, direction); - public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) - { - if (!_hudControlProvider.IsInGame || !_currentMapStateProvider.Characters.TryGetValue(characterID, out var character)) - return; + ShowWaterSplashiesIfNeeded(CharacterActionState.Walking, characterID); - Animator.StartOtherCharacterWalkAnimation(characterID, destination, direction); + if (IsSteppingStone(character.RenderProperties)) + _sfxPlayer.PlaySfx(SoundEffectID.JumpStone); + } - ShowWaterSplashiesIfNeeded(CharacterActionState.Walking, characterID); + public void StartOtherCharacterAttackAnimation(int characterID, int noteIndex = -1) + { + if (!_hudControlProvider.IsInGame || !_currentMapStateProvider.Characters.TryGetValue(characterID, out var character)) + return; - if (IsSteppingStone(character.RenderProperties)) - _sfxPlayer.PlaySfx(SoundEffectID.JumpStone); - } + if (noteIndex >= 0 || IsInstrumentWeapon(character.RenderProperties.WeaponGraphic)) + Animator.Emote(characterID, EOLib.Domain.Character.Emote.MusicNotes); - public void StartOtherCharacterAttackAnimation(int characterID, int noteIndex = -1) - { - if (!_hudControlProvider.IsInGame || !_currentMapStateProvider.Characters.TryGetValue(characterID, out var character)) - return; + Animator.StartOtherCharacterAttackAnimation(characterID, () => PlayWeaponSound(character, noteIndex)); + ShowWaterSplashiesIfNeeded(CharacterActionState.Attacking, characterID); + } - if (noteIndex >= 0 || IsInstrumentWeapon(character.RenderProperties.WeaponGraphic)) - Animator.Emote(characterID, EOLib.Domain.Character.Emote.MusicNotes); + public void NotifyWarpLeaveEffect(int characterId, WarpEffect anim) + { + if (anim == WarpEffect.Admin && _characterRendererProvider.CharacterRenderers.ContainsKey(characterId)) + _characterRendererProvider.CharacterRenderers[characterId].PlayEffect((int)HardCodedEffect.WarpLeave); + else if (characterId != _characterRepository.MainCharacter.ID && anim == WarpEffect.Scroll) + _sfxPlayer.PlaySfx(SoundEffectID.ScrollTeleport); + } - Animator.StartOtherCharacterAttackAnimation(characterID, () => PlayWeaponSound(character, noteIndex)); - ShowWaterSplashiesIfNeeded(CharacterActionState.Attacking, characterID); + public void NotifyWarpEnterEffect(int characterId, WarpEffect anim) + { + if (anim == WarpEffect.Admin) + { + if (!_characterRendererProvider.CharacterRenderers.ContainsKey(characterId)) + _characterRendererProvider.NeedsWarpArriveAnimation.Add(characterId); + else + _characterRendererProvider.CharacterRenderers[characterId].PlayEffect((int)HardCodedEffect.WarpArrive); } + } + + public void NotifyPotionEffect(int playerId, int effectId) + { + if (playerId == _characterRepository.MainCharacter.ID) + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.PlayEffect(effectId + 1)); + else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) + _characterRendererProvider.CharacterRenderers[playerId].PlayEffect(effectId + 1); + } + + public void NotifyStartSpellCast(int playerId, int spellId) + { + var shoutName = _pubFileProvider.ESFFile[spellId].Shout; + _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellPrep(shoutName.ToLower()); + } - public void NotifyWarpLeaveEffect(int characterId, WarpEffect anim) + public void NotifyTargetNpcSpellCast(int playerId) + { + // Main player starts its spell cast animation immediately when targeting NPC + // Other players need to wait for packet to be received and do it here + // this is some spaghetti... + if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) { - if (anim == WarpEffect.Admin && _characterRendererProvider.CharacterRenderers.ContainsKey(characterId)) - _characterRendererProvider.CharacterRenderers[characterId].PlayEffect((int)HardCodedEffect.WarpLeave); - else if (characterId != _characterRepository.MainCharacter.ID && anim == WarpEffect.Scroll) - _sfxPlayer.PlaySfx(SoundEffectID.ScrollTeleport); + Animator.StartOtherCharacterSpellCast(playerId); } + } - public void NotifyWarpEnterEffect(int characterId, WarpEffect anim) + public void NotifySelfSpellCast(int playerId, int spellId, int spellHp, int percentHealth) + { + var spellGraphic = _pubFileProvider.ESFFile[spellId].Graphic; + + if (playerId == _characterRepository.MainCharacter.ID) { - if (anim == WarpEffect.Admin) + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => { - if (!_characterRendererProvider.CharacterRenderers.ContainsKey(characterId)) - _characterRendererProvider.NeedsWarpArriveAnimation.Add(characterId); - else - _characterRendererProvider.CharacterRenderers[characterId].PlayEffect((int)HardCodedEffect.WarpArrive); - } + cr.ShoutSpellCast(); + cr.PlayEffect(spellGraphic); + cr.ShowDamageCounter(spellHp, percentHealth, isHeal: true); + }); } - - public void NotifyPotionEffect(int playerId, int effectId) + else { - if (playerId == _characterRepository.MainCharacter.ID) - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.PlayEffect(effectId + 1)); - else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) - _characterRendererProvider.CharacterRenderers[playerId].PlayEffect(effectId + 1); + Animator.StartOtherCharacterSpellCast(playerId); + _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellCast(); + _characterRendererProvider.CharacterRenderers[playerId].PlayEffect(spellGraphic); + _characterRendererProvider.CharacterRenderers[playerId].ShowDamageCounter(spellHp, percentHealth, isHeal: true); } + } - public void NotifyStartSpellCast(int playerId, int spellId) + public void NotifyTargetOtherSpellCast(int sourcePlayerID, int targetPlayerID, int spellId, int recoveredHP, int targetPercentHealth) + { + if (sourcePlayerID == _characterRepository.MainCharacter.ID) { - var shoutName = _pubFileProvider.ESFFile[spellId].Shout; - _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellPrep(shoutName.ToLower()); + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.ShoutSpellCast()); } - - public void NotifyTargetNpcSpellCast(int playerId) + else { - // Main player starts its spell cast animation immediately when targeting NPC - // Other players need to wait for packet to be received and do it here - // this is some spaghetti... - if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) - { - Animator.StartOtherCharacterSpellCast(playerId); - } + Animator.StartOtherCharacterSpellCast(sourcePlayerID); + _characterRendererProvider.CharacterRenderers[sourcePlayerID].ShoutSpellCast(); } - public void NotifySelfSpellCast(int playerId, int spellId, int spellHp, int percentHealth) - { - var spellGraphic = _pubFileProvider.ESFFile[spellId].Graphic; + var spellData = _pubFileProvider.ESFFile[spellId]; - if (playerId == _characterRepository.MainCharacter.ID) - { - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => - { - cr.ShoutSpellCast(); - cr.PlayEffect(spellGraphic); - cr.ShowDamageCounter(spellHp, percentHealth, isHeal: true); - }); - } - else + if (targetPlayerID == _characterRepository.MainCharacter.ID) + { + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => { - Animator.StartOtherCharacterSpellCast(playerId); - _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellCast(); - _characterRendererProvider.CharacterRenderers[playerId].PlayEffect(spellGraphic); - _characterRendererProvider.CharacterRenderers[playerId].ShowDamageCounter(spellHp, percentHealth, isHeal: true); - } + cr.PlayEffect(spellData.Graphic); + cr.ShowDamageCounter(recoveredHP, targetPercentHealth, isHeal: spellData.Type == EOLib.IO.SpellType.Heal); + }); } + else + { + _characterRendererProvider.CharacterRenderers[targetPlayerID].PlayEffect(spellData.Graphic); + _characterRendererProvider.CharacterRenderers[targetPlayerID].ShowDamageCounter(recoveredHP, targetPercentHealth, isHeal: spellData.Type == EOLib.IO.SpellType.Heal); + } + } - public void NotifyTargetOtherSpellCast(int sourcePlayerID, int targetPlayerID, int spellId, int recoveredHP, int targetPercentHealth) + public void NotifyGroupSpellCast(int playerId, int spellId, int spellHp, List spellTargets) + { + if (playerId == _characterRepository.MainCharacter.ID) { - if (sourcePlayerID == _characterRepository.MainCharacter.ID) - { - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.ShoutSpellCast()); - } - else - { - Animator.StartOtherCharacterSpellCast(sourcePlayerID); - _characterRendererProvider.CharacterRenderers[sourcePlayerID].ShoutSpellCast(); - } + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.ShoutSpellCast()); + } + else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) + { + Animator.StartOtherCharacterSpellCast(playerId); + _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellCast(); + } - var spellData = _pubFileProvider.ESFFile[spellId]; + var spellData = _pubFileProvider.ESFFile[spellId]; - if (targetPlayerID == _characterRepository.MainCharacter.ID) + foreach (var target in spellTargets) + { + if (target.TargetId == _characterRepository.MainCharacter.ID) { _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => { cr.PlayEffect(spellData.Graphic); - cr.ShowDamageCounter(recoveredHP, targetPercentHealth, isHeal: spellData.Type == EOLib.IO.SpellType.Heal); + cr.ShowDamageCounter(spellHp, target.PercentHealth, isHeal: true); }); } - else + else if (_characterRendererProvider.CharacterRenderers.ContainsKey(target.TargetId)) { - _characterRendererProvider.CharacterRenderers[targetPlayerID].PlayEffect(spellData.Graphic); - _characterRendererProvider.CharacterRenderers[targetPlayerID].ShowDamageCounter(recoveredHP, targetPercentHealth, isHeal: spellData.Type == EOLib.IO.SpellType.Heal); + _characterRendererProvider.CharacterRenderers[target.TargetId].PlayEffect(spellData.Graphic); + _characterRendererProvider.CharacterRenderers[target.TargetId].ShowDamageCounter(spellHp, target.PercentHealth, isHeal: true); } } + } - public void NotifyGroupSpellCast(int playerId, int spellId, int spellHp, List spellTargets) + public void NotifyMapEffect(EOLib.IO.Map.MapEffect effect, int strength = 0) + { + switch (effect) { - if (playerId == _characterRepository.MainCharacter.ID) - { - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.ShoutSpellCast()); - } - else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) - { - Animator.StartOtherCharacterSpellCast(playerId); - _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellCast(); - } - - var spellData = _pubFileProvider.ESFFile[spellId]; - - foreach (var target in spellTargets) - { - if (target.TargetId == _characterRepository.MainCharacter.ID) - { - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => - { - cr.PlayEffect(spellData.Graphic); - cr.ShowDamageCounter(spellHp, target.PercentHealth, isHeal: true); - }); - } - else if (_characterRendererProvider.CharacterRenderers.ContainsKey(target.TargetId)) - { - _characterRendererProvider.CharacterRenderers[target.TargetId].PlayEffect(spellData.Graphic); - _characterRendererProvider.CharacterRenderers[target.TargetId].ShowDamageCounter(spellHp, target.PercentHealth, isHeal: true); - } - } + case EOLib.IO.Map.MapEffect.Quake1: + case EOLib.IO.Map.MapEffect.Quake2: + case EOLib.IO.Map.MapEffect.Quake3: + case EOLib.IO.Map.MapEffect.Quake4: + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + mapRenderer.StartEarthquake(strength); + _sfxPlayer.PlaySfx(SoundEffectID.Earthquake); + break; + case EOLib.IO.Map.MapEffect.HPDrain: + _sfxPlayer.PlaySfx(SoundEffectID.MapEffectHPDrain); + break; + case EOLib.IO.Map.MapEffect.TPDrain: + _sfxPlayer.PlaySfx(SoundEffectID.MapEffectTPDrain); + break; + case EOLib.IO.Map.MapEffect.Spikes: + _sfxPlayer.PlaySfx(SoundEffectID.Spikes); + break; } + } - public void NotifyMapEffect(EOLib.IO.Map.MapEffect effect, int strength = 0) + public void NotifyEmote(int playerId, Emote emote) + { + switch (emote) { - switch (effect) - { - case EOLib.IO.Map.MapEffect.Quake1: - case EOLib.IO.Map.MapEffect.Quake2: - case EOLib.IO.Map.MapEffect.Quake3: - case EOLib.IO.Map.MapEffect.Quake4: - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - mapRenderer.StartEarthquake(strength); - _sfxPlayer.PlaySfx(SoundEffectID.Earthquake); - break; - case EOLib.IO.Map.MapEffect.HPDrain: - _sfxPlayer.PlaySfx(SoundEffectID.MapEffectHPDrain); - break; - case EOLib.IO.Map.MapEffect.TPDrain: - _sfxPlayer.PlaySfx(SoundEffectID.MapEffectTPDrain); - break; - case EOLib.IO.Map.MapEffect.Spikes: - _sfxPlayer.PlaySfx(SoundEffectID.Spikes); - break; - } + case EOLib.Domain.Character.Emote.Trade: + _sfxPlayer.PlaySfx(SoundEffectID.TradeAccepted); + break; + case EOLib.Domain.Character.Emote.LevelUp: + _sfxPlayer.PlaySfx(SoundEffectID.LevelUp); + break; } - public void NotifyEmote(int playerId, Emote emote) + try { - switch (emote) - { - case EOLib.Domain.Character.Emote.Trade: - _sfxPlayer.PlaySfx(SoundEffectID.TradeAccepted); - break; - case EOLib.Domain.Character.Emote.LevelUp: - _sfxPlayer.PlaySfx(SoundEffectID.LevelUp); - break; - } - - try - { - Animator.Emote(playerId, emote); - } - catch (InvalidOperationException) - { - // if still transitioning to in-game state, the game will crash because the in-game control set is not completely set up yet - } + Animator.Emote(playerId, emote); } - - public void MakeMainPlayerDrunk() + catch (InvalidOperationException) { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_USE_DRUNK); + // if still transitioning to in-game state, the game will crash because the in-game control set is not completely set up yet } + } - public void NotifyEffectAtLocation(MapCoordinate location, int effectId) - { - if (_hudControlProvider.IsInGame) - { - _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer) - .RenderEffect(location, effectId); - } - } - public void NotifyAdminHideEffect(int playerId) + public void MakeMainPlayerDrunk() + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_USE_DRUNK); + } + + public void NotifyEffectAtLocation(MapCoordinate location, int effectId) + { + if (_hudControlProvider.IsInGame) { - if (playerId == _characterRepository.MainCharacter.ID) - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.PlayEffect((int)HardCodedEffect.AdminHide)); - else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) - _characterRendererProvider.CharacterRenderers[playerId].PlayEffect((int)HardCodedEffect.AdminHide); + _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer) + .RenderEffect(location, effectId); } + } + public void NotifyAdminHideEffect(int playerId) + { + if (playerId == _characterRepository.MainCharacter.ID) + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.PlayEffect((int)HardCodedEffect.AdminHide)); + else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) + _characterRendererProvider.CharacterRenderers[playerId].PlayEffect((int)HardCodedEffect.AdminHide); + } + + private void ShowWaterSplashiesIfNeeded(CharacterActionState action, int characterID) + { + var characterRenderer = characterID == _characterRepository.MainCharacter.ID + ? _characterRendererProvider.MainCharacterRenderer + : _characterRendererProvider.CharacterRenderers.ContainsKey(characterID) + ? Option.Some(_characterRendererProvider.CharacterRenderers[characterID]) + : Option.None(); - private void ShowWaterSplashiesIfNeeded(CharacterActionState action, int characterID) + characterRenderer.MatchSome(cr => { - var characterRenderer = characterID == _characterRepository.MainCharacter.ID - ? _characterRendererProvider.MainCharacterRenderer - : _characterRendererProvider.CharacterRenderers.ContainsKey(characterID) - ? Option.Some(_characterRendererProvider.CharacterRenderers[characterID]) - : Option.None(); + var rp = cr.Character.RenderProperties; - characterRenderer.MatchSome(cr => + if (action == CharacterActionState.Attacking) { - var rp = cr.Character.RenderProperties; - - if (action == CharacterActionState.Attacking) + if (_currentMapProvider.CurrentMap.Tiles[rp.MapY, rp.MapX] == TileSpec.Water) { - if (_currentMapProvider.CurrentMap.Tiles[rp.MapY, rp.MapX] == TileSpec.Water) - { - cr.PlayEffect((int)HardCodedEffect.WaterSplashies); - _sfxPlayer.PlaySfx(SoundEffectID.Water); - } + cr.PlayEffect((int)HardCodedEffect.WaterSplashies); + _sfxPlayer.PlaySfx(SoundEffectID.Water); } - else if (action == CharacterActionState.Walking) + } + else if (action == CharacterActionState.Walking) + { + if (_currentMapProvider.CurrentMap.Tiles[rp.GetDestinationY(), rp.GetDestinationX()] == TileSpec.Water) { - if (_currentMapProvider.CurrentMap.Tiles[rp.GetDestinationY(), rp.GetDestinationX()] == TileSpec.Water) - { - cr.PlayEffect((int)HardCodedEffect.WaterSplashies); - _sfxPlayer.PlaySfx(SoundEffectID.Water); - } + cr.PlayEffect((int)HardCodedEffect.WaterSplashies); + _sfxPlayer.PlaySfx(SoundEffectID.Water); } - }); - } + } + }); + } - private void CancelSpellPrep() - { - Animator.MainCharacterCancelSpellPrep(); - _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.StopShout()); - } + private void CancelSpellPrep() + { + Animator.MainCharacterCancelSpellPrep(); + _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.StopShout()); + } - private void PlayMainCharacterWalkSfx() - { - if (_characterRepository.MainCharacter.NoWall) - _sfxPlayer.PlaySfx(SoundEffectID.NoWallWalk); - else if (IsSteppingStone(_characterRepository.MainCharacter.RenderProperties)) - _sfxPlayer.PlaySfx(SoundEffectID.JumpStone); - } + private void PlayMainCharacterWalkSfx() + { + if (_characterRepository.MainCharacter.NoWall) + _sfxPlayer.PlaySfx(SoundEffectID.NoWallWalk); + else if (IsSteppingStone(_characterRepository.MainCharacter.RenderProperties)) + _sfxPlayer.PlaySfx(SoundEffectID.JumpStone); + } - private void PlayWeaponSound(EOLib.Domain.Character.Character character, int noteIndex = -1) - { - var weaponMetadata = _weaponMetadataProvider.GetValueOrDefault(character.RenderProperties.WeaponGraphic); + private void PlayWeaponSound(EOLib.Domain.Character.Character character, int noteIndex = -1) + { + var weaponMetadata = _weaponMetadataProvider.GetValueOrDefault(character.RenderProperties.WeaponGraphic); - if (noteIndex >= 0 && noteIndex < 36) + if (noteIndex >= 0 && noteIndex < 36) + { + var firstSfx = weaponMetadata.SFX.FirstOrDefault(); + if (firstSfx == SoundEffectID.Harp1) { - var firstSfx = weaponMetadata.SFX.FirstOrDefault(); - if (firstSfx == SoundEffectID.Harp1) - { - _sfxPlayer.PlayHarpNote(noteIndex); - } - else if (firstSfx == SoundEffectID.Guitar1) - { - _sfxPlayer.PlayGuitarNote(noteIndex); - } + _sfxPlayer.PlayHarpNote(noteIndex); } - else + else if (firstSfx == SoundEffectID.Guitar1) { - var index = _random.Next(0, weaponMetadata.SFX.Length); - _sfxPlayer.PlaySfx(weaponMetadata.SFX[index]); + _sfxPlayer.PlayGuitarNote(noteIndex); } } - - private bool IsInstrumentWeapon(int weaponGraphic) - { - return Constants.Instruments.Any(x => x == weaponGraphic); - } - - private bool IsSteppingStone(CharacterRenderProperties renderProps) + else { - return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump - || _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump; + var index = _random.Next(0, weaponMetadata.SFX.Length); + _sfxPlayer.PlaySfx(weaponMetadata.SFX[index]); } + } - private ICharacterAnimator Animator => _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator); + private bool IsInstrumentWeapon(int weaponGraphic) + { + return Constants.Instruments.Any(x => x == weaponGraphic); } - public interface ICharacterAnimationActions + private bool IsSteppingStone(CharacterRenderProperties renderProps) { - void Face(EODirection direction); + return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump + || _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump; + } - void StartWalking(Option targetCoordinate, bool ghosted = false); + private ICharacterAnimator Animator => _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator); +} - void CancelClickToWalk(); +public interface ICharacterAnimationActions +{ + void Face(EODirection direction); - void StartAttacking(int noteIndex = -1); + void StartWalking(Option targetCoordinate, bool ghosted = false); - bool PrepareMainCharacterSpell(int spellId, ISpellTargetable spellTarget); + void CancelClickToWalk(); - void Emote(Emote whichEmote); - } + void StartAttacking(int noteIndex = -1); + + bool PrepareMainCharacterSpell(int spellId, ISpellTargetable spellTarget); + + void Emote(Emote whichEmote); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterAnimator.cs b/EndlessClient/Rendering/Character/CharacterAnimator.cs index 496a02f01..c6ac50068 100644 --- a/EndlessClient/Rendering/Character/CharacterAnimator.cs +++ b/EndlessClient/Rendering/Character/CharacterAnimator.cs @@ -17,596 +17,595 @@ using System.Diagnostics; using System.Linq; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +public class CharacterAnimator : GameComponent, ICharacterAnimator { - public class CharacterAnimator : GameComponent, ICharacterAnimator + public const int TICKS_PER_WALK_FRAME = 9; // 9 x10ms ticks per walk frame + public const int TICKS_PER_FRAME = 12; // 12 x10ms ticks per attack frame + public const int TICKS_PER_CAST_TIME = 48; + + private readonly ICharacterRepository _characterRepository; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly ICharacterActions _characterActions; + private readonly IWalkValidationActions _walkValidationActions; + private readonly IPathFinder _pathFinder; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + private readonly IMetadataProvider _weaponMetadataProvider; + + // todo: this state should really be managed better + private readonly Dictionary _queuedDirections; + private readonly Dictionary _queuedPositions; + private readonly Dictionary _otherPlayerStartWalkingTimes; + private readonly Dictionary _otherPlayerStartAttackingTimes; + private readonly Dictionary _otherPlayerStartSpellCastTimes; + private readonly Dictionary _startEmoteTimes; + + private Option _mainPlayerStartShoutTick; + private ESFRecord _shoutSpellData; + private ISpellTargetable _spellTarget; + + private Queue _walkPath; + private Option _targetCoordinate; + + public CharacterAnimator(IEndlessGameProvider gameProvider, + ICharacterRepository characterRepository, + ICurrentMapStateRepository currentMapStateRepository, + ICurrentMapProvider currentMapProvider, + ISpellSlotDataRepository spellSlotDataRepository, + ICharacterActions characterActions, + IWalkValidationActions walkValidationActions, + IPathFinder pathFinder, + IFixedTimeStepRepository fixedTimeStepRepository, + IMetadataProvider weaponMetadataProvider) + : base((Game)gameProvider.Game) { - public const int TICKS_PER_WALK_FRAME = 9; // 9 x10ms ticks per walk frame - public const int TICKS_PER_FRAME = 12; // 12 x10ms ticks per attack frame - public const int TICKS_PER_CAST_TIME = 48; - - private readonly ICharacterRepository _characterRepository; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly ICharacterActions _characterActions; - private readonly IWalkValidationActions _walkValidationActions; - private readonly IPathFinder _pathFinder; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - private readonly IMetadataProvider _weaponMetadataProvider; - - // todo: this state should really be managed better - private readonly Dictionary _queuedDirections; - private readonly Dictionary _queuedPositions; - private readonly Dictionary _otherPlayerStartWalkingTimes; - private readonly Dictionary _otherPlayerStartAttackingTimes; - private readonly Dictionary _otherPlayerStartSpellCastTimes; - private readonly Dictionary _startEmoteTimes; - - private Option _mainPlayerStartShoutTick; - private ESFRecord _shoutSpellData; - private ISpellTargetable _spellTarget; - - private Queue _walkPath; - private Option _targetCoordinate; - - public CharacterAnimator(IEndlessGameProvider gameProvider, - ICharacterRepository characterRepository, - ICurrentMapStateRepository currentMapStateRepository, - ICurrentMapProvider currentMapProvider, - ISpellSlotDataRepository spellSlotDataRepository, - ICharacterActions characterActions, - IWalkValidationActions walkValidationActions, - IPathFinder pathFinder, - IFixedTimeStepRepository fixedTimeStepRepository, - IMetadataProvider weaponMetadataProvider) - : base((Game)gameProvider.Game) - { - _characterRepository = characterRepository; - _currentMapStateRepository = currentMapStateRepository; - _currentMapProvider = currentMapProvider; - _spellSlotDataRepository = spellSlotDataRepository; - _characterActions = characterActions; - _walkValidationActions = walkValidationActions; - _pathFinder = pathFinder; - _fixedTimeStepRepository = fixedTimeStepRepository; - _weaponMetadataProvider = weaponMetadataProvider; - _queuedDirections = new Dictionary(); - _queuedPositions = new Dictionary(); - _otherPlayerStartWalkingTimes = new Dictionary(); - _otherPlayerStartAttackingTimes = new Dictionary(); - _otherPlayerStartSpellCastTimes = new Dictionary(); - _startEmoteTimes = new Dictionary(); - - _walkPath = new Queue(); - } + _characterRepository = characterRepository; + _currentMapStateRepository = currentMapStateRepository; + _currentMapProvider = currentMapProvider; + _spellSlotDataRepository = spellSlotDataRepository; + _characterActions = characterActions; + _walkValidationActions = walkValidationActions; + _pathFinder = pathFinder; + _fixedTimeStepRepository = fixedTimeStepRepository; + _weaponMetadataProvider = weaponMetadataProvider; + _queuedDirections = new Dictionary(); + _queuedPositions = new Dictionary(); + _otherPlayerStartWalkingTimes = new Dictionary(); + _otherPlayerStartAttackingTimes = new Dictionary(); + _otherPlayerStartSpellCastTimes = new Dictionary(); + _startEmoteTimes = new Dictionary(); + + _walkPath = new Queue(); + } - public override void Update(GameTime gameTime) + public override void Update(GameTime gameTime) + { + if (_fixedTimeStepRepository.IsWalkUpdateFrame) { - if (_fixedTimeStepRepository.IsWalkUpdateFrame) - { - AnimateCharacterWalking(); - } - - AnimateCharacterAttacking(); - AnimateCharacterSpells(); - AnimateCharacterEmotes(); - - base.Update(gameTime); + AnimateCharacterWalking(); } - public void MainCharacterFace(EODirection direction) - { - if (_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) - { - _queuedDirections[_characterRepository.MainCharacter.ID] = direction; - return; - } + AnimateCharacterAttacking(); + AnimateCharacterSpells(); + AnimateCharacterEmotes(); - var renderProperties = _characterRepository.MainCharacter.RenderProperties.WithDirection(direction); - var newMainCharacter = _characterRepository.MainCharacter.WithRenderProperties(renderProperties); - _characterRepository.MainCharacter = newMainCharacter; + base.Update(gameTime); + } - _characterActions.Face(direction); + public void MainCharacterFace(EODirection direction) + { + if (_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) + { + _queuedDirections[_characterRepository.MainCharacter.ID] = direction; + return; } - public void StartMainCharacterWalkAnimation(Option targetCoordinate, bool ghosted, Action sfxCallback) - { - _walkPath.Clear(); + var renderProperties = _characterRepository.MainCharacter.RenderProperties.WithDirection(direction); + var newMainCharacter = _characterRepository.MainCharacter.WithRenderProperties(renderProperties); + _characterRepository.MainCharacter = newMainCharacter; - targetCoordinate.Match( - some: tc => - { - _targetCoordinate = targetCoordinate; + _characterActions.Face(direction); + } - var rp = _characterRepository.MainCharacter.RenderProperties; - var characterCoord = new MapCoordinate(rp.MapX, rp.MapY); + public void StartMainCharacterWalkAnimation(Option targetCoordinate, bool ghosted, Action sfxCallback) + { + _walkPath.Clear(); - _walkPath = _pathFinder.FindPath(characterCoord, tc); + targetCoordinate.Match( + some: tc => + { + _targetCoordinate = targetCoordinate; - if (!_walkPath.Any()) return; + var rp = _characterRepository.MainCharacter.RenderProperties; + var characterCoord = new MapCoordinate(rp.MapX, rp.MapY); - if (!_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) - { - rp = FaceTarget(characterCoord, _walkPath.Peek(), rp); - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(rp); - } + _walkPath = _pathFinder.FindPath(characterCoord, tc); - doTheWalk(); - }, - none: doTheWalk); + if (!_walkPath.Any()) return; - void doTheWalk() - { - if (_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) + if (!_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) { - _otherPlayerStartWalkingTimes[_characterRepository.MainCharacter.ID].SetReplay(sfxCallback); - return; + rp = FaceTarget(characterCoord, _walkPath.Peek(), rp); + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(rp); } - var startWalkingTime = new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount, sfxCallback); - _otherPlayerStartWalkingTimes.Add(_characterRepository.MainCharacter.ID, startWalkingTime); + doTheWalk(); + }, + none: doTheWalk); - _characterActions.Walk(ghosted); - startWalkingTime.SoundEffect(); - } - } - - public void CancelClickToWalk() - { - _walkPath.Clear(); - } - - public void StartMainCharacterAttackAnimation(Action sfxCallback) + void doTheWalk() { - if (_otherPlayerStartAttackingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) + if (_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) { - _otherPlayerStartAttackingTimes[_characterRepository.MainCharacter.ID].SetReplay(sfxCallback); + _otherPlayerStartWalkingTimes[_characterRepository.MainCharacter.ID].SetReplay(sfxCallback); return; } - var startAttackingTime = new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount, sfxCallback); - _otherPlayerStartAttackingTimes.Add(_characterRepository.MainCharacter.ID, startAttackingTime); + var startWalkingTime = new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount, sfxCallback); + _otherPlayerStartWalkingTimes.Add(_characterRepository.MainCharacter.ID, startWalkingTime); + + _characterActions.Walk(ghosted); + startWalkingTime.SoundEffect(); } + } - public bool MainCharacterShoutSpellPrep(ESFRecord spellData, ISpellTargetable target) - { - if (_mainPlayerStartShoutTick.HasValue) - return false; + public void CancelClickToWalk() + { + _walkPath.Clear(); + } - _mainPlayerStartShoutTick = Option.Some(_fixedTimeStepRepository.TickCount); - _shoutSpellData = spellData; - _spellTarget = target; - return true; + public void StartMainCharacterAttackAnimation(Action sfxCallback) + { + if (_otherPlayerStartAttackingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) + { + _otherPlayerStartAttackingTimes[_characterRepository.MainCharacter.ID].SetReplay(sfxCallback); + return; } - public void MainCharacterCancelSpellPrep() - { - _mainPlayerStartShoutTick = Option.None(); - _shoutSpellData = null; - _spellTarget = null; + var startAttackingTime = new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount, sfxCallback); + _otherPlayerStartAttackingTimes.Add(_characterRepository.MainCharacter.ID, startAttackingTime); + } - _spellSlotDataRepository.SelectedSpellSlot = Option.None(); - _spellSlotDataRepository.SpellIsPrepared = false; - } + public bool MainCharacterShoutSpellPrep(ESFRecord spellData, ISpellTargetable target) + { + if (_mainPlayerStartShoutTick.HasValue) + return false; - public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) - { - if (_otherPlayerStartWalkingTimes.ContainsKey(characterID)) - { - _otherPlayerStartWalkingTimes[characterID].SetReplay(); - _queuedDirections[characterID] = direction; - _queuedPositions[characterID] = destination; - return; - } + _mainPlayerStartShoutTick = Option.Some(_fixedTimeStepRepository.TickCount); + _shoutSpellData = spellData; + _spellTarget = target; + return true; + } - var startWalkingTimeAndID = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); - _otherPlayerStartWalkingTimes.Add(characterID, startWalkingTimeAndID); - } + public void MainCharacterCancelSpellPrep() + { + _mainPlayerStartShoutTick = Option.None(); + _shoutSpellData = null; + _spellTarget = null; - public void StartOtherCharacterAttackAnimation(int characterID, Action sfxCallback) - { - if (_otherPlayerStartAttackingTimes.ContainsKey(characterID)) - { - _otherPlayerStartAttackingTimes[characterID].SetReplay(sfxCallback); - return; - } + _spellSlotDataRepository.SelectedSpellSlot = Option.None(); + _spellSlotDataRepository.SpellIsPrepared = false; + } - var startAttackingTime = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount, sfxCallback); - _otherPlayerStartAttackingTimes.Add(characterID, startAttackingTime); + public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) + { + if (_otherPlayerStartWalkingTimes.ContainsKey(characterID)) + { + _otherPlayerStartWalkingTimes[characterID].SetReplay(); + _queuedDirections[characterID] = direction; + _queuedPositions[characterID] = destination; + return; } - public void StartOtherCharacterSpellCast(int characterID) + var startWalkingTimeAndID = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); + _otherPlayerStartWalkingTimes.Add(characterID, startWalkingTimeAndID); + } + + public void StartOtherCharacterAttackAnimation(int characterID, Action sfxCallback) + { + if (_otherPlayerStartAttackingTimes.ContainsKey(characterID)) { - if (_otherPlayerStartWalkingTimes.ContainsKey(characterID) || - _otherPlayerStartAttackingTimes.ContainsKey(characterID)) - return; + _otherPlayerStartAttackingTimes[characterID].SetReplay(sfxCallback); + return; + } - if (_otherPlayerStartSpellCastTimes.ContainsKey(characterID)) - { - ResetCharacterAnimationFrames(characterID); - _otherPlayerStartSpellCastTimes.Remove(characterID); - } + var startAttackingTime = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount, sfxCallback); + _otherPlayerStartAttackingTimes.Add(characterID, startAttackingTime); + } - var startAttackingTimeAndID = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); - _otherPlayerStartSpellCastTimes.Add(characterID, startAttackingTimeAndID); - } + public void StartOtherCharacterSpellCast(int characterID) + { + if (_otherPlayerStartWalkingTimes.ContainsKey(characterID) || + _otherPlayerStartAttackingTimes.ContainsKey(characterID)) + return; - public bool Emote(int characterID, Emote whichEmote) + if (_otherPlayerStartSpellCastTimes.ContainsKey(characterID)) { - if (((_otherPlayerStartWalkingTimes.ContainsKey(characterID) || - _otherPlayerStartAttackingTimes.ContainsKey(characterID) || - _otherPlayerStartSpellCastTimes.ContainsKey(characterID)) && whichEmote != EOLib.Domain.Character.Emote.LevelUp) || - _startEmoteTimes.ContainsKey(characterID)) - return false; - - var startEmoteTime = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); - if (characterID == _characterRepository.MainCharacter.ID) - { - var rp = _characterRepository.MainCharacter.RenderProperties.WithEmote(whichEmote); - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(rp); - } - else if (_currentMapStateRepository.Characters.TryGetValue(characterID, out var otherCharacter)) - { - var rp = otherCharacter.RenderProperties.WithEmote(whichEmote); - _currentMapStateRepository.Characters.Update(otherCharacter, otherCharacter.WithRenderProperties(rp)); - } - else - { - _currentMapStateRepository.UnknownPlayerIDs.Add(characterID); - return false; - } - - _startEmoteTimes[characterID] = startEmoteTime; - return true; + ResetCharacterAnimationFrames(characterID); + _otherPlayerStartSpellCastTimes.Remove(characterID); } - public void StopAllCharacterAnimations() + var startAttackingTimeAndID = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); + _otherPlayerStartSpellCastTimes.Add(characterID, startAttackingTimeAndID); + } + + public bool Emote(int characterID, Emote whichEmote) + { + if (((_otherPlayerStartWalkingTimes.ContainsKey(characterID) || + _otherPlayerStartAttackingTimes.ContainsKey(characterID) || + _otherPlayerStartSpellCastTimes.ContainsKey(characterID)) && whichEmote != EOLib.Domain.Character.Emote.LevelUp) || + _startEmoteTimes.ContainsKey(characterID)) + return false; + + var startEmoteTime = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); + if (characterID == _characterRepository.MainCharacter.ID) + { + var rp = _characterRepository.MainCharacter.RenderProperties.WithEmote(whichEmote); + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(rp); + } + else if (_currentMapStateRepository.Characters.TryGetValue(characterID, out var otherCharacter)) + { + var rp = otherCharacter.RenderProperties.WithEmote(whichEmote); + _currentMapStateRepository.Characters.Update(otherCharacter, otherCharacter.WithRenderProperties(rp)); + } + else { - _otherPlayerStartWalkingTimes.Clear(); - _otherPlayerStartAttackingTimes.Clear(); - _otherPlayerStartSpellCastTimes.Clear(); - _walkPath.Clear(); - - _characterRepository.MainCharacter = - _characterRepository.MainCharacter.WithRenderProperties( - _characterRepository.MainCharacter.RenderProperties.ResetAnimationFrames()); - - var characterPairs = _currentMapStateRepository.Characters - .Select(c => (Old: c, New: c.WithRenderProperties(c.RenderProperties.ResetAnimationFrames()))) - .ToList(); - foreach (var (Old, New) in characterPairs) - _currentMapStateRepository.Characters.Update(Old, New); + _currentMapStateRepository.UnknownPlayerIDs.Add(characterID); + return false; } - #region Walk Animation + _startEmoteTimes[characterID] = startEmoteTime; + return true; + } + + public void StopAllCharacterAnimations() + { + _otherPlayerStartWalkingTimes.Clear(); + _otherPlayerStartAttackingTimes.Clear(); + _otherPlayerStartSpellCastTimes.Clear(); + _walkPath.Clear(); + + _characterRepository.MainCharacter = + _characterRepository.MainCharacter.WithRenderProperties( + _characterRepository.MainCharacter.RenderProperties.ResetAnimationFrames()); + + var characterPairs = _currentMapStateRepository.Characters + .Select(c => (Old: c, New: c.WithRenderProperties(c.RenderProperties.ResetAnimationFrames()))) + .ToList(); + foreach (var (Old, New) in characterPairs) + _currentMapStateRepository.Characters.Update(Old, New); + } + + #region Walk Animation - private void AnimateCharacterWalking() + private void AnimateCharacterWalking() + { + var playersDoneWalking = new List(); + foreach (var pair in _otherPlayerStartWalkingTimes.Values) { - var playersDoneWalking = new List(); - foreach (var pair in _otherPlayerStartWalkingTimes.Values) + var sendWalk = false; + + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_WALK_FRAME) { - var sendWalk = false; + GetCurrentCharacterFromRepository(pair).Match( + none: () => playersDoneWalking.Add(pair.UniqueID), + some: currentCharacter => + { + var renderProperties = currentCharacter.RenderProperties; + var nextFrameRenderProperties = AnimateOneWalkFrame(renderProperties); - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_WALK_FRAME) - { - GetCurrentCharacterFromRepository(pair).Match( - none: () => playersDoneWalking.Add(pair.UniqueID), - some: currentCharacter => + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) { - var renderProperties = currentCharacter.RenderProperties; - var nextFrameRenderProperties = AnimateOneWalkFrame(renderProperties); + var isMainCharacter = currentCharacter == _characterRepository.MainCharacter; - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) + if (pair.Replay) { - var isMainCharacter = currentCharacter == _characterRepository.MainCharacter; - - if (pair.Replay) - { - var nextFramePropertiesWithDirection = _queuedDirections.ContainsKey(pair.UniqueID) - ? nextFrameRenderProperties.WithDirection(_queuedDirections[pair.UniqueID]) - : nextFrameRenderProperties; - _queuedDirections.Remove(pair.UniqueID); + var nextFramePropertiesWithDirection = _queuedDirections.ContainsKey(pair.UniqueID) + ? nextFrameRenderProperties.WithDirection(_queuedDirections[pair.UniqueID]) + : nextFrameRenderProperties; + _queuedDirections.Remove(pair.UniqueID); - var canMoveToDestinationCoordinates = _walkValidationActions.CanMoveToCoordinates( - nextFramePropertiesWithDirection.GetDestinationX(), - nextFramePropertiesWithDirection.GetDestinationY()) == WalkValidationResult.Walkable; + var canMoveToDestinationCoordinates = _walkValidationActions.CanMoveToCoordinates( + nextFramePropertiesWithDirection.GetDestinationX(), + nextFramePropertiesWithDirection.GetDestinationY()) == WalkValidationResult.Walkable; - if (!isMainCharacter || (isMainCharacter && canMoveToDestinationCoordinates)) - { - // send the walk packet after the game state has been updated so the correct coordinates are sent - sendWalk = isMainCharacter; + if (!isMainCharacter || (isMainCharacter && canMoveToDestinationCoordinates)) + { + // send the walk packet after the game state has been updated so the correct coordinates are sent + sendWalk = isMainCharacter; - var extraFrameProps = AnimateOneWalkFrame(nextFramePropertiesWithDirection.ResetAnimationFrames()); - pair.ClearReplay(); + var extraFrameProps = AnimateOneWalkFrame(nextFramePropertiesWithDirection.ResetAnimationFrames()); + pair.ClearReplay(); - nextFrameRenderProperties = extraFrameProps; - pair.SoundEffect(); - } - else - { - // tried to replay but the new destination position is not walkable - playersDoneWalking.Add(pair.UniqueID); - } + nextFrameRenderProperties = extraFrameProps; + pair.SoundEffect(); } - else if (isMainCharacter && _walkPath.Any()) + else { - var characterCoord = new MapCoordinate(nextFrameRenderProperties.MapX, nextFrameRenderProperties.MapY); - - _walkPath = _targetCoordinate.Match( - some: tc => - { - if (tc.Equals(characterCoord)) - return new Queue(); - return _pathFinder.FindPath(characterCoord, tc); - }, - none: () => new Queue()); - - if (_walkPath.Any()) - { - var next = _walkPath.Dequeue(); - nextFrameRenderProperties = FaceTarget(characterCoord, next, nextFrameRenderProperties); - - sendWalk = true; - pair.SoundEffect(); - nextFrameRenderProperties = AnimateOneWalkFrame(nextFrameRenderProperties.ResetAnimationFrames()); - } - else + // tried to replay but the new destination position is not walkable + playersDoneWalking.Add(pair.UniqueID); + } + } + else if (isMainCharacter && _walkPath.Any()) + { + var characterCoord = new MapCoordinate(nextFrameRenderProperties.MapX, nextFrameRenderProperties.MapY); + + _walkPath = _targetCoordinate.Match( + some: tc => { - playersDoneWalking.Add(pair.UniqueID); - } + if (tc.Equals(characterCoord)) + return new Queue(); + return _pathFinder.FindPath(characterCoord, tc); + }, + none: () => new Queue()); + + if (_walkPath.Any()) + { + var next = _walkPath.Dequeue(); + nextFrameRenderProperties = FaceTarget(characterCoord, next, nextFrameRenderProperties); + + sendWalk = true; + pair.SoundEffect(); + nextFrameRenderProperties = AnimateOneWalkFrame(nextFrameRenderProperties.ResetAnimationFrames()); } else { - if (_queuedPositions.ContainsKey(pair.UniqueID)) - { - nextFrameRenderProperties = nextFrameRenderProperties - .WithMapX(_queuedPositions[pair.UniqueID].X) - .WithMapY(_queuedPositions[pair.UniqueID].Y); - _queuedPositions.Remove(pair.UniqueID); - } - playersDoneWalking.Add(pair.UniqueID); } } - - var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); - UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); - - if (sendWalk) + else { - _characterActions.Walk(false); + if (_queuedPositions.ContainsKey(pair.UniqueID)) + { + nextFrameRenderProperties = nextFrameRenderProperties + .WithMapX(_queuedPositions[pair.UniqueID].X) + .WithMapY(_queuedPositions[pair.UniqueID].Y); + _queuedPositions.Remove(pair.UniqueID); + } + + playersDoneWalking.Add(pair.UniqueID); } - }); - } - } + } + + var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); + UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); - foreach (var key in playersDoneWalking) - _otherPlayerStartWalkingTimes.Remove(key); + if (sendWalk) + { + _characterActions.Walk(false); + } + }); + } } - private CharacterRenderProperties AnimateOneWalkFrame(CharacterRenderProperties renderProperties) - { - var isSteppingStone = _currentMapProvider.CurrentMap.Tiles[renderProperties.MapY, renderProperties.MapX] == TileSpec.Jump - || _currentMapProvider.CurrentMap.Tiles[renderProperties.GetDestinationY(), renderProperties.GetDestinationX()] == TileSpec.Jump; + foreach (var key in playersDoneWalking) + _otherPlayerStartWalkingTimes.Remove(key); + } - var nextFrameRenderProperties = renderProperties.WithNextWalkFrame(isSteppingStone); - if (nextFrameRenderProperties.CurrentAction != CharacterActionState.Walking) - { - nextFrameRenderProperties = nextFrameRenderProperties - .WithMapX(nextFrameRenderProperties.GetDestinationX()) - .WithMapY(nextFrameRenderProperties.GetDestinationY()); - } + private CharacterRenderProperties AnimateOneWalkFrame(CharacterRenderProperties renderProperties) + { + var isSteppingStone = _currentMapProvider.CurrentMap.Tiles[renderProperties.MapY, renderProperties.MapX] == TileSpec.Jump + || _currentMapProvider.CurrentMap.Tiles[renderProperties.GetDestinationY(), renderProperties.GetDestinationX()] == TileSpec.Jump; - return nextFrameRenderProperties; + var nextFrameRenderProperties = renderProperties.WithNextWalkFrame(isSteppingStone); + if (nextFrameRenderProperties.CurrentAction != CharacterActionState.Walking) + { + nextFrameRenderProperties = nextFrameRenderProperties + .WithMapX(nextFrameRenderProperties.GetDestinationX()) + .WithMapY(nextFrameRenderProperties.GetDestinationY()); } - private CharacterRenderProperties FaceTarget(MapCoordinate characterCoord, MapCoordinate next, CharacterRenderProperties rp) - { - var diff = next - characterCoord; + return nextFrameRenderProperties; + } - if (diff.X != 0 && diff.Y != 0) - throw new InvalidOperationException("Trying to move in a diagonal."); + private CharacterRenderProperties FaceTarget(MapCoordinate characterCoord, MapCoordinate next, CharacterRenderProperties rp) + { + var diff = next - characterCoord; - if (diff.X < 0) - { - return rp.WithDirection(EODirection.Left); - } - else if (diff.X > 0) - { - return rp.WithDirection(EODirection.Right); - } - else if (diff.Y < 0) - { - return rp.WithDirection(EODirection.Up); - } - else if (diff.Y > 0) - { - return rp.WithDirection(EODirection.Down); - } + if (diff.X != 0 && diff.Y != 0) + throw new InvalidOperationException("Trying to move in a diagonal."); - return rp; + if (diff.X < 0) + { + return rp.WithDirection(EODirection.Left); + } + else if (diff.X > 0) + { + return rp.WithDirection(EODirection.Right); + } + else if (diff.Y < 0) + { + return rp.WithDirection(EODirection.Up); + } + else if (diff.Y > 0) + { + return rp.WithDirection(EODirection.Down); } - #endregion + return rp; + } + + #endregion - #region Attack Animation + #region Attack Animation - private void AnimateCharacterAttacking() + private void AnimateCharacterAttacking() + { + var playersDoneAttacking = new HashSet(); + foreach (var pair in _otherPlayerStartAttackingTimes.Values) { - var playersDoneAttacking = new HashSet(); - foreach (var pair in _otherPlayerStartAttackingTimes.Values) + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME) { - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME) - { - GetCurrentCharacterFromRepository(pair).Match( - none: () => playersDoneAttacking.Add(pair.UniqueID), - some: currentCharacter => - { - var renderProperties = currentCharacter.RenderProperties; - var isRanged = _weaponMetadataProvider.GetValueOrDefault(renderProperties.WeaponGraphic).Ranged; - var nextFrameRenderProperties = renderProperties.WithNextAttackFrame(isRanged); + GetCurrentCharacterFromRepository(pair).Match( + none: () => playersDoneAttacking.Add(pair.UniqueID), + some: currentCharacter => + { + var renderProperties = currentCharacter.RenderProperties; + var isRanged = _weaponMetadataProvider.GetValueOrDefault(renderProperties.WeaponGraphic).Ranged; + var nextFrameRenderProperties = renderProperties.WithNextAttackFrame(isRanged); - if (nextFrameRenderProperties.ActualAttackFrame == 2) - pair.SoundEffect(); + if (nextFrameRenderProperties.ActualAttackFrame == 2) + pair.SoundEffect(); - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) + { + if (pair.Replay) { - if (pair.Replay) - { - nextFrameRenderProperties = renderProperties.ResetAnimationFrames().WithNextAttackFrame(isRanged); - pair.ClearReplay(); - } - else - { - playersDoneAttacking.Add(pair.UniqueID); - } + nextFrameRenderProperties = renderProperties.ResetAnimationFrames().WithNextAttackFrame(isRanged); + pair.ClearReplay(); + } + else + { + playersDoneAttacking.Add(pair.UniqueID); } + } - var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); - UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); - }); - } + var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); + UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); + }); } - - foreach (var key in playersDoneAttacking) - _otherPlayerStartAttackingTimes.Remove(key); } - #endregion + foreach (var key in playersDoneAttacking) + _otherPlayerStartAttackingTimes.Remove(key); + } + + #endregion - #region Spell Animation + #region Spell Animation - private void AnimateCharacterSpells() + private void AnimateCharacterSpells() + { + _mainPlayerStartShoutTick.MatchSome(startTick => { - _mainPlayerStartShoutTick.MatchSome(startTick => + if (_fixedTimeStepRepository.TickCount - startTick >= (ulong)(_shoutSpellData.CastTime * TICKS_PER_CAST_TIME)) { - if (_fixedTimeStepRepository.TickCount - startTick >= (ulong)(_shoutSpellData.CastTime * TICKS_PER_CAST_TIME)) - { - _otherPlayerStartSpellCastTimes.Add(_characterRepository.MainCharacter.ID, new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount)); - _characterActions.CastSpell(_shoutSpellData.ID, _spellTarget); - MainCharacterCancelSpellPrep(); + _otherPlayerStartSpellCastTimes.Add(_characterRepository.MainCharacter.ID, new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount)); + _characterActions.CastSpell(_shoutSpellData.ID, _spellTarget); + MainCharacterCancelSpellPrep(); - var nextRenderProps = _characterRepository.MainCharacter.RenderProperties.WithCurrentAction(CharacterActionState.SpellCast); - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(nextRenderProps); - } - }); + var nextRenderProps = _characterRepository.MainCharacter.RenderProperties.WithCurrentAction(CharacterActionState.SpellCast); + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(nextRenderProps); + } + }); - var playersDoneCasting = new HashSet(); - foreach (var pair in _otherPlayerStartSpellCastTimes.Values) + var playersDoneCasting = new HashSet(); + foreach (var pair in _otherPlayerStartSpellCastTimes.Values) + { + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME) { - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME) - { - GetCurrentCharacterFromRepository(pair).Match( - none: () => playersDoneCasting.Add(pair.UniqueID), - some: currentCharacter => - { - var renderProperties = currentCharacter.RenderProperties; - var nextFrameRenderProperties = renderProperties.WithNextSpellCastFrame(); + GetCurrentCharacterFromRepository(pair).Match( + none: () => playersDoneCasting.Add(pair.UniqueID), + some: currentCharacter => + { + var renderProperties = currentCharacter.RenderProperties; + var nextFrameRenderProperties = renderProperties.WithNextSpellCastFrame(); - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) - playersDoneCasting.Add(pair.UniqueID); + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) + playersDoneCasting.Add(pair.UniqueID); - var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); - UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); - }); - } + var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); + UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); + }); } - - foreach (var key in playersDoneCasting) - _otherPlayerStartSpellCastTimes.Remove(key); } - #endregion + foreach (var key in playersDoneCasting) + _otherPlayerStartSpellCastTimes.Remove(key); + } + + #endregion - #region Emote Animation + #region Emote Animation - private void AnimateCharacterEmotes() + private void AnimateCharacterEmotes() + { + var playersDoneEmoting = new HashSet(); + foreach (var pair in _startEmoteTimes.Values) { - var playersDoneEmoting = new HashSet(); - foreach (var pair in _startEmoteTimes.Values) + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME * 2) { - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME * 2) - { - GetCurrentCharacterFromRepository(pair).Match( - none: () => playersDoneEmoting.Add(pair.UniqueID), - some: currentCharacter => - { - var renderProperties = currentCharacter.RenderProperties; - var nextFrameRenderProperties = renderProperties.WithNextEmoteFrame(); + GetCurrentCharacterFromRepository(pair).Match( + none: () => playersDoneEmoting.Add(pair.UniqueID), + some: currentCharacter => + { + var renderProperties = currentCharacter.RenderProperties; + var nextFrameRenderProperties = renderProperties.WithNextEmoteFrame(); - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing, CharacterActionState.Sitting)) - playersDoneEmoting.Add(pair.UniqueID); + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing, CharacterActionState.Sitting)) + playersDoneEmoting.Add(pair.UniqueID); - var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); - UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); - }); - } + var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); + UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); + }); } - - foreach (var key in playersDoneEmoting) - _startEmoteTimes.Remove(key); } - #endregion + foreach (var key in playersDoneEmoting) + _startEmoteTimes.Remove(key); + } + + #endregion - private Option GetCurrentCharacterFromRepository(RenderFrameActionTime pair) - { - return pair.UniqueID == _characterRepository.MainCharacter.ID - ? Option.Some(_characterRepository.MainCharacter) - : _currentMapStateRepository.Characters.TryGetValue(pair.UniqueID, out var character) - ? Option.Some(character) - : Option.None(); - } + private Option GetCurrentCharacterFromRepository(RenderFrameActionTime pair) + { + return pair.UniqueID == _characterRepository.MainCharacter.ID + ? Option.Some(_characterRepository.MainCharacter) + : _currentMapStateRepository.Characters.TryGetValue(pair.UniqueID, out var character) + ? Option.Some(character) + : Option.None(); + } - private void UpdateCharacterInRepository(EOLib.Domain.Character.Character currentCharacter, - EOLib.Domain.Character.Character nextFrameCharacter) + private void UpdateCharacterInRepository(EOLib.Domain.Character.Character currentCharacter, + EOLib.Domain.Character.Character nextFrameCharacter) + { + if (currentCharacter == _characterRepository.MainCharacter) { - if (currentCharacter == _characterRepository.MainCharacter) - { - _characterRepository.MainCharacter = nextFrameCharacter; - } - else - { - _currentMapStateRepository.Characters.Update(currentCharacter, nextFrameCharacter); - } + _characterRepository.MainCharacter = nextFrameCharacter; } - - private void ResetCharacterAnimationFrames(int characterID) + else { - var character = _currentMapStateRepository.Characters[characterID]; - var renderProps = character.RenderProperties.ResetAnimationFrames(); - var newCharacter = character.WithRenderProperties(renderProps); - _currentMapStateRepository.Characters.Update(character, newCharacter); + _currentMapStateRepository.Characters.Update(currentCharacter, nextFrameCharacter); } } - public interface ICharacterAnimator : IGameComponent + private void ResetCharacterAnimationFrames(int characterID) { - void MainCharacterFace(EODirection direction); + var character = _currentMapStateRepository.Characters[characterID]; + var renderProps = character.RenderProperties.ResetAnimationFrames(); + var newCharacter = character.WithRenderProperties(renderProps); + _currentMapStateRepository.Characters.Update(character, newCharacter); + } +} - void StartMainCharacterWalkAnimation(Option targetCoordinate, bool ghosted, Action sfxCallback); +public interface ICharacterAnimator : IGameComponent +{ + void MainCharacterFace(EODirection direction); - void CancelClickToWalk(); + void StartMainCharacterWalkAnimation(Option targetCoordinate, bool ghosted, Action sfxCallback); - void StartMainCharacterAttackAnimation(Action sfxCallback); + void CancelClickToWalk(); - bool MainCharacterShoutSpellPrep(ESFRecord spellData, ISpellTargetable spellTarget); + void StartMainCharacterAttackAnimation(Action sfxCallback); - void MainCharacterCancelSpellPrep(); + bool MainCharacterShoutSpellPrep(ESFRecord spellData, ISpellTargetable spellTarget); - void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction); + void MainCharacterCancelSpellPrep(); - void StartOtherCharacterAttackAnimation(int characterID, Action sfxCallback); + void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction); - void StartOtherCharacterSpellCast(int characterID); + void StartOtherCharacterAttackAnimation(int characterID, Action sfxCallback); - bool Emote(int characterID, Emote whichEmote); + void StartOtherCharacterSpellCast(int characterID); - void StopAllCharacterAnimations(); - } + bool Emote(int characterID, Emote whichEmote); + + void StopAllCharacterAnimations(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterRenderer.cs b/EndlessClient/Rendering/Character/CharacterRenderer.cs index be14bc636..a88126a80 100644 --- a/EndlessClient/Rendering/Character/CharacterRenderer.cs +++ b/EndlessClient/Rendering/Character/CharacterRenderer.cs @@ -22,534 +22,533 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +public class CharacterRenderer : DrawableGameComponent, ICharacterRenderer { - public class CharacterRenderer : DrawableGameComponent, ICharacterRenderer - { - private readonly object _rt_locker_ = new object(); + private readonly object _rt_locker_ = new object(); - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IHealthBarRendererFactory _healthBarRendererFactory; - private readonly IChatBubbleFactory _chatBubbleFactory; - private readonly ICharacterProvider _characterProvider; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly ICharacterPropertyRendererBuilder _characterPropertyRendererBuilder; - private readonly ICharacterTextures _characterTextures; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly IMetadataProvider _hatMetadataProvider; - private readonly IMetadataProvider _weaponMetadataProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private readonly IEffectRenderer _effectRenderer; + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IHealthBarRendererFactory _healthBarRendererFactory; + private readonly IChatBubbleFactory _chatBubbleFactory; + private readonly ICharacterProvider _characterProvider; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly ICharacterPropertyRendererBuilder _characterPropertyRendererBuilder; + private readonly ICharacterTextures _characterTextures; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly IMetadataProvider _hatMetadataProvider; + private readonly IMetadataProvider _weaponMetadataProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IEffectRenderer _effectRenderer; - private readonly bool _isUiControl; + private readonly bool _isUiControl; - private EOLib.Domain.Character.Character _character; - private bool _textureUpdateRequired, _positionIsRelative = true; + private EOLib.Domain.Character.Character _character; + private bool _textureUpdateRequired, _positionIsRelative = true; - private SpriteBatch _sb; - private RenderTarget2D _charRenderTarget; - private Texture2D _outline; + private SpriteBatch _sb; + private RenderTarget2D _charRenderTarget; + private Texture2D _outline; - private BlinkingLabel _nameLabel; - private string _shoutName = string.Empty; - private DateTime? _spellCastTime; - private bool _showName = true; + private BlinkingLabel _nameLabel; + private string _shoutName = string.Empty; + private DateTime? _spellCastTime; + private bool _showName = true; - private IHealthBarRenderer _healthBarRenderer; - private Lazy _chatBubble; + private IHealthBarRenderer _healthBarRenderer; + private Lazy _chatBubble; - private bool _lastIsDead; + private bool _lastIsDead; - private Color[] _rtColorData; + private Color[] _rtColorData; - public EOLib.Domain.Character.Character Character + public EOLib.Domain.Character.Character Character + { + get { return _character; } + set { - get { return _character; } - set - { - if (_character == value) return; - _textureUpdateRequired = _character.RenderProperties.GetHashCode() != value.RenderProperties.GetHashCode(); - _character = value; - } + if (_character == value) return; + _textureUpdateRequired = _character.RenderProperties.GetHashCode() != value.RenderProperties.GetHashCode(); + _character = value; } + } - public bool Transparent { get; set; } - - public Rectangle DrawArea { get; private set; } - - public ISpellTargetable SpellTarget => Character; + public bool Transparent { get; set; } - public int NameLabelY { get; private set; } + public Rectangle DrawArea { get; private set; } - public int HorizontalCenter { get; private set; } + public ISpellTargetable SpellTarget => Character; - public bool IsAlive => !Character.RenderProperties.IsDead; + public int NameLabelY { get; private set; } - public CharacterRenderer(Game game, - IRenderTargetFactory renderTargetFactory, - IHealthBarRendererFactory healthBarRendererFactory, - IChatBubbleFactory chatBubbleFactory, - ICharacterProvider characterProvider, - IRenderOffsetCalculator renderOffsetCalculator, - ICharacterPropertyRendererBuilder characterPropertyRendererBuilder, - ICharacterTextures characterTextures, - ICurrentMapProvider currentMapProvider, - IUserInputProvider userInputProvider, - IEffectRendererFactory effectRendererFactory, - IMetadataProvider hatMetadataProvider, - IMetadataProvider weaponMetadataProvider, - ISfxPlayer sfxPlayer, - IClientWindowSizeRepository clientWindowSizeRepository, - EOLib.Domain.Character.Character character, - bool isUiControl) - : base(game) - { - _renderTargetFactory = renderTargetFactory; - _healthBarRendererFactory = healthBarRendererFactory; - _chatBubbleFactory = chatBubbleFactory; - _characterProvider = characterProvider; - _renderOffsetCalculator = renderOffsetCalculator; - _characterPropertyRendererBuilder = characterPropertyRendererBuilder; - _characterTextures = characterTextures; - _currentMapProvider = currentMapProvider; - _userInputProvider = userInputProvider; - _hatMetadataProvider = hatMetadataProvider; - _weaponMetadataProvider = weaponMetadataProvider; - _effectRenderer = effectRendererFactory.Create(); - _sfxPlayer = sfxPlayer; - _clientWindowSizeRepository = clientWindowSizeRepository; - _character = character; - _isUiControl = isUiControl; - - _chatBubble = new Lazy(() => _chatBubbleFactory.CreateChatBubble(this)); - - _clientWindowSizeRepository.GameWindowSizeChanged += RecreateRenderTargetEvent; - } + public int HorizontalCenter { get; private set; } - #region Game Component + public bool IsAlive => !Character.RenderProperties.IsDead; - public override void Initialize() - { - RecreateRenderTarget(); + public CharacterRenderer(Game game, + IRenderTargetFactory renderTargetFactory, + IHealthBarRendererFactory healthBarRendererFactory, + IChatBubbleFactory chatBubbleFactory, + ICharacterProvider characterProvider, + IRenderOffsetCalculator renderOffsetCalculator, + ICharacterPropertyRendererBuilder characterPropertyRendererBuilder, + ICharacterTextures characterTextures, + ICurrentMapProvider currentMapProvider, + IUserInputProvider userInputProvider, + IEffectRendererFactory effectRendererFactory, + IMetadataProvider hatMetadataProvider, + IMetadataProvider weaponMetadataProvider, + ISfxPlayer sfxPlayer, + IClientWindowSizeRepository clientWindowSizeRepository, + EOLib.Domain.Character.Character character, + bool isUiControl) + : base(game) + { + _renderTargetFactory = renderTargetFactory; + _healthBarRendererFactory = healthBarRendererFactory; + _chatBubbleFactory = chatBubbleFactory; + _characterProvider = characterProvider; + _renderOffsetCalculator = renderOffsetCalculator; + _characterPropertyRendererBuilder = characterPropertyRendererBuilder; + _characterTextures = characterTextures; + _currentMapProvider = currentMapProvider; + _userInputProvider = userInputProvider; + _hatMetadataProvider = hatMetadataProvider; + _weaponMetadataProvider = weaponMetadataProvider; + _effectRenderer = effectRendererFactory.Create(); + _sfxPlayer = sfxPlayer; + _clientWindowSizeRepository = clientWindowSizeRepository; + _character = character; + _isUiControl = isUiControl; + + _chatBubble = new Lazy(() => _chatBubbleFactory.CreateChatBubble(this)); + + _clientWindowSizeRepository.GameWindowSizeChanged += RecreateRenderTargetEvent; + } - _sb = new SpriteBatch(Game.GraphicsDevice); + #region Game Component - if (!_isUiControl) - { - _nameLabel = new BlinkingLabel(Constants.FontSize08pt5) - { - Visible = true, - TextWidth = 89, - TextAlign = LabelAlignment.MiddleCenter, - ForeColor = Color.White, - AutoSize = true, - Text = _character?.Name ?? string.Empty, - DrawOrder = 30, - KeepInClientWindowBounds = false, - }; - _nameLabel.Initialize(); - - if (!_nameLabel.Game.Components.Contains(_nameLabel)) - _nameLabel.Game.Components.Add(_nameLabel); - - _nameLabel.DrawPosition = GetNameLabelPosition(); - - _healthBarRenderer = _healthBarRendererFactory.CreateHealthBarRenderer(this); - } + public override void Initialize() + { + RecreateRenderTarget(); - base.Initialize(); - } + _sb = new SpriteBatch(Game.GraphicsDevice); - protected override void LoadContent() + if (!_isUiControl) { - _textureUpdateRequired = true; - _characterTextures.Refresh(_character.RenderProperties); + _nameLabel = new BlinkingLabel(Constants.FontSize08pt5) + { + Visible = true, + TextWidth = 89, + TextAlign = LabelAlignment.MiddleCenter, + ForeColor = Color.White, + AutoSize = true, + Text = _character?.Name ?? string.Empty, + DrawOrder = 30, + KeepInClientWindowBounds = false, + }; + _nameLabel.Initialize(); + + if (!_nameLabel.Game.Components.Contains(_nameLabel)) + _nameLabel.Game.Components.Add(_nameLabel); - _outline = new Texture2D(GraphicsDevice, 1, 1); - _outline.SetData(new[] { Color.White }); + _nameLabel.DrawPosition = GetNameLabelPosition(); - base.LoadContent(); + _healthBarRenderer = _healthBarRendererFactory.CreateHealthBarRenderer(this); } - public override void Update(GameTime gameTime) - { - // Effects can be rendered when character is not visible (leaving map) - _effectRenderer.Update(); + base.Initialize(); + } - if (!Visible) - return; + protected override void LoadContent() + { + _textureUpdateRequired = true; + _characterTextures.Refresh(_character.RenderProperties); - if (_positionIsRelative) - SetGridCoordinatePosition(); + _outline = new Texture2D(GraphicsDevice, 1, 1); + _outline.SetData(new[] { Color.White }); - if (_textureUpdateRequired) - { - _characterTextures.Refresh(_character.RenderProperties); - DrawToRenderTarget(); + base.LoadContent(); + } - _textureUpdateRequired = false; - } + public override void Update(GameTime gameTime) + { + // Effects can be rendered when character is not visible (leaving map) + _effectRenderer.Update(); - if (!_isUiControl) - { - UpdateNameLabel(); + if (!Visible) + return; - _healthBarRenderer?.Update(gameTime); + if (_positionIsRelative) + SetGridCoordinatePosition(); - CheckForDead(); - } + if (_textureUpdateRequired) + { + _characterTextures.Refresh(_character.RenderProperties); + DrawToRenderTarget(); - base.Update(gameTime); + _textureUpdateRequired = false; } - public override void Draw(GameTime gameTime) + if (!_isUiControl) { - if (!Visible || _sb.IsDisposed || - (Character == _characterProvider.MainCharacter && !_characterProvider.HasAvatar)) - return; + UpdateNameLabel(); - if (!Character.RenderProperties.IsHidden || _characterProvider.MainCharacter.AdminLevel > 0) - { - _sb.Begin(); - DrawToSpriteBatch(_sb); - - if (_sb.IsDisposed) - return; - _sb.End(); - } + _healthBarRenderer?.Update(gameTime); - base.Draw(gameTime); + CheckForDead(); } - #endregion - - #region ICharacterRenderer + base.Update(gameTime); + } - public void SetAbsoluteScreenPosition(int xPosition, int yPosition) - { - SetScreenCoordinates(xPosition, yPosition); - _positionIsRelative = false; - } + public override void Draw(GameTime gameTime) + { + if (!Visible || _sb.IsDisposed || + (Character == _characterProvider.MainCharacter && !_characterProvider.HasAvatar)) + return; - public void SetToCenterScreenPosition() + if (!Character.RenderProperties.IsHidden || _characterProvider.MainCharacter.AdminLevel > 0) { - var skinRect = _characterTextures.Skin.SourceRectangle; - - var xCoord = _clientWindowSizeRepository.Resizable - ? (_clientWindowSizeRepository.Width - skinRect.Width) / 2 - : 310; - var yCoord = _clientWindowSizeRepository.Resizable - ? (_clientWindowSizeRepository.Height - skinRect.Height) / 2 - 11 - : (298 - skinRect.Height) / 2 - skinRect.Height / 4 - 3; + _sb.Begin(); + DrawToSpriteBatch(_sb); - SetAbsoluteScreenPosition(xCoord, yCoord); + if (_sb.IsDisposed) + return; + _sb.End(); } - public void DrawToSpriteBatch(SpriteBatch spriteBatch) - { - _effectRenderer.DrawBehindTarget(spriteBatch); + base.Draw(gameTime); + } - if (Visible) - { - lock (_rt_locker_) - { - spriteBatch.Draw(_charRenderTarget, new Vector2(0, GetSteppingStoneOffset(Character.RenderProperties)), GetAlphaColor()); - } - } + #endregion - _effectRenderer.DrawInFrontOfTarget(spriteBatch); + #region ICharacterRenderer - if (!_isUiControl) - _healthBarRenderer?.DrawToSpriteBatch(spriteBatch); - } + public void SetAbsoluteScreenPosition(int xPosition, int yPosition) + { + SetScreenCoordinates(xPosition, yPosition); + _positionIsRelative = false; + } - public void ShowName() => _showName = true; + public void SetToCenterScreenPosition() + { + var skinRect = _characterTextures.Skin.SourceRectangle; - public void HideName() => _showName = false; + var xCoord = _clientWindowSizeRepository.Resizable + ? (_clientWindowSizeRepository.Width - skinRect.Width) / 2 + : 310; + var yCoord = _clientWindowSizeRepository.Resizable + ? (_clientWindowSizeRepository.Height - skinRect.Height) / 2 - 11 + : (298 - skinRect.Height) / 2 - skinRect.Height / 4 - 3; - #endregion + SetAbsoluteScreenPosition(xCoord, yCoord); + } - #region Update/Drawing Helpers + public void DrawToSpriteBatch(SpriteBatch spriteBatch) + { + _effectRenderer.DrawBehindTarget(spriteBatch); - private void DrawToRenderTarget() + if (Visible) { - var weaponMetadata = _weaponMetadataProvider.GetValueOrDefault(Character.RenderProperties.WeaponGraphic); - lock (_rt_locker_) { - GraphicsDevice.SetRenderTarget(_charRenderTarget); - GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); - _sb.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend); - - var characterPropertyRenderers = _characterPropertyRendererBuilder - .BuildList(_characterTextures, _character.RenderProperties) - .Where(x => x.CanRender); - foreach (var renderer in characterPropertyRenderers) - renderer.Render(_sb, DrawArea, weaponMetadata); - - //if (_gameStateProvider.CurrentState == GameStates.None) - //{ - // _sb.Draw(_outline, DrawArea.WithSize(DrawArea.Width, 1), Color.Black); - // _sb.Draw(_outline, DrawArea.WithPosition(new Vector2(DrawArea.X + DrawArea.Width, DrawArea.Y)).WithSize(1, DrawArea.Height), Color.Black); - // _sb.Draw(_outline, DrawArea.WithPosition(new Vector2(DrawArea.X, DrawArea.Y + DrawArea.Height)).WithSize(DrawArea.Width, 1), Color.Black); - // _sb.Draw(_outline, DrawArea.WithSize(1, DrawArea.Height), Color.Black); - - // _sb.Draw(_outline, DrawArea, Color.FromNonPremultiplied(255, 0, 0, 64)); - //} - - _sb.End(); - GraphicsDevice.SetRenderTarget(null); - - ClipHair(); + spriteBatch.Draw(_charRenderTarget, new Vector2(0, GetSteppingStoneOffset(Character.RenderProperties)), GetAlphaColor()); } } - private Color GetAlphaColor() - { - // don't render the transparent character layer if hidden/dead, otherwise the additive blending - // will render it with full alpha - if (_character.RenderProperties.IsHidden || _character.RenderProperties.IsDead) - return Transparent ? Color.Transparent : Color.FromNonPremultiplied(255, 255, 255, 128); - - return Transparent - ? Color.FromNonPremultiplied(255, 255, 255, 128) - : Color.White; - } + _effectRenderer.DrawInFrontOfTarget(spriteBatch); - private void SetGridCoordinatePosition() - { - var centerX = _clientWindowSizeRepository.Resizable ? (_clientWindowSizeRepository.Width - DrawArea.Width) / 2 : 310; - var centerY = _clientWindowSizeRepository.Resizable ? (_clientWindowSizeRepository.Height - DrawArea.Height) / 2 - 8 : 104; + if (!_isUiControl) + _healthBarRenderer?.DrawToSpriteBatch(spriteBatch); + } - var screenX = _renderOffsetCalculator.CalculateOffsetX(_character.RenderProperties) + centerX - GetMainCharacterOffsetX(); - var screenY = _renderOffsetCalculator.CalculateOffsetY(_character.RenderProperties) + centerY - GetMainCharacterOffsetY(); + public void ShowName() => _showName = true; - SetScreenCoordinates(screenX, screenY); - } + public void HideName() => _showName = false; - private void SetScreenCoordinates(int xPosition, int yPosition) - { - if (DrawArea.X != xPosition || DrawArea.Y != yPosition) - { - // size of standing still skin texture - DrawArea = new Rectangle(xPosition, yPosition, 18, 58); - HorizontalCenter = xPosition + 9; - _textureUpdateRequired = true; - } - } + #endregion + + #region Update/Drawing Helpers - private int GetMainCharacterOffsetX() + private void DrawToRenderTarget() + { + var weaponMetadata = _weaponMetadataProvider.GetValueOrDefault(Character.RenderProperties.WeaponGraphic); + + lock (_rt_locker_) { - return _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); + GraphicsDevice.SetRenderTarget(_charRenderTarget); + GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); + _sb.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend); + + var characterPropertyRenderers = _characterPropertyRendererBuilder + .BuildList(_characterTextures, _character.RenderProperties) + .Where(x => x.CanRender); + foreach (var renderer in characterPropertyRenderers) + renderer.Render(_sb, DrawArea, weaponMetadata); + + //if (_gameStateProvider.CurrentState == GameStates.None) + //{ + // _sb.Draw(_outline, DrawArea.WithSize(DrawArea.Width, 1), Color.Black); + // _sb.Draw(_outline, DrawArea.WithPosition(new Vector2(DrawArea.X + DrawArea.Width, DrawArea.Y)).WithSize(1, DrawArea.Height), Color.Black); + // _sb.Draw(_outline, DrawArea.WithPosition(new Vector2(DrawArea.X, DrawArea.Y + DrawArea.Height)).WithSize(DrawArea.Width, 1), Color.Black); + // _sb.Draw(_outline, DrawArea.WithSize(1, DrawArea.Height), Color.Black); + + // _sb.Draw(_outline, DrawArea, Color.FromNonPremultiplied(255, 0, 0, 64)); + //} + + _sb.End(); + GraphicsDevice.SetRenderTarget(null); + + ClipHair(); } + } - private int GetMainCharacterOffsetY() + private Color GetAlphaColor() + { + // don't render the transparent character layer if hidden/dead, otherwise the additive blending + // will render it with full alpha + if (_character.RenderProperties.IsHidden || _character.RenderProperties.IsDead) + return Transparent ? Color.Transparent : Color.FromNonPremultiplied(255, 255, 255, 128); + + return Transparent + ? Color.FromNonPremultiplied(255, 255, 255, 128) + : Color.White; + } + + private void SetGridCoordinatePosition() + { + var centerX = _clientWindowSizeRepository.Resizable ? (_clientWindowSizeRepository.Width - DrawArea.Width) / 2 : 310; + var centerY = _clientWindowSizeRepository.Resizable ? (_clientWindowSizeRepository.Height - DrawArea.Height) / 2 - 8 : 104; + + var screenX = _renderOffsetCalculator.CalculateOffsetX(_character.RenderProperties) + centerX - GetMainCharacterOffsetX(); + var screenY = _renderOffsetCalculator.CalculateOffsetY(_character.RenderProperties) + centerY - GetMainCharacterOffsetY(); + + SetScreenCoordinates(screenX, screenY); + } + + private void SetScreenCoordinates(int xPosition, int yPosition) + { + if (DrawArea.X != xPosition || DrawArea.Y != yPosition) { - return _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); + // size of standing still skin texture + DrawArea = new Rectangle(xPosition, yPosition, 18, 58); + HorizontalCenter = xPosition + 9; + _textureUpdateRequired = true; } + } - private void UpdateNameLabel() - { - if (_isUiControl || _healthBarRenderer == null || _nameLabel == null) - return; + private int GetMainCharacterOffsetX() + { + return _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); + } - if (_healthBarRenderer.Visible) - { - _nameLabel.Visible = false; - } - else if (DrawArea.Contains(_userInputProvider.CurrentMouseState.Position) && _showName) - { - _nameLabel.Visible = true; - _nameLabel.BlinkRate = null; - _nameLabel.Text = !string.IsNullOrWhiteSpace(_character.GuildTag) ? $"{_character.Name} {_character.GuildTag}" : _character.Name; - } - else if (_shoutName != string.Empty && _nameLabel.Text != _shoutName) - { - _nameLabel.Visible = true; - _nameLabel.BlinkRate = 250; - _nameLabel.Text = _shoutName; - } - else if (_shoutName == string.Empty) - { - _nameLabel.Visible = false; - } + private int GetMainCharacterOffsetY() + { + return _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); + } - if (_spellCastTime.HasValue && (DateTime.Now - _spellCastTime.Value).TotalMilliseconds >= 600) - { - StopShout(); - } + private void UpdateNameLabel() + { + if (_isUiControl || _healthBarRenderer == null || _nameLabel == null) + return; - _nameLabel.DrawPosition = GetNameLabelPosition(); + if (_healthBarRenderer.Visible) + { + _nameLabel.Visible = false; } - - private Vector2 GetNameLabelPosition() + else if (DrawArea.Contains(_userInputProvider.CurrentMouseState.Position) && _showName) { - NameLabelY = DrawArea.Y - 12 - (int)(_nameLabel?.ActualHeight ?? 0) + ((int)Character.RenderProperties.SitState) * 10; - return new Vector2(HorizontalCenter - (_nameLabel.ActualWidth / 2f), NameLabelY); + _nameLabel.Visible = true; + _nameLabel.BlinkRate = null; + _nameLabel.Text = !string.IsNullOrWhiteSpace(_character.GuildTag) ? $"{_character.Name} {_character.GuildTag}" : _character.Name; } - - private bool GetIsSteppingStone(CharacterRenderProperties renderProps) + else if (_shoutName != string.Empty && _nameLabel.Text != _shoutName) { - if (_isUiControl) - return false; - - return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump - || (renderProps.IsActing(CharacterActionState.Walking) && _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump); + _nameLabel.Visible = true; + _nameLabel.BlinkRate = 250; + _nameLabel.Text = _shoutName; + } + else if (_shoutName == string.Empty) + { + _nameLabel.Visible = false; } - private int GetSteppingStoneOffset(CharacterRenderProperties renderProps) + if (_spellCastTime.HasValue && (DateTime.Now - _spellCastTime.Value).TotalMilliseconds >= 600) { - var isSteppingStone = GetIsSteppingStone(renderProps); + StopShout(); + } - if (isSteppingStone && renderProps.IsActing(CharacterActionState.Walking)) - { - switch (renderProps.ActualWalkFrame) - { - case 1: return -8; - case 2: return -16; - case 3: return -16; - case 4: return -8; - } - } + _nameLabel.DrawPosition = GetNameLabelPosition(); + } - return 0; - } + private Vector2 GetNameLabelPosition() + { + NameLabelY = DrawArea.Y - 12 - (int)(_nameLabel?.ActualHeight ?? 0) + ((int)Character.RenderProperties.SitState) * 10; + return new Vector2(HorizontalCenter - (_nameLabel.ActualWidth / 2f), NameLabelY); + } - private void CheckForDead() + private bool GetIsSteppingStone(CharacterRenderProperties renderProps) + { + if (_isUiControl) + return false; + + return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump + || (renderProps.IsActing(CharacterActionState.Walking) && _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump); + } + + private int GetSteppingStoneOffset(CharacterRenderProperties renderProps) + { + var isSteppingStone = GetIsSteppingStone(renderProps); + + if (isSteppingStone && renderProps.IsActing(CharacterActionState.Walking)) { - if (_lastIsDead != _character.RenderProperties.IsDead) + switch (renderProps.ActualWalkFrame) { - _lastIsDead = _character.RenderProperties.IsDead; - if (_lastIsDead) - { - _sfxPlayer.PlaySfx(SoundEffectID.Dead); - } + case 1: return -8; + case 2: return -16; + case 3: return -16; + case 4: return -8; } } - private void ClipHair() - { - if (Character.RenderProperties.HatGraphic == 0 || - _hatMetadataProvider.GetValueOrDefault(Character.RenderProperties.HatGraphic).ClipMode != HatMaskType.Standard) - return; + return 0; + } - lock (_rt_locker_) + private void CheckForDead() + { + if (_lastIsDead != _character.RenderProperties.IsDead) + { + _lastIsDead = _character.RenderProperties.IsDead; + if (_lastIsDead) { - // oof. I really need to learn how to use shaders or stencil buffer. - // https://gamedev.stackexchange.com/questions/38118/best-way-to-mask-2d-sprites-in-xna/38150#38150 - - // note: this operation causes a high number of GC events as the character's frame changes (walking/attacking) - _charRenderTarget.GetData(_rtColorData); - for (int i = 0; i < _rtColorData.Length; i++) - { - if (_rtColorData[i] == Color.Black) - _rtColorData[i].A = 0; - } - _charRenderTarget.SetData(_rtColorData); + _sfxPlayer.PlaySfx(SoundEffectID.Dead); } } + } - #endregion + private void ClipHair() + { + if (Character.RenderProperties.HatGraphic == 0 || + _hatMetadataProvider.GetValueOrDefault(Character.RenderProperties.HatGraphic).ClipMode != HatMaskType.Standard) + return; - public bool EffectIsPlaying() + lock (_rt_locker_) { - return _effectRenderer.State == EffectState.Playing; + // oof. I really need to learn how to use shaders or stencil buffer. + // https://gamedev.stackexchange.com/questions/38118/best-way-to-mask-2d-sprites-in-xna/38150#38150 + + // note: this operation causes a high number of GC events as the character's frame changes (walking/attacking) + _charRenderTarget.GetData(_rtColorData); + for (int i = 0; i < _rtColorData.Length; i++) + { + if (_rtColorData[i] == Color.Black) + _rtColorData[i].A = 0; + } + _charRenderTarget.SetData(_rtColorData); } + } - public void PlayEffect(int graphic) - { - if (_effectRenderer.EffectID == graphic && _effectRenderer.State == EffectState.Playing) - _effectRenderer.Restart(); + #endregion - _effectRenderer.PlayEffect(graphic, this); - } + public bool EffectIsPlaying() + { + return _effectRenderer.State == EffectState.Playing; + } - // Called when the spell cast begins - public void ShoutSpellPrep(string spellName) - { - _shoutName = spellName; - } + public void PlayEffect(int graphic) + { + if (_effectRenderer.EffectID == graphic && _effectRenderer.State == EffectState.Playing) + _effectRenderer.Restart(); - // Called when the spell prep time ends and the player actually casts the spell - public void ShoutSpellCast() - { - _nameLabel.BlinkRate = null; - _nameLabel.ForeColor = Color.FromNonPremultiplied(0xf5, 0xc8, 0x9c, 0xff); // todo: make constant for this - _spellCastTime = DateTime.Now; - } + _effectRenderer.PlayEffect(graphic, this); + } - // Called when the shout (spell prep time) should be cancelled without casting - public void StopShout() - { - if (_nameLabel == null) - return; + // Called when the spell cast begins + public void ShoutSpellPrep(string spellName) + { + _shoutName = spellName; + } - _nameLabel.Visible = false; - _nameLabel.Text = _character.Name; - _nameLabel.ForeColor = Color.White; - _nameLabel.BlinkRate = null; - _shoutName = string.Empty; - _spellCastTime = null; - } + // Called when the spell prep time ends and the player actually casts the spell + public void ShoutSpellCast() + { + _nameLabel.BlinkRate = null; + _nameLabel.ForeColor = Color.FromNonPremultiplied(0xf5, 0xc8, 0x9c, 0xff); // todo: make constant for this + _spellCastTime = DateTime.Now; + } - public void ShowDamageCounter(int damage, int percentHealth, bool isHeal) - { - if (isHeal) - _healthBarRenderer.SetHealth(damage, percentHealth, () => _chatBubble.Value.Show()); - else - _healthBarRenderer.SetDamage(damage.SomeWhen(d => d > 0), percentHealth, () => _chatBubble.Value.Show()); + // Called when the shout (spell prep time) should be cancelled without casting + public void StopShout() + { + if (_nameLabel == null) + return; + + _nameLabel.Visible = false; + _nameLabel.Text = _character.Name; + _nameLabel.ForeColor = Color.White; + _nameLabel.BlinkRate = null; + _shoutName = string.Empty; + _spellCastTime = null; + } - _chatBubble.Value.Hide(); - } + public void ShowDamageCounter(int damage, int percentHealth, bool isHeal) + { + if (isHeal) + _healthBarRenderer.SetHealth(damage, percentHealth, () => _chatBubble.Value.Show()); + else + _healthBarRenderer.SetDamage(damage.SomeWhen(d => d > 0), percentHealth, () => _chatBubble.Value.Show()); - public void ShowChatBubble(string message, bool isGroupChat) - { - _chatBubble.Value.SetMessage(message, isGroupChat); - } + _chatBubble.Value.Hide(); + } + + public void ShowChatBubble(string message, bool isGroupChat) + { + _chatBubble.Value.SetMessage(message, isGroupChat); + } - private void RecreateRenderTarget() + private void RecreateRenderTarget() + { + lock (_rt_locker_) { - lock (_rt_locker_) - { - _charRenderTarget?.Dispose(); - _charRenderTarget = _renderTargetFactory.CreateRenderTarget(); + _charRenderTarget?.Dispose(); + _charRenderTarget = _renderTargetFactory.CreateRenderTarget(); - _rtColorData = new Color[_charRenderTarget.Width * _charRenderTarget.Height]; - } + _rtColorData = new Color[_charRenderTarget.Width * _charRenderTarget.Height]; } + } - private void RecreateRenderTargetEvent(object sender, EventArgs e) - { - RecreateRenderTarget(); + private void RecreateRenderTargetEvent(object sender, EventArgs e) + { + RecreateRenderTarget(); - if (_character == _characterProvider.MainCharacter) - SetToCenterScreenPosition(); - } + if (_character == _characterProvider.MainCharacter) + SetToCenterScreenPosition(); + } - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - _outline?.Dispose(); + _outline?.Dispose(); - if (Game != null && Game.Components != null && Game.Components.Contains(_nameLabel)) - Game.Components.Remove(_nameLabel); - _nameLabel?.Dispose(); + if (Game != null && Game.Components != null && Game.Components.Contains(_nameLabel)) + Game.Components.Remove(_nameLabel); + _nameLabel?.Dispose(); - if (_chatBubble.IsValueCreated) - _chatBubble.Value?.Dispose(); + if (_chatBubble.IsValueCreated) + _chatBubble.Value?.Dispose(); - _sb?.Dispose(); + _sb?.Dispose(); - _clientWindowSizeRepository.GameWindowSizeChanged -= RecreateRenderTargetEvent; + _clientWindowSizeRepository.GameWindowSizeChanged -= RecreateRenderTargetEvent; - lock (_rt_locker_) - _charRenderTarget?.Dispose(); - } - - base.Dispose(disposing); + lock (_rt_locker_) + _charRenderTarget?.Dispose(); } + + base.Dispose(disposing); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs b/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs index 219739c6f..2aea2c751 100644 --- a/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs +++ b/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs @@ -11,186 +11,185 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +[AutoMappedType] +public class CharacterRendererUpdater : ICharacterRendererUpdater { - [AutoMappedType] - public class CharacterRendererUpdater : ICharacterRendererUpdater + private readonly ICharacterProvider _characterProvider; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly ICharacterRendererRepository _characterRendererRepository; + private readonly ICharacterStateCache _characterStateCache; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + + public CharacterRendererUpdater(ICharacterProvider characterProvider, + ICurrentMapStateRepository currentMapStateRepository, + ICharacterRendererFactory characterRendererFactory, + ICharacterRendererRepository characterRendererRepository, + ICharacterStateCache characterStateCache, + IFixedTimeStepRepository fixedTimeStepRepository) { - private readonly ICharacterProvider _characterProvider; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly ICharacterRendererRepository _characterRendererRepository; - private readonly ICharacterStateCache _characterStateCache; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - - public CharacterRendererUpdater(ICharacterProvider characterProvider, - ICurrentMapStateRepository currentMapStateRepository, - ICharacterRendererFactory characterRendererFactory, - ICharacterRendererRepository characterRendererRepository, - ICharacterStateCache characterStateCache, - IFixedTimeStepRepository fixedTimeStepRepository) - { - _characterProvider = characterProvider; - _currentMapStateRepository = currentMapStateRepository; - _characterRendererFactory = characterRendererFactory; - _characterRendererRepository = characterRendererRepository; - _characterStateCache = characterStateCache; - _fixedTimeStepRepository = fixedTimeStepRepository; - } + _characterProvider = characterProvider; + _currentMapStateRepository = currentMapStateRepository; + _characterRendererFactory = characterRendererFactory; + _characterRendererRepository = characterRendererRepository; + _characterStateCache = characterStateCache; + _fixedTimeStepRepository = fixedTimeStepRepository; + } - public void UpdateCharacters(GameTime gameTime) - { - CreateMainCharacterRendererAndCacheProperties(); - CreateOtherCharacterRenderersAndCacheProperties(); - UpdateAllCharacters(gameTime); + public void UpdateCharacters(GameTime gameTime) + { + CreateMainCharacterRendererAndCacheProperties(); + CreateOtherCharacterRenderersAndCacheProperties(); + UpdateAllCharacters(gameTime); - RemoveStaleCharacters(); - UpdateDeadCharacters(); - } + RemoveStaleCharacters(); + UpdateDeadCharacters(); + } - private void CreateMainCharacterRendererAndCacheProperties() - { - var actual = _characterProvider.MainCharacter; - var cached = _characterStateCache.MainCharacter; + private void CreateMainCharacterRendererAndCacheProperties() + { + var actual = _characterProvider.MainCharacter; + var cached = _characterStateCache.MainCharacter; - cached.Match( - some: c => - { - if (c != actual) - { - _characterRendererRepository.MainCharacterRenderer.MatchSome(r => r.Character = _characterProvider.MainCharacter); - _characterStateCache.UpdateMainCharacterState(actual); - } - }, - none: () => + cached.Match( + some: c => + { + if (c != actual) { + _characterRendererRepository.MainCharacterRenderer.MatchSome(r => r.Character = _characterProvider.MainCharacter); _characterStateCache.UpdateMainCharacterState(actual); + } + }, + none: () => + { + _characterStateCache.UpdateMainCharacterState(actual); - var renderer = InitializeRendererForCharacter(_characterProvider.MainCharacter); - renderer.SetToCenterScreenPosition(); - _characterRendererRepository.MainCharacterRenderer = Option.Some(renderer); - }); - } + var renderer = InitializeRendererForCharacter(_characterProvider.MainCharacter); + renderer.SetToCenterScreenPosition(); + _characterRendererRepository.MainCharacterRenderer = Option.Some(renderer); + }); + } - private void CreateOtherCharacterRenderersAndCacheProperties() + private void CreateOtherCharacterRenderersAndCacheProperties() + { + foreach (var character in _currentMapStateRepository.Characters) { - foreach (var character in _currentMapStateRepository.Characters) - { - var id = character.ID; + var id = character.ID; - _characterStateCache.HasCharacterWithID(id) - .SomeWhen(b => b) - .Map(_ => _characterStateCache.OtherCharacters[id]) - .Match( - some: cached => - { - if (cached != character) - { - if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) - _characterRendererRepository.CharacterRenderers[id].Character = character; - _characterStateCache.UpdateCharacterState(id, character); - } - }, - none: () => + _characterStateCache.HasCharacterWithID(id) + .SomeWhen(b => b) + .Map(_ => _characterStateCache.OtherCharacters[id]) + .Match( + some: cached => + { + if (cached != character) { + if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) + _characterRendererRepository.CharacterRenderers[id].Character = character; _characterStateCache.UpdateCharacterState(id, character); + } + }, + none: () => + { + _characterStateCache.UpdateCharacterState(id, character); - var renderer = InitializeRendererForCharacter(character); + var renderer = InitializeRendererForCharacter(character); - if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) - { - _characterRendererRepository.CharacterRenderers[id].Dispose(); - _characterRendererRepository.CharacterRenderers.Remove(id); - } - _characterRendererRepository.CharacterRenderers.Add(id, renderer); - }); - - if (_characterRendererRepository.NeedsWarpArriveAnimation.Contains(id) && - _characterRendererRepository.CharacterRenderers.ContainsKey(id)) - { - _characterRendererRepository.CharacterRenderers[id].PlayEffect((int)HardCodedEffect.WarpArrive); - _characterRendererRepository.NeedsWarpArriveAnimation.Remove(id); - } + if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) + { + _characterRendererRepository.CharacterRenderers[id].Dispose(); + _characterRendererRepository.CharacterRenderers.Remove(id); + } + _characterRendererRepository.CharacterRenderers.Add(id, renderer); + }); + + if (_characterRendererRepository.NeedsWarpArriveAnimation.Contains(id) && + _characterRendererRepository.CharacterRenderers.ContainsKey(id)) + { + _characterRendererRepository.CharacterRenderers[id].PlayEffect((int)HardCodedEffect.WarpArrive); + _characterRendererRepository.NeedsWarpArriveAnimation.Remove(id); } } + } - private void UpdateAllCharacters(GameTime gameTime) - { - _characterRendererRepository.MainCharacterRenderer.MatchSome(x => x.Update(gameTime)); - foreach (var renderer in _characterRendererRepository.CharacterRenderers.Values) - renderer.Update(gameTime); - } + private void UpdateAllCharacters(GameTime gameTime) + { + _characterRendererRepository.MainCharacterRenderer.MatchSome(x => x.Update(gameTime)); + foreach (var renderer in _characterRendererRepository.CharacterRenderers.Values) + renderer.Update(gameTime); + } + + private void RemoveStaleCharacters() + { + var staleIDs = _characterStateCache.OtherCharacters.Keys + .Where(x => !_currentMapStateRepository.Characters.ContainsKey(x)); - private void RemoveStaleCharacters() + foreach (var id in staleIDs) { - var staleIDs = _characterStateCache.OtherCharacters.Keys - .Where(x => !_currentMapStateRepository.Characters.ContainsKey(x)); + _characterStateCache.RemoveCharacterState(id); - foreach (var id in staleIDs) + if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) { - _characterStateCache.RemoveCharacterState(id); - - if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) + if (_characterRendererRepository.CharacterRenderers[id].EffectIsPlaying()) { - if (_characterRendererRepository.CharacterRenderers[id].EffectIsPlaying()) - { - _characterRendererRepository.CharacterRenderers[id].Visible = false; - continue; - } - - _characterRendererRepository.CharacterRenderers[id].Dispose(); - _characterRendererRepository.CharacterRenderers.Remove(id); + _characterRendererRepository.CharacterRenderers[id].Visible = false; + continue; } + + _characterRendererRepository.CharacterRenderers[id].Dispose(); + _characterRendererRepository.CharacterRenderers.Remove(id); } } + } - private void UpdateDeadCharacters() - { - var deadCharacters = new List(); + private void UpdateDeadCharacters() + { + var deadCharacters = new List(); - foreach (var character in _currentMapStateRepository.Characters.Where(x => x.RenderProperties.IsDead)) - { - _characterStateCache.DeathStartTimes.SingleOrNone(x => x.UniqueID == character.ID) - .Match( - none: () => _characterStateCache.AddDeathStartTime(character.ID), - some: actionTime => + foreach (var character in _currentMapStateRepository.Characters.Where(x => x.RenderProperties.IsDead)) + { + _characterStateCache.DeathStartTimes.SingleOrNone(x => x.UniqueID == character.ID) + .Match( + none: () => _characterStateCache.AddDeathStartTime(character.ID), + some: actionTime => + { + if ((_fixedTimeStepRepository.TickCount - actionTime.ActionTick) >= 200) // 200 ticks * 10ms = 2 seconds { - if ((_fixedTimeStepRepository.TickCount - actionTime.ActionTick) >= 200) // 200 ticks * 10ms = 2 seconds - { - _characterStateCache.RemoveDeathStartTime(character.ID); - _characterStateCache.RemoveCharacterState(character.ID); + _characterStateCache.RemoveDeathStartTime(character.ID); + _characterStateCache.RemoveCharacterState(character.ID); - if (_characterRendererRepository.CharacterRenderers.ContainsKey(character.ID)) - { - _characterRendererRepository.CharacterRenderers[character.ID].Dispose(); - _characterRendererRepository.CharacterRenderers.Remove(character.ID); - } - - deadCharacters.Add(character); + if (_characterRendererRepository.CharacterRenderers.ContainsKey(character.ID)) + { + _characterRendererRepository.CharacterRenderers[character.ID].Dispose(); + _characterRendererRepository.CharacterRenderers.Remove(character.ID); } - }); - } - foreach (var dead in deadCharacters) - _currentMapStateRepository.Characters.Remove(dead); + deadCharacters.Add(character); + } + }); } - private ICharacterRenderer InitializeRendererForCharacter(EOLib.Domain.Character.Character character) - { - var renderer = _characterRendererFactory.CreateCharacterRenderer(character, isUiControl: false); - renderer.Initialize(); - return renderer; - } + foreach (var dead in deadCharacters) + _currentMapStateRepository.Characters.Remove(dead); + } - public void Dispose() - { - _characterStateCache.Reset(); - _characterRendererRepository.Dispose(); - } + private ICharacterRenderer InitializeRendererForCharacter(EOLib.Domain.Character.Character character) + { + var renderer = _characterRendererFactory.CreateCharacterRenderer(character, isUiControl: false); + renderer.Initialize(); + return renderer; } - public interface ICharacterRendererUpdater : IDisposable + public void Dispose() { - void UpdateCharacters(GameTime gameTime); + _characterStateCache.Reset(); + _characterRendererRepository.Dispose(); } +} + +public interface ICharacterRendererUpdater : IDisposable +{ + void UpdateCharacters(GameTime gameTime); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterStateCache.cs b/EndlessClient/Rendering/Character/CharacterStateCache.cs index bbd518cf3..ebdc70dc1 100644 --- a/EndlessClient/Rendering/Character/CharacterStateCache.cs +++ b/EndlessClient/Rendering/Character/CharacterStateCache.cs @@ -7,74 +7,73 @@ using DomainCharacter = EOLib.Domain.Character.Character; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +[AutoMappedType(IsSingleton = true)] +public class CharacterStateCache : ICharacterStateCache { - [AutoMappedType(IsSingleton = true)] - public class CharacterStateCache : ICharacterStateCache + public Option MainCharacter { get; private set; } + + private readonly Dictionary _otherCharacters; + private readonly List _deathStartTimes; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + + public IReadOnlyDictionary OtherCharacters => _otherCharacters; + + public IReadOnlyList DeathStartTimes => _deathStartTimes; + + public CharacterStateCache(IFixedTimeStepRepository fixedTimeStepRepository) + { + MainCharacter = Option.None(); + _otherCharacters = new Dictionary(); + _deathStartTimes = new List(); + _fixedTimeStepRepository = fixedTimeStepRepository; + } + + public bool HasCharacterWithID(int id) + { + return _otherCharacters.ContainsKey(id); + } + + public void UpdateMainCharacterState(DomainCharacter updatedCharacter) + { + MainCharacter = Option.Some(updatedCharacter); + } + + public void UpdateCharacterState(int id, DomainCharacter updatedCharacter) + { + _otherCharacters[id] = updatedCharacter; + } + + public void RemoveCharacterState(int id) + { + _otherCharacters.Remove(id); + } + + public void AddDeathStartTime(int id) + { + if (_deathStartTimes.Any(x => x.UniqueID == id)) + throw new ArgumentException("That character already started dying...", nameof(id)); + + _deathStartTimes.Add(new RenderFrameActionTime(id, _fixedTimeStepRepository.TickCount)); + } + + public void RemoveDeathStartTime(int id) + { + if (_deathStartTimes.All(x => x.UniqueID != id)) + throw new ArgumentException("That character isn't dying...", nameof(id)); + + _deathStartTimes.RemoveAll(x => x.UniqueID == id); + } + + public void ClearAllOtherCharacterStates() + { + _otherCharacters.Clear(); + } + + public void Reset() { - public Option MainCharacter { get; private set; } - - private readonly Dictionary _otherCharacters; - private readonly List _deathStartTimes; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - - public IReadOnlyDictionary OtherCharacters => _otherCharacters; - - public IReadOnlyList DeathStartTimes => _deathStartTimes; - - public CharacterStateCache(IFixedTimeStepRepository fixedTimeStepRepository) - { - MainCharacter = Option.None(); - _otherCharacters = new Dictionary(); - _deathStartTimes = new List(); - _fixedTimeStepRepository = fixedTimeStepRepository; - } - - public bool HasCharacterWithID(int id) - { - return _otherCharacters.ContainsKey(id); - } - - public void UpdateMainCharacterState(DomainCharacter updatedCharacter) - { - MainCharacter = Option.Some(updatedCharacter); - } - - public void UpdateCharacterState(int id, DomainCharacter updatedCharacter) - { - _otherCharacters[id] = updatedCharacter; - } - - public void RemoveCharacterState(int id) - { - _otherCharacters.Remove(id); - } - - public void AddDeathStartTime(int id) - { - if (_deathStartTimes.Any(x => x.UniqueID == id)) - throw new ArgumentException("That character already started dying...", nameof(id)); - - _deathStartTimes.Add(new RenderFrameActionTime(id, _fixedTimeStepRepository.TickCount)); - } - - public void RemoveDeathStartTime(int id) - { - if (_deathStartTimes.All(x => x.UniqueID != id)) - throw new ArgumentException("That character isn't dying...", nameof(id)); - - _deathStartTimes.RemoveAll(x => x.UniqueID == id); - } - - public void ClearAllOtherCharacterStates() - { - _otherCharacters.Clear(); - } - - public void Reset() - { - MainCharacter = Option.None(); - ClearAllOtherCharacterStates(); - } + MainCharacter = Option.None(); + ClearAllOtherCharacterStates(); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterTextures.cs b/EndlessClient/Rendering/Character/CharacterTextures.cs index 9cfa89f4c..23997259b 100644 --- a/EndlessClient/Rendering/Character/CharacterTextures.cs +++ b/EndlessClient/Rendering/Character/CharacterTextures.cs @@ -3,48 +3,47 @@ using EOLib.Domain.Character; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +[MappedType(BaseType = typeof(ICharacterTextures))] +public class CharacterTextures : ICharacterTextures { - [MappedType(BaseType = typeof(ICharacterTextures))] - public class CharacterTextures : ICharacterTextures + private readonly ICharacterSpriteCalculator _characterSpriteCalculator; + public ISpriteSheet Boots { get; private set; } + public ISpriteSheet Armor { get; private set; } + public ISpriteSheet Hat { get; private set; } + public ISpriteSheet Shield { get; private set; } + public ISpriteSheet Weapon { get; private set; } + public ISpriteSheet WeaponExtra { get; private set; } + public ISpriteSheet WeaponSlash { get; private set; } + + public ISpriteSheet Hair { get; private set; } + public ISpriteSheet Skin { get; private set; } + + public ISpriteSheet Emote { get; private set; } + public ISpriteSheet Face { get; private set; } + + public CharacterTextures(ICharacterSpriteCalculator characterSpriteCalculator) + { + _characterSpriteCalculator = characterSpriteCalculator; + } + + public void Refresh(CharacterRenderProperties characterRenderProperties) { - private readonly ICharacterSpriteCalculator _characterSpriteCalculator; - public ISpriteSheet Boots { get; private set; } - public ISpriteSheet Armor { get; private set; } - public ISpriteSheet Hat { get; private set; } - public ISpriteSheet Shield { get; private set; } - public ISpriteSheet Weapon { get; private set; } - public ISpriteSheet WeaponExtra { get; private set; } - public ISpriteSheet WeaponSlash { get; private set; } - - public ISpriteSheet Hair { get; private set; } - public ISpriteSheet Skin { get; private set; } - - public ISpriteSheet Emote { get; private set; } - public ISpriteSheet Face { get; private set; } - - public CharacterTextures(ICharacterSpriteCalculator characterSpriteCalculator) - { - _characterSpriteCalculator = characterSpriteCalculator; - } - - public void Refresh(CharacterRenderProperties characterRenderProperties) - { - Boots = _characterSpriteCalculator.GetBootsTexture(characterRenderProperties); - Armor = _characterSpriteCalculator.GetArmorTexture(characterRenderProperties); - Hat = _characterSpriteCalculator.GetHatTexture(characterRenderProperties); - Shield = _characterSpriteCalculator.GetShieldTexture(characterRenderProperties); - - var weaponTextures = _characterSpriteCalculator.GetWeaponTextures(characterRenderProperties); - Weapon = weaponTextures[0]; - WeaponExtra = weaponTextures[1]; - - WeaponSlash = _characterSpriteCalculator.GetWeaponSlash(characterRenderProperties); - - Hair = _characterSpriteCalculator.GetHairTexture(characterRenderProperties); - Skin = _characterSpriteCalculator.GetSkinTexture(characterRenderProperties); - Emote = _characterSpriteCalculator.GetEmoteTexture(characterRenderProperties); - Face = _characterSpriteCalculator.GetFaceTexture(characterRenderProperties); - } + Boots = _characterSpriteCalculator.GetBootsTexture(characterRenderProperties); + Armor = _characterSpriteCalculator.GetArmorTexture(characterRenderProperties); + Hat = _characterSpriteCalculator.GetHatTexture(characterRenderProperties); + Shield = _characterSpriteCalculator.GetShieldTexture(characterRenderProperties); + + var weaponTextures = _characterSpriteCalculator.GetWeaponTextures(characterRenderProperties); + Weapon = weaponTextures[0]; + WeaponExtra = weaponTextures[1]; + + WeaponSlash = _characterSpriteCalculator.GetWeaponSlash(characterRenderProperties); + + Hair = _characterSpriteCalculator.GetHairTexture(characterRenderProperties); + Skin = _characterSpriteCalculator.GetSkinTexture(characterRenderProperties); + Emote = _characterSpriteCalculator.GetEmoteTexture(characterRenderProperties); + Face = _characterSpriteCalculator.GetFaceTexture(characterRenderProperties); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ICharacterRenderer.cs b/EndlessClient/Rendering/Character/ICharacterRenderer.cs index 02a7d51a4..b0b30b0d4 100644 --- a/EndlessClient/Rendering/Character/ICharacterRenderer.cs +++ b/EndlessClient/Rendering/Character/ICharacterRenderer.cs @@ -2,24 +2,23 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +public interface ICharacterRenderer : IDrawable, IUpdateable, IGameComponent, IDisposable, IMapActor, ISpellCaster { - public interface ICharacterRenderer : IDrawable, IUpdateable, IGameComponent, IDisposable, IMapActor, ISpellCaster - { - EOLib.Domain.Character.Character Character { get; set; } + EOLib.Domain.Character.Character Character { get; set; } - new bool Visible { get; set; } + new bool Visible { get; set; } - bool Transparent { get; set; } + bool Transparent { get; set; } - void SetAbsoluteScreenPosition(int xPosition, int yPosition); + void SetAbsoluteScreenPosition(int xPosition, int yPosition); - void SetToCenterScreenPosition(); + void SetToCenterScreenPosition(); - void DrawToSpriteBatch(SpriteBatch spriteBatch); + void DrawToSpriteBatch(SpriteBatch spriteBatch); - void ShowName(); + void ShowName(); - void HideName(); - } + void HideName(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs b/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs index 3249f039e..78122a6fb 100644 --- a/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs +++ b/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs @@ -3,51 +3,50 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +public interface ICharacterRendererRepository : IDisposable { - public interface ICharacterRendererRepository : IDisposable - { - Option MainCharacterRenderer { get; set; } + Option MainCharacterRenderer { get; set; } - Dictionary CharacterRenderers { get; set; } + Dictionary CharacterRenderers { get; set; } - HashSet NeedsWarpArriveAnimation { get; } - } + HashSet NeedsWarpArriveAnimation { get; } +} - public interface ICharacterRendererProvider - { - Option MainCharacterRenderer { get; } +public interface ICharacterRendererProvider +{ + Option MainCharacterRenderer { get; } - IReadOnlyDictionary CharacterRenderers { get; } + IReadOnlyDictionary CharacterRenderers { get; } - HashSet NeedsWarpArriveAnimation { get; } - } + HashSet NeedsWarpArriveAnimation { get; } +} - [AutoMappedType(IsSingleton = true)] - public class CharacterRendererRepository : ICharacterRendererRepository, ICharacterRendererProvider - { - public Option MainCharacterRenderer { get; set; } +[AutoMappedType(IsSingleton = true)] +public class CharacterRendererRepository : ICharacterRendererRepository, ICharacterRendererProvider +{ + public Option MainCharacterRenderer { get; set; } - public Dictionary CharacterRenderers { get; set; } + public Dictionary CharacterRenderers { get; set; } - IReadOnlyDictionary ICharacterRendererProvider.CharacterRenderers => CharacterRenderers; + IReadOnlyDictionary ICharacterRendererProvider.CharacterRenderers => CharacterRenderers; - public HashSet NeedsWarpArriveAnimation { get; set; } + public HashSet NeedsWarpArriveAnimation { get; set; } - public CharacterRendererRepository() - { - CharacterRenderers = new Dictionary(64); - NeedsWarpArriveAnimation = new HashSet(); - } + public CharacterRendererRepository() + { + CharacterRenderers = new Dictionary(64); + NeedsWarpArriveAnimation = new HashSet(); + } - public void Dispose() - { - MainCharacterRenderer.MatchSome(x => x.Dispose()); - MainCharacterRenderer = Option.None(); + public void Dispose() + { + MainCharacterRenderer.MatchSome(x => x.Dispose()); + MainCharacterRenderer = Option.None(); - foreach (var renderer in CharacterRenderers.Values) - renderer.Dispose(); - CharacterRenderers.Clear(); - } + foreach (var renderer in CharacterRenderers.Values) + renderer.Dispose(); + CharacterRenderers.Clear(); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ICharacterStateCache.cs b/EndlessClient/Rendering/Character/ICharacterStateCache.cs index 4dba53934..5fa2892af 100644 --- a/EndlessClient/Rendering/Character/ICharacterStateCache.cs +++ b/EndlessClient/Rendering/Character/ICharacterStateCache.cs @@ -3,30 +3,29 @@ using DomainCharacter = EOLib.Domain.Character.Character; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +public interface ICharacterStateCache { - public interface ICharacterStateCache - { - Option MainCharacter { get; } + Option MainCharacter { get; } - IReadOnlyDictionary OtherCharacters { get; } + IReadOnlyDictionary OtherCharacters { get; } - IReadOnlyList DeathStartTimes { get; } + IReadOnlyList DeathStartTimes { get; } - bool HasCharacterWithID(int id); + bool HasCharacterWithID(int id); - void UpdateMainCharacterState(DomainCharacter updatedCharacter); + void UpdateMainCharacterState(DomainCharacter updatedCharacter); - void UpdateCharacterState(int id, DomainCharacter updatedCharacter); + void UpdateCharacterState(int id, DomainCharacter updatedCharacter); - void RemoveCharacterState(int id); + void RemoveCharacterState(int id); - void AddDeathStartTime(int id); + void AddDeathStartTime(int id); - void RemoveDeathStartTime(int id); + void RemoveDeathStartTime(int id); - void ClearAllOtherCharacterStates(); + void ClearAllOtherCharacterStates(); - void Reset(); - } + void Reset(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ICharacterTextures.cs b/EndlessClient/Rendering/Character/ICharacterTextures.cs index ae4e0d2f5..3c29d3d07 100644 --- a/EndlessClient/Rendering/Character/ICharacterTextures.cs +++ b/EndlessClient/Rendering/Character/ICharacterTextures.cs @@ -2,24 +2,23 @@ using EOLib.Domain.Character; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +public interface ICharacterTextures { - public interface ICharacterTextures - { - ISpriteSheet Boots { get; } - ISpriteSheet Armor { get; } - ISpriteSheet Hat { get; } - ISpriteSheet Shield { get; } - ISpriteSheet Weapon { get; } - ISpriteSheet WeaponExtra { get; } - ISpriteSheet WeaponSlash { get; } + ISpriteSheet Boots { get; } + ISpriteSheet Armor { get; } + ISpriteSheet Hat { get; } + ISpriteSheet Shield { get; } + ISpriteSheet Weapon { get; } + ISpriteSheet WeaponExtra { get; } + ISpriteSheet WeaponSlash { get; } - ISpriteSheet Hair { get; } - ISpriteSheet Skin { get; } + ISpriteSheet Hair { get; } + ISpriteSheet Skin { get; } - ISpriteSheet Emote { get; } - ISpriteSheet Face { get; } + ISpriteSheet Emote { get; } + ISpriteSheet Face { get; } - void Refresh(CharacterRenderProperties characterRenderProperties); - } + void Refresh(CharacterRenderProperties characterRenderProperties); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ISpellCaster.cs b/EndlessClient/Rendering/Character/ISpellCaster.cs index b357779ac..06a26c4ff 100644 --- a/EndlessClient/Rendering/Character/ISpellCaster.cs +++ b/EndlessClient/Rendering/Character/ISpellCaster.cs @@ -1,11 +1,10 @@ -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +public interface ISpellCaster { - public interface ISpellCaster - { - void ShoutSpellPrep(string spellName); + void ShoutSpellPrep(string spellName); - void ShoutSpellCast(); + void ShoutSpellCast(); - void StopShout(); - } + void StopShout(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs b/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs index fda41ba48..2ea30d84c 100644 --- a/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs +++ b/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs @@ -11,239 +11,238 @@ using System; using System.Diagnostics; -namespace EndlessClient.Rendering.Character +namespace EndlessClient.Rendering.Character; + +public class PeriodicEmoteHandler : GameComponent, IPeriodicEmoteHandler { - public class PeriodicEmoteHandler : GameComponent, IPeriodicEmoteHandler + // Time before periodic AFK emotes start firing (5 minutes) + private const int AFK_TIME_MS = 300000; + // Time between each emote once period emotes start firing (30 seconds) + private const int AFK_TIME_BETWEEN_EMOTES_MS = 30000; + + // Time before periodic alert messages start firing (30 minutes) + private const int AFK_TIME_ALERT_MS = 1800000; + // Time between each periodic alert message fires (60 seconds) + private const int AFK_TIME_BETWEEN_ALERTS_MS = 60000; + // Time between first alert and alternate alert (3.6 seconds) + private const int AFK_TIME_ALT_ALERT_MS = 3600; + + // Time from arena launch until the block messages start showing + private const int ARENA_BLOCK_INITIAL_TIME_MS = 6000; + // Time between subsequent messages + private const int ARENA_BLOCK_WARNING_INTERVAL_MS = 1200; + // Intervals before disconnect + private const int ARENA_BLOCK_MAX_WARNINGS = 6; + + private readonly ICharacterActions _characterActions; + private readonly IChatBubbleActions _chatBubbleActions; + private readonly IUserInputTimeProvider _userInputTimeProvider; + private readonly ICharacterRepository _characterRepository; + private readonly ICharacterAnimator _animator; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IMainButtonController _mainButtonController; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ISfxPlayer _sfxPlayer; + + private readonly Random _random; + + // drunk stuff + private Option _drunkStart; + private Option _drunkTimeSinceLastEmote; + private int _drunkIntervalSeconds; + private double _drunkTimeoutSeconds; + + // afk stuff + private Option _afkTimeSinceLastEmote; + private Option _afkTimeSinceLastAlert; + private bool _altAlert; + + // arena block stuff + private Option _arenaTimer; + private int _arenaWarningCounter; + + public PeriodicEmoteHandler(IEndlessGameProvider endlessGameProvider, + ICharacterActions characterActions, + IChatBubbleActions chatBubbleActions, + IUserInputTimeProvider userInputTimeProvider, + ICharacterRepository characterRepository, + ICharacterAnimator animator, + IStatusLabelSetter statusLabelSetter, + IMainButtonController mainButtonController, + ILocalizedStringFinder localizedStringFinder, + ISfxPlayer sfxPlayer) + : base((Game)endlessGameProvider.Game) { - // Time before periodic AFK emotes start firing (5 minutes) - private const int AFK_TIME_MS = 300000; - // Time between each emote once period emotes start firing (30 seconds) - private const int AFK_TIME_BETWEEN_EMOTES_MS = 30000; - - // Time before periodic alert messages start firing (30 minutes) - private const int AFK_TIME_ALERT_MS = 1800000; - // Time between each periodic alert message fires (60 seconds) - private const int AFK_TIME_BETWEEN_ALERTS_MS = 60000; - // Time between first alert and alternate alert (3.6 seconds) - private const int AFK_TIME_ALT_ALERT_MS = 3600; - - // Time from arena launch until the block messages start showing - private const int ARENA_BLOCK_INITIAL_TIME_MS = 6000; - // Time between subsequent messages - private const int ARENA_BLOCK_WARNING_INTERVAL_MS = 1200; - // Intervals before disconnect - private const int ARENA_BLOCK_MAX_WARNINGS = 6; - - private readonly ICharacterActions _characterActions; - private readonly IChatBubbleActions _chatBubbleActions; - private readonly IUserInputTimeProvider _userInputTimeProvider; - private readonly ICharacterRepository _characterRepository; - private readonly ICharacterAnimator _animator; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IMainButtonController _mainButtonController; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ISfxPlayer _sfxPlayer; - - private readonly Random _random; - - // drunk stuff - private Option _drunkStart; - private Option _drunkTimeSinceLastEmote; - private int _drunkIntervalSeconds; - private double _drunkTimeoutSeconds; - - // afk stuff - private Option _afkTimeSinceLastEmote; - private Option _afkTimeSinceLastAlert; - private bool _altAlert; - - // arena block stuff - private Option _arenaTimer; - private int _arenaWarningCounter; - - public PeriodicEmoteHandler(IEndlessGameProvider endlessGameProvider, - ICharacterActions characterActions, - IChatBubbleActions chatBubbleActions, - IUserInputTimeProvider userInputTimeProvider, - ICharacterRepository characterRepository, - ICharacterAnimator animator, - IStatusLabelSetter statusLabelSetter, - IMainButtonController mainButtonController, - ILocalizedStringFinder localizedStringFinder, - ISfxPlayer sfxPlayer) - : base((Game)endlessGameProvider.Game) - { - _characterActions = characterActions; - _chatBubbleActions = chatBubbleActions; - _userInputTimeProvider = userInputTimeProvider; - _characterRepository = characterRepository; - _animator = animator; - _statusLabelSetter = statusLabelSetter; - _mainButtonController = mainButtonController; - _localizedStringFinder = localizedStringFinder; - _sfxPlayer = sfxPlayer; - _random = new Random(); - } + _characterActions = characterActions; + _chatBubbleActions = chatBubbleActions; + _userInputTimeProvider = userInputTimeProvider; + _characterRepository = characterRepository; + _animator = animator; + _statusLabelSetter = statusLabelSetter; + _mainButtonController = mainButtonController; + _localizedStringFinder = localizedStringFinder; + _sfxPlayer = sfxPlayer; + _random = new Random(); + } - public override void Update(GameTime gameTime) - { - _drunkStart.Match( - some: ds => + public override void Update(GameTime gameTime) + { + _drunkStart.Match( + some: ds => + { + if ((DateTime.Now - ds).TotalSeconds > _drunkTimeoutSeconds) { - if ((DateTime.Now - ds).TotalSeconds > _drunkTimeoutSeconds) - { - _drunkStart = Option.None(); - _drunkTimeSinceLastEmote = Option.None(); - _drunkIntervalSeconds = 0; + _drunkStart = Option.None(); + _drunkTimeSinceLastEmote = Option.None(); + _drunkIntervalSeconds = 0; - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties( - _characterRepository.MainCharacter.RenderProperties.WithIsDrunk(false)); - } - else + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties( + _characterRepository.MainCharacter.RenderProperties.WithIsDrunk(false)); + } + else + { + _drunkTimeSinceLastEmote.MatchSome(dt => { - _drunkTimeSinceLastEmote.MatchSome(dt => + if (dt.Elapsed.TotalSeconds > _drunkIntervalSeconds) { - if (dt.Elapsed.TotalSeconds > _drunkIntervalSeconds) - { - _drunkIntervalSeconds = _random.Next(4, 7); - _drunkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); + _drunkIntervalSeconds = _random.Next(4, 7); + _drunkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); - if (_animator.Emote(_characterRepository.MainCharacter.ID, Emote.Drunk)) - _characterActions.Emote(Emote.Drunk); - } - }); - } - }, - none: () => + if (_animator.Emote(_characterRepository.MainCharacter.ID, Emote.Drunk)) + _characterActions.Emote(Emote.Drunk); + } + }); + } + }, + none: () => + { + if (_characterRepository.MainCharacter.RenderProperties.IsDrunk) { - if (_characterRepository.MainCharacter.RenderProperties.IsDrunk) - { - _drunkStart = Option.Some(DateTime.Now); - _drunkIntervalSeconds = _random.Next(4, 7); - _drunkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); + _drunkStart = Option.Some(DateTime.Now); + _drunkIntervalSeconds = _random.Next(4, 7); + _drunkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); - if (_animator.Emote(_characterRepository.MainCharacter.ID, Emote.Drunk)) - _characterActions.Emote(Emote.Drunk); - } - }); + if (_animator.Emote(_characterRepository.MainCharacter.ID, Emote.Drunk)) + _characterActions.Emote(Emote.Drunk); + } + }); - var now = DateTime.Now; + var now = DateTime.Now; - if ((now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_MS) + if ((now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_MS) + { + if ((now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_MS + AFK_TIME_ALERT_MS) { - if ((now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_MS + AFK_TIME_ALERT_MS) - { - _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); - } - else - { - _afkTimeSinceLastEmote.Match( - some: at => - { - if (at.ElapsedMilliseconds >= AFK_TIME_BETWEEN_EMOTES_MS) - { - _animator.Emote(_characterRepository.MainCharacter.ID, Emote.Moon); - _characterActions.Emote(Emote.Moon); - _afkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); - } - }, - none: () => + _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); + } + else + { + _afkTimeSinceLastEmote.Match( + some: at => + { + if (at.ElapsedMilliseconds >= AFK_TIME_BETWEEN_EMOTES_MS) { _animator.Emote(_characterRepository.MainCharacter.ID, Emote.Moon); _characterActions.Emote(Emote.Moon); _afkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); - }); - - if ((DateTime.Now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_ALERT_MS) + } + }, + none: () => { - _afkTimeSinceLastAlert.Match( - some: at => - { - if (at.ElapsedMilliseconds >= AFK_TIME_BETWEEN_ALERTS_MS) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_TOO_LONG); - _afkTimeSinceLastAlert = Option.Some(Stopwatch.StartNew()); - _altAlert = false; - } - }, - none: () => + _animator.Emote(_characterRepository.MainCharacter.ID, Emote.Moon); + _characterActions.Emote(Emote.Moon); + _afkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); + }); + + if ((DateTime.Now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_ALERT_MS) + { + _afkTimeSinceLastAlert.Match( + some: at => + { + if (at.ElapsedMilliseconds >= AFK_TIME_BETWEEN_ALERTS_MS) { _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_TOO_LONG); _afkTimeSinceLastAlert = Option.Some(Stopwatch.StartNew()); _altAlert = false; - }); + } + }, + none: () => + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_TOO_LONG); + _afkTimeSinceLastAlert = Option.Some(Stopwatch.StartNew()); + _altAlert = false; + }); - _afkTimeSinceLastAlert.Match( - some: at => + _afkTimeSinceLastAlert.Match( + some: at => + { + if (at.ElapsedMilliseconds >= AFK_TIME_ALT_ALERT_MS && !_altAlert) { - if (at.ElapsedMilliseconds >= AFK_TIME_ALT_ALERT_MS && !_altAlert) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_PLEASE_START_MOVING); - _altAlert = true; - } - }, - none: () => _altAlert = false); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_PLEASE_START_MOVING); + _altAlert = true; + } + }, + none: () => _altAlert = false); } } - else - { - _afkTimeSinceLastEmote = Option.None(); - _afkTimeSinceLastAlert = Option.None(); - } + } + else + { + _afkTimeSinceLastEmote = Option.None(); + _afkTimeSinceLastAlert = Option.None(); + } - _arenaTimer.MatchSome( - some: a => + _arenaTimer.MatchSome( + some: a => + { + if ((_arenaWarningCounter == 0 && a.ElapsedMilliseconds >= ARENA_BLOCK_INITIAL_TIME_MS) || + (_arenaWarningCounter > 0 && a.ElapsedMilliseconds >= ARENA_BLOCK_WARNING_INTERVAL_MS)) { - if ((_arenaWarningCounter == 0 && a.ElapsedMilliseconds >= ARENA_BLOCK_INITIAL_TIME_MS) || - (_arenaWarningCounter > 0 && a.ElapsedMilliseconds >= ARENA_BLOCK_WARNING_INTERVAL_MS)) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ARENA_DO_NOT_BLOCK_LINE); - _sfxPlayer.PlaySfx(SoundEffectID.ArenaTickSound); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ARENA_DO_NOT_BLOCK_LINE); + _sfxPlayer.PlaySfx(SoundEffectID.ArenaTickSound); - if (_arenaWarningCounter == 1) - { - var resource = _localizedStringFinder.GetString(EOResourceID.ARENA_PLEASE_MOVE_FROM_PLACE); - _chatBubbleActions.ShowChatBubbleForMainCharacter(resource); - } - else if (_arenaWarningCounter == ARENA_BLOCK_MAX_WARNINGS) - { - _arenaTimer = Option.None(); - _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); - } - - StartArenaBlockTimer(); - _arenaWarningCounter++; + if (_arenaWarningCounter == 1) + { + var resource = _localizedStringFinder.GetString(EOResourceID.ARENA_PLEASE_MOVE_FROM_PLACE); + _chatBubbleActions.ShowChatBubbleForMainCharacter(resource); + } + else if (_arenaWarningCounter == ARENA_BLOCK_MAX_WARNINGS) + { + _arenaTimer = Option.None(); + _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); } - }); + StartArenaBlockTimer(); + _arenaWarningCounter++; + } - base.Update(gameTime); - } + }); - public void SetDrunkTimeout(int beerPotency) - { - _drunkTimeoutSeconds = (100 + (beerPotency * 10)) / 8.0; - } + base.Update(gameTime); + } - public void StartArenaBlockTimer() - { - _arenaTimer = Option.Some(Stopwatch.StartNew()); - } + public void SetDrunkTimeout(int beerPotency) + { + _drunkTimeoutSeconds = (100 + (beerPotency * 10)) / 8.0; + } - public void CancelArenaBlockTimer() - { - _arenaTimer = Option.None(); - _arenaWarningCounter = 0; - } + public void StartArenaBlockTimer() + { + _arenaTimer = Option.Some(Stopwatch.StartNew()); } - public interface IPeriodicEmoteHandler : IGameComponent, IUpdateable + public void CancelArenaBlockTimer() { - void SetDrunkTimeout(int beerPotency); + _arenaTimer = Option.None(); + _arenaWarningCounter = 0; + } +} - void StartArenaBlockTimer(); +public interface IPeriodicEmoteHandler : IGameComponent, IUpdateable +{ + void SetDrunkTimeout(int beerPotency); - void CancelArenaBlockTimer(); - } + void StartArenaBlockTimer(); + + void CancelArenaBlockTimer(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs index 768f8320c..6facc7822 100644 --- a/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs @@ -7,71 +7,70 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class ArmorRenderer : BaseCharacterPropertyRenderer { - public class ArmorRenderer : BaseCharacterPropertyRenderer - { - private readonly ISpriteSheet _armorSheet; + private readonly ISpriteSheet _armorSheet; - public override bool CanRender => _armorSheet.HasTexture && _renderProperties.ArmorGraphic != 0; + public override bool CanRender => _armorSheet.HasTexture && _renderProperties.ArmorGraphic != 0; - public ArmorRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet armorSheet) - : base(renderProperties) - { - _armorSheet = armorSheet; - } + public ArmorRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet armorSheet) + : base(renderProperties) + { + _armorSheet = armorSheet; + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var offsets = GetOffsets(parentCharacterDrawArea.Size.ToVector2(), weaponMetadata.Ranged); - var drawLoc = new Vector2(parentCharacterDrawArea.X - 2 + offsets.X, parentCharacterDrawArea.Y + offsets.Y); - Render(spriteBatch, _armorSheet, drawLoc); - } + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + var offsets = GetOffsets(parentCharacterDrawArea.Size.ToVector2(), weaponMetadata.Ranged); + var drawLoc = new Vector2(parentCharacterDrawArea.X - 2 + offsets.X, parentCharacterDrawArea.Y + offsets.Y); + Render(spriteBatch, _armorSheet, drawLoc); + } - private Vector2 GetOffsets(Vector2 parentCharacterSize, bool ranged) + private Vector2 GetOffsets(Vector2 parentCharacterSize, bool ranged) + { + var resX = -(float)Math.Floor(Math.Abs(_armorSheet.SourceRectangle.Width - parentCharacterSize.X) / 2); + var resY = -(float)Math.Floor(Math.Abs(_armorSheet.SourceRectangle.Height - parentCharacterSize.Y) / 2); + + if ((_renderProperties.RenderAttackFrame == 2 && !ranged) || + (_renderProperties.RenderAttackFrame == 1 && ranged)) { - var resX = -(float)Math.Floor(Math.Abs(_armorSheet.SourceRectangle.Width - parentCharacterSize.X) / 2); - var resY = -(float)Math.Floor(Math.Abs(_armorSheet.SourceRectangle.Height - parentCharacterSize.Y) / 2); + resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 4 : 0; - if ((_renderProperties.RenderAttackFrame == 2 && !ranged) || - (_renderProperties.RenderAttackFrame == 1 && ranged)) + if (ranged) { - resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 4 : 0; - - if (ranged) - { - var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; - resX += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) - ? 2 * factor - : 4 * factor; + var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; + resX += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) + ? 2 * factor + : 4 * factor; - resY += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? 1 : 0; - } + resY += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? 1 : 0; } - else if (_renderProperties.SitState != SitState.Standing) + } + else if (_renderProperties.SitState != SitState.Standing) + { + if (_renderProperties.SitState == SitState.Chair) { - if (_renderProperties.SitState == SitState.Chair) - { - resX -= 1; - resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 2 : 0; - } - else - { - resX += _renderProperties.IsFacing(EODirection.Left) ? _renderProperties.Gender : _renderProperties.IsFacing(EODirection.Up) ? -_renderProperties.Gender : 0; - resX -= _renderProperties.IsFacing(EODirection.Down, EODirection.Up) ? (2 - _renderProperties.Gender) : _renderProperties.Gender; - resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 12 : 9; - } + resX -= 1; + resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 2 : 0; } else { - resX += 2; + resX += _renderProperties.IsFacing(EODirection.Left) ? _renderProperties.Gender : _renderProperties.IsFacing(EODirection.Up) ? -_renderProperties.Gender : 0; + resX -= _renderProperties.IsFacing(EODirection.Down, EODirection.Up) ? (2 - _renderProperties.Gender) : _renderProperties.Gender; + resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 12 : 9; } + } + else + { + resX += 2; + } - if (_renderProperties.SitState == SitState.Standing) - resY -= (_renderProperties.IsActing(CharacterActionState.Walking) ? 4 : 3) + _renderProperties.Gender; + if (_renderProperties.SitState == SitState.Standing) + resY -= (_renderProperties.IsActing(CharacterActionState.Walking) ? 4 : 3) + _renderProperties.Gender; - return new Vector2(resX, resY); - } + return new Vector2(resX, resY); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs b/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs index 2eae9521b..5970278c9 100644 --- a/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs @@ -6,31 +6,30 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public abstract class BaseCharacterPropertyRenderer : ICharacterPropertyRenderer { - public abstract class BaseCharacterPropertyRenderer : ICharacterPropertyRenderer - { - protected readonly CharacterRenderProperties _renderProperties; + protected readonly CharacterRenderProperties _renderProperties; - public abstract bool CanRender { get; } + public abstract bool CanRender { get; } - public float LayerDepth { get; set; } + public float LayerDepth { get; set; } - protected virtual bool ShouldFlip => _renderProperties.IsFacing(EODirection.Up, EODirection.Right); + protected virtual bool ShouldFlip => _renderProperties.IsFacing(EODirection.Up, EODirection.Right); - protected BaseCharacterPropertyRenderer(CharacterRenderProperties renderProperties) - { - _renderProperties = renderProperties; - LayerDepth = 1.0f; - } + protected BaseCharacterPropertyRenderer(CharacterRenderProperties renderProperties) + { + _renderProperties = renderProperties; + LayerDepth = 1.0f; + } - public abstract void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata); + public abstract void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata); - protected virtual void Render(SpriteBatch spriteBatch, ISpriteSheet sheet, Vector2 drawLoc, int alpha = 255) - { - spriteBatch.Draw(sheet.SheetTexture, drawLoc, sheet.SourceRectangle, Color.FromNonPremultiplied(255, 255, 255, alpha), 0.0f, Vector2.Zero, 1.0f, - ShouldFlip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, - LayerDepth); - } + protected virtual void Render(SpriteBatch spriteBatch, ISpriteSheet sheet, Vector2 drawLoc, int alpha = 255) + { + spriteBatch.Draw(sheet.SheetTexture, drawLoc, sheet.SourceRectangle, Color.FromNonPremultiplied(255, 255, 255, alpha), 0.0f, Vector2.Zero, 1.0f, + ShouldFlip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, + LayerDepth); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs b/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs index f2ca4ee5e..cdbe4f5ac 100644 --- a/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs @@ -7,84 +7,83 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class BootsRenderer : BaseCharacterPropertyRenderer { - public class BootsRenderer : BaseCharacterPropertyRenderer - { - private readonly ISpriteSheet _bootsSheet; + private readonly ISpriteSheet _bootsSheet; - public override bool CanRender => _bootsSheet.HasTexture && _renderProperties.BootsGraphic != 0; + public override bool CanRender => _bootsSheet.HasTexture && _renderProperties.BootsGraphic != 0; - public BootsRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet bootsSheet) - : base(renderProperties) - { - _bootsSheet = bootsSheet; - } + public BootsRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet bootsSheet) + : base(renderProperties) + { + _bootsSheet = bootsSheet; + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); - var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, - // Center the Y coordinate over the bottom half of the character sprite - parentCharacterDrawArea.Y + offsets.Y); - Render(spriteBatch, _bootsSheet, drawLoc); - } + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); + var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, + // Center the Y coordinate over the bottom half of the character sprite + parentCharacterDrawArea.Y + offsets.Y); + Render(spriteBatch, _bootsSheet, drawLoc); + } + + private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) + { + var resX = -(float)Math.Floor(Math.Abs((float)_bootsSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); + var resY = (int)Math.Floor(parentCharacterDrawArea.Height / 3f) * 2 - 1 - _renderProperties.Gender; - private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) + if (_renderProperties.IsActing(CharacterActionState.Walking)) { - var resX = -(float)Math.Floor(Math.Abs((float)_bootsSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); - var resY = (int)Math.Floor(parentCharacterDrawArea.Height / 3f) * 2 - 1 - _renderProperties.Gender; + resY -= 1; - if (_renderProperties.IsActing(CharacterActionState.Walking)) - { + if (_renderProperties.RenderWalkFrame == 2) resY -= 1; + } + else if (_renderProperties.RenderAttackFrame == 2) + { + var isDownOrLeft = _renderProperties.IsFacing(EODirection.Down, EODirection.Left); + var factor = isDownOrLeft ? -1 : 1; + var extra = !isDownOrLeft ? 2 * _renderProperties.Gender : 0; - if (_renderProperties.RenderWalkFrame == 2) - resY -= 1; - } - else if (_renderProperties.RenderAttackFrame == 2) - { - var isDownOrLeft = _renderProperties.IsFacing(EODirection.Down, EODirection.Left); - var factor = isDownOrLeft ? -1 : 1; - var extra = !isDownOrLeft ? 2 * _renderProperties.Gender : 0; + resX += 2 * factor; + resY += 1 * factor - extra; + } + else if (_renderProperties.RenderAttackFrame == 1 && ranged) + { + var isDownOrLeft = _renderProperties.IsFacing(EODirection.Down, EODirection.Left); + var isDownOrRight = _renderProperties.IsFacing(EODirection.Down, EODirection.Right); + var factor = isDownOrLeft ? -1 : 1; + var offset = isDownOrRight ? 5 : 3; + var extra = !isDownOrRight ? 4 * _renderProperties.Gender : 1 * _renderProperties.Gender; - resX += 2 * factor; - resY += 1 * factor - extra; - } - else if (_renderProperties.RenderAttackFrame == 1 && ranged) - { - var isDownOrLeft = _renderProperties.IsFacing(EODirection.Down, EODirection.Left); - var isDownOrRight = _renderProperties.IsFacing(EODirection.Down, EODirection.Right); - var factor = isDownOrLeft ? -1 : 1; - var offset = isDownOrRight ? 5 : 3; - var extra = !isDownOrRight ? 4 * _renderProperties.Gender : 1 * _renderProperties.Gender; + resX += factor * (offset + extra); + } + else if (_renderProperties.SitState != SitState.Standing) + { + resX -= 3; + resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? -3 : 2; - resX += factor * (offset + extra); - } - else if (_renderProperties.SitState != SitState.Standing) + if (_renderProperties.SitState == SitState.Floor) { - resX -= 3; - resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? -3 : 2; + var factor = _renderProperties.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; - if (_renderProperties.SitState == SitState.Floor) + if (_renderProperties.Gender == 0) { - var factor = _renderProperties.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; - - if (_renderProperties.Gender == 0) - { - resX += (_renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 1 : -1) * factor; - resY += _renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 2 : 3; - } - else if (_renderProperties.Gender == 1) - { - resX += (_renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 0 : -1) * factor; - resY += 4; - } + resX += (_renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 1 : -1) * factor; + resY += _renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 2 : 3; + } + else if (_renderProperties.Gender == 1) + { + resX += (_renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 0 : -1) * factor; + resY += 4; } } - - return new Vector2(resX, resY); } + + return new Vector2(resX, resY); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs b/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs index 016df3bc5..07e590ae6 100644 --- a/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs +++ b/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs @@ -11,92 +11,91 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +[AutoMappedType] +public class CharacterPropertyRendererBuilder : ICharacterPropertyRendererBuilder { - [AutoMappedType] - public class CharacterPropertyRendererBuilder : ICharacterPropertyRendererBuilder + private readonly IEIFFileProvider _eifFileProvider; + private readonly IMetadataProvider _hatMetadataProvider; + private readonly IMetadataProvider _shieldMetadataProvider; + + public CharacterPropertyRendererBuilder(IEIFFileProvider eifFileProvider, + IMetadataProvider hatMetadataProvider, + IMetadataProvider shieldMetadataProvider) { - private readonly IEIFFileProvider _eifFileProvider; - private readonly IMetadataProvider _hatMetadataProvider; - private readonly IMetadataProvider _shieldMetadataProvider; + _eifFileProvider = eifFileProvider; + _hatMetadataProvider = hatMetadataProvider; + _shieldMetadataProvider = shieldMetadataProvider; + } - public CharacterPropertyRendererBuilder(IEIFFileProvider eifFileProvider, - IMetadataProvider hatMetadataProvider, - IMetadataProvider shieldMetadataProvider) - { - _eifFileProvider = eifFileProvider; - _hatMetadataProvider = hatMetadataProvider; - _shieldMetadataProvider = shieldMetadataProvider; - } + public IEnumerable BuildList(ICharacterTextures textures, + CharacterRenderProperties renderProperties) + { + const float BaseLayer = 0.00001f; - public IEnumerable BuildList(ICharacterTextures textures, - CharacterRenderProperties renderProperties) + // Melee weapons render extra behind the character + yield return new WeaponRenderer(renderProperties, textures.WeaponExtra) { LayerDepth = BaseLayer }; + yield return new ShieldRenderer(renderProperties, textures.Shield, IsShieldOnBack(renderProperties.ShieldGraphic)) + { + LayerDepth = BaseLayer * (IsShieldBehindCharacter(renderProperties) ? 2 : 13) + }; + yield return new WeaponRenderer(renderProperties, textures.Weapon) { - const float BaseLayer = 0.00001f; + LayerDepth = BaseLayer * (IsWeaponBehindCharacter(renderProperties) ? 3 : 12) + }; - // Melee weapons render extra behind the character - yield return new WeaponRenderer(renderProperties, textures.WeaponExtra) { LayerDepth = BaseLayer }; - yield return new ShieldRenderer(renderProperties, textures.Shield, IsShieldOnBack(renderProperties.ShieldGraphic)) - { - LayerDepth = BaseLayer * (IsShieldBehindCharacter(renderProperties) ? 2 : 13) - }; - yield return new WeaponRenderer(renderProperties, textures.Weapon) - { - LayerDepth = BaseLayer * (IsWeaponBehindCharacter(renderProperties) ? 3 : 12) - }; + yield return new SkinRenderer(renderProperties, textures.Skin) { LayerDepth = BaseLayer * 4 }; + yield return new FaceRenderer(renderProperties, textures.Face, textures.Skin) { LayerDepth = BaseLayer * 5 }; + yield return new EmoteRenderer(renderProperties, textures.Emote, textures.Skin) { LayerDepth = BaseLayer * 6 }; - yield return new SkinRenderer(renderProperties, textures.Skin) { LayerDepth = BaseLayer * 4 }; - yield return new FaceRenderer(renderProperties, textures.Face, textures.Skin) { LayerDepth = BaseLayer * 5 }; - yield return new EmoteRenderer(renderProperties, textures.Emote, textures.Skin) { LayerDepth = BaseLayer * 6 }; + yield return new BootsRenderer(renderProperties, textures.Boots) { LayerDepth = BaseLayer * 7 }; + yield return new ArmorRenderer(renderProperties, textures.Armor) { LayerDepth = BaseLayer * 8 }; - yield return new BootsRenderer(renderProperties, textures.Boots) { LayerDepth = BaseLayer * 7 }; - yield return new ArmorRenderer(renderProperties, textures.Armor) { LayerDepth = BaseLayer * 8 }; + var hatMaskType = GetHatMaskType(renderProperties.HatGraphic); + yield return new HatRenderer(renderProperties, textures.Hat, textures.Hair) + { + LayerDepth = BaseLayer * (hatMaskType == HatMaskType.FaceMask ? 10 : 11) + }; - var hatMaskType = GetHatMaskType(renderProperties.HatGraphic); - yield return new HatRenderer(renderProperties, textures.Hat, textures.Hair) + if (hatMaskType != HatMaskType.HideHair) + yield return new HairRenderer(renderProperties, textures.Hair) { - LayerDepth = BaseLayer * (hatMaskType == HatMaskType.FaceMask ? 10 : 11) + LayerDepth = BaseLayer * (hatMaskType == HatMaskType.FaceMask ? 11 : 10) }; - if (hatMaskType != HatMaskType.HideHair) - yield return new HairRenderer(renderProperties, textures.Hair) - { - LayerDepth = BaseLayer * (hatMaskType == HatMaskType.FaceMask ? 11 : 10) - }; - - yield return new WeaponSlashRenderer(renderProperties, textures.WeaponSlash) { LayerDepth = BaseLayer * 14 }; - } - - private bool IsShieldBehindCharacter(CharacterRenderProperties renderProperties) - { - return renderProperties.IsFacing(EODirection.Right, EODirection.Down) && IsShieldOnBack(renderProperties.ShieldGraphic); - } + yield return new WeaponSlashRenderer(renderProperties, textures.WeaponSlash) { LayerDepth = BaseLayer * 14 }; + } - private bool IsWeaponBehindCharacter(CharacterRenderProperties renderProperties) - { - var weaponInfo = EIFFile.FirstOrDefault( - x => x.Type == ItemType.Weapon && - x.DollGraphic == renderProperties.WeaponGraphic); + private bool IsShieldBehindCharacter(CharacterRenderProperties renderProperties) + { + return renderProperties.IsFacing(EODirection.Right, EODirection.Down) && IsShieldOnBack(renderProperties.ShieldGraphic); + } - var pass1 = renderProperties.RenderAttackFrame < 2; - var pass2 = renderProperties.IsFacing(EODirection.Up, EODirection.Left); - var pass3 = weaponInfo == null || weaponInfo.SubType == ItemSubType.Ranged; + private bool IsWeaponBehindCharacter(CharacterRenderProperties renderProperties) + { + var weaponInfo = EIFFile.FirstOrDefault( + x => x.Type == ItemType.Weapon && + x.DollGraphic == renderProperties.WeaponGraphic); - return pass1 || pass2 || pass3; - } + var pass1 = renderProperties.RenderAttackFrame < 2; + var pass2 = renderProperties.IsFacing(EODirection.Up, EODirection.Left); + var pass3 = weaponInfo == null || weaponInfo.SubType == ItemSubType.Ranged; - private HatMaskType GetHatMaskType(int hatGraphic) - { - if (hatGraphic == 0) return HatMaskType.Standard; - return _hatMetadataProvider.GetValueOrDefault(hatGraphic).ClipMode; - } + return pass1 || pass2 || pass3; + } - private bool IsShieldOnBack(int shieldGraphic) - { - if (shieldGraphic == 0) return false; - return _shieldMetadataProvider.GetValueOrDefault(shieldGraphic).IsShieldOnBack; - } + private HatMaskType GetHatMaskType(int hatGraphic) + { + if (hatGraphic == 0) return HatMaskType.Standard; + return _hatMetadataProvider.GetValueOrDefault(hatGraphic).ClipMode; + } - private IPubFile EIFFile => _eifFileProvider.EIFFile ?? new EIFFile(); + private bool IsShieldOnBack(int shieldGraphic) + { + if (shieldGraphic == 0) return false; + return _shieldMetadataProvider.GetValueOrDefault(shieldGraphic).IsShieldOnBack; } + + private IPubFile EIFFile => _eifFileProvider.EIFFile ?? new EIFFile(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs b/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs index 10978e828..3431c6d7b 100644 --- a/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs @@ -4,36 +4,35 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class EmoteRenderer : BaseCharacterPropertyRenderer { - public class EmoteRenderer : BaseCharacterPropertyRenderer - { - private readonly ISpriteSheet _emoteSheet; - private readonly ISpriteSheet _skinSheet; - private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; + private readonly ISpriteSheet _emoteSheet; + private readonly ISpriteSheet _skinSheet; + private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; - public override bool CanRender => _renderProperties.EmoteFrame > 0; + public override bool CanRender => _renderProperties.EmoteFrame > 0; - protected override bool ShouldFlip => false; + protected override bool ShouldFlip => false; - public EmoteRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet emoteSheet, - ISpriteSheet skinSheet) - : base(renderProperties) - { - _emoteSheet = emoteSheet; - _skinSheet = skinSheet; - _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); - } + public EmoteRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet emoteSheet, + ISpriteSheet skinSheet) + : base(renderProperties) + { + _emoteSheet = emoteSheet; + _skinSheet = skinSheet; + _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - if (_emoteSheet is EmptySpriteSheet) - return; + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + if (_emoteSheet is EmptySpriteSheet) + return; - var skinLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); - var emotePos = new Vector2(skinLoc.X - 15, parentCharacterDrawArea.Y - _emoteSheet.SheetTexture.Height); - Render(spriteBatch, _emoteSheet, emotePos, 128); - } + var skinLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); + var emotePos = new Vector2(skinLoc.X - 15, parentCharacterDrawArea.Y - _emoteSheet.SheetTexture.Height); + Render(spriteBatch, _emoteSheet, emotePos, 128); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs b/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs index 80f57e6b0..737f36d63 100644 --- a/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs @@ -6,44 +6,43 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class FaceRenderer : BaseCharacterPropertyRenderer { - public class FaceRenderer : BaseCharacterPropertyRenderer + private readonly ISpriteSheet _faceSheet; + private readonly ISpriteSheet _skinSheet; + private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; + + public override bool CanRender => _renderProperties.IsActing(CharacterActionState.Emote) && + _renderProperties.EmoteFrame > 0 && + _renderProperties.Emote != Emote.Trade && + _renderProperties.Emote != Emote.LevelUp && + _renderProperties.Emote != Emote.MusicNotes; + + public FaceRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet faceSheet, + ISpriteSheet skinSheet) + : base(renderProperties) + { + _faceSheet = faceSheet; + _skinSheet = skinSheet; + _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); + } + + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) { - private readonly ISpriteSheet _faceSheet; - private readonly ISpriteSheet _skinSheet; - private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; - - public override bool CanRender => _renderProperties.IsActing(CharacterActionState.Emote) && - _renderProperties.EmoteFrame > 0 && - _renderProperties.Emote != Emote.Trade && - _renderProperties.Emote != Emote.LevelUp && - _renderProperties.Emote != Emote.MusicNotes; - - public FaceRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet faceSheet, - ISpriteSheet skinSheet) - : base(renderProperties) - { - _faceSheet = faceSheet; - _skinSheet = skinSheet; - _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); - } - - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - if (!_renderProperties.IsFacing(EODirection.Down, EODirection.Right)) - return; - - var skinLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); - - var adjustX = _renderProperties.IsFacing(EODirection.Down) - ? _renderProperties.SitState == SitState.Standing ? 2 : 8 - : 3; - - var facePos = new Vector2(skinLoc.X + adjustX, skinLoc.Y + (_renderProperties.Gender == 0 ? 2 : 0)); - - Render(spriteBatch, _faceSheet, facePos); - } + if (!_renderProperties.IsFacing(EODirection.Down, EODirection.Right)) + return; + + var skinLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); + + var adjustX = _renderProperties.IsFacing(EODirection.Down) + ? _renderProperties.SitState == SitState.Standing ? 2 : 8 + : 3; + + var facePos = new Vector2(skinLoc.X + adjustX, skinLoc.Y + (_renderProperties.Gender == 0 ? 2 : 0)); + + Render(spriteBatch, _faceSheet, facePos); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs b/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs index 53e904a0d..69e96510b 100644 --- a/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs +++ b/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs @@ -4,65 +4,64 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class HairRenderLocationCalculator { - public class HairRenderLocationCalculator + private readonly CharacterRenderProperties _renderProperties; + + public HairRenderLocationCalculator(CharacterRenderProperties renderProperties) + { + _renderProperties = renderProperties; + } + + public Vector2 CalculateDrawLocationOfCharacterHair(Rectangle hairRectangle, Rectangle parentCharacterDrawArea, bool ranged) { - private readonly CharacterRenderProperties _renderProperties; + var resX = -(float)Math.Floor(Math.Abs((float)hairRectangle.Width - parentCharacterDrawArea.Width) / 2) - 1; + var resY = -(float)Math.Floor(Math.Abs(hairRectangle.Height - (parentCharacterDrawArea.Height / 2f)) / 2) - _renderProperties.Gender; - public HairRenderLocationCalculator(CharacterRenderProperties renderProperties) + var isFlipped = _renderProperties.IsFacing(EODirection.Up, EODirection.Right); + + if (ranged && _renderProperties.RenderAttackFrame == 1) { - _renderProperties = renderProperties; + var rangedXOff = _renderProperties.Gender == 0 ? 1 : 3; + resX += rangedXOff * (isFlipped ? 1 : -1); + resY += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? _renderProperties.Gender : 0; } - - public Vector2 CalculateDrawLocationOfCharacterHair(Rectangle hairRectangle, Rectangle parentCharacterDrawArea, bool ranged) + else if (_renderProperties.RenderAttackFrame == 2) { - var resX = -(float)Math.Floor(Math.Abs((float)hairRectangle.Width - parentCharacterDrawArea.Width) / 2) - 1; - var resY = -(float)Math.Floor(Math.Abs(hairRectangle.Height - (parentCharacterDrawArea.Height / 2f)) / 2) - _renderProperties.Gender; + resX += isFlipped ? 4 : -4; + resX += _renderProperties.IsFacing(EODirection.Up) + ? _renderProperties.Gender * -2 + : _renderProperties.IsFacing(EODirection.Left) + ? _renderProperties.Gender * 2 + : 0; - var isFlipped = _renderProperties.IsFacing(EODirection.Up, EODirection.Right); + resY += _renderProperties.IsFacing(EODirection.Up, EODirection.Left) ? 1 : 5; + resY -= _renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? _renderProperties.Gender : 0; + } + else if (_renderProperties.SitState != SitState.Standing) + { + resX -= 3; - if (ranged && _renderProperties.RenderAttackFrame == 1) + var flootSitFactor = _renderProperties.SitState == SitState.Floor ? 2 : 1; + if (_renderProperties.IsFacing(EODirection.Right, EODirection.Down)) { - var rangedXOff = _renderProperties.Gender == 0 ? 1 : 3; - resX += rangedXOff * (isFlipped ? 1 : -1); - resY += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? _renderProperties.Gender : 0; + resY += (9 + _renderProperties.Gender) * flootSitFactor; } - else if (_renderProperties.RenderAttackFrame == 2) + else { - resX += isFlipped ? 4 : -4; - resX += _renderProperties.IsFacing(EODirection.Up) - ? _renderProperties.Gender * -2 - : _renderProperties.IsFacing(EODirection.Left) - ? _renderProperties.Gender * 2 - : 0; - - resY += _renderProperties.IsFacing(EODirection.Up, EODirection.Left) ? 1 : 5; - resY -= _renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? _renderProperties.Gender : 0; - } - else if (_renderProperties.SitState != SitState.Standing) - { - resX -= 3; - - var flootSitFactor = _renderProperties.SitState == SitState.Floor ? 2 : 1; - if (_renderProperties.IsFacing(EODirection.Right, EODirection.Down)) + if (_renderProperties.SitState == SitState.Floor) { - resY += (9 + _renderProperties.Gender) * flootSitFactor; + resX += _renderProperties.IsFacing(EODirection.Left) ? 2 : -2; + resY -= 1; } - else - { - if (_renderProperties.SitState == SitState.Floor) - { - resX += _renderProperties.IsFacing(EODirection.Left) ? 2 : -2; - resY -= 1; - } - resY += (11 + _renderProperties.Gender) * flootSitFactor; - } + resY += (11 + _renderProperties.Gender) * flootSitFactor; } - - var flippedOffset = isFlipped ? 2 : 0; - return parentCharacterDrawArea.Location.ToVector2() + new Vector2(resX + flippedOffset, resY); } + + var flippedOffset = isFlipped ? 2 : 0; + return parentCharacterDrawArea.Location.ToVector2() + new Vector2(resX + flippedOffset, resY); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs b/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs index e499b7f4c..18e7d75df 100644 --- a/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs @@ -4,27 +4,26 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class HairRenderer : BaseCharacterPropertyRenderer { - public class HairRenderer : BaseCharacterPropertyRenderer - { - private readonly ISpriteSheet _hairSheet; - private readonly HairRenderLocationCalculator _hairRenderLocationCalculator; + private readonly ISpriteSheet _hairSheet; + private readonly HairRenderLocationCalculator _hairRenderLocationCalculator; - public override bool CanRender => _hairSheet.HasTexture && _renderProperties.HairStyle != 0; + public override bool CanRender => _hairSheet.HasTexture && _renderProperties.HairStyle != 0; - public HairRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet hairSheet) - : base(renderProperties) - { - _hairSheet = hairSheet; - _hairRenderLocationCalculator = new HairRenderLocationCalculator(_renderProperties); - } + public HairRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet hairSheet) + : base(renderProperties) + { + _hairSheet = hairSheet; + _hairRenderLocationCalculator = new HairRenderLocationCalculator(_renderProperties); + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var drawLoc = _hairRenderLocationCalculator.CalculateDrawLocationOfCharacterHair(_hairSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); - Render(spriteBatch, _hairSheet, drawLoc); - } + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + var drawLoc = _hairRenderLocationCalculator.CalculateDrawLocationOfCharacterHair(_hairSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); + Render(spriteBatch, _hairSheet, drawLoc); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs b/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs index 798c50454..180fe6c1b 100644 --- a/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs @@ -6,43 +6,42 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class HatRenderer : BaseCharacterPropertyRenderer { - public class HatRenderer : BaseCharacterPropertyRenderer - { - private readonly ISpriteSheet _hatSheet; - private readonly ISpriteSheet _hairSheet; - private readonly HairRenderLocationCalculator _hairRenderLocationCalculator; + private readonly ISpriteSheet _hatSheet; + private readonly ISpriteSheet _hairSheet; + private readonly HairRenderLocationCalculator _hairRenderLocationCalculator; - public override bool CanRender => _hatSheet.HasTexture && _renderProperties.HatGraphic != 0; + public override bool CanRender => _hatSheet.HasTexture && _renderProperties.HatGraphic != 0; - public HatRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet hatSheet, - ISpriteSheet hairSheet) - : base(renderProperties) - { - _hatSheet = hatSheet; - _hairSheet = hairSheet; + public HatRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet hatSheet, + ISpriteSheet hairSheet) + : base(renderProperties) + { + _hatSheet = hatSheet; + _hairSheet = hairSheet; - _hairRenderLocationCalculator = new HairRenderLocationCalculator(_renderProperties); - } + _hairRenderLocationCalculator = new HairRenderLocationCalculator(_renderProperties); + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var hairDrawLoc = _hairRenderLocationCalculator.CalculateDrawLocationOfCharacterHair(_hairSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); - var offsets = GetOffsets(); + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + var hairDrawLoc = _hairRenderLocationCalculator.CalculateDrawLocationOfCharacterHair(_hairSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); + var offsets = GetOffsets(); - Render(spriteBatch, _hatSheet, hairDrawLoc + offsets); - } + Render(spriteBatch, _hatSheet, hairDrawLoc + offsets); + } - private Vector2 GetOffsets() - { - var xOff = 0f; - var yOff = -3f; + private Vector2 GetOffsets() + { + var xOff = 0f; + var yOff = -3f; - var flippedOffset = _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? -2 : 0; + var flippedOffset = _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? -2 : 0; - return new Vector2(xOff + flippedOffset, yOff); - } + return new Vector2(xOff + flippedOffset, yOff); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs index fc8199f84..f57affd94 100644 --- a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs @@ -2,14 +2,13 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public interface ICharacterPropertyRenderer { - public interface ICharacterPropertyRenderer - { - bool CanRender { get; } + bool CanRender { get; } - float LayerDepth { get; set; } + float LayerDepth { get; set; } - void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata); - } + void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata); } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs index be977a4be..844e1f027 100644 --- a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs +++ b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs @@ -2,11 +2,10 @@ using EOLib.Domain.Character; using System.Collections.Generic; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public interface ICharacterPropertyRendererBuilder { - public interface ICharacterPropertyRendererBuilder - { - IEnumerable BuildList(ICharacterTextures characterTextures, - CharacterRenderProperties renderProperties); - } + IEnumerable BuildList(ICharacterTextures characterTextures, + CharacterRenderProperties renderProperties); } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs index c8c7f54dd..95e52c593 100644 --- a/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs @@ -7,110 +7,109 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class ShieldRenderer : BaseCharacterPropertyRenderer { - public class ShieldRenderer : BaseCharacterPropertyRenderer - { - private readonly ISpriteSheet _shieldSheet; - private readonly bool _isShieldOnBack; + private readonly ISpriteSheet _shieldSheet; + private readonly bool _isShieldOnBack; - public override bool CanRender => _shieldSheet.HasTexture && _renderProperties.ShieldGraphic != 0; + public override bool CanRender => _shieldSheet.HasTexture && _renderProperties.ShieldGraphic != 0; - // NOTE: The original client flips the arrows when facing left or up from the standing frame. - // I'm guessing this is a Vult bug. The offsets are wonky if this is enabled and I don't feel like figuring them out. - //protected override bool ShouldFlip => _renderProperties.SitState == SitState.Floor - //? _isShieldOnBack && _renderProperties.IsFacing(EODirection.Left, EODirection.Right) - //: base.ShouldFlip; + // NOTE: The original client flips the arrows when facing left or up from the standing frame. + // I'm guessing this is a Vult bug. The offsets are wonky if this is enabled and I don't feel like figuring them out. + //protected override bool ShouldFlip => _renderProperties.SitState == SitState.Floor + //? _isShieldOnBack && _renderProperties.IsFacing(EODirection.Left, EODirection.Right) + //: base.ShouldFlip; - public ShieldRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet shieldSheet, - bool isShieldOnBack) - : base(renderProperties) - { - _shieldSheet = shieldSheet; - _isShieldOnBack = isShieldOnBack; - } + public ShieldRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet shieldSheet, + bool isShieldOnBack) + : base(renderProperties) + { + _shieldSheet = shieldSheet; + _isShieldOnBack = isShieldOnBack; + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); - var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, parentCharacterDrawArea.Y + offsets.Y); - Render(spriteBatch, _shieldSheet, drawLoc); - } + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); + var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, parentCharacterDrawArea.Y + offsets.Y); + Render(spriteBatch, _shieldSheet, drawLoc); + } - private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) + private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) + { + float resX, resY; + + if (_isShieldOnBack) { - float resX, resY; + resX = -(float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); + resY = -(float)Math.Floor(parentCharacterDrawArea.Height / 3f) - _renderProperties.Gender; - if (_isShieldOnBack) + if (_renderProperties.RenderAttackFrame == 2) + resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 2 : -2; + else if (ranged && _renderProperties.RenderAttackFrame == 1) { - resX = -(float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); - resY = -(float)Math.Floor(parentCharacterDrawArea.Height / 3f) - _renderProperties.Gender; + // This currently does *not* match up perfectly with the original client. The original client doesn't keep + // the arrows aligned on the attack frame, so they look like they are sliding across the back of the character. + // I like it better this way (the offset is fixed for the arrows) so I'm not fixing it. + var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; + var extra = _renderProperties.Gender * 2; + resX += factor * (1 + extra); + } + else if (_renderProperties.SitState != SitState.Standing) + { + // These are the same offsets as hair - if (_renderProperties.RenderAttackFrame == 2) - resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 2 : -2; - else if (ranged && _renderProperties.RenderAttackFrame == 1) + resX -= 3; + + var flootSitFactor = _renderProperties.SitState == SitState.Floor ? 2 : 1; + if (_renderProperties.IsFacing(EODirection.Right, EODirection.Down)) { - // This currently does *not* match up perfectly with the original client. The original client doesn't keep - // the arrows aligned on the attack frame, so they look like they are sliding across the back of the character. - // I like it better this way (the offset is fixed for the arrows) so I'm not fixing it. - var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; - var extra = _renderProperties.Gender * 2; - resX += factor * (1 + extra); + resY += (9 + _renderProperties.Gender) * flootSitFactor; } - else if (_renderProperties.SitState != SitState.Standing) + else { - // These are the same offsets as hair - - resX -= 3; - - var flootSitFactor = _renderProperties.SitState == SitState.Floor ? 2 : 1; - if (_renderProperties.IsFacing(EODirection.Right, EODirection.Down)) + if (_renderProperties.SitState == SitState.Floor) { - resY += (9 + _renderProperties.Gender) * flootSitFactor; + resX += _renderProperties.IsFacing(EODirection.Left) ? 2 : -2; + resY -= 1; } - else - { - if (_renderProperties.SitState == SitState.Floor) - { - resX += _renderProperties.IsFacing(EODirection.Left) ? 2 : -2; - resY -= 1; - } - resY += (11 + _renderProperties.Gender) * flootSitFactor; - } + resY += (11 + _renderProperties.Gender) * flootSitFactor; } } - else + } + else + { + resX = (float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); + resY = (float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Height - parentCharacterDrawArea.Height) / 2) + 5; + + if (_renderProperties.IsFacing(EODirection.Down, EODirection.Left)) { - resX = (float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); - resY = (float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Height - parentCharacterDrawArea.Height) / 2) + 5; + resX -= parentCharacterDrawArea.Width * 1.5f; - if (_renderProperties.IsFacing(EODirection.Down, EODirection.Left)) - { - resX -= parentCharacterDrawArea.Width * 1.5f; + if (_renderProperties.RenderAttackFrame == 2) + resX -= 2; - if (_renderProperties.RenderAttackFrame == 2) - resX -= 2; + resX += 2; + } + else + { + resX -= parentCharacterDrawArea.Width / 1.5f; + if (_renderProperties.RenderAttackFrame == 2) resX += 2; - } - else - { - resX -= parentCharacterDrawArea.Width / 1.5f; - if (_renderProperties.RenderAttackFrame == 2) - resX += 2; - - resX -= 3; - } - - resY -= _renderProperties.Gender; - if (_renderProperties.IsActing(CharacterActionState.Walking)) - resY -= 1; + resX -= 3; } - return new Vector2(resX, resY); + resY -= _renderProperties.Gender; + if (_renderProperties.IsActing(CharacterActionState.Walking)) + resY -= 1; } + + return new Vector2(resX, resY); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs b/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs index c346df073..28843211c 100644 --- a/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs +++ b/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs @@ -4,80 +4,79 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class SkinRenderLocationCalculator { - public class SkinRenderLocationCalculator + private readonly CharacterRenderProperties _renderProperties; + + public SkinRenderLocationCalculator(CharacterRenderProperties renderProperties) { - private readonly CharacterRenderProperties _renderProperties; + _renderProperties = renderProperties; + } - public SkinRenderLocationCalculator(CharacterRenderProperties renderProperties) - { - _renderProperties = renderProperties; - } + public Vector2 CalculateDrawLocationOfCharacterSkin(Rectangle skinRectangle, Rectangle parentCharacterDrawArea, bool ranged) + { + float resX, resY; - public Vector2 CalculateDrawLocationOfCharacterSkin(Rectangle skinRectangle, Rectangle parentCharacterDrawArea, bool ranged) + // Ranged weapon attack frame is offset based on the Left or Right border of the parent character draw area + // Ranged weapon graphics do not use the centering approach + if (ranged && _renderProperties.RenderAttackFrame == 1) { - float resX, resY; - - // Ranged weapon attack frame is offset based on the Left or Right border of the parent character draw area - // Ranged weapon graphics do not use the centering approach - if (ranged && _renderProperties.RenderAttackFrame == 1) - { - var isFlipped = _renderProperties.IsFacing(EODirection.Right, EODirection.Up); - var needsExtraOffset = _renderProperties.IsFacing(EODirection.Right, EODirection.Down); + var isFlipped = _renderProperties.IsFacing(EODirection.Right, EODirection.Up); + var needsExtraOffset = _renderProperties.IsFacing(EODirection.Right, EODirection.Down); - var startPixelX = isFlipped ? parentCharacterDrawArea.Left : parentCharacterDrawArea.Right; - var offsetFactor = isFlipped ? 0 : -1; + var startPixelX = isFlipped ? parentCharacterDrawArea.Left : parentCharacterDrawArea.Right; + var offsetFactor = isFlipped ? 0 : -1; - resX = startPixelX + ((needsExtraOffset ? 2 : 0) + skinRectangle.Width) * offsetFactor; + resX = startPixelX + ((needsExtraOffset ? 2 : 0) + skinRectangle.Width) * offsetFactor; - // essentially, is it facing EODirection.Right? - if (isFlipped && needsExtraOffset) - resX += 2; + // essentially, is it facing EODirection.Right? + if (isFlipped && needsExtraOffset) + resX += 2; - // male needs an extra +/- 2 - if (_renderProperties.Gender == 1) - resX += 2 * (isFlipped ? 1 : -1); + // male needs an extra +/- 2 + if (_renderProperties.Gender == 1) + resX += 2 * (isFlipped ? 1 : -1); - resY = parentCharacterDrawArea.Y + (needsExtraOffset ? 1 : 0); - } - else if (_renderProperties.SitState != SitState.Standing) - { - var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; + resY = parentCharacterDrawArea.Y + (needsExtraOffset ? 1 : 0); + } + else if (_renderProperties.SitState != SitState.Standing) + { + var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; - resX = -(int)Math.Floor((float)(skinRectangle.Width - parentCharacterDrawArea.Width)); - resY = parentCharacterDrawArea.Bottom - skinRectangle.Height; + resX = -(int)Math.Floor((float)(skinRectangle.Width - parentCharacterDrawArea.Width)); + resY = parentCharacterDrawArea.Bottom - skinRectangle.Height; - resX += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? 2 * factor : 3 * factor; + resX += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? 2 * factor : 3 * factor; - var genderAdjustFactor = (_renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 0 : 1) * _renderProperties.Gender; - resX += parentCharacterDrawArea.X + (genderAdjustFactor * factor); + var genderAdjustFactor = (_renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 0 : 1) * _renderProperties.Gender; + resX += parentCharacterDrawArea.X + (genderAdjustFactor * factor); - resY += (_renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 7 : 5) - _renderProperties.Gender; + resY += (_renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 7 : 5) - _renderProperties.Gender; - if (_renderProperties.SitState == SitState.Floor) - { - resX += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? -factor : 0; - resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 1 : 0; - } - } - else + if (_renderProperties.SitState == SitState.Floor) { - resX = -(float)Math.Floor(Math.Abs((float)skinRectangle.Width - parentCharacterDrawArea.Width) / 2); - resY = -(float)Math.Floor(Math.Abs((float)skinRectangle.Height - parentCharacterDrawArea.Height) / 2); - - if (_renderProperties.IsActing(CharacterActionState.SpellCast)) - resY -= 2; + resX += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? -factor : 0; + resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 1 : 0; + } + } + else + { + resX = -(float)Math.Floor(Math.Abs((float)skinRectangle.Width - parentCharacterDrawArea.Width) / 2); + resY = -(float)Math.Floor(Math.Abs((float)skinRectangle.Height - parentCharacterDrawArea.Height) / 2); - // This specific frame is a bitch - if (_renderProperties.Gender == 1 && _renderProperties.RenderAttackFrame == 1) - resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 2 : -2; + if (_renderProperties.IsActing(CharacterActionState.SpellCast)) + resY -= 2; - resX += parentCharacterDrawArea.X; - resY += parentCharacterDrawArea.Y; - } + // This specific frame is a bitch + if (_renderProperties.Gender == 1 && _renderProperties.RenderAttackFrame == 1) + resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 2 : -2; - return new Vector2(resX, resY); + resX += parentCharacterDrawArea.X; + resY += parentCharacterDrawArea.Y; } + + return new Vector2(resX, resY); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs b/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs index 99c2c8107..f8d1e78c4 100644 --- a/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs @@ -4,28 +4,27 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class SkinRenderer : BaseCharacterPropertyRenderer { - public class SkinRenderer : BaseCharacterPropertyRenderer - { - private readonly ISpriteSheet _skinSheet; - private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; + private readonly ISpriteSheet _skinSheet; + private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; - public override bool CanRender => true; + public override bool CanRender => true; - public SkinRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet skinSheet) - : base(renderProperties) - { - _skinSheet = skinSheet; + public SkinRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet skinSheet) + : base(renderProperties) + { + _skinSheet = skinSheet; - _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); - } + _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var drawLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); - Render(spriteBatch, _skinSheet, drawLoc); - } + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + var drawLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); + Render(spriteBatch, _skinSheet, drawLoc); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs b/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs index 7709d977d..783e4f063 100644 --- a/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs @@ -7,55 +7,54 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class WeaponRenderer : BaseCharacterPropertyRenderer { - public class WeaponRenderer : BaseCharacterPropertyRenderer + private readonly ISpriteSheet _weaponSheet; + + public override bool CanRender => _weaponSheet.HasTexture && _renderProperties.WeaponGraphic != 0; + + public WeaponRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet weaponSheet) + : base(renderProperties) + { + _weaponSheet = weaponSheet; + } + + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) { - private readonly ISpriteSheet _weaponSheet; - - public override bool CanRender => _weaponSheet.HasTexture && _renderProperties.WeaponGraphic != 0; - - public WeaponRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet weaponSheet) - : base(renderProperties) - { - _weaponSheet = weaponSheet; - } - - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - if (_renderProperties.IsActing(CharacterActionState.Sitting, CharacterActionState.SpellCast) || - (_renderProperties.CurrentAction == CharacterActionState.Emote && _renderProperties.SitState != SitState.Standing)) - return; - - var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); - var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, parentCharacterDrawArea.Y + offsets.Y); - Render(spriteBatch, _weaponSheet, drawLoc); - } - - private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) - { - float resX, resY; - - resX = -(float)Math.Floor(Math.Abs((float)_weaponSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); - resY = -(float)Math.Floor(Math.Abs((float)_weaponSheet.SourceRectangle.Height - parentCharacterDrawArea.Height) / 2) - 5; - - var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; - var isDownOrRight = _renderProperties.IsFacing(EODirection.Down, EODirection.Right); - - resX += (parentCharacterDrawArea.Width / 1.5f - 3) * factor; - if (_renderProperties.RenderAttackFrame == 2) - resX += 2 * factor; - else if (_renderProperties.RenderAttackFrame == 1 && ranged) - resX += (isDownOrRight ? 6 : 4) * factor; - - resY -= 1 + _renderProperties.Gender; - if (_renderProperties.IsActing(CharacterActionState.Walking)) - resY -= 1; - else if (_renderProperties.RenderAttackFrame == 1 && ranged) - resY += isDownOrRight ? 1 : 0; - - return new Vector2(resX, resY); - } + if (_renderProperties.IsActing(CharacterActionState.Sitting, CharacterActionState.SpellCast) || + (_renderProperties.CurrentAction == CharacterActionState.Emote && _renderProperties.SitState != SitState.Standing)) + return; + + var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); + var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, parentCharacterDrawArea.Y + offsets.Y); + Render(spriteBatch, _weaponSheet, drawLoc); + } + + private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) + { + float resX, resY; + + resX = -(float)Math.Floor(Math.Abs((float)_weaponSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); + resY = -(float)Math.Floor(Math.Abs((float)_weaponSheet.SourceRectangle.Height - parentCharacterDrawArea.Height) / 2) - 5; + + var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; + var isDownOrRight = _renderProperties.IsFacing(EODirection.Down, EODirection.Right); + + resX += (parentCharacterDrawArea.Width / 1.5f - 3) * factor; + if (_renderProperties.RenderAttackFrame == 2) + resX += 2 * factor; + else if (_renderProperties.RenderAttackFrame == 1 && ranged) + resX += (isDownOrRight ? 6 : 4) * factor; + + resY -= 1 + _renderProperties.Gender; + if (_renderProperties.IsActing(CharacterActionState.Walking)) + resY -= 1; + else if (_renderProperties.RenderAttackFrame == 1 && ranged) + resY += isDownOrRight ? 1 : 0; + + return new Vector2(resX, resY); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs b/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs index 3ac4ca2a7..e7404f10c 100644 --- a/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs @@ -5,42 +5,41 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties +namespace EndlessClient.Rendering.CharacterProperties; + +public class WeaponSlashRenderer : BaseCharacterPropertyRenderer { - public class WeaponSlashRenderer : BaseCharacterPropertyRenderer - { - private readonly ISpriteSheet _slashSheet; + private readonly ISpriteSheet _slashSheet; - public override bool CanRender => _slashSheet.HasTexture && _renderProperties.WeaponGraphic != 0 && _renderProperties.RenderAttackFrame == 2; + public override bool CanRender => _slashSheet.HasTexture && _renderProperties.WeaponGraphic != 0 && _renderProperties.RenderAttackFrame == 2; - protected override bool ShouldFlip => false; + protected override bool ShouldFlip => false; - public WeaponSlashRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet slashSheet) - : base(renderProperties) - { - _slashSheet = slashSheet; - } + public WeaponSlashRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet slashSheet) + : base(renderProperties) + { + _slashSheet = slashSheet; + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - if (weaponMetadata.Slash == null || weaponMetadata.Ranged) - return; + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + if (weaponMetadata.Slash == null || weaponMetadata.Ranged) + return; - var offsets = GetOffsets(parentCharacterDrawArea) - new Vector2(0, _renderProperties.Gender); - Render(spriteBatch, _slashSheet, parentCharacterDrawArea.Location.ToVector2() + offsets, 96); - } + var offsets = GetOffsets(parentCharacterDrawArea) - new Vector2(0, _renderProperties.Gender); + Render(spriteBatch, _slashSheet, parentCharacterDrawArea.Location.ToVector2() + offsets, 96); + } - private Vector2 GetOffsets(Rectangle parentCharacterDrawArea) + private Vector2 GetOffsets(Rectangle parentCharacterDrawArea) + { + return _renderProperties.Direction switch { - return _renderProperties.Direction switch - { - EODirection.Down => new Vector2(-30, 4), - EODirection.Left => new Vector2(-34, -9), - EODirection.Up => new Vector2(-6, -9), - EODirection.Right => new Vector2(-10, 4), - _ => Vector2.Zero - }; - } + EODirection.Down => new Vector2(-30, 4), + EODirection.Left => new Vector2(-34, -9), + EODirection.Up => new Vector2(-6, -9), + EODirection.Right => new Vector2(-10, 4), + _ => Vector2.Zero + }; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubble.cs b/EndlessClient/Rendering/Chat/ChatBubble.cs index 58add07d0..d4ca72f6f 100644 --- a/EndlessClient/Rendering/Chat/ChatBubble.cs +++ b/EndlessClient/Rendering/Chat/ChatBubble.cs @@ -8,192 +8,191 @@ using System.Diagnostics; using XNAControls; -namespace EndlessClient.Rendering.Chat +namespace EndlessClient.Rendering.Chat; + +public class ChatBubble : DrawableGameComponent, IChatBubble { - public class ChatBubble : DrawableGameComponent, IChatBubble + private readonly IMapActor _parent; + private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; + private readonly IConfigurationProvider _configurationProvider; + private readonly SpriteBatch _spriteBatch; + + private readonly XNALabel _textLabel; + + private bool _isGroupChat; + private Vector2 _drawLocation; + private Option _startTime; + + public ChatBubble(IMapActor referenceRenderer, + IChatBubbleTextureProvider chatBubbleTextureProvider, + IEndlessGameProvider gameProvider, + IConfigurationProvider configurationProvider) + : base((Game)gameProvider.Game) { - private readonly IMapActor _parent; - private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; - private readonly IConfigurationProvider _configurationProvider; - private readonly SpriteBatch _spriteBatch; - - private readonly XNALabel _textLabel; - - private bool _isGroupChat; - private Vector2 _drawLocation; - private Option _startTime; - - public ChatBubble(IMapActor referenceRenderer, - IChatBubbleTextureProvider chatBubbleTextureProvider, - IEndlessGameProvider gameProvider, - IConfigurationProvider configurationProvider) - : base((Game)gameProvider.Game) - { - _parent = referenceRenderer; - _chatBubbleTextureProvider = chatBubbleTextureProvider; - _configurationProvider = configurationProvider; - _spriteBatch = new SpriteBatch(((Game)gameProvider.Game).GraphicsDevice); + _parent = referenceRenderer; + _chatBubbleTextureProvider = chatBubbleTextureProvider; + _configurationProvider = configurationProvider; + _spriteBatch = new SpriteBatch(((Game)gameProvider.Game).GraphicsDevice); - _textLabel = new XNALabel(Constants.FontSize08pt5) - { - Visible = false, - TextWidth = 102, - HardBreak = 150, - Hyphen = "-", - ForeColor = Color.Black, - AutoSize = true, - Text = string.Empty, - DrawOrder = 30, - KeepInClientWindowBounds = false, - }; - - _drawLocation = Vector2.Zero; - _startTime = Option.None(); - - DrawOrder = 29; - Visible = false; - } - - public override void Initialize() + _textLabel = new XNALabel(Constants.FontSize08pt5) { - _textLabel.Initialize(); + Visible = false, + TextWidth = 102, + HardBreak = 150, + Hyphen = "-", + ForeColor = Color.Black, + AutoSize = true, + Text = string.Empty, + DrawOrder = 30, + KeepInClientWindowBounds = false, + }; + + _drawLocation = Vector2.Zero; + _startTime = Option.None(); + + DrawOrder = 29; + Visible = false; + } - if (!_textLabel.Game.Components.Contains(_textLabel)) - _textLabel.Game.Components.Add(_textLabel); + public override void Initialize() + { + _textLabel.Initialize(); - base.Initialize(); - } + if (!_textLabel.Game.Components.Contains(_textLabel)) + _textLabel.Game.Components.Add(_textLabel); - public void SetMessage(string message, bool isGroupChat) - { - if (!_configurationProvider.ShowChatBubbles || !_parent.IsAlive) - return; + base.Initialize(); + } - _isGroupChat = isGroupChat; - _textLabel.Text = message; - Visible = true; - _textLabel.Visible = true; + public void SetMessage(string message, bool isGroupChat) + { + if (!_configurationProvider.ShowChatBubbles || !_parent.IsAlive) + return; - _startTime = Option.Some(Stopwatch.StartNew()); - } + _isGroupChat = isGroupChat; + _textLabel.Text = message; + Visible = true; + _textLabel.Visible = true; - public void Hide() - { - Visible = _textLabel.Visible = false; - } + _startTime = Option.Some(Stopwatch.StartNew()); + } - public void Show() - { - Visible = _textLabel.Visible = _parent.IsAlive && _startTime.HasValue; - } + public void Hide() + { + Visible = _textLabel.Visible = false; + } - public override void Update(GameTime gameTime) - { - SetLabelDrawPosition(); - _drawLocation = _textLabel.DrawPosition - new Vector2( - _chatBubbleTextureProvider.ChatBubbleTextures[ChatBubbleTexture.TopLeft].Width, - _chatBubbleTextureProvider.ChatBubbleTextures[ChatBubbleTexture.TopLeft].Height); + public void Show() + { + Visible = _textLabel.Visible = _parent.IsAlive && _startTime.HasValue; + } - _startTime.MatchSome(st => - { - if (st.ElapsedMilliseconds > (24 + _textLabel.Text.Length / 3) * 120) - { - _textLabel.Visible = false; - Visible = false; - _startTime = Option.None(); - } - }); - - base.Update(gameTime); - } + public override void Update(GameTime gameTime) + { + SetLabelDrawPosition(); + _drawLocation = _textLabel.DrawPosition - new Vector2( + _chatBubbleTextureProvider.ChatBubbleTextures[ChatBubbleTexture.TopLeft].Width, + _chatBubbleTextureProvider.ChatBubbleTextures[ChatBubbleTexture.TopLeft].Height); - public override void Draw(GameTime gameTime) + _startTime.MatchSome(st => { - var TL = GetTexture(ChatBubbleTexture.TopLeft); - var TM = GetTexture(ChatBubbleTexture.TopMiddle); - var TR = GetTexture(ChatBubbleTexture.TopRight); - var ML = GetTexture(ChatBubbleTexture.MiddleLeft); - var MM = GetTexture(ChatBubbleTexture.MiddleMiddle); - var MR = GetTexture(ChatBubbleTexture.MiddleRight); - var BL = GetTexture(ChatBubbleTexture.BottomLeft); - var BM = GetTexture(ChatBubbleTexture.BottomMiddle); - var BR = GetTexture(ChatBubbleTexture.BottomRight); - var NUB = GetTexture(ChatBubbleTexture.Nubbin); - - var xCov = TL.Width; - var yCov = TL.Height; - - var color = _isGroupChat ? Color.FromNonPremultiplied(247, 234, 164, 232) : Color.FromNonPremultiplied(255, 255, 255, 232); - - _spriteBatch.Begin(); - - //top row - _spriteBatch.Draw(TL, _drawLocation, color); - int xCur; - for (xCur = xCov; xCur < _textLabel.ActualWidth + 6; xCur += TM.Width) + if (st.ElapsedMilliseconds > (24 + _textLabel.Text.Length / 3) * 120) { - _spriteBatch.Draw(TM, _drawLocation + new Vector2(xCur, 0), color); + _textLabel.Visible = false; + Visible = false; + _startTime = Option.None(); } - _spriteBatch.Draw(TR, _drawLocation + new Vector2(xCur, 0), color); + }); - //middle area - int y; - for (y = yCov; y < _textLabel.ActualHeight; y += ML.Height) - { - _spriteBatch.Draw(ML, _drawLocation + new Vector2(0, y), color); - int x; - for (x = xCov; x < xCur; x += MM.Width) - { - _spriteBatch.Draw(MM, _drawLocation + new Vector2(x, y), color); - } - _spriteBatch.Draw(MR, _drawLocation + new Vector2(xCur, y), color); - } + base.Update(gameTime); + } + + public override void Draw(GameTime gameTime) + { + var TL = GetTexture(ChatBubbleTexture.TopLeft); + var TM = GetTexture(ChatBubbleTexture.TopMiddle); + var TR = GetTexture(ChatBubbleTexture.TopRight); + var ML = GetTexture(ChatBubbleTexture.MiddleLeft); + var MM = GetTexture(ChatBubbleTexture.MiddleMiddle); + var MR = GetTexture(ChatBubbleTexture.MiddleRight); + var BL = GetTexture(ChatBubbleTexture.BottomLeft); + var BM = GetTexture(ChatBubbleTexture.BottomMiddle); + var BR = GetTexture(ChatBubbleTexture.BottomRight); + var NUB = GetTexture(ChatBubbleTexture.Nubbin); + + var xCov = TL.Width; + var yCov = TL.Height; + + var color = _isGroupChat ? Color.FromNonPremultiplied(247, 234, 164, 232) : Color.FromNonPremultiplied(255, 255, 255, 232); + + _spriteBatch.Begin(); + + //top row + _spriteBatch.Draw(TL, _drawLocation, color); + int xCur; + for (xCur = xCov; xCur < _textLabel.ActualWidth + 6; xCur += TM.Width) + { + _spriteBatch.Draw(TM, _drawLocation + new Vector2(xCur, 0), color); + } + _spriteBatch.Draw(TR, _drawLocation + new Vector2(xCur, 0), color); - //bottom row - _spriteBatch.Draw(BL, _drawLocation + new Vector2(0, y), color); - int x2; - for (x2 = xCov; x2 < xCur; x2 += BM.Width) + //middle area + int y; + for (y = yCov; y < _textLabel.ActualHeight; y += ML.Height) + { + _spriteBatch.Draw(ML, _drawLocation + new Vector2(0, y), color); + int x; + for (x = xCov; x < xCur; x += MM.Width) { - _spriteBatch.Draw(BM, _drawLocation + new Vector2(x2, y), color); + _spriteBatch.Draw(MM, _drawLocation + new Vector2(x, y), color); } - _spriteBatch.Draw(BR, _drawLocation + new Vector2(x2, y), color); - - y += BM.Height; - _spriteBatch.Draw(NUB, _drawLocation + new Vector2((x2 + BR.Width - NUB.Width) / 2f, y - 1), color); - - _spriteBatch.End(); + _spriteBatch.Draw(MR, _drawLocation + new Vector2(xCur, y), color); } - private void SetLabelDrawPosition() + //bottom row + _spriteBatch.Draw(BL, _drawLocation + new Vector2(0, y), color); + int x2; + for (x2 = xCov; x2 < xCur; x2 += BM.Width) { - _textLabel.DrawPosition = new Vector2( - _parent.HorizontalCenter - _textLabel.ActualWidth / 2.0f, - _parent.NameLabelY - _textLabel.ActualHeight + 10); + _spriteBatch.Draw(BM, _drawLocation + new Vector2(x2, y), color); } + _spriteBatch.Draw(BR, _drawLocation + new Vector2(x2, y), color); - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (Game.Components != null && Game.Components.Contains(this)) - Game.Components.Remove(this); + y += BM.Height; + _spriteBatch.Draw(NUB, _drawLocation + new Vector2((x2 + BR.Width - NUB.Width) / 2f, y - 1), color); - _textLabel.Dispose(); - } - } + _spriteBatch.End(); + } - private Texture2D GetTexture(ChatBubbleTexture whichTexture) => - _chatBubbleTextureProvider.ChatBubbleTextures[whichTexture]; + private void SetLabelDrawPosition() + { + _textLabel.DrawPosition = new Vector2( + _parent.HorizontalCenter - _textLabel.ActualWidth / 2.0f, + _parent.NameLabelY - _textLabel.ActualHeight + 10); } - public interface IChatBubble : IDisposable + protected override void Dispose(bool disposing) { - bool Visible { get; } + if (disposing) + { + if (Game.Components != null && Game.Components.Contains(this)) + Game.Components.Remove(this); + + _textLabel.Dispose(); + } + } + + private Texture2D GetTexture(ChatBubbleTexture whichTexture) => + _chatBubbleTextureProvider.ChatBubbleTextures[whichTexture]; +} - void SetMessage(string message, bool isGroupChat); +public interface IChatBubble : IDisposable +{ + bool Visible { get; } - void Hide(); + void SetMessage(string message, bool isGroupChat); - void Show(); - } + void Hide(); + + void Show(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs b/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs index 630c98a05..8d53216a0 100644 --- a/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs +++ b/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs @@ -2,37 +2,36 @@ using EndlessClient.GameExecution; using EOLib.Config; -namespace EndlessClient.Rendering.Chat +namespace EndlessClient.Rendering.Chat; + +[AutoMappedType] +public class ChatBubbleFactory : IChatBubbleFactory { - [AutoMappedType] - public class ChatBubbleFactory : IChatBubbleFactory - { - private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IConfigurationProvider _configurationProvider; + private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IConfigurationProvider _configurationProvider; - public ChatBubbleFactory(IChatBubbleTextureProvider chatBubbleTextureProvider, - IEndlessGameProvider endlessGameProvider, - IConfigurationProvider configurationProvider) - { - _chatBubbleTextureProvider = chatBubbleTextureProvider; - _endlessGameProvider = endlessGameProvider; - _configurationProvider = configurationProvider; - } + public ChatBubbleFactory(IChatBubbleTextureProvider chatBubbleTextureProvider, + IEndlessGameProvider endlessGameProvider, + IConfigurationProvider configurationProvider) + { + _chatBubbleTextureProvider = chatBubbleTextureProvider; + _endlessGameProvider = endlessGameProvider; + _configurationProvider = configurationProvider; + } - public IChatBubble CreateChatBubble(IMapActor owner) - { - var chatBubble = new ChatBubble(owner, _chatBubbleTextureProvider, _endlessGameProvider, _configurationProvider); + public IChatBubble CreateChatBubble(IMapActor owner) + { + var chatBubble = new ChatBubble(owner, _chatBubbleTextureProvider, _endlessGameProvider, _configurationProvider); - if (!_endlessGameProvider.Game.Components.Contains(chatBubble)) - _endlessGameProvider.Game.Components.Add(chatBubble); + if (!_endlessGameProvider.Game.Components.Contains(chatBubble)) + _endlessGameProvider.Game.Components.Add(chatBubble); - return chatBubble; - } + return chatBubble; } +} - public interface IChatBubbleFactory - { - IChatBubble CreateChatBubble(IMapActor owner); - } +public interface IChatBubbleFactory +{ + IChatBubble CreateChatBubble(IMapActor owner); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs b/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs index ee6c96602..6d7905973 100644 --- a/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs +++ b/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs @@ -1,16 +1,15 @@ -namespace EndlessClient.Rendering.Chat +namespace EndlessClient.Rendering.Chat; + +public enum ChatBubbleTexture { - public enum ChatBubbleTexture - { - TopLeft, - TopMiddle, - TopRight, - MiddleLeft, - MiddleMiddle, - MiddleRight, - BottomLeft, - BottomMiddle, - BottomRight, - Nubbin - } + TopLeft, + TopMiddle, + TopRight, + MiddleLeft, + MiddleMiddle, + MiddleRight, + BottomLeft, + BottomMiddle, + BottomRight, + Nubbin } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs b/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs index e9a3cdbf9..9a70b3ceb 100644 --- a/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs +++ b/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs @@ -4,42 +4,41 @@ using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; -namespace EndlessClient.Rendering.Chat -{ - [MappedType(BaseType = typeof(IChatBubbleTextureProvider), IsSingleton = true)] - public class ChatBubbleTextureProvider : IChatBubbleTextureProvider - { - private readonly IContentProvider _contentProvider; - private readonly Dictionary _chatBubbleTextures; +namespace EndlessClient.Rendering.Chat; - public IReadOnlyDictionary ChatBubbleTextures => _chatBubbleTextures; +[MappedType(BaseType = typeof(IChatBubbleTextureProvider), IsSingleton = true)] +public class ChatBubbleTextureProvider : IChatBubbleTextureProvider +{ + private readonly IContentProvider _contentProvider; + private readonly Dictionary _chatBubbleTextures; - public ChatBubbleTextureProvider(IContentProvider contentProvider) - { - _contentProvider = contentProvider; - _chatBubbleTextures = new Dictionary(); - } + public IReadOnlyDictionary ChatBubbleTextures => _chatBubbleTextures; - public void LoadContent() - { - _chatBubbleTextures.Add(ChatBubbleTexture.TopLeft, _contentProvider.Textures[ContentProvider.ChatTL]); - _chatBubbleTextures.Add(ChatBubbleTexture.TopMiddle, _contentProvider.Textures[ContentProvider.ChatTM]); - _chatBubbleTextures.Add(ChatBubbleTexture.TopRight, _contentProvider.Textures[ContentProvider.ChatTR]); - _chatBubbleTextures.Add(ChatBubbleTexture.MiddleLeft, _contentProvider.Textures[ContentProvider.ChatML]); - _chatBubbleTextures.Add(ChatBubbleTexture.MiddleMiddle, _contentProvider.Textures[ContentProvider.ChatMM]); - _chatBubbleTextures.Add(ChatBubbleTexture.MiddleRight, _contentProvider.Textures[ContentProvider.ChatMR]); - //todo: change the first 'R' to a 'B' (for bottom) - _chatBubbleTextures.Add(ChatBubbleTexture.BottomLeft, _contentProvider.Textures[ContentProvider.ChatRL]); - _chatBubbleTextures.Add(ChatBubbleTexture.BottomMiddle, _contentProvider.Textures[ContentProvider.ChatRM]); - _chatBubbleTextures.Add(ChatBubbleTexture.BottomRight, _contentProvider.Textures[ContentProvider.ChatRR]); - _chatBubbleTextures.Add(ChatBubbleTexture.Nubbin, _contentProvider.Textures[ContentProvider.ChatNUB]); - } + public ChatBubbleTextureProvider(IContentProvider contentProvider) + { + _contentProvider = contentProvider; + _chatBubbleTextures = new Dictionary(); } - public interface IChatBubbleTextureProvider + public void LoadContent() { - IReadOnlyDictionary ChatBubbleTextures { get; } - - void LoadContent(); + _chatBubbleTextures.Add(ChatBubbleTexture.TopLeft, _contentProvider.Textures[ContentProvider.ChatTL]); + _chatBubbleTextures.Add(ChatBubbleTexture.TopMiddle, _contentProvider.Textures[ContentProvider.ChatTM]); + _chatBubbleTextures.Add(ChatBubbleTexture.TopRight, _contentProvider.Textures[ContentProvider.ChatTR]); + _chatBubbleTextures.Add(ChatBubbleTexture.MiddleLeft, _contentProvider.Textures[ContentProvider.ChatML]); + _chatBubbleTextures.Add(ChatBubbleTexture.MiddleMiddle, _contentProvider.Textures[ContentProvider.ChatMM]); + _chatBubbleTextures.Add(ChatBubbleTexture.MiddleRight, _contentProvider.Textures[ContentProvider.ChatMR]); + //todo: change the first 'R' to a 'B' (for bottom) + _chatBubbleTextures.Add(ChatBubbleTexture.BottomLeft, _contentProvider.Textures[ContentProvider.ChatRL]); + _chatBubbleTextures.Add(ChatBubbleTexture.BottomMiddle, _contentProvider.Textures[ContentProvider.ChatRM]); + _chatBubbleTextures.Add(ChatBubbleTexture.BottomRight, _contentProvider.Textures[ContentProvider.ChatRR]); + _chatBubbleTextures.Add(ChatBubbleTexture.Nubbin, _contentProvider.Textures[ContentProvider.ChatNUB]); } +} + +public interface IChatBubbleTextureProvider +{ + IReadOnlyDictionary ChatBubbleTextures { get; } + + void LoadContent(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatColorExtensions.cs b/EndlessClient/Rendering/Chat/ChatColorExtensions.cs index cf46f5dff..4d68c3a28 100644 --- a/EndlessClient/Rendering/Chat/ChatColorExtensions.cs +++ b/EndlessClient/Rendering/Chat/ChatColorExtensions.cs @@ -3,22 +3,21 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.Rendering.Chat +namespace EndlessClient.Rendering.Chat; + +public static class ChatColorExtensions { - public static class ChatColorExtensions + public static Color ToColor(this ChatColor chatColor) { - public static Color ToColor(this ChatColor chatColor) + switch (chatColor) { - switch (chatColor) - { - case ChatColor.Default: return Color.Black; - case ChatColor.Error: return Color.FromNonPremultiplied(0x7d, 0x0a, 0x0a, 0xff); - case ChatColor.PM: return Color.FromNonPremultiplied(0x5a, 0x3c, 0x00, 0xff); - case ChatColor.Server: return Color.FromNonPremultiplied(0xe6, 0xd2, 0xc8, 0xff); - case ChatColor.ServerGlobal: return ColorConstants.LightYellowText; - case ChatColor.Admin: return Color.FromNonPremultiplied(0xc8, 0xaa, 0x96, 0xff); - default: throw new ArgumentOutOfRangeException(nameof(chatColor), chatColor, "Unrecognized chat color"); - } + case ChatColor.Default: return Color.Black; + case ChatColor.Error: return Color.FromNonPremultiplied(0x7d, 0x0a, 0x0a, 0xff); + case ChatColor.PM: return Color.FromNonPremultiplied(0x5a, 0x3c, 0x00, 0xff); + case ChatColor.Server: return Color.FromNonPremultiplied(0xe6, 0xd2, 0xc8, 0xff); + case ChatColor.ServerGlobal: return ColorConstants.LightYellowText; + case ChatColor.Admin: return Color.FromNonPremultiplied(0xc8, 0xaa, 0x96, 0xff); + default: throw new ArgumentOutOfRangeException(nameof(chatColor), chatColor, "Unrecognized chat color"); } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatRenderable.cs b/EndlessClient/Rendering/Chat/ChatRenderable.cs index 9d9728d3b..073f03ddd 100644 --- a/EndlessClient/Rendering/Chat/ChatRenderable.cs +++ b/EndlessClient/Rendering/Chat/ChatRenderable.cs @@ -7,90 +7,89 @@ using MonoGame.Extended.BitmapFonts; using Optional.Unsafe; -namespace EndlessClient.Rendering.Chat +namespace EndlessClient.Rendering.Chat; + +public class ChatRenderable : IChatRenderable { - public class ChatRenderable : IChatRenderable + private const int ICON_GRAPHIC_X_OFF = 3; + private const int CHAT_MESSAGE_X_OFF = 20; + + private readonly INativeGraphicsManager _nativeGraphicsManager; + + private readonly string _partialMessage; + + protected virtual int HeaderYOffset => 3; + + public int DisplayIndex { get; set; } + + public ChatData Data { get; private set; } + + public ChatRenderable(INativeGraphicsManager nativeGraphicsManager, + int displayIndex, + ChatData data, + string partialMessage = null) + { + _nativeGraphicsManager = nativeGraphicsManager; + + DisplayIndex = displayIndex; + Data = data; + _partialMessage = partialMessage; + } + + public override bool Equals(object obj) { - private const int ICON_GRAPHIC_X_OFF = 3; - private const int CHAT_MESSAGE_X_OFF = 20; - - private readonly INativeGraphicsManager _nativeGraphicsManager; - - private readonly string _partialMessage; - - protected virtual int HeaderYOffset => 3; - - public int DisplayIndex { get; set; } - - public ChatData Data { get; private set; } - - public ChatRenderable(INativeGraphicsManager nativeGraphicsManager, - int displayIndex, - ChatData data, - string partialMessage = null) - { - _nativeGraphicsManager = nativeGraphicsManager; - - DisplayIndex = displayIndex; - Data = data; - _partialMessage = partialMessage; - } - - public override bool Equals(object obj) - { - if (!(obj is ChatRenderable)) return false; - var other = (ChatRenderable)obj; - - return other.Data.Equals(Data) - && other._partialMessage.Equals(_partialMessage); - } - - public override int GetHashCode() - { - var hash = 397 ^ Data.GetHashCode(); - hash = (hash * 397) ^ DisplayIndex.GetHashCode(); - hash = (hash * 397) ^ _partialMessage.GetHashCode(); - return hash; - } - - public void Render(IHudPanel parentPanel, SpriteBatch spriteBatch, BitmapFont chatFont) - { - spriteBatch.Begin(); - - var pos = parentPanel.DrawPosition + new Vector2(0, DisplayIndex * 13); - spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true), - new Vector2(pos.X + ICON_GRAPHIC_X_OFF, pos.Y + HeaderYOffset), - GetChatIconRectangle(Data.Icon), - Color.White); - - string strToDraw; - if (string.IsNullOrEmpty(Data.Who)) - strToDraw = _partialMessage; - else - strToDraw = Data.Who + " " + _partialMessage; - - spriteBatch.DrawString(chatFont, - strToDraw, - new Vector2(pos.X + CHAT_MESSAGE_X_OFF, pos.Y + HeaderYOffset), - Data.ChatColor.ToColor()); - - spriteBatch.End(); - } - - private static Rectangle? GetChatIconRectangle(ChatIcon icon) - { - var (x, y, width, height) = icon.GetChatIconRectangleBounds().ValueOrDefault(); - return new Rectangle(x, y, width, height); - } + if (!(obj is ChatRenderable)) return false; + var other = (ChatRenderable)obj; + + return other.Data.Equals(Data) + && other._partialMessage.Equals(_partialMessage); + } + + public override int GetHashCode() + { + var hash = 397 ^ Data.GetHashCode(); + hash = (hash * 397) ^ DisplayIndex.GetHashCode(); + hash = (hash * 397) ^ _partialMessage.GetHashCode(); + return hash; } - public class NewsChatRenderable : ChatRenderable + public void Render(IHudPanel parentPanel, SpriteBatch spriteBatch, BitmapFont chatFont) { - protected override int HeaderYOffset => 23; + spriteBatch.Begin(); + + var pos = parentPanel.DrawPosition + new Vector2(0, DisplayIndex * 13); + spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true), + new Vector2(pos.X + ICON_GRAPHIC_X_OFF, pos.Y + HeaderYOffset), + GetChatIconRectangle(Data.Icon), + Color.White); + + string strToDraw; + if (string.IsNullOrEmpty(Data.Who)) + strToDraw = _partialMessage; + else + strToDraw = Data.Who + " " + _partialMessage; + + spriteBatch.DrawString(chatFont, + strToDraw, + new Vector2(pos.X + CHAT_MESSAGE_X_OFF, pos.Y + HeaderYOffset), + Data.ChatColor.ToColor()); + + spriteBatch.End(); + } - public NewsChatRenderable(INativeGraphicsManager nativeGraphicsManager, int displayIndex, ChatData data, string partialMessage) - : base(nativeGraphicsManager, displayIndex, data, partialMessage) - { - } + private static Rectangle? GetChatIconRectangle(ChatIcon icon) + { + var (x, y, width, height) = icon.GetChatIconRectangleBounds().ValueOrDefault(); + return new Rectangle(x, y, width, height); + } +} + +public class NewsChatRenderable : ChatRenderable +{ + protected override int HeaderYOffset => 23; + + public NewsChatRenderable(INativeGraphicsManager nativeGraphicsManager, int displayIndex, ChatData data, string partialMessage) + : base(nativeGraphicsManager, displayIndex, data, partialMessage) + { } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs b/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs index 6e0ac4955..da6fdded7 100644 --- a/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs +++ b/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs @@ -9,128 +9,127 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering.Chat +namespace EndlessClient.Rendering.Chat; + +public class ChatRenderableGenerator : IChatRenderableGenerator { - public class ChatRenderableGenerator : IChatRenderableGenerator + private class ChatPair { - private class ChatPair - { - public string Text { get; set; } - public bool IsFirstLineOfMultilineMessage { get; set; } - } + public string Text { get; set; } + public bool IsFirstLineOfMultilineMessage { get; set; } + } + + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly BitmapFont _chatFont; - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly BitmapFont _chatFont; + public ChatRenderableGenerator(INativeGraphicsManager nativeGraphicsManager, + IFriendIgnoreListService friendIgnoreListService, + BitmapFont chatFont) + { + _nativeGraphicsManager = nativeGraphicsManager; + _friendIgnoreListService = friendIgnoreListService; + _chatFont = chatFont; + } + + public IReadOnlyList GenerateNewsRenderables(IReadOnlyList newsText) + { + newsText = newsText.Where(x => !string.IsNullOrEmpty(x)).ToList(); - public ChatRenderableGenerator(INativeGraphicsManager nativeGraphicsManager, - IFriendIgnoreListService friendIgnoreListService, - BitmapFont chatFont) + var newsTextWithBlankLines = new List(); + foreach (var news in newsText) { - _nativeGraphicsManager = nativeGraphicsManager; - _friendIgnoreListService = friendIgnoreListService; - _chatFont = chatFont; + newsTextWithBlankLines.Add(news); + if (news != newsText.Last()) + newsTextWithBlankLines.Add(" "); } - public IReadOnlyList GenerateNewsRenderables(IReadOnlyList newsText) - { - newsText = newsText.Where(x => !string.IsNullOrEmpty(x)).ToList(); + var splitStrings = SplitTextIntoLines(string.Empty, newsTextWithBlankLines); + return splitStrings.Select(CreateNewsRenderableFromChatPair).ToList(); + } - var newsTextWithBlankLines = new List(); - foreach (var news in newsText) - { - newsTextWithBlankLines.Add(news); - if (news != newsText.Last()) - newsTextWithBlankLines.Add(" "); - } + public IReadOnlyList GenerateChatRenderables(IEnumerable chatData) + { + var ignoreList = _friendIgnoreListService.LoadList(Constants.IgnoreListFile); - var splitStrings = SplitTextIntoLines(string.Empty, newsTextWithBlankLines); - return splitStrings.Select(CreateNewsRenderableFromChatPair).ToList(); + var retList = new List(); + foreach (var data in chatData) + { + if (ignoreList.Any(x => x.Equals(data.Who, StringComparison.InvariantCultureIgnoreCase))) + continue; + + var splitStrings = SplitTextIntoLines(data.Who, new[] { data.Message }); + var renderables = splitStrings.Select( + (pair, i) => CreateChatRenderableFromChatPair(pair, i, data)) + .ToList(); + retList.AddRange(renderables); } - public IReadOnlyList GenerateChatRenderables(IEnumerable chatData) - { - var ignoreList = _friendIgnoreListService.LoadList(Constants.IgnoreListFile); + return retList; + } - var retList = new List(); - foreach (var data in chatData) - { - if (ignoreList.Any(x => x.Equals(data.Who, StringComparison.InvariantCultureIgnoreCase))) - continue; - - var splitStrings = SplitTextIntoLines(data.Who, new[] { data.Message }); - var renderables = splitStrings.Select( - (pair, i) => CreateChatRenderableFromChatPair(pair, i, data)) - .ToList(); - retList.AddRange(renderables); - } + private IReadOnlyList SplitTextIntoLines(string who, IReadOnlyList input) + { + var retStrings = new List(); + who = who ?? string.Empty; - return retList; - } + // padding string for additional lines if it is a multi-line message + var indentForUserName = string.Empty; + while (_chatFont.MeasureString(indentForUserName).Width < _chatFont.MeasureString(who).Width) + indentForUserName += " "; + indentForUserName += string.IsNullOrEmpty(who) ? string.Empty : " "; - private IReadOnlyList SplitTextIntoLines(string who, IReadOnlyList input) + var splitter = new TextSplitter("", _chatFont) { - var retStrings = new List(); - who = who ?? string.Empty; + LineLength = 380, + HardBreak = 425, + Hyphen = "-", + LineIndent = indentForUserName + }; - // padding string for additional lines if it is a multi-line message - var indentForUserName = string.Empty; - while (_chatFont.MeasureString(indentForUserName).Width < _chatFont.MeasureString(who).Width) - indentForUserName += " "; - indentForUserName += string.IsNullOrEmpty(who) ? string.Empty : " "; + foreach (var text in input) + { + if (string.IsNullOrWhiteSpace(who) && string.IsNullOrWhiteSpace(text)) + { + retStrings.Add(new ChatPair { Text = " ", IsFirstLineOfMultilineMessage = true }); + continue; + } - var splitter = new TextSplitter("", _chatFont) + splitter.Text = string.IsNullOrEmpty(who) ? text : $"{who} {text}"; + if (!splitter.NeedsProcessing) { - LineLength = 380, - HardBreak = 425, - Hyphen = "-", - LineIndent = indentForUserName - }; + retStrings.Add(new ChatPair { Text = text, IsFirstLineOfMultilineMessage = true }); + continue; + } - foreach (var text in input) + var stringsToAdd = splitter.SplitIntoLines(); + if (who.Length > 0) { - if (string.IsNullOrWhiteSpace(who) && string.IsNullOrWhiteSpace(text)) - { - retStrings.Add(new ChatPair { Text = " ", IsFirstLineOfMultilineMessage = true }); - continue; - } - - splitter.Text = string.IsNullOrEmpty(who) ? text : $"{who} {text}"; - if (!splitter.NeedsProcessing) - { - retStrings.Add(new ChatPair { Text = text, IsFirstLineOfMultilineMessage = true }); - continue; - } - - var stringsToAdd = splitter.SplitIntoLines(); - if (who.Length > 0) - { - stringsToAdd[0] = stringsToAdd[0].Remove(0, who.Length + 1); - } - - retStrings.AddRange(stringsToAdd.Select((str, i) => new ChatPair { Text = str, IsFirstLineOfMultilineMessage = i == 0 })); + stringsToAdd[0] = stringsToAdd[0].Remove(0, who.Length + 1); } - return retStrings; + retStrings.AddRange(stringsToAdd.Select((str, i) => new ChatPair { Text = str, IsFirstLineOfMultilineMessage = i == 0 })); } - private NewsChatRenderable CreateNewsRenderableFromChatPair(ChatPair pair, int i) - { - var shouldShowNoteIcon = pair.IsFirstLineOfMultilineMessage && !string.IsNullOrWhiteSpace(pair.Text); - var chatData = new ChatData(ChatTab.Local, "", pair.Text, shouldShowNoteIcon ? ChatIcon.Note : ChatIcon.None, log: false); - return new NewsChatRenderable(_nativeGraphicsManager, i, chatData, pair.Text); - } + return retStrings; + } - private ChatRenderable CreateChatRenderableFromChatPair(ChatPair pair, int displayIndex, ChatData data) - { - var modifiedData = new ChatData( - data.Tab, - pair.IsFirstLineOfMultilineMessage ? data.Who : string.Empty, - data.Message, - pair.IsFirstLineOfMultilineMessage ? data.Icon : ChatIcon.None, - data.ChatColor); - - return new ChatRenderable(_nativeGraphicsManager, displayIndex, modifiedData, pair.Text); - } + private NewsChatRenderable CreateNewsRenderableFromChatPair(ChatPair pair, int i) + { + var shouldShowNoteIcon = pair.IsFirstLineOfMultilineMessage && !string.IsNullOrWhiteSpace(pair.Text); + var chatData = new ChatData(ChatTab.Local, "", pair.Text, shouldShowNoteIcon ? ChatIcon.Note : ChatIcon.None, log: false); + return new NewsChatRenderable(_nativeGraphicsManager, i, chatData, pair.Text); + } + + private ChatRenderable CreateChatRenderableFromChatPair(ChatPair pair, int displayIndex, ChatData data) + { + var modifiedData = new ChatData( + data.Tab, + pair.IsFirstLineOfMultilineMessage ? data.Who : string.Empty, + data.Message, + pair.IsFirstLineOfMultilineMessage ? data.Icon : ChatIcon.None, + data.ChatColor); + + return new ChatRenderable(_nativeGraphicsManager, displayIndex, modifiedData, pair.Text); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/IChatRenderable.cs b/EndlessClient/Rendering/Chat/IChatRenderable.cs index 24fda7fa1..31e65d7db 100644 --- a/EndlessClient/Rendering/Chat/IChatRenderable.cs +++ b/EndlessClient/Rendering/Chat/IChatRenderable.cs @@ -3,14 +3,13 @@ using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.BitmapFonts; -namespace EndlessClient.Rendering.Chat +namespace EndlessClient.Rendering.Chat; + +public interface IChatRenderable { - public interface IChatRenderable - { - int DisplayIndex { get; set; } + int DisplayIndex { get; set; } - ChatData Data { get; } + ChatData Data { get; } - void Render(IHudPanel parentPanel, SpriteBatch spriteBatch, BitmapFont chatFont); - } + void Render(IHudPanel parentPanel, SpriteBatch spriteBatch, BitmapFont chatFont); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs b/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs index 27a6ad5f3..678181759 100644 --- a/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs +++ b/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs @@ -1,12 +1,11 @@ using EOLib.Domain.Chat; using System.Collections.Generic; -namespace EndlessClient.Rendering.Chat +namespace EndlessClient.Rendering.Chat; + +public interface IChatRenderableGenerator { - public interface IChatRenderableGenerator - { - IReadOnlyList GenerateNewsRenderables(IReadOnlyList newsText); + IReadOnlyList GenerateNewsRenderables(IReadOnlyList newsText); - IReadOnlyList GenerateChatRenderables(IEnumerable chatData); - } + IReadOnlyList GenerateChatRenderables(IEnumerable chatData); } \ No newline at end of file diff --git a/EndlessClient/Rendering/ClientWindowSizeRepository.cs b/EndlessClient/Rendering/ClientWindowSizeRepository.cs index 17cbd99fe..8a5625031 100644 --- a/EndlessClient/Rendering/ClientWindowSizeRepository.cs +++ b/EndlessClient/Rendering/ClientWindowSizeRepository.cs @@ -4,107 +4,106 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +public interface IClientWindowSizeProvider { - public interface IClientWindowSizeProvider - { - int Width { get; } - int Height { get; } + int Width { get; } + int Height { get; } - bool Resizable { get; } + bool Resizable { get; } - event EventHandler GameWindowSizeChanged; - } + event EventHandler GameWindowSizeChanged; +} - public interface IClientWindowSizeRepository : IResettable, IClientWindowSizeProvider - { - new int Width { get; set; } - new int Height { get; set; } +public interface IClientWindowSizeRepository : IResettable, IClientWindowSizeProvider +{ + new int Width { get; set; } + new int Height { get; set; } - new bool Resizable { get; set; } - } + new bool Resizable { get; set; } +} - [AutoMappedType(IsSingleton = true)] - public class ClientWindowSizeRepository : IClientWindowSizeProvider, IClientWindowSizeRepository, IResettable - { - public const int DEFAULT_BACKBUFFER_WIDTH = 640; - public const int DEFAULT_BACKBUFFER_HEIGHT = 480; +[AutoMappedType(IsSingleton = true)] +public class ClientWindowSizeRepository : IClientWindowSizeProvider, IClientWindowSizeRepository, IResettable +{ + public const int DEFAULT_BACKBUFFER_WIDTH = 640; + public const int DEFAULT_BACKBUFFER_HEIGHT = 480; - private readonly IGameWindowRepository _gameWindowRepository; - private readonly IGraphicsDeviceRepository _graphicsDeviceRepository; + private readonly IGameWindowRepository _gameWindowRepository; + private readonly IGraphicsDeviceRepository _graphicsDeviceRepository; - private readonly List> _resizeEvents; + private readonly List> _resizeEvents; - public int Width + public int Width + { + get => _gameWindowRepository.Window.ClientBounds.Width; + set { - get => _gameWindowRepository.Window.ClientBounds.Width; - set - { - if (value < DEFAULT_BACKBUFFER_WIDTH) - value = DEFAULT_BACKBUFFER_WIDTH; - - _graphicsDeviceRepository.GraphicsDeviceManager.PreferredBackBufferWidth = value; - _graphicsDeviceRepository.GraphicsDeviceManager.ApplyChanges(); - - foreach (var evnt in _resizeEvents) - evnt(this, EventArgs.Empty); - } - } + if (value < DEFAULT_BACKBUFFER_WIDTH) + value = DEFAULT_BACKBUFFER_WIDTH; - public int Height - { - get => _gameWindowRepository.Window.ClientBounds.Height; - set - { - if (value < DEFAULT_BACKBUFFER_HEIGHT) - value = DEFAULT_BACKBUFFER_HEIGHT; - - _graphicsDeviceRepository.GraphicsDeviceManager.PreferredBackBufferHeight = value; - _graphicsDeviceRepository.GraphicsDeviceManager.ApplyChanges(); - - foreach (var evnt in _resizeEvents) - evnt(this, EventArgs.Empty); - } + _graphicsDeviceRepository.GraphicsDeviceManager.PreferredBackBufferWidth = value; + _graphicsDeviceRepository.GraphicsDeviceManager.ApplyChanges(); + + foreach (var evnt in _resizeEvents) + evnt(this, EventArgs.Empty); } + } - public bool Resizable + public int Height + { + get => _gameWindowRepository.Window.ClientBounds.Height; + set { - get => _gameWindowRepository.Window.AllowUserResizing; - set => _gameWindowRepository.Window.AllowUserResizing = value; + if (value < DEFAULT_BACKBUFFER_HEIGHT) + value = DEFAULT_BACKBUFFER_HEIGHT; + + _graphicsDeviceRepository.GraphicsDeviceManager.PreferredBackBufferHeight = value; + _graphicsDeviceRepository.GraphicsDeviceManager.ApplyChanges(); + + foreach (var evnt in _resizeEvents) + evnt(this, EventArgs.Empty); } + } + + public bool Resizable + { + get => _gameWindowRepository.Window.AllowUserResizing; + set => _gameWindowRepository.Window.AllowUserResizing = value; + } - public event EventHandler GameWindowSizeChanged + public event EventHandler GameWindowSizeChanged + { + add { - add - { - _gameWindowRepository.Window.ClientSizeChanged += value; - _resizeEvents.Add(value); - } - remove - { - _gameWindowRepository.Window.ClientSizeChanged -= value; - _resizeEvents.Remove(value); - } + _gameWindowRepository.Window.ClientSizeChanged += value; + _resizeEvents.Add(value); } - - public ClientWindowSizeRepository(IGameWindowRepository gameWindowRepository, - IGraphicsDeviceRepository graphicsDeviceRepository) + remove { - _gameWindowRepository = gameWindowRepository; - _graphicsDeviceRepository = graphicsDeviceRepository; - _resizeEvents = new List>(); + _gameWindowRepository.Window.ClientSizeChanged -= value; + _resizeEvents.Remove(value); } + } - public void ResetState() - { - foreach (var evnt in _resizeEvents) - GameWindowSizeChanged -= evnt; - _resizeEvents.Clear(); + public ClientWindowSizeRepository(IGameWindowRepository gameWindowRepository, + IGraphicsDeviceRepository graphicsDeviceRepository) + { + _gameWindowRepository = gameWindowRepository; + _graphicsDeviceRepository = graphicsDeviceRepository; + _resizeEvents = new List>(); + } + + public void ResetState() + { + foreach (var evnt in _resizeEvents) + GameWindowSizeChanged -= evnt; + _resizeEvents.Clear(); - Resizable = false; + Resizable = false; - Width = DEFAULT_BACKBUFFER_WIDTH; - Height = DEFAULT_BACKBUFFER_HEIGHT; - } + Width = DEFAULT_BACKBUFFER_WIDTH; + Height = DEFAULT_BACKBUFFER_HEIGHT; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/ContextMenuRenderer.cs b/EndlessClient/Rendering/ContextMenuRenderer.cs index c58f8d02e..5f81e1c06 100644 --- a/EndlessClient/Rendering/ContextMenuRenderer.cs +++ b/EndlessClient/Rendering/ContextMenuRenderer.cs @@ -25,334 +25,333 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +public class ContextMenuRenderer : XNAControl, IContextMenuRenderer { - public class ContextMenuRenderer : XNAControl, IContextMenuRenderer + private enum MenuAction { - private enum MenuAction - { - Paperdoll, - Book, - Join, - Invite, - Trade, - Whisper, - Friend, - Ignore, - NUM_MENU_ACTIONS - } + Paperdoll, + Book, + Join, + Invite, + Trade, + Whisper, + Friend, + Ignore, + NUM_MENU_ACTIONS + } - private readonly Texture2D _backgroundTexture, _bgfill; - private readonly Rectangle _outSource, _overSource; - private readonly Dictionary _menuActions; - private Option _overRect; - - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IPaperdollActions _paperdollActions; - private readonly IBookActions _bookActions; - private readonly IPartyActions _partyActions; - private readonly ITradeActions _tradeActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly IHudControlProvider _hudControlProvider; - private readonly IContextMenuRepository _contextMenuRepository; - private readonly IPartyDataProvider _partyDataProvider; - private readonly ICharacterRenderer _characterRenderer; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ISfxPlayer _sfxPlayer; - - private static DateTime? _lastTradeRequestedTime; - private static DateTime? _lastPartyRequestTime; - - public ContextMenuRenderer(INativeGraphicsManager nativeGraphicsManager, - IInGameDialogActions inGameDialogActions, - IPaperdollActions paperdollActions, - IBookActions bookActions, - IPartyActions partyActions, - ITradeActions tradeActions, - IStatusLabelSetter statusLabelSetter, - IFriendIgnoreListService friendIgnoreListService, - IHudControlProvider hudControlProvider, - IContextMenuRepository contextMenuRepository, - IPartyDataProvider partyDataProvider, - ICharacterRenderer characterRenderer, - ICurrentMapStateProvider currentMapStateProvider, - IEOMessageBoxFactory messageBoxFactory, - IClientWindowSizeProvider clientWindowSizeProvider, - ISfxPlayer sfxPlayer) + private readonly Texture2D _backgroundTexture, _bgfill; + private readonly Rectangle _outSource, _overSource; + private readonly Dictionary _menuActions; + private Option _overRect; + + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IPaperdollActions _paperdollActions; + private readonly IBookActions _bookActions; + private readonly IPartyActions _partyActions; + private readonly ITradeActions _tradeActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly IHudControlProvider _hudControlProvider; + private readonly IContextMenuRepository _contextMenuRepository; + private readonly IPartyDataProvider _partyDataProvider; + private readonly ICharacterRenderer _characterRenderer; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ISfxPlayer _sfxPlayer; + + private static DateTime? _lastTradeRequestedTime; + private static DateTime? _lastPartyRequestTime; + + public ContextMenuRenderer(INativeGraphicsManager nativeGraphicsManager, + IInGameDialogActions inGameDialogActions, + IPaperdollActions paperdollActions, + IBookActions bookActions, + IPartyActions partyActions, + ITradeActions tradeActions, + IStatusLabelSetter statusLabelSetter, + IFriendIgnoreListService friendIgnoreListService, + IHudControlProvider hudControlProvider, + IContextMenuRepository contextMenuRepository, + IPartyDataProvider partyDataProvider, + ICharacterRenderer characterRenderer, + ICurrentMapStateProvider currentMapStateProvider, + IEOMessageBoxFactory messageBoxFactory, + IClientWindowSizeProvider clientWindowSizeProvider, + ISfxPlayer sfxPlayer) + { + _menuActions = new Dictionary(); + _inGameDialogActions = inGameDialogActions; + _paperdollActions = paperdollActions; + _bookActions = bookActions; + _partyActions = partyActions; + _tradeActions = tradeActions; + _statusLabelSetter = statusLabelSetter; + _friendIgnoreListService = friendIgnoreListService; + _hudControlProvider = hudControlProvider; + _contextMenuRepository = contextMenuRepository; + _partyDataProvider = partyDataProvider; + _characterRenderer = characterRenderer; + _currentMapStateProvider = currentMapStateProvider; + _messageBoxFactory = messageBoxFactory; + _clientWindowSizeProvider = clientWindowSizeProvider; + _sfxPlayer = sfxPlayer; + + //first, load up the images. split in half: the right half is the 'over' text + _backgroundTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 41, true); + + const int W = 96, H = 137; + _outSource = new Rectangle(0, 0, W, H); + _overSource = new Rectangle(W, 0, W, H); + + //this GFX is stupid. a bunch of white space throws off coordinates so I have to use hard-coded values + //define regions for clicking and their associated actions + //6,11,86,14 + for (int i = 0; i < (int)MenuAction.NUM_MENU_ACTIONS; ++i) { - _menuActions = new Dictionary(); - _inGameDialogActions = inGameDialogActions; - _paperdollActions = paperdollActions; - _bookActions = bookActions; - _partyActions = partyActions; - _tradeActions = tradeActions; - _statusLabelSetter = statusLabelSetter; - _friendIgnoreListService = friendIgnoreListService; - _hudControlProvider = hudControlProvider; - _contextMenuRepository = contextMenuRepository; - _partyDataProvider = partyDataProvider; - _characterRenderer = characterRenderer; - _currentMapStateProvider = currentMapStateProvider; - _messageBoxFactory = messageBoxFactory; - _clientWindowSizeProvider = clientWindowSizeProvider; - _sfxPlayer = sfxPlayer; - - //first, load up the images. split in half: the right half is the 'over' text - _backgroundTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 41, true); - - const int W = 96, H = 137; - _outSource = new Rectangle(0, 0, W, H); - _overSource = new Rectangle(W, 0, W, H); - - //this GFX is stupid. a bunch of white space throws off coordinates so I have to use hard-coded values - //define regions for clicking and their associated actions - //6,11,86,14 - for (int i = 0; i < (int)MenuAction.NUM_MENU_ACTIONS; ++i) - { - Rectangle region = new Rectangle(6, (i < 5 ? 11 : 13) + 14 * i, 86, 14); - _menuActions.Add(region, GetActionFromMenuAction((MenuAction)i)); - } - - //set the fill color - _bgfill = new Texture2D(GraphicsDevice, 1, 1); - _bgfill.SetData(new[] { Color.White }); - - SetPositionBasedOnCharacterRenderer(_characterRenderer); - SetSize(W, H); - - OnMouseOver += ContextMenuRenderer_OnMouseOver; - - // Update this before map renderer so that clicks are handled first - UpdateOrder = -20; + Rectangle region = new Rectangle(6, (i < 5 ? 11 : 13) + 14 * i, 86, 14); + _menuActions.Add(region, GetActionFromMenuAction((MenuAction)i)); } - public override void Initialize() - { - base.Initialize(); + //set the fill color + _bgfill = new Texture2D(GraphicsDevice, 1, 1); + _bgfill.SetData(new[] { Color.White }); - if (!Game.Components.Contains(this)) - Game.Components.Add(this); - } + SetPositionBasedOnCharacterRenderer(_characterRenderer); + SetSize(W, H); - private void SetPositionBasedOnCharacterRenderer(ICharacterRenderer renderer) - { - //rules for draw location: - // 1. try to the right first - if it doesn't fit (width-wise), go to the left - // 2. if it will be out of the game area, move it up/down so that it is not clipped by the screen bounds + OnMouseOver += ContextMenuRenderer_OnMouseOver; - // hide and disable as soon as mouse click either on or out of bounds -- obviously handle event for mouse click on particular text + // Update this before map renderer so that clicks are handled first + UpdateOrder = -20; + } - Rectangle rendRect = renderer.DrawArea; + public override void Initialize() + { + base.Initialize(); - DrawPosition = new Vector2(rendRect.Right + 20, rendRect.Y); + if (!Game.Components.Contains(this)) + Game.Components.Add(this); + } - if (DrawArea.Right > _clientWindowSizeProvider.Width - 15) - { - // case: goes off the right side of the screen, show on the left - DrawPosition = new Vector2(rendRect.X - DrawArea.Width - 20, DrawPosition.Y); - } + private void SetPositionBasedOnCharacterRenderer(ICharacterRenderer renderer) + { + //rules for draw location: + // 1. try to the right first - if it doesn't fit (width-wise), go to the left + // 2. if it will be out of the game area, move it up/down so that it is not clipped by the screen bounds - // 308px is the bottom of the display area for map stuff - if (DrawArea.Bottom > (_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Height : 308)) - { - //case: goes off bottom of the screen, adjust new rectangle so it is above 308 - DrawPosition = new Vector2(DrawPosition.X, 298 - DrawArea.Height); - } - else if (DrawArea.Y < 25) - { - //case: goes off top of screen, adjust new rectangle so it aligns with top of character head - DrawPosition = new Vector2(DrawPosition.X, 35); - } + // hide and disable as soon as mouse click either on or out of bounds -- obviously handle event for mouse click on particular text - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_MENU_BELONGS_TO_PLAYER, $" {renderer.Character.Name}"); - } + Rectangle rendRect = renderer.DrawArea; + + DrawPosition = new Vector2(rendRect.Right + 20, rendRect.Y); - protected override bool ShouldUpdate() + if (DrawArea.Right > _clientWindowSizeProvider.Width - 15) { - return base.ShouldUpdate(); + // case: goes off the right side of the screen, show on the left + DrawPosition = new Vector2(rendRect.X - DrawArea.Width - 20, DrawPosition.Y); } - protected override void OnDrawControl(GameTime gameTime) + // 308px is the bottom of the display area for map stuff + if (DrawArea.Bottom > (_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Height : 308)) { - _spriteBatch.Begin(); - - _spriteBatch.Draw(_bgfill, DrawAreaWithParentOffset, Color.FromNonPremultiplied(0xff, 0xff, 0xff, 192)); - - _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _outSource, Color.White); - _overRect.MatchSome(r => - { - _spriteBatch.Draw(_backgroundTexture, - new Vector2(DrawAreaWithParentOffset.X, DrawAreaWithParentOffset.Y) + new Vector2(r.X, r.Y), - r.WithPosition(new Vector2(r.X + _overSource.X, r.Y + _overSource.Y)), - Color.White); - }); - - _spriteBatch.End(); - - base.OnDrawControl(gameTime); + //case: goes off bottom of the screen, adjust new rectangle so it is above 308 + DrawPosition = new Vector2(DrawPosition.X, 298 - DrawArea.Height); } - - private void ContextMenuRenderer_OnMouseOver(object sender, MouseStateExtended e) + else if (DrawArea.Y < 25) { - bool found = false; - foreach (var (sourceRect, menuAction) in _menuActions) - { - if (sourceRect.Contains(e.Position - DrawAreaWithParentOffset.Location)) - { - _overRect = Option.Some(sourceRect); - found = true; - break; - } - } - - if (!found) - { - _overRect = Option.None(); - } + //case: goes off top of screen, adjust new rectangle so it aligns with top of character head + DrawPosition = new Vector2(DrawPosition.X, 35); } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (eventArgs.Button == MouseButton.Left) - { - _overRect.MatchSome(sourceRect => - { - if (!_menuActions.ContainsKey(sourceRect)) return; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_MENU_BELONGS_TO_PLAYER, $" {renderer.Character.Name}"); + } - var menuAction = _menuActions[sourceRect]; - menuAction(); - }); - } + protected override bool ShouldUpdate() + { + return base.ShouldUpdate(); + } - _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); - Game.Components.Remove(this); - Dispose(); + _spriteBatch.Draw(_bgfill, DrawAreaWithParentOffset, Color.FromNonPremultiplied(0xff, 0xff, 0xff, 192)); - _contextMenuRepository.ContextMenu = Option.None(); + _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _outSource, Color.White); + _overRect.MatchSome(r => + { + _spriteBatch.Draw(_backgroundTexture, + new Vector2(DrawAreaWithParentOffset.X, DrawAreaWithParentOffset.Y) + new Vector2(r.X, r.Y), + r.WithPosition(new Vector2(r.X + _overSource.X, r.Y + _overSource.Y)), + Color.White); + }); - return true; - } + _spriteBatch.End(); - /* Helper maps MenuAction enum value to a member method for easy initialization */ - private Action GetActionFromMenuAction(MenuAction menuAction) + base.OnDrawControl(gameTime); + } + + private void ContextMenuRenderer_OnMouseOver(object sender, MouseStateExtended e) + { + bool found = false; + foreach (var (sourceRect, menuAction) in _menuActions) { - switch (menuAction) + if (sourceRect.Contains(e.Position - DrawAreaWithParentOffset.Location)) { - case MenuAction.Paperdoll: return ShowPaperdollAction; - case MenuAction.Book: return ShowBook; - case MenuAction.Join: return JoinParty; - case MenuAction.Invite: return InviteToParty; - case MenuAction.Trade: return Trade; - case MenuAction.Whisper: return PrivateMessage; - case MenuAction.Friend: return AddFriend; - case MenuAction.Ignore: return AddIgnore; - default: throw new ArgumentOutOfRangeException(nameof(menuAction)); + _overRect = Option.Some(sourceRect); + found = true; + break; } } - private void ShowPaperdollAction() - { - _paperdollActions.RequestPaperdoll(_characterRenderer.Character.ID); - _inGameDialogActions.ShowPaperdollDialog(_characterRenderer.Character, isMainCharacter: false); - } - - private void ShowBook() + if (!found) { - _bookActions.RequestBook(_characterRenderer.Character.ID); - _inGameDialogActions.ShowBookDialog(_characterRenderer.Character, isMainCharacter: false); + _overRect = Option.None(); } + } - private void JoinParty() + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (eventArgs.Button == MouseButton.Left) { - if (_partyDataProvider.Members.Any(x => x.CharacterID == _characterRenderer.Character.ID)) + _overRect.MatchSome(sourceRect => { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, _characterRenderer.Character.Name + " ", EOResourceID.STATUS_LABEL_PARTY_IS_ALREADY_MEMBER, showChatError: true); - return; - } + if (!_menuActions.ContainsKey(sourceRect)) return; - if (_lastPartyRequestTime != null && (DateTime.Now - _lastPartyRequestTime.Value).TotalSeconds < Constants.PartyRequestTimeoutSeconds) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_PARTY_RECENTLY_REQUESTED, showChatError: true); - return; - } - - _lastPartyRequestTime = DateTime.Now; - _partyActions.RequestParty(PartyRequestType.Join, _characterRenderer.Character.ID); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_PARTY_REQUESTED_TO_JOIN); + var menuAction = _menuActions[sourceRect]; + menuAction(); + }); } - private void InviteToParty() - { - if (_partyDataProvider.Members.Any(x => x.CharacterID == _characterRenderer.Character.ID)) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, _characterRenderer.Character.Name + " ", EOResourceID.STATUS_LABEL_PARTY_IS_ALREADY_MEMBER, showChatError: true); - return; - } + _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - if (_lastPartyRequestTime != null && (DateTime.Now - _lastPartyRequestTime.Value).TotalSeconds < Constants.PartyRequestTimeoutSeconds) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_PARTY_RECENTLY_REQUESTED, showChatError: true); - return; - } + Game.Components.Remove(this); + Dispose(); - _lastPartyRequestTime = DateTime.Now; - _partyActions.RequestParty(PartyRequestType.Invite, _characterRenderer.Character.ID); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, _characterRenderer.Character.Name, EOResourceID.STATUS_LABEL_PARTY_IS_INVITED); - } + _contextMenuRepository.ContextMenu = Option.None(); - private void Trade() - { - if (_currentMapStateProvider.IsJail) - { - _messageBoxFactory.CreateMessageBox(EOResourceID.JAIL_WARNING_CANNOT_TRADE, EOResourceID.STATUS_LABEL_TYPE_WARNING).ShowDialog(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_TRADE); - return; - } + return true; + } - if (_lastTradeRequestedTime != null && (DateTime.Now - _lastTradeRequestedTime.Value).TotalSeconds < Constants.TradeRequestTimeoutSeconds) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_TRADE_RECENTLY_REQUESTED); - return; - } + /* Helper maps MenuAction enum value to a member method for easy initialization */ + private Action GetActionFromMenuAction(MenuAction menuAction) + { + switch (menuAction) + { + case MenuAction.Paperdoll: return ShowPaperdollAction; + case MenuAction.Book: return ShowBook; + case MenuAction.Join: return JoinParty; + case MenuAction.Invite: return InviteToParty; + case MenuAction.Trade: return Trade; + case MenuAction.Whisper: return PrivateMessage; + case MenuAction.Friend: return AddFriend; + case MenuAction.Ignore: return AddIgnore; + default: throw new ArgumentOutOfRangeException(nameof(menuAction)); + } + } - _lastTradeRequestedTime = DateTime.Now; + private void ShowPaperdollAction() + { + _paperdollActions.RequestPaperdoll(_characterRenderer.Character.ID); + _inGameDialogActions.ShowPaperdollDialog(_characterRenderer.Character, isMainCharacter: false); + } - _tradeActions.RequestTrade(_characterRenderer.Character.ID); + private void ShowBook() + { + _bookActions.RequestBook(_characterRenderer.Character.ID); + _inGameDialogActions.ShowBookDialog(_characterRenderer.Character, isMainCharacter: false); + } - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_TRADE_REQUESTED_TO_TRADE); + private void JoinParty() + { + if (_partyDataProvider.Members.Any(x => x.CharacterID == _characterRenderer.Character.ID)) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, _characterRenderer.Character.Name + " ", EOResourceID.STATUS_LABEL_PARTY_IS_ALREADY_MEMBER, showChatError: true); + return; } - private void PrivateMessage() + if (_lastPartyRequestTime != null && (DateTime.Now - _lastPartyRequestTime.Value).TotalSeconds < Constants.PartyRequestTimeoutSeconds) { - _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{_characterRenderer.Character.Name} "; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_PARTY_RECENTLY_REQUESTED, showChatError: true); + return; } - private void AddFriend() + _lastPartyRequestTime = DateTime.Now; + _partyActions.RequestParty(PartyRequestType.Join, _characterRenderer.Character.ID); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_PARTY_REQUESTED_TO_JOIN); + } + + private void InviteToParty() + { + if (_partyDataProvider.Members.Any(x => x.CharacterID == _characterRenderer.Character.ID)) { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, $"{_characterRenderer.Character.Name} ", EOResourceID.STATUS_LABEL_WILL_BE_YOUR_FRIEND); - _friendIgnoreListService.SaveNewFriend(Constants.FriendListFile, _characterRenderer.Character.Name); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, _characterRenderer.Character.Name + " ", EOResourceID.STATUS_LABEL_PARTY_IS_ALREADY_MEMBER, showChatError: true); + return; } - private void AddIgnore() + if (_lastPartyRequestTime != null && (DateTime.Now - _lastPartyRequestTime.Value).TotalSeconds < Constants.PartyRequestTimeoutSeconds) { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, $"{_characterRenderer.Character.Name} ", EOResourceID.STATUS_LABEL_WILL_BE_IGNORED); - _friendIgnoreListService.SaveNewIgnore(Constants.IgnoreListFile, _characterRenderer.Character.Name); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_PARTY_RECENTLY_REQUESTED, showChatError: true); + return; } - protected override void Dispose(bool disposing) + _lastPartyRequestTime = DateTime.Now; + _partyActions.RequestParty(PartyRequestType.Invite, _characterRenderer.Character.ID); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, _characterRenderer.Character.Name, EOResourceID.STATUS_LABEL_PARTY_IS_INVITED); + } + + private void Trade() + { + if (_currentMapStateProvider.IsJail) { - if (disposing) - _bgfill.Dispose(); + _messageBoxFactory.CreateMessageBox(EOResourceID.JAIL_WARNING_CANNOT_TRADE, EOResourceID.STATUS_LABEL_TYPE_WARNING).ShowDialog(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_TRADE); + return; + } - base.Dispose(disposing); + if (_lastTradeRequestedTime != null && (DateTime.Now - _lastTradeRequestedTime.Value).TotalSeconds < Constants.TradeRequestTimeoutSeconds) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_TRADE_RECENTLY_REQUESTED); + return; } + + _lastTradeRequestedTime = DateTime.Now; + + _tradeActions.RequestTrade(_characterRenderer.Character.ID); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_TRADE_REQUESTED_TO_TRADE); + } + + private void PrivateMessage() + { + _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{_characterRenderer.Character.Name} "; + } + + private void AddFriend() + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, $"{_characterRenderer.Character.Name} ", EOResourceID.STATUS_LABEL_WILL_BE_YOUR_FRIEND); + _friendIgnoreListService.SaveNewFriend(Constants.FriendListFile, _characterRenderer.Character.Name); } - public interface IContextMenuRenderer : IXNAControl + private void AddIgnore() { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, $"{_characterRenderer.Character.Name} ", EOResourceID.STATUS_LABEL_WILL_BE_IGNORED); + _friendIgnoreListService.SaveNewIgnore(Constants.IgnoreListFile, _characterRenderer.Character.Name); } + + protected override void Dispose(bool disposing) + { + if (disposing) + _bgfill.Dispose(); + + base.Dispose(disposing); + } +} + +public interface IContextMenuRenderer : IXNAControl +{ } \ No newline at end of file diff --git a/EndlessClient/Rendering/ContextMenuRepository.cs b/EndlessClient/Rendering/ContextMenuRepository.cs index f0650e66a..a30d5a919 100644 --- a/EndlessClient/Rendering/ContextMenuRepository.cs +++ b/EndlessClient/Rendering/ContextMenuRepository.cs @@ -1,26 +1,25 @@ using AutomaticTypeMapper; using Optional; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +public interface IContextMenuProvider { - public interface IContextMenuProvider - { - Option ContextMenu { get; } - } + Option ContextMenu { get; } +} - public interface IContextMenuRepository - { - Option ContextMenu { get; set; } - } +public interface IContextMenuRepository +{ + Option ContextMenu { get; set; } +} - [AutoMappedType(IsSingleton = true)] - public class ContextMenuRepository : IContextMenuProvider, IContextMenuRepository - { - public Option ContextMenu { get; set; } +[AutoMappedType(IsSingleton = true)] +public class ContextMenuRepository : IContextMenuProvider, IContextMenuRepository +{ + public Option ContextMenu { get; set; } - public ContextMenuRepository() - { - ContextMenu = Option.None(); - } + public ContextMenuRepository() + { + ContextMenu = Option.None(); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/DispatcherGameComponent.cs b/EndlessClient/Rendering/DispatcherGameComponent.cs index 66eeded55..2c27c5c26 100644 --- a/EndlessClient/Rendering/DispatcherGameComponent.cs +++ b/EndlessClient/Rendering/DispatcherGameComponent.cs @@ -7,42 +7,41 @@ using System.Threading; using System.Threading.Tasks; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +[MappedType(BaseType = typeof(IGameComponent), IsSingleton = true)] +public class DispatcherGameComponent : GameComponent { - [MappedType(BaseType = typeof(IGameComponent), IsSingleton = true)] - public class DispatcherGameComponent : GameComponent + private static readonly object _queuelocker_ = new object(); + private static readonly Queue _actions = new Queue(); + private static readonly SemaphoreSlim _signal = new SemaphoreSlim(0); + + public DispatcherGameComponent(IEndlessGameProvider endlessGameProvider) + : base((Game)endlessGameProvider.Game) { - private static readonly object _queuelocker_ = new object(); - private static readonly Queue _actions = new Queue(); - private static readonly SemaphoreSlim _signal = new SemaphoreSlim(0); + } - public DispatcherGameComponent(IEndlessGameProvider endlessGameProvider) - : base((Game)endlessGameProvider.Game) + public static async Task Invoke(Action action) + { + lock (_queuelocker_) { + _actions.Enqueue(action); } - public static async Task Invoke(Action action) - { - lock (_queuelocker_) - { - _actions.Enqueue(action); - } - - await _signal.WaitAsync().ConfigureAwait(false); - } + await _signal.WaitAsync().ConfigureAwait(false); + } - public override void Update(GameTime gameTime) + public override void Update(GameTime gameTime) + { + lock (_queuelocker_) { - lock (_queuelocker_) + if (_actions.Any()) { - if (_actions.Any()) - { - _actions.Dequeue().Invoke(); - _signal.Release(); - } + _actions.Dequeue().Invoke(); + _signal.Release(); } - - base.Update(gameTime); } + + base.Update(gameTime); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectAnimationType.cs b/EndlessClient/Rendering/Effects/EffectAnimationType.cs index 3792c38b3..342d22fe7 100644 --- a/EndlessClient/Rendering/Effects/EffectAnimationType.cs +++ b/EndlessClient/Rendering/Effects/EffectAnimationType.cs @@ -1,12 +1,11 @@ using System; -namespace EndlessClient.Rendering.Effects +namespace EndlessClient.Rendering.Effects; + +public enum EffectAnimationType { - public enum EffectAnimationType - { - Static = 0, - VerticalSliding = 1, - Position = 2, - Flickering = 3 - } + Static = 0, + VerticalSliding = 1, + Position = 2, + Flickering = 3 } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectLayer.cs b/EndlessClient/Rendering/Effects/EffectLayer.cs index c5a37cd24..380a35781 100644 --- a/EndlessClient/Rendering/Effects/EffectLayer.cs +++ b/EndlessClient/Rendering/Effects/EffectLayer.cs @@ -1,9 +1,8 @@ -namespace EndlessClient.Rendering.Effects +namespace EndlessClient.Rendering.Effects; + +public enum EffectLayer { - public enum EffectLayer - { - Behind, - Transparent, - InFront - } + Behind, + Transparent, + InFront } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectRenderer.cs b/EndlessClient/Rendering/Effects/EffectRenderer.cs index d23ae9644..d4bc8289c 100644 --- a/EndlessClient/Rendering/Effects/EffectRenderer.cs +++ b/EndlessClient/Rendering/Effects/EffectRenderer.cs @@ -13,208 +13,207 @@ using DomainCharacter = EOLib.Domain.Character.Character; using DomainNPC = EOLib.Domain.NPC.NPC; -namespace EndlessClient.Rendering.Effects +namespace EndlessClient.Rendering.Effects; + +public enum EffectState { - public enum EffectState - { - Stopped, - Playing, - } + Stopped, + Playing, +} - public sealed class EffectRenderer : IEffectRenderer - { - private readonly IEffectSpriteManager _effectSpriteManager; - private readonly ISfxPlayer _sfxPlayer; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly ICharacterProvider _characterProvider; +public sealed class EffectRenderer : IEffectRenderer +{ + private readonly IEffectSpriteManager _effectSpriteManager; + private readonly ISfxPlayer _sfxPlayer; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly ICharacterProvider _characterProvider; - private Option _targetCoordinate; - private Option _targetActor; + private Option _targetCoordinate; + private Option _targetActor; - private EffectMetadata _metadata; - private IList _effectInfo; - private Stopwatch _lastFrameTimer; + private EffectMetadata _metadata; + private IList _effectInfo; + private Stopwatch _lastFrameTimer; - private int _nextEffectID; - private Option _nextTargetCoordinate; + private int _nextEffectID; + private Option _nextTargetCoordinate; - public int EffectID { get; private set; } + public int EffectID { get; private set; } - public EffectState State { get; private set; } + public EffectState State { get; private set; } - public EffectRenderer(IEffectSpriteManager effectSpriteManager, - ISfxPlayer sfxPlayer, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IRenderOffsetCalculator renderOffsetCalculator, - ICharacterProvider characterProvider) - { - _effectSpriteManager = effectSpriteManager; - _sfxPlayer = sfxPlayer; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _renderOffsetCalculator = renderOffsetCalculator; - _characterProvider = characterProvider; - _lastFrameTimer = new Stopwatch(); - _effectInfo = new List(); - } + public EffectRenderer(IEffectSpriteManager effectSpriteManager, + ISfxPlayer sfxPlayer, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IRenderOffsetCalculator renderOffsetCalculator, + ICharacterProvider characterProvider) + { + _effectSpriteManager = effectSpriteManager; + _sfxPlayer = sfxPlayer; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _renderOffsetCalculator = renderOffsetCalculator; + _characterProvider = characterProvider; + _lastFrameTimer = new Stopwatch(); + _effectInfo = new List(); + } - public void PlayEffect(int effectID, MapCoordinate target) - { - EffectID = effectID; - _targetCoordinate = Option.Some(target); - StartPlaying(); - } + public void PlayEffect(int effectID, MapCoordinate target) + { + EffectID = effectID; + _targetCoordinate = Option.Some(target); + StartPlaying(); + } - public void PlayEffect(int effectID, IMapActor target) - { - EffectID = effectID; - _targetActor = Option.Some(target); - StartPlaying(); - } + public void PlayEffect(int effectID, IMapActor target) + { + EffectID = effectID; + _targetActor = Option.Some(target); + StartPlaying(); + } - public void QueueEffect(int effectID, MapCoordinate target) - { - _nextEffectID = effectID; - _nextTargetCoordinate = Option.Some(target); - } + public void QueueEffect(int effectID, MapCoordinate target) + { + _nextEffectID = effectID; + _nextTargetCoordinate = Option.Some(target); + } - public void Restart() - { - if (State != EffectState.Playing) - return; + public void Restart() + { + if (State != EffectState.Playing) + return; - foreach (var effect in _effectInfo) - effect.Restart(); + foreach (var effect in _effectInfo) + effect.Restart(); - State = EffectState.Playing; + State = EffectState.Playing; - if (_metadata.SoundEffect != SoundEffectID.NONE) - { - _sfxPlayer.PlaySfx(_metadata.SoundEffect); - } + if (_metadata.SoundEffect != SoundEffectID.NONE) + { + _sfxPlayer.PlaySfx(_metadata.SoundEffect); } + } + + public void Update() + { + if (!_effectInfo.Any()) + return; - public void Update() + if (_lastFrameTimer.ElapsedMilliseconds >= 120) { - if (!_effectInfo.Any()) - return; + _lastFrameTimer.Restart(); + _effectInfo.ToList().ForEach(ei => ei.NextFrame()); - if (_lastFrameTimer.ElapsedMilliseconds >= 120) - { - _lastFrameTimer.Restart(); - _effectInfo.ToList().ForEach(ei => ei.NextFrame()); + var doneEffects = _effectInfo.Where(ei => ei.Done); + doneEffects.ToList().ForEach(ei => _effectInfo.Remove(ei)); + } - var doneEffects = _effectInfo.Where(ei => ei.Done); - doneEffects.ToList().ForEach(ei => _effectInfo.Remove(ei)); - } + if (!_effectInfo.Any()) + { + State = EffectState.Stopped; + _lastFrameTimer.Stop(); - if (!_effectInfo.Any()) + _nextTargetCoordinate.MatchSome(_ => { - State = EffectState.Stopped; - _lastFrameTimer.Stop(); + EffectID = _nextEffectID; + _nextEffectID = 0; - _nextTargetCoordinate.MatchSome(_ => - { - EffectID = _nextEffectID; - _nextEffectID = 0; - - _targetCoordinate = _nextTargetCoordinate; - _nextTargetCoordinate = Option.None(); - StartPlaying(); - }); - } + _targetCoordinate = _nextTargetCoordinate; + _nextTargetCoordinate = Option.None(); + StartPlaying(); + }); } + } - public void DrawBehindTarget(SpriteBatch sb, bool beginHasBeenCalled = true) - { - if (!_effectInfo.Any()) - return; + public void DrawBehindTarget(SpriteBatch sb, bool beginHasBeenCalled = true) + { + if (!_effectInfo.Any()) + return; - DrawEffects(sb, beginHasBeenCalled, _effectInfo.Where(x => !x.OnTopOfCharacter)); - } + DrawEffects(sb, beginHasBeenCalled, _effectInfo.Where(x => !x.OnTopOfCharacter)); + } - public void DrawInFrontOfTarget(SpriteBatch sb, bool beginHasBeenCalled = true) - { - if (!_effectInfo.Any()) - return; + public void DrawInFrontOfTarget(SpriteBatch sb, bool beginHasBeenCalled = true) + { + if (!_effectInfo.Any()) + return; - DrawEffects(sb, beginHasBeenCalled, _effectInfo.Where(x => x.OnTopOfCharacter)); - } + DrawEffects(sb, beginHasBeenCalled, _effectInfo.Where(x => x.OnTopOfCharacter)); + } - private void StartPlaying() - { - _lastFrameTimer.Restart(); + private void StartPlaying() + { + _lastFrameTimer.Restart(); - _metadata = _effectSpriteManager.GetEffectMetadata(EffectID); - _effectInfo = _effectSpriteManager.GetEffectInfo(EffectID, _metadata); + _metadata = _effectSpriteManager.GetEffectMetadata(EffectID); + _effectInfo = _effectSpriteManager.GetEffectInfo(EffectID, _metadata); - State = EffectState.Playing; + State = EffectState.Playing; - if (_metadata.SoundEffect != SoundEffectID.NONE) - { - _sfxPlayer.PlaySfx(_metadata.SoundEffect); - } + if (_metadata.SoundEffect != SoundEffectID.NONE) + { + _sfxPlayer.PlaySfx(_metadata.SoundEffect); } + } - private void DrawEffects(SpriteBatch sb, bool beginHasBeenCalled, IEnumerable effectSprites) - { - if (!beginHasBeenCalled) - sb.Begin(); + private void DrawEffects(SpriteBatch sb, bool beginHasBeenCalled, IEnumerable effectSprites) + { + if (!beginHasBeenCalled) + sb.Begin(); - var targetBasePosition = _targetCoordinate.Match( - some: c => _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c), - none: () => _targetActor.Match( - some: actor => + var targetBasePosition = _targetCoordinate.Match( + some: c => _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c), + none: () => _targetActor.Match( + some: actor => + { + return actor.SpellTarget switch { - return actor.SpellTarget switch - { - DomainCharacter c => GetCharacterBasePosition(c), - DomainNPC n => GetNPCBasePosition(n), - _ => Vector2.Zero - }; - }, - none: () => Vector2.Zero)); - - foreach (var effectInfo in effectSprites) - { - effectInfo.DrawToSpriteBatch(sb, targetBasePosition); - } - - if (!beginHasBeenCalled) - sb.End(); - } - - private Vector2 GetCharacterBasePosition(DomainCharacter c) + DomainCharacter c => GetCharacterBasePosition(c), + DomainNPC n => GetNPCBasePosition(n), + _ => Vector2.Zero + }; + }, + none: () => Vector2.Zero)); + + foreach (var effectInfo in effectSprites) { - var walkExtra = new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(c.RenderProperties), _renderOffsetCalculator.CalculateWalkAdjustY(c.RenderProperties)); - return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c.RenderProperties.Coordinates()) + walkExtra; + effectInfo.DrawToSpriteBatch(sb, targetBasePosition); } - private Vector2 GetNPCBasePosition(DomainNPC n) - { - var walkExtra = new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(n), _renderOffsetCalculator.CalculateWalkAdjustY(n)); - return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(n.X, n.Y) + walkExtra; - } + if (!beginHasBeenCalled) + sb.End(); + } + + private Vector2 GetCharacterBasePosition(DomainCharacter c) + { + var walkExtra = new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(c.RenderProperties), _renderOffsetCalculator.CalculateWalkAdjustY(c.RenderProperties)); + return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c.RenderProperties.Coordinates()) + walkExtra; } - public interface IEffectRenderer + private Vector2 GetNPCBasePosition(DomainNPC n) { - int EffectID { get; } + var walkExtra = new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(n), _renderOffsetCalculator.CalculateWalkAdjustY(n)); + return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(n.X, n.Y) + walkExtra; + } +} + +public interface IEffectRenderer +{ + int EffectID { get; } - EffectState State { get; } + EffectState State { get; } - void PlayEffect(int effectID, MapCoordinate target); + void PlayEffect(int effectID, MapCoordinate target); - void PlayEffect(int effectID, IMapActor target); + void PlayEffect(int effectID, IMapActor target); - void QueueEffect(int effectID, MapCoordinate target); + void QueueEffect(int effectID, MapCoordinate target); - void Restart(); + void Restart(); - void Update(); + void Update(); - void DrawBehindTarget(SpriteBatch sb, bool beginHasBeenCalled = true); + void DrawBehindTarget(SpriteBatch sb, bool beginHasBeenCalled = true); - void DrawInFrontOfTarget(SpriteBatch sb, bool beginHasBeenCalled = true); - } + void DrawInFrontOfTarget(SpriteBatch sb, bool beginHasBeenCalled = true); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectRendererFactory.cs b/EndlessClient/Rendering/Effects/EffectRendererFactory.cs index 04354f61a..1b9c1abea 100644 --- a/EndlessClient/Rendering/Effects/EffectRendererFactory.cs +++ b/EndlessClient/Rendering/Effects/EffectRendererFactory.cs @@ -2,38 +2,37 @@ using EndlessClient.Audio; using EOLib.Domain.Character; -namespace EndlessClient.Rendering.Effects -{ - [AutoMappedType] - public class EffectRendererFactory : IEffectRendererFactory - { - private readonly IEffectSpriteManager _effectSpriteManager; - private readonly ISfxPlayer _sfxPlayer; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly ICharacterProvider _characterProvider; +namespace EndlessClient.Rendering.Effects; - public EffectRendererFactory(IEffectSpriteManager effectSpriteManager, - ISfxPlayer sfxPlayer, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IRenderOffsetCalculator renderOffsetCalculator, - ICharacterProvider characterProvider) - { - _effectSpriteManager = effectSpriteManager; - _sfxPlayer = sfxPlayer; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _renderOffsetCalculator = renderOffsetCalculator; - _characterProvider = characterProvider; - } +[AutoMappedType] +public class EffectRendererFactory : IEffectRendererFactory +{ + private readonly IEffectSpriteManager _effectSpriteManager; + private readonly ISfxPlayer _sfxPlayer; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly ICharacterProvider _characterProvider; - public IEffectRenderer Create() - { - return new EffectRenderer(_effectSpriteManager, _sfxPlayer, _gridDrawCoordinateCalculator, _renderOffsetCalculator, _characterProvider); - } + public EffectRendererFactory(IEffectSpriteManager effectSpriteManager, + ISfxPlayer sfxPlayer, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IRenderOffsetCalculator renderOffsetCalculator, + ICharacterProvider characterProvider) + { + _effectSpriteManager = effectSpriteManager; + _sfxPlayer = sfxPlayer; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _renderOffsetCalculator = renderOffsetCalculator; + _characterProvider = characterProvider; } - public interface IEffectRendererFactory + public IEffectRenderer Create() { - IEffectRenderer Create(); + return new EffectRenderer(_effectSpriteManager, _sfxPlayer, _gridDrawCoordinateCalculator, _renderOffsetCalculator, _characterProvider); } +} + +public interface IEffectRendererFactory +{ + IEffectRenderer Create(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs b/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs index 5e19c8081..f93574bf9 100644 --- a/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs +++ b/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs @@ -5,113 +5,112 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering.Effects +namespace EndlessClient.Rendering.Effects; + +public class EffectSpriteInfo : IEffectSpriteInfo { - public class EffectSpriteInfo : IEffectSpriteInfo - { - private readonly EffectMetadata _metadata; - private readonly EffectLayer _layer; - private readonly Texture2D _graphic; - private readonly Random _random; + private readonly EffectMetadata _metadata; + private readonly EffectLayer _layer; + private readonly Texture2D _graphic; + private readonly Random _random; - private int _displayFrame = -1; - private int _actualFrame; - private int _iterations; + private int _displayFrame = -1; + private int _actualFrame; + private int _iterations; - public bool OnTopOfCharacter => _layer != EffectLayer.Behind; - public bool Done => _iterations == _metadata.Loops; + public bool OnTopOfCharacter => _layer != EffectLayer.Behind; + public bool Done => _iterations == _metadata.Loops; - public EffectSpriteInfo(EffectMetadata metadata, - EffectLayer layer, - Texture2D graphic) - { - _metadata = metadata; - _layer = layer; - _graphic = graphic; - _random = new Random(); + public EffectSpriteInfo(EffectMetadata metadata, + EffectLayer layer, + Texture2D graphic) + { + _metadata = metadata; + _layer = layer; + _graphic = graphic; + _random = new Random(); - _displayFrame = GetDisplayFrame(); - } + _displayFrame = GetDisplayFrame(); + } - public void NextFrame() - { - if (Done) return; + public void NextFrame() + { + if (Done) return; - _displayFrame = GetDisplayFrame(); - _actualFrame++; + _displayFrame = GetDisplayFrame(); + _actualFrame++; - if (_actualFrame >= _metadata.Frames) - { - ResetFrame(); - _iterations++; - } - } - - public void Restart() + if (_actualFrame >= _metadata.Frames) { ResetFrame(); - _iterations = 0; + _iterations++; } + } - public void DrawToSpriteBatch(SpriteBatch sb, Vector2 gridCoordinatePosition) - { - var sourceRect = GetFrameSourceRectangle(); - var drawLocation = GetDrawLocation(sourceRect, gridCoordinatePosition); - var alpha = _layer == EffectLayer.Transparent ? 128 : 255; - - sb.Draw(_graphic, drawLocation, sourceRect, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } + public void Restart() + { + ResetFrame(); + _iterations = 0; + } - private Rectangle GetFrameSourceRectangle() - { - var frameWidth = _graphic.Width / _metadata.Frames; - return new Rectangle(_displayFrame * frameWidth, 0, frameWidth, _graphic.Height); - } + public void DrawToSpriteBatch(SpriteBatch sb, Vector2 gridCoordinatePosition) + { + var sourceRect = GetFrameSourceRectangle(); + var drawLocation = GetDrawLocation(sourceRect, gridCoordinatePosition); + var alpha = _layer == EffectLayer.Transparent ? 128 : 255; - private Vector2 GetDrawLocation(Rectangle textureSourceRectangle, Vector2 gridCoordinatePosition) - { - const int GridWidth = 64; + sb.Draw(_graphic, drawLocation, sourceRect, Color.FromNonPremultiplied(255, 255, 255, alpha)); + } - var targetX = gridCoordinatePosition.X + (GridWidth - textureSourceRectangle.Width) / 2; - var targetY = gridCoordinatePosition.Y - (textureSourceRectangle.Height - (36 + (int)Math.Floor((textureSourceRectangle.Height - 100) / 2.0))); + private Rectangle GetFrameSourceRectangle() + { + var frameWidth = _graphic.Width / _metadata.Frames; + return new Rectangle(_displayFrame * frameWidth, 0, frameWidth, _graphic.Height); + } - var slidingMetadata = _metadata.VerticalSlidingMetadata ?? new VerticalSlidingEffectMetadata(0); - var positionMetadata = _metadata.PositionOffsetMetadata ?? new PositionOffsetEffectMetadata(new List(), new List()); + private Vector2 GetDrawLocation(Rectangle textureSourceRectangle, Vector2 gridCoordinatePosition) + { + const int GridWidth = 64; - var additionalX = _metadata.AnimationType switch - { - EffectAnimationType.Position => positionMetadata.OffsetXByFrame.Count < _displayFrame ? positionMetadata.OffsetXByFrame[_displayFrame] : 0, - _ => 0 - }; + var targetX = gridCoordinatePosition.X + (GridWidth - textureSourceRectangle.Width) / 2; + var targetY = gridCoordinatePosition.Y - (textureSourceRectangle.Height - (36 + (int)Math.Floor((textureSourceRectangle.Height - 100) / 2.0))); - var additionalY = _metadata.AnimationType switch - { - EffectAnimationType.VerticalSliding => slidingMetadata.FrameOffsetY * _displayFrame, - EffectAnimationType.Position => positionMetadata.OffsetYByFrame.Count < _displayFrame ? positionMetadata.OffsetYByFrame[_displayFrame] : 0, - _ => 0 - }; + var slidingMetadata = _metadata.VerticalSlidingMetadata ?? new VerticalSlidingEffectMetadata(0); + var positionMetadata = _metadata.PositionOffsetMetadata ?? new PositionOffsetEffectMetadata(new List(), new List()); - return new Vector2(targetX + _metadata.OffsetX + additionalX, targetY + _metadata.OffsetY + additionalY); - } + var additionalX = _metadata.AnimationType switch + { + EffectAnimationType.Position => positionMetadata.OffsetXByFrame.Count < _displayFrame ? positionMetadata.OffsetXByFrame[_displayFrame] : 0, + _ => 0 + }; - private int GetDisplayFrame() + var additionalY = _metadata.AnimationType switch { - return _metadata.AnimationType switch - { - EffectAnimationType.Flickering => - _random.Next( - _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0, - 1 + (_metadata.RandomFlickeringMetadata?.LastFrame ?? _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0)), - _ => _displayFrame + 1 - }; - } + EffectAnimationType.VerticalSliding => slidingMetadata.FrameOffsetY * _displayFrame, + EffectAnimationType.Position => positionMetadata.OffsetYByFrame.Count < _displayFrame ? positionMetadata.OffsetYByFrame[_displayFrame] : 0, + _ => 0 + }; + + return new Vector2(targetX + _metadata.OffsetX + additionalX, targetY + _metadata.OffsetY + additionalY); + } - private void ResetFrame() + private int GetDisplayFrame() + { + return _metadata.AnimationType switch { - _actualFrame = 0; + EffectAnimationType.Flickering => + _random.Next( + _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0, + 1 + (_metadata.RandomFlickeringMetadata?.LastFrame ?? _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0)), + _ => _displayFrame + 1 + }; + } - if (_metadata.AnimationType != EffectAnimationType.Flickering) - _displayFrame = 0; - } + private void ResetFrame() + { + _actualFrame = 0; + + if (_metadata.AnimationType != EffectAnimationType.Flickering) + _displayFrame = 0; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectSpriteManager.cs b/EndlessClient/Rendering/Effects/EffectSpriteManager.cs index e04c60a53..40fc5f3a2 100644 --- a/EndlessClient/Rendering/Effects/EffectSpriteManager.cs +++ b/EndlessClient/Rendering/Effects/EffectSpriteManager.cs @@ -5,58 +5,57 @@ using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; -namespace EndlessClient.Rendering.Effects +namespace EndlessClient.Rendering.Effects; + +[AutoMappedType] +public class EffectSpriteManager : IEffectSpriteManager { - [AutoMappedType] - public class EffectSpriteManager : IEffectSpriteManager + private readonly INativeGraphicsManager _graphicsManager; + private readonly IMetadataProvider _effectMetadataProvider; + + public EffectSpriteManager(INativeGraphicsManager graphicsManager, + IMetadataProvider effectMetadataProvider) + { + _graphicsManager = graphicsManager; + _effectMetadataProvider = effectMetadataProvider; + } + + public EffectMetadata GetEffectMetadata(int graphic) + { + return _effectMetadataProvider.GetValueOrDefault(graphic); + } + + public IList GetEffectInfo(int graphic) { - private readonly INativeGraphicsManager _graphicsManager; - private readonly IMetadataProvider _effectMetadataProvider; - - public EffectSpriteManager(INativeGraphicsManager graphicsManager, - IMetadataProvider effectMetadataProvider) - { - _graphicsManager = graphicsManager; - _effectMetadataProvider = effectMetadataProvider; - } - - public EffectMetadata GetEffectMetadata(int graphic) - { - return _effectMetadataProvider.GetValueOrDefault(graphic); - } - - public IList GetEffectInfo(int graphic) - { - return GetEffectInfo(graphic, GetEffectMetadata(graphic)); - } - - public IList GetEffectInfo(int graphic, EffectMetadata metadata) - { - var baseGraphic = 101 + (graphic - 1) * 3; - - var retList = new List(); - if (metadata.HasBehindLayer) - retList.Add(new EffectSpriteInfo(metadata, EffectLayer.Behind, GetGraphic(baseGraphic))); - if (metadata.HasTransparentLayer) - retList.Add(new EffectSpriteInfo(metadata, EffectLayer.Transparent, GetGraphic(baseGraphic + 1))); - if (metadata.HasInFrontLayer) - retList.Add(new EffectSpriteInfo(metadata, EffectLayer.InFront, GetGraphic(baseGraphic + 2))); - - return retList; - } - - private Texture2D GetGraphic(int actualResourceID) - { - return _graphicsManager.TextureFromResource(GFXTypes.Spells, actualResourceID - 100, true); - } + return GetEffectInfo(graphic, GetEffectMetadata(graphic)); } - public interface IEffectSpriteManager + public IList GetEffectInfo(int graphic, EffectMetadata metadata) { - EffectMetadata GetEffectMetadata(int graphic); + var baseGraphic = 101 + (graphic - 1) * 3; - IList GetEffectInfo(int graphic); + var retList = new List(); + if (metadata.HasBehindLayer) + retList.Add(new EffectSpriteInfo(metadata, EffectLayer.Behind, GetGraphic(baseGraphic))); + if (metadata.HasTransparentLayer) + retList.Add(new EffectSpriteInfo(metadata, EffectLayer.Transparent, GetGraphic(baseGraphic + 1))); + if (metadata.HasInFrontLayer) + retList.Add(new EffectSpriteInfo(metadata, EffectLayer.InFront, GetGraphic(baseGraphic + 2))); - IList GetEffectInfo(int graphic, EffectMetadata metadata); + return retList; } + + private Texture2D GetGraphic(int actualResourceID) + { + return _graphicsManager.TextureFromResource(GFXTypes.Spells, actualResourceID - 100, true); + } +} + +public interface IEffectSpriteManager +{ + EffectMetadata GetEffectMetadata(int graphic); + + IList GetEffectInfo(int graphic); + + IList GetEffectInfo(int graphic, EffectMetadata metadata); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/HardCodedEffect.cs b/EndlessClient/Rendering/Effects/HardCodedEffect.cs index 8736778b2..b28ae5e9f 100644 --- a/EndlessClient/Rendering/Effects/HardCodedEffect.cs +++ b/EndlessClient/Rendering/Effects/HardCodedEffect.cs @@ -1,16 +1,15 @@ -namespace EndlessClient.Rendering.Effects +namespace EndlessClient.Rendering.Effects; + +public enum HardCodedEffect { - public enum HardCodedEffect - { - Fire = 1, - Love = 2, - WarpLeave = 3, - WarpArrive = 4, - Celebrate = 5, - Sparkles = 6, - Evil = 7, - Terror = 8, - WaterSplashies = 9, - AdminHide = 25, - } + Fire = 1, + Love = 2, + WarpLeave = 3, + WarpArrive = 4, + Celebrate = 5, + Sparkles = 6, + Evil = 7, + Terror = 8, + WaterSplashies = 9, + AdminHide = 25, } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs b/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs index 4b5d38a64..11a72c671 100644 --- a/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs +++ b/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs @@ -2,15 +2,14 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Effects +namespace EndlessClient.Rendering.Effects; + +public interface IEffectSpriteInfo { - public interface IEffectSpriteInfo - { - bool OnTopOfCharacter { get; } - bool Done { get; } + bool OnTopOfCharacter { get; } + bool Done { get; } - void NextFrame(); - void Restart(); - void DrawToSpriteBatch(SpriteBatch sb, Vector2 gridCoordinatePosition); - } + void NextFrame(); + void Restart(); + void DrawToSpriteBatch(SpriteBatch sb, Vector2 gridCoordinatePosition); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs b/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs index d2d1b81a5..751875c7d 100644 --- a/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs +++ b/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs @@ -2,15 +2,14 @@ using Newtonsoft.Json; using System.Collections.Generic; -namespace EndlessClient.Rendering.Effects +namespace EndlessClient.Rendering.Effects; + +[Record] +public sealed partial class PositionOffsetEffectMetadata { - [Record] - public sealed partial class PositionOffsetEffectMetadata - { - [JsonProperty("xOffsetPerFrame")] - public IReadOnlyList OffsetXByFrame { get; } + [JsonProperty("xOffsetPerFrame")] + public IReadOnlyList OffsetXByFrame { get; } - [JsonProperty("yOffsetPerFrame")] - public IReadOnlyList OffsetYByFrame { get; } - } + [JsonProperty("yOffsetPerFrame")] + public IReadOnlyList OffsetYByFrame { get; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs b/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs index 4d20baae3..891964254 100644 --- a/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs +++ b/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs @@ -1,15 +1,14 @@ using Amadevus.RecordGenerator; using Newtonsoft.Json; -namespace EndlessClient.Rendering.Effects +namespace EndlessClient.Rendering.Effects; + +[Record] +public sealed partial class RandomFlickeringEffectMetadata { - [Record] - public sealed partial class RandomFlickeringEffectMetadata - { - [JsonProperty("firstFrame")] - public int FirstFrame { get; } + [JsonProperty("firstFrame")] + public int FirstFrame { get; } - [JsonProperty("lastFrame")] - public int LastFrame { get; } - } + [JsonProperty("lastFrame")] + public int LastFrame { get; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs b/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs index 317e2eee8..342c2773b 100644 --- a/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs +++ b/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs @@ -1,12 +1,11 @@ using Amadevus.RecordGenerator; using Newtonsoft.Json; -namespace EndlessClient.Rendering.Effects +namespace EndlessClient.Rendering.Effects; + +[Record] +public sealed partial class VerticalSlidingEffectMetadata { - [Record] - public sealed partial class VerticalSlidingEffectMetadata - { - [JsonProperty("yOffsetPerFrame")] - public int FrameOffsetY { get; } - } + [JsonProperty("yOffsetPerFrame")] + public int FrameOffsetY { get; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs b/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs index 60c176080..0e70c6629 100644 --- a/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs @@ -12,80 +12,79 @@ using EOLib.Domain.Map; using Microsoft.Xna.Framework; -namespace EndlessClient.Rendering.Factories +namespace EndlessClient.Rendering.Factories; + +[MappedType(BaseType = typeof(ICharacterRendererFactory))] +public class CharacterRendererFactory : ICharacterRendererFactory { - [MappedType(BaseType = typeof(ICharacterRendererFactory))] - public class CharacterRendererFactory : ICharacterRendererFactory - { - private readonly IEndlessGameProvider _gameProvider; - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IHealthBarRendererFactory _healthBarRendererFactory; - private readonly IChatBubbleFactory _chatBubbleFactory; - private readonly ICharacterProvider _characterProvider; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly ICharacterPropertyRendererBuilder _characterPropertyRendererBuilder; - private readonly ICharacterTextures _characterTextures; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly IEffectRendererFactory _effectRendererFactory; - private readonly IMetadataProvider _hatMetadataProvider; - private readonly IMetadataProvider _weaponMetadataProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IEndlessGameProvider _gameProvider; + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IHealthBarRendererFactory _healthBarRendererFactory; + private readonly IChatBubbleFactory _chatBubbleFactory; + private readonly ICharacterProvider _characterProvider; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly ICharacterPropertyRendererBuilder _characterPropertyRendererBuilder; + private readonly ICharacterTextures _characterTextures; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly IEffectRendererFactory _effectRendererFactory; + private readonly IMetadataProvider _hatMetadataProvider; + private readonly IMetadataProvider _weaponMetadataProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - public CharacterRendererFactory(IEndlessGameProvider gameProvider, - IRenderTargetFactory renderTargetFactory, - IHealthBarRendererFactory healthBarRendererFactory, - IChatBubbleFactory chatBubbleFactory, - ICharacterProvider characterProvider, - IRenderOffsetCalculator renderOffsetCalculator, - ICharacterPropertyRendererBuilder characterPropertyRendererBuilder, - ICharacterTextures characterTextures, - ICurrentMapProvider currentMapProvider, - IUserInputProvider userInputProvider, - IEffectRendererFactory effectRendererFactory, - IMetadataProvider hatMetadataProvider, - IMetadataProvider weaponMetadataProvider, - ISfxPlayer sfxPlayer, - IClientWindowSizeRepository clientWindowSizeRepository) - { - _gameProvider = gameProvider; - _renderTargetFactory = renderTargetFactory; - _healthBarRendererFactory = healthBarRendererFactory; - _chatBubbleFactory = chatBubbleFactory; - _characterProvider = characterProvider; - _renderOffsetCalculator = renderOffsetCalculator; - _characterPropertyRendererBuilder = characterPropertyRendererBuilder; - _characterTextures = characterTextures; - _currentMapProvider = currentMapProvider; - _userInputProvider = userInputProvider; - _effectRendererFactory = effectRendererFactory; - _hatMetadataProvider = hatMetadataProvider; - _weaponMetadataProvider = weaponMetadataProvider; - _sfxPlayer = sfxPlayer; - _clientWindowSizeRepository = clientWindowSizeRepository; - } + public CharacterRendererFactory(IEndlessGameProvider gameProvider, + IRenderTargetFactory renderTargetFactory, + IHealthBarRendererFactory healthBarRendererFactory, + IChatBubbleFactory chatBubbleFactory, + ICharacterProvider characterProvider, + IRenderOffsetCalculator renderOffsetCalculator, + ICharacterPropertyRendererBuilder characterPropertyRendererBuilder, + ICharacterTextures characterTextures, + ICurrentMapProvider currentMapProvider, + IUserInputProvider userInputProvider, + IEffectRendererFactory effectRendererFactory, + IMetadataProvider hatMetadataProvider, + IMetadataProvider weaponMetadataProvider, + ISfxPlayer sfxPlayer, + IClientWindowSizeRepository clientWindowSizeRepository) + { + _gameProvider = gameProvider; + _renderTargetFactory = renderTargetFactory; + _healthBarRendererFactory = healthBarRendererFactory; + _chatBubbleFactory = chatBubbleFactory; + _characterProvider = characterProvider; + _renderOffsetCalculator = renderOffsetCalculator; + _characterPropertyRendererBuilder = characterPropertyRendererBuilder; + _characterTextures = characterTextures; + _currentMapProvider = currentMapProvider; + _userInputProvider = userInputProvider; + _effectRendererFactory = effectRendererFactory; + _hatMetadataProvider = hatMetadataProvider; + _weaponMetadataProvider = weaponMetadataProvider; + _sfxPlayer = sfxPlayer; + _clientWindowSizeRepository = clientWindowSizeRepository; + } - public ICharacterRenderer CreateCharacterRenderer(EOLib.Domain.Character.Character character, bool isUiControl) - { - return new CharacterRenderer( - (Game)_gameProvider.Game, - _renderTargetFactory, - _healthBarRendererFactory, - _chatBubbleFactory, - _characterProvider, - _renderOffsetCalculator, - _characterPropertyRendererBuilder, - _characterTextures, - _currentMapProvider, - _userInputProvider, - _effectRendererFactory, - _hatMetadataProvider, - _weaponMetadataProvider, - _sfxPlayer, - _clientWindowSizeRepository, - character, - isUiControl); - } + public ICharacterRenderer CreateCharacterRenderer(EOLib.Domain.Character.Character character, bool isUiControl) + { + return new CharacterRenderer( + (Game)_gameProvider.Game, + _renderTargetFactory, + _healthBarRendererFactory, + _chatBubbleFactory, + _characterProvider, + _renderOffsetCalculator, + _characterPropertyRendererBuilder, + _characterTextures, + _currentMapProvider, + _userInputProvider, + _effectRendererFactory, + _hatMetadataProvider, + _weaponMetadataProvider, + _sfxPlayer, + _clientWindowSizeRepository, + character, + isUiControl); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs b/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs index d65096ee6..3c9e08275 100644 --- a/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs @@ -13,83 +13,82 @@ using EOLib.Domain.Trade; using EOLib.Graphics; -namespace EndlessClient.Rendering.Factories -{ - [AutoMappedType] - public class ContextMenuRendererFactory : IContextMenuRendererFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IPaperdollActions _paperdollActions; - private readonly IBookActions _bookActions; - private readonly IPartyActions _partyActions; - private readonly ITradeActions _tradeActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly IHudControlProvider _hudControlProvider; - private readonly IContextMenuRepository _contextMenuRepository; - private readonly IPartyDataProvider _partyDataProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ISfxPlayer _sfxPlayer; +namespace EndlessClient.Rendering.Factories; - public ContextMenuRendererFactory(INativeGraphicsManager nativeGraphicsManager, - IInGameDialogActions inGameDialogActions, - IPaperdollActions paperdollActions, - IBookActions bookActions, - IPartyActions partyActions, - ITradeActions tradeActions, - IStatusLabelSetter statusLabelSetter, - IFriendIgnoreListService friendIgnoreListService, - IHudControlProvider hudControlProvider, - IContextMenuRepository contextMenuRepository, - IPartyDataProvider partyDataProvider, - ICurrentMapStateProvider currentMapStateProvider, - IEOMessageBoxFactory messageBoxFactory, - IClientWindowSizeProvider clientWindowSizeProvider, - ISfxPlayer sfxPlayer) - { - _nativeGraphicsManager = nativeGraphicsManager; - _inGameDialogActions = inGameDialogActions; - _paperdollActions = paperdollActions; - _bookActions = bookActions; - _partyActions = partyActions; - _tradeActions = tradeActions; - _statusLabelSetter = statusLabelSetter; - _friendIgnoreListService = friendIgnoreListService; - _hudControlProvider = hudControlProvider; - _contextMenuRepository = contextMenuRepository; - _partyDataProvider = partyDataProvider; - _currentMapStateProvider = currentMapStateProvider; - _messageBoxFactory = messageBoxFactory; - _clientWindowSizeProvider = clientWindowSizeProvider; - _sfxPlayer = sfxPlayer; - } +[AutoMappedType] +public class ContextMenuRendererFactory : IContextMenuRendererFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IPaperdollActions _paperdollActions; + private readonly IBookActions _bookActions; + private readonly IPartyActions _partyActions; + private readonly ITradeActions _tradeActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly IHudControlProvider _hudControlProvider; + private readonly IContextMenuRepository _contextMenuRepository; + private readonly IPartyDataProvider _partyDataProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ISfxPlayer _sfxPlayer; - public IContextMenuRenderer CreateContextMenuRenderer(ICharacterRenderer characterRenderer) - { - return new ContextMenuRenderer(_nativeGraphicsManager, - _inGameDialogActions, - _paperdollActions, - _bookActions, - _partyActions, - _tradeActions, - _statusLabelSetter, - _friendIgnoreListService, - _hudControlProvider, - _contextMenuRepository, - _partyDataProvider, - characterRenderer, - _currentMapStateProvider, - _messageBoxFactory, - _clientWindowSizeProvider, - _sfxPlayer); - } + public ContextMenuRendererFactory(INativeGraphicsManager nativeGraphicsManager, + IInGameDialogActions inGameDialogActions, + IPaperdollActions paperdollActions, + IBookActions bookActions, + IPartyActions partyActions, + ITradeActions tradeActions, + IStatusLabelSetter statusLabelSetter, + IFriendIgnoreListService friendIgnoreListService, + IHudControlProvider hudControlProvider, + IContextMenuRepository contextMenuRepository, + IPartyDataProvider partyDataProvider, + ICurrentMapStateProvider currentMapStateProvider, + IEOMessageBoxFactory messageBoxFactory, + IClientWindowSizeProvider clientWindowSizeProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _inGameDialogActions = inGameDialogActions; + _paperdollActions = paperdollActions; + _bookActions = bookActions; + _partyActions = partyActions; + _tradeActions = tradeActions; + _statusLabelSetter = statusLabelSetter; + _friendIgnoreListService = friendIgnoreListService; + _hudControlProvider = hudControlProvider; + _contextMenuRepository = contextMenuRepository; + _partyDataProvider = partyDataProvider; + _currentMapStateProvider = currentMapStateProvider; + _messageBoxFactory = messageBoxFactory; + _clientWindowSizeProvider = clientWindowSizeProvider; + _sfxPlayer = sfxPlayer; } - public interface IContextMenuRendererFactory + public IContextMenuRenderer CreateContextMenuRenderer(ICharacterRenderer characterRenderer) { - IContextMenuRenderer CreateContextMenuRenderer(ICharacterRenderer characterRenderer); + return new ContextMenuRenderer(_nativeGraphicsManager, + _inGameDialogActions, + _paperdollActions, + _bookActions, + _partyActions, + _tradeActions, + _statusLabelSetter, + _friendIgnoreListService, + _hudControlProvider, + _contextMenuRepository, + _partyDataProvider, + characterRenderer, + _currentMapStateProvider, + _messageBoxFactory, + _clientWindowSizeProvider, + _sfxPlayer); } +} + +public interface IContextMenuRendererFactory +{ + IContextMenuRenderer CreateContextMenuRenderer(ICharacterRenderer characterRenderer); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs b/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs index 273c8002e..d36ffac80 100644 --- a/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs @@ -1,26 +1,25 @@ using AutomaticTypeMapper; using EOLib.Graphics; -namespace EndlessClient.Rendering.Factories -{ - [AutoMappedType] - public class HealthBarRendererFactory : IHealthBarRendererFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; +namespace EndlessClient.Rendering.Factories; - public HealthBarRendererFactory(INativeGraphicsManager nativeGraphicsManager) - { - _nativeGraphicsManager = nativeGraphicsManager; - } +[AutoMappedType] +public class HealthBarRendererFactory : IHealthBarRendererFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; - public IHealthBarRenderer CreateHealthBarRenderer(IMapActor parentReference) - { - return new HealthBarRenderer(_nativeGraphicsManager, parentReference); - } + public HealthBarRendererFactory(INativeGraphicsManager nativeGraphicsManager) + { + _nativeGraphicsManager = nativeGraphicsManager; } - public interface IHealthBarRendererFactory + public IHealthBarRenderer CreateHealthBarRenderer(IMapActor parentReference) { - IHealthBarRenderer CreateHealthBarRenderer(IMapActor entity); + return new HealthBarRenderer(_nativeGraphicsManager, parentReference); } +} + +public interface IHealthBarRendererFactory +{ + IHealthBarRenderer CreateHealthBarRenderer(IMapActor entity); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs b/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs index 76e9ee0b5..c3d2c6db2 100644 --- a/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs @@ -1,9 +1,8 @@ using EndlessClient.Rendering.Character; -namespace EndlessClient.Rendering.Factories +namespace EndlessClient.Rendering.Factories; + +public interface ICharacterRendererFactory { - public interface ICharacterRendererFactory - { - ICharacterRenderer CreateCharacterRenderer(EOLib.Domain.Character.Character character, bool isUiControl); - } + ICharacterRenderer CreateCharacterRenderer(EOLib.Domain.Character.Character character, bool isUiControl); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/IMapRendererFactory.cs b/EndlessClient/Rendering/Factories/IMapRendererFactory.cs index f70bd5d30..692c7226b 100644 --- a/EndlessClient/Rendering/Factories/IMapRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/IMapRendererFactory.cs @@ -1,9 +1,8 @@ using EndlessClient.Rendering.Map; -namespace EndlessClient.Rendering.Factories +namespace EndlessClient.Rendering.Factories; + +public interface IMapRendererFactory { - public interface IMapRendererFactory - { - IMapRenderer CreateMapRenderer(); - } + IMapRenderer CreateMapRenderer(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs b/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs index 5619cb444..b3860ab42 100644 --- a/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs +++ b/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs @@ -1,10 +1,9 @@ using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Factories +namespace EndlessClient.Rendering.Factories; + +public interface IRenderTargetFactory { - public interface IRenderTargetFactory - { - RenderTarget2D CreateRenderTarget(); - RenderTarget2D CreateRenderTarget(int width, int height); - } + RenderTarget2D CreateRenderTarget(); + RenderTarget2D CreateRenderTarget(int width, int height); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/MapRendererFactory.cs b/EndlessClient/Rendering/Factories/MapRendererFactory.cs index 29815b5d8..f79aa38f2 100644 --- a/EndlessClient/Rendering/Factories/MapRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/MapRendererFactory.cs @@ -11,85 +11,84 @@ using EOLib.Domain.Character; using EOLib.Domain.Map; -namespace EndlessClient.Rendering.Factories +namespace EndlessClient.Rendering.Factories; + +[MappedType(BaseType = typeof(IMapRendererFactory))] +public class MapRendererFactory : IMapRendererFactory { - [MappedType(BaseType = typeof(IMapRendererFactory))] - public class MapRendererFactory : IMapRendererFactory - { - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IEffectRendererFactory _effectRendererFactory; - private readonly IMapEntityRendererProvider _mapEntityRendererProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IContentProvider _contentProvider; - private readonly IMapRenderDistanceCalculator _mapRenderDistanceCalculator; - private readonly ICharacterRendererUpdater _characterRendererUpdater; - private readonly INPCRendererUpdater _npcRendererUpdater; - private readonly IDynamicMapObjectUpdater _dynamicMapObjectUpdater; - private readonly IConfigurationProvider _configurationProvider; - private readonly IMouseCursorRendererFactory _mouseCursorRendererFactory; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IEffectRendererFactory _effectRendererFactory; + private readonly IMapEntityRendererProvider _mapEntityRendererProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IContentProvider _contentProvider; + private readonly IMapRenderDistanceCalculator _mapRenderDistanceCalculator; + private readonly ICharacterRendererUpdater _characterRendererUpdater; + private readonly INPCRendererUpdater _npcRendererUpdater; + private readonly IDynamicMapObjectUpdater _dynamicMapObjectUpdater; + private readonly IConfigurationProvider _configurationProvider; + private readonly IMouseCursorRendererFactory _mouseCursorRendererFactory; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - public MapRendererFactory(IEndlessGameProvider endlessGameProvider, - IRenderTargetFactory renderTargetFactory, - IEffectRendererFactory effectRendererFactory, - IMapEntityRendererProvider mapEntityRendererProvider, - ICharacterProvider characterProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - IContentProvider contentProvider, - IMapRenderDistanceCalculator mapRenderDistanceCalculator, - ICharacterRendererUpdater characterRendererUpdater, - INPCRendererUpdater npcRendererUpdater, - IDynamicMapObjectUpdater dynamicMapObjectUpdater, - IConfigurationProvider configurationProvider, - IMouseCursorRendererFactory mouseCursorRendererFactory, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeRepository clientWindowSizeRepository, - IFixedTimeStepRepository fixedTimeStepRepository) - { - _endlessGameProvider = endlessGameProvider; - _renderTargetFactory = renderTargetFactory; - _effectRendererFactory = effectRendererFactory; - _mapEntityRendererProvider = mapEntityRendererProvider; - _characterProvider = characterProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _contentProvider = contentProvider; - _mapRenderDistanceCalculator = mapRenderDistanceCalculator; - _characterRendererUpdater = characterRendererUpdater; - _npcRendererUpdater = npcRendererUpdater; - _dynamicMapObjectUpdater = dynamicMapObjectUpdater; - _configurationProvider = configurationProvider; - _mouseCursorRendererFactory = mouseCursorRendererFactory; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _clientWindowSizeRepository = clientWindowSizeRepository; - _fixedTimeStepRepository = fixedTimeStepRepository; - } + public MapRendererFactory(IEndlessGameProvider endlessGameProvider, + IRenderTargetFactory renderTargetFactory, + IEffectRendererFactory effectRendererFactory, + IMapEntityRendererProvider mapEntityRendererProvider, + ICharacterProvider characterProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + IContentProvider contentProvider, + IMapRenderDistanceCalculator mapRenderDistanceCalculator, + ICharacterRendererUpdater characterRendererUpdater, + INPCRendererUpdater npcRendererUpdater, + IDynamicMapObjectUpdater dynamicMapObjectUpdater, + IConfigurationProvider configurationProvider, + IMouseCursorRendererFactory mouseCursorRendererFactory, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeRepository clientWindowSizeRepository, + IFixedTimeStepRepository fixedTimeStepRepository) + { + _endlessGameProvider = endlessGameProvider; + _renderTargetFactory = renderTargetFactory; + _effectRendererFactory = effectRendererFactory; + _mapEntityRendererProvider = mapEntityRendererProvider; + _characterProvider = characterProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _contentProvider = contentProvider; + _mapRenderDistanceCalculator = mapRenderDistanceCalculator; + _characterRendererUpdater = characterRendererUpdater; + _npcRendererUpdater = npcRendererUpdater; + _dynamicMapObjectUpdater = dynamicMapObjectUpdater; + _configurationProvider = configurationProvider; + _mouseCursorRendererFactory = mouseCursorRendererFactory; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _clientWindowSizeRepository = clientWindowSizeRepository; + _fixedTimeStepRepository = fixedTimeStepRepository; + } - public IMapRenderer CreateMapRenderer() - { - return new MapRenderer(_endlessGameProvider.Game, - _renderTargetFactory, - _effectRendererFactory, - _mapEntityRendererProvider, - _characterProvider, - _currentMapProvider, - _currentMapStateProvider, - _contentProvider, - _mapRenderDistanceCalculator, - _characterRendererUpdater, - _npcRendererUpdater, - _dynamicMapObjectUpdater, - _configurationProvider, - _mouseCursorRendererFactory.Create(), - _gridDrawCoordinateCalculator, - _clientWindowSizeRepository, - _fixedTimeStepRepository); - } + public IMapRenderer CreateMapRenderer() + { + return new MapRenderer(_endlessGameProvider.Game, + _renderTargetFactory, + _effectRendererFactory, + _mapEntityRendererProvider, + _characterProvider, + _currentMapProvider, + _currentMapStateProvider, + _contentProvider, + _mapRenderDistanceCalculator, + _characterRendererUpdater, + _npcRendererUpdater, + _dynamicMapObjectUpdater, + _configurationProvider, + _mouseCursorRendererFactory.Create(), + _gridDrawCoordinateCalculator, + _clientWindowSizeRepository, + _fixedTimeStepRepository); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs b/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs index 3ebc0e979..3fa56abc6 100644 --- a/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs @@ -8,61 +8,60 @@ using EOLib.Graphics; using EOLib.IO.Repositories; -namespace EndlessClient.Rendering.Factories +namespace EndlessClient.Rendering.Factories; + +[AutoMappedType] +public class MouseCursorRendererFactory : IMouseCursorRendererFactory { - [AutoMappedType] - public class MouseCursorRendererFactory : IMouseCursorRendererFactory + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IMapCellStateProvider _mapCellStateProvider; + private readonly IItemStringService _itemStringService; + private readonly IItemNameColorService _itemNameColorService; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly IContextMenuProvider _contextMenuProvider; + public MouseCursorRendererFactory(INativeGraphicsManager nativeGraphicsManager, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IMapCellStateProvider mapCellStateProvider, + IItemStringService itemStringService, + IItemNameColorService itemNameColorService, + IEIFFileProvider eifFileProvider, + ICurrentMapProvider currentMapProvider, + IUserInputProvider userInputProvider, + IActiveDialogProvider activeDialogProvider, + IContextMenuProvider contextMenuProvider) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IMapCellStateProvider _mapCellStateProvider; - private readonly IItemStringService _itemStringService; - private readonly IItemNameColorService _itemNameColorService; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly IContextMenuProvider _contextMenuProvider; - public MouseCursorRendererFactory(INativeGraphicsManager nativeGraphicsManager, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IMapCellStateProvider mapCellStateProvider, - IItemStringService itemStringService, - IItemNameColorService itemNameColorService, - IEIFFileProvider eifFileProvider, - ICurrentMapProvider currentMapProvider, - IUserInputProvider userInputProvider, - IActiveDialogProvider activeDialogProvider, - IContextMenuProvider contextMenuProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _mapCellStateProvider = mapCellStateProvider; - _itemStringService = itemStringService; - _itemNameColorService = itemNameColorService; - _eifFileProvider = eifFileProvider; - _currentMapProvider = currentMapProvider; - _userInputProvider = userInputProvider; - _activeDialogProvider = activeDialogProvider; - _contextMenuProvider = contextMenuProvider; - } - - public IMouseCursorRenderer Create() - { - return new MouseCursorRenderer(_nativeGraphicsManager, - _gridDrawCoordinateCalculator, - _mapCellStateProvider, - _itemStringService, - _itemNameColorService, - _eifFileProvider, - _currentMapProvider, - _userInputProvider, - _activeDialogProvider, - _contextMenuProvider); - } + _nativeGraphicsManager = nativeGraphicsManager; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _mapCellStateProvider = mapCellStateProvider; + _itemStringService = itemStringService; + _itemNameColorService = itemNameColorService; + _eifFileProvider = eifFileProvider; + _currentMapProvider = currentMapProvider; + _userInputProvider = userInputProvider; + _activeDialogProvider = activeDialogProvider; + _contextMenuProvider = contextMenuProvider; } - public interface IMouseCursorRendererFactory + public IMouseCursorRenderer Create() { - IMouseCursorRenderer Create(); + return new MouseCursorRenderer(_nativeGraphicsManager, + _gridDrawCoordinateCalculator, + _mapCellStateProvider, + _itemStringService, + _itemNameColorService, + _eifFileProvider, + _currentMapProvider, + _userInputProvider, + _activeDialogProvider, + _contextMenuProvider); } +} + +public interface IMouseCursorRendererFactory +{ + IMouseCursorRenderer Create(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/RenderTargetFactory.cs b/EndlessClient/Rendering/Factories/RenderTargetFactory.cs index 1234a95d7..f1241659a 100644 --- a/EndlessClient/Rendering/Factories/RenderTargetFactory.cs +++ b/EndlessClient/Rendering/Factories/RenderTargetFactory.cs @@ -2,35 +2,34 @@ using EOLib.Graphics; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Factories +namespace EndlessClient.Rendering.Factories; + +[MappedType(BaseType = typeof(IRenderTargetFactory))] +public class RenderTargetFactory : IRenderTargetFactory { - [MappedType(BaseType = typeof(IRenderTargetFactory))] - public class RenderTargetFactory : IRenderTargetFactory - { - private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - public RenderTargetFactory(IGraphicsDeviceProvider graphicsDeviceProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _graphicsDeviceProvider = graphicsDeviceProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - } + public RenderTargetFactory(IGraphicsDeviceProvider graphicsDeviceProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _graphicsDeviceProvider = graphicsDeviceProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + } - public RenderTarget2D CreateRenderTarget() - { - return CreateRenderTarget(_clientWindowSizeProvider.Width, _clientWindowSizeProvider.Height); - } + public RenderTarget2D CreateRenderTarget() + { + return CreateRenderTarget(_clientWindowSizeProvider.Width, _clientWindowSizeProvider.Height); + } - public RenderTarget2D CreateRenderTarget(int width, int height) - { - return new RenderTarget2D( - _graphicsDeviceProvider.GraphicsDevice, - width, - height, - false, - SurfaceFormat.Color, - DepthFormat.None); - } + public RenderTarget2D CreateRenderTarget(int width, int height) + { + return new RenderTarget2D( + _graphicsDeviceProvider.GraphicsDevice, + width, + height, + false, + SurfaceFormat.Color, + DepthFormat.None); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs b/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs index 373262174..7d8f16a45 100644 --- a/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs +++ b/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs @@ -7,181 +7,180 @@ using DomainNPC = EOLib.Domain.NPC.NPC; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +[AutoMappedType] +public class GridDrawCoordinateCalculator : IGridDrawCoordinateCalculator { - [AutoMappedType] - public class GridDrawCoordinateCalculator : IGridDrawCoordinateCalculator + private readonly ICharacterProvider _characterProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + + public GridDrawCoordinateCalculator(ICharacterProvider characterProvider, + ICurrentMapProvider currentMapProvider, + IRenderOffsetCalculator renderOffsetCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) { - private readonly ICharacterProvider _characterProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - - public GridDrawCoordinateCalculator(ICharacterProvider characterProvider, - ICurrentMapProvider currentMapProvider, - IRenderOffsetCalculator renderOffsetCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _characterProvider = characterProvider; - _currentMapProvider = currentMapProvider; - _renderOffsetCalculator = renderOffsetCalculator; - _clientWindowSizeProvider = clientWindowSizeProvider; - } + _characterProvider = characterProvider; + _currentMapProvider = currentMapProvider; + _renderOffsetCalculator = renderOffsetCalculator; + _clientWindowSizeProvider = clientWindowSizeProvider; + } - public Vector2 CalculateRawRenderCoordinatesFromGridUnits(int gridX, int gridY, int tileWidth = 64, int tileHeight = 32) - { - var widthFactor = tileWidth / 2; - var heightFactor = tileHeight / 2; + public Vector2 CalculateRawRenderCoordinatesFromGridUnits(int gridX, int gridY, int tileWidth = 64, int tileHeight = 32) + { + var widthFactor = tileWidth / 2; + var heightFactor = tileHeight / 2; - return new Vector2((gridX * widthFactor) - (gridY * widthFactor), - (gridY * heightFactor) + (gridX * heightFactor)); - } + return new Vector2((gridX * widthFactor) - (gridY * widthFactor), + (gridY * heightFactor) + (gridX * heightFactor)); + } - public Vector2 CalculateDrawCoordinatesFromGridUnits(int gridX, int gridY) - { - var widthFactor = _clientWindowSizeProvider.Width / 2; // 640 * (1/2) - 1 - var heightFactor = _clientWindowSizeProvider.Resizable - ? _clientWindowSizeProvider.Height / 2 - : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 2 + public Vector2 CalculateDrawCoordinatesFromGridUnits(int gridX, int gridY) + { + var widthFactor = _clientWindowSizeProvider.Width / 2; // 640 * (1/2) - 1 + var heightFactor = _clientWindowSizeProvider.Resizable + ? _clientWindowSizeProvider.Height / 2 + : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 2 - return new Vector2(widthFactor, heightFactor) + CalculateRawRenderCoordinatesFromGridUnits(gridX, gridY) - GetMainCharacterOffsets(); - } + return new Vector2(widthFactor, heightFactor) + CalculateRawRenderCoordinatesFromGridUnits(gridX, gridY) - GetMainCharacterOffsets(); + } - public Vector2 CalculateDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate) - { - return CalculateDrawCoordinatesFromGridUnits(mapCoordinate.X, mapCoordinate.Y); - } + public Vector2 CalculateDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate) + { + return CalculateDrawCoordinatesFromGridUnits(mapCoordinate.X, mapCoordinate.Y); + } - public Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(int gridX, int gridY) - { - return CalculateDrawCoordinatesFromGridUnits(gridX, gridY) - - new Vector2(IGridDrawCoordinateCalculator.DefaultGridWidth / 2, 0); - } + public Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(int gridX, int gridY) + { + return CalculateDrawCoordinatesFromGridUnits(gridX, gridY) - + new Vector2(IGridDrawCoordinateCalculator.DefaultGridWidth / 2, 0); + } - public Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate) - { - return CalculateBaseLayerDrawCoordinatesFromGridUnits(mapCoordinate.X, mapCoordinate.Y); - } + public Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate) + { + return CalculateBaseLayerDrawCoordinatesFromGridUnits(mapCoordinate.X, mapCoordinate.Y); + } - public Vector2 CalculateGroundLayerRenderTargetDrawCoordinates(bool isMiniMap = false, int tileWidth = 64, int tileHeight = 32) - { - var ViewportWidthFactor = _clientWindowSizeProvider.Width / 2 - 1; // 640 * (1/2) - 1 - var ViewportHeightFactor = _clientWindowSizeProvider.Resizable - ? _clientWindowSizeProvider.Height / 2 - : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 2 + public Vector2 CalculateGroundLayerRenderTargetDrawCoordinates(bool isMiniMap = false, int tileWidth = 64, int tileHeight = 32) + { + var ViewportWidthFactor = _clientWindowSizeProvider.Width / 2 - 1; // 640 * (1/2) - 1 + var ViewportHeightFactor = _clientWindowSizeProvider.Resizable + ? _clientWindowSizeProvider.Height / 2 + : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 2 - var rp = _characterProvider.MainCharacter.RenderProperties; - var cx = isMiniMap ? _characterProvider.MainCharacter.X : rp.MapX; - var cy = isMiniMap ? _characterProvider.MainCharacter.Y : rp.MapY; + var rp = _characterProvider.MainCharacter.RenderProperties; + var cx = isMiniMap ? _characterProvider.MainCharacter.X : rp.MapX; + var cy = isMiniMap ? _characterProvider.MainCharacter.Y : rp.MapY; - var mapHeightPlusOne = _currentMapProvider.CurrentMap.Properties.Height + 1; + var mapHeightPlusOne = _currentMapProvider.CurrentMap.Properties.Height + 1; - var tileWidthFactor = tileWidth / 2; - var tileHeightFactor = tileHeight / 2; + var tileWidthFactor = tileWidth / 2; + var tileHeightFactor = tileHeight / 2; - var walkAdjustOffsets = isMiniMap ? Vector2.Zero : GetMainCharacterWalkAdjustOffsets(); + var walkAdjustOffsets = isMiniMap ? Vector2.Zero : GetMainCharacterWalkAdjustOffsets(); - // opposite of the algorithm for rendering the base layers - return new Vector2(ViewportWidthFactor - (mapHeightPlusOne * tileWidthFactor) + (cy * tileWidthFactor) - (cx * tileWidthFactor), - ViewportHeightFactor - (cy * tileHeightFactor) - (cx * tileHeightFactor)) - walkAdjustOffsets; - } + // opposite of the algorithm for rendering the base layers + return new Vector2(ViewportWidthFactor - (mapHeightPlusOne * tileWidthFactor) + (cy * tileWidthFactor) - (cx * tileWidthFactor), + ViewportHeightFactor - (cy * tileHeightFactor) - (cx * tileHeightFactor)) - walkAdjustOffsets; + } - public Vector2 CalculateDrawCoordinates(DomainNPC npc) - { - var ViewportWidthFactor = _clientWindowSizeProvider.Width / 2 - 1; // 640 * (1/2) - 1 - var ViewportHeightFactor = _clientWindowSizeProvider.Resizable - ? _clientWindowSizeProvider.Height / 2 - : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 1 // ??? + public Vector2 CalculateDrawCoordinates(DomainNPC npc) + { + var ViewportWidthFactor = _clientWindowSizeProvider.Width / 2 - 1; // 640 * (1/2) - 1 + var ViewportHeightFactor = _clientWindowSizeProvider.Resizable + ? _clientWindowSizeProvider.Height / 2 + : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 1 // ??? - var npcOffsetX = _renderOffsetCalculator.CalculateOffsetX(npc); - var npcOffsetY = _renderOffsetCalculator.CalculateOffsetY(npc); + var npcOffsetX = _renderOffsetCalculator.CalculateOffsetX(npc); + var npcOffsetY = _renderOffsetCalculator.CalculateOffsetY(npc); - var mainOffsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); - var mainOffsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); + var mainOffsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); + var mainOffsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); - return new Vector2(ViewportWidthFactor + npcOffsetX - mainOffsetX, - ViewportHeightFactor + npcOffsetY - mainOffsetY + 16); - } + return new Vector2(ViewportWidthFactor + npcOffsetX - mainOffsetX, + ViewportHeightFactor + npcOffsetY - mainOffsetY + 16); + } - public MapCoordinate CalculateGridCoordinatesFromDrawLocation(Vector2 drawLocation) + public MapCoordinate CalculateGridCoordinatesFromDrawLocation(Vector2 drawLocation) + { + //need to solve this system of equations to get x, y on the grid + //(x * 32) - (y * 32) + 288 - c.OffsetX, => pixX = 32x - 32y + 288 - c.OffsetX + //(y * 16) + (x * 16) + 144 - c.OffsetY => 2pixY = 32y + 32x + 288 - 2c.OffsetY + // => 2pixY + pixX = 64x + 576 - c.OffsetX - 2c.OffsetY + // => 2pixY + pixX - 576 + c.OffsetX + 2c.OffsetY = 64x + // => _gridX = (pixX + 2pixY - 576 + c.OffsetX + 2c.OffsetY) / 64; <= + //pixY = (_gridX * 16) + (_gridY * 16) + 144 - c.OffsetY => + //(pixY - (_gridX * 16) - 144 + c.OffsetY) / 16 = _gridY + + if (_clientWindowSizeProvider.Resizable) { - //need to solve this system of equations to get x, y on the grid - //(x * 32) - (y * 32) + 288 - c.OffsetX, => pixX = 32x - 32y + 288 - c.OffsetX - //(y * 16) + (x * 16) + 144 - c.OffsetY => 2pixY = 32y + 32x + 288 - 2c.OffsetY - // => 2pixY + pixX = 64x + 576 - c.OffsetX - 2c.OffsetY - // => 2pixY + pixX - 576 + c.OffsetX + 2c.OffsetY = 64x - // => _gridX = (pixX + 2pixY - 576 + c.OffsetX + 2c.OffsetY) / 64; <= - //pixY = (_gridX * 16) + (_gridY * 16) + 144 - c.OffsetY => - //(pixY - (_gridX * 16) - 144 + c.OffsetY) / 16 = _gridY - - if (_clientWindowSizeProvider.Resizable) - { - var msX = drawLocation.X; - var msY = drawLocation.Y - IGridDrawCoordinateCalculator.DefaultGridHeight / 2; - - var widthFactor = _clientWindowSizeProvider.Width / 2; - var heightFactor = _clientWindowSizeProvider.Height / 2; - - var offsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); - var offsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); - - var gridX = (int)Math.Round((msX + (2 * msY) - widthFactor - heightFactor * 2 + offsetX + (2 * offsetY)) / 64.0); - var gridY = (int)Math.Round((msY - (16 * gridX) - heightFactor + offsetY) / 16.0); - - return new MapCoordinate(gridX, gridY); - } - else - { - const int ViewportWidthFactor = 288; // 640 * (1/2) - 32 - const int ViewportHeightFactor = 142; // 480 * (3/10) - 2 - - var msX = drawLocation.X - IGridDrawCoordinateCalculator.DefaultGridWidth / 2; - var msY = drawLocation.Y - IGridDrawCoordinateCalculator.DefaultGridHeight / 2; - - var offsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); - var offsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); - - var gridX = (int)Math.Round((msX + 2 * msY - (ViewportWidthFactor * 2) + offsetX + 2 * offsetY) / 64.0); - var gridY = (int)Math.Round((msY - gridX * 16 - ViewportHeightFactor + offsetY) / 16.0); - - return new MapCoordinate(gridX, gridY); - } - } + var msX = drawLocation.X; + var msY = drawLocation.Y - IGridDrawCoordinateCalculator.DefaultGridHeight / 2; - private Vector2 GetMainCharacterOffsets() - { - var props = _characterProvider.MainCharacter.RenderProperties; - return new Vector2(_renderOffsetCalculator.CalculateOffsetX(props), - _renderOffsetCalculator.CalculateOffsetY(props)); - } + var widthFactor = _clientWindowSizeProvider.Width / 2; + var heightFactor = _clientWindowSizeProvider.Height / 2; + + var offsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); + var offsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); + + var gridX = (int)Math.Round((msX + (2 * msY) - widthFactor - heightFactor * 2 + offsetX + (2 * offsetY)) / 64.0); + var gridY = (int)Math.Round((msY - (16 * gridX) - heightFactor + offsetY) / 16.0); - private Vector2 GetMainCharacterWalkAdjustOffsets() + return new MapCoordinate(gridX, gridY); + } + else { - var props = _characterProvider.MainCharacter.RenderProperties; - return new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(props), - _renderOffsetCalculator.CalculateWalkAdjustY(props)); + const int ViewportWidthFactor = 288; // 640 * (1/2) - 32 + const int ViewportHeightFactor = 142; // 480 * (3/10) - 2 + + var msX = drawLocation.X - IGridDrawCoordinateCalculator.DefaultGridWidth / 2; + var msY = drawLocation.Y - IGridDrawCoordinateCalculator.DefaultGridHeight / 2; + + var offsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); + var offsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); + + var gridX = (int)Math.Round((msX + 2 * msY - (ViewportWidthFactor * 2) + offsetX + 2 * offsetY) / 64.0); + var gridY = (int)Math.Round((msY - gridX * 16 - ViewportHeightFactor + offsetY) / 16.0); + + return new MapCoordinate(gridX, gridY); } } - public interface IGridDrawCoordinateCalculator + private Vector2 GetMainCharacterOffsets() + { + var props = _characterProvider.MainCharacter.RenderProperties; + return new Vector2(_renderOffsetCalculator.CalculateOffsetX(props), + _renderOffsetCalculator.CalculateOffsetY(props)); + } + + private Vector2 GetMainCharacterWalkAdjustOffsets() { - const int DefaultGridWidth = 64; - const int DefaultGridHeight = 32; + var props = _characterProvider.MainCharacter.RenderProperties; + return new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(props), + _renderOffsetCalculator.CalculateWalkAdjustY(props)); + } +} - Vector2 CalculateRawRenderCoordinatesFromGridUnits(int gridX, int gridY, int tileWidth = DefaultGridWidth, int tileHeight = DefaultGridHeight); +public interface IGridDrawCoordinateCalculator +{ + const int DefaultGridWidth = 64; + const int DefaultGridHeight = 32; - Vector2 CalculateDrawCoordinatesFromGridUnits(int gridX, int gridY); + Vector2 CalculateRawRenderCoordinatesFromGridUnits(int gridX, int gridY, int tileWidth = DefaultGridWidth, int tileHeight = DefaultGridHeight); - Vector2 CalculateDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate); + Vector2 CalculateDrawCoordinatesFromGridUnits(int gridX, int gridY); - Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(int gridX, int gridY); + Vector2 CalculateDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate); - Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate); + Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(int gridX, int gridY); - Vector2 CalculateGroundLayerRenderTargetDrawCoordinates(bool isMiniMap = false, int tileWidth = DefaultGridWidth, int tileHeight = DefaultGridHeight); + Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate); - Vector2 CalculateDrawCoordinates(DomainNPC npc); + Vector2 CalculateGroundLayerRenderTargetDrawCoordinates(bool isMiniMap = false, int tileWidth = DefaultGridWidth, int tileHeight = DefaultGridHeight); - MapCoordinate CalculateGridCoordinatesFromDrawLocation(Vector2 drawLocation); - } + Vector2 CalculateDrawCoordinates(DomainNPC npc); + + MapCoordinate CalculateGridCoordinatesFromDrawLocation(Vector2 drawLocation); } \ No newline at end of file diff --git a/EndlessClient/Rendering/HealthBarRenderer.cs b/EndlessClient/Rendering/HealthBarRenderer.cs index 11cb8b9be..9d4c2ea19 100644 --- a/EndlessClient/Rendering/HealthBarRenderer.cs +++ b/EndlessClient/Rendering/HealthBarRenderer.cs @@ -6,160 +6,159 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +public class HealthBarRenderer : IHealthBarRenderer { - public class HealthBarRenderer : IHealthBarRenderer - { - private const int DigitWidth = 9; + private const int DigitWidth = 9; - private readonly IMapActor _parentReference; + private readonly IMapActor _parentReference; - private readonly Texture2D _sourceTexture; - private static readonly Point _numberSpritesOffset, _healthBarSpritesOffset; - private static readonly Rectangle _healthBarBackgroundSource; + private readonly Texture2D _sourceTexture; + private static readonly Point _numberSpritesOffset, _healthBarSpritesOffset; + private static readonly Rectangle _healthBarBackgroundSource; - private Action _doneCallback; - private bool _isMiss; - private List _numberSourceRectangles; - private Rectangle _healthBarSourceRectangle; + private Action _doneCallback; + private bool _isMiss; + private List _numberSourceRectangles; + private Rectangle _healthBarSourceRectangle; - private float _frameOffset; - private Vector2 _damageCounterPosition, _healthBarPosition; + private float _frameOffset; + private Vector2 _damageCounterPosition, _healthBarPosition; - public bool Visible { get; private set; } + public bool Visible { get; private set; } - static HealthBarRenderer() - { - _numberSpritesOffset = new Point(40, 28); - _healthBarSpritesOffset = new Point(0, 28); - _healthBarBackgroundSource = new Rectangle(0, 28, 40, 7); - } + static HealthBarRenderer() + { + _numberSpritesOffset = new Point(40, 28); + _healthBarSpritesOffset = new Point(0, 28); + _healthBarBackgroundSource = new Rectangle(0, 28, 40, 7); + } - public HealthBarRenderer(INativeGraphicsManager nativeGraphicsManager, - IMapActor parentReference) - { - _parentReference = parentReference; - _sourceTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); - _numberSourceRectangles = new List(); - } + public HealthBarRenderer(INativeGraphicsManager nativeGraphicsManager, + IMapActor parentReference) + { + _parentReference = parentReference; + _sourceTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); + _numberSourceRectangles = new List(); + } - public void SetDamage(Option value, int percentHealth, Action doneCallback = null) - { - Visible = true; - _isMiss = !value.HasValue; - _doneCallback = doneCallback; - _frameOffset = 0; + public void SetDamage(Option value, int percentHealth, Action doneCallback = null) + { + Visible = true; + _isMiss = !value.HasValue; + _doneCallback = doneCallback; + _frameOffset = 0; - _numberSourceRectangles.Clear(); + _numberSourceRectangles.Clear(); - value.Match( - some: v => _numberSourceRectangles.AddRange( - GetNumberSourceRectangles(v, isHeal: false) - .Select(x => new Rectangle(_numberSpritesOffset + x.Location, x.Size))), - none: () => _numberSourceRectangles.Add(new Rectangle(_numberSpritesOffset + new Point(92, 0), new Point(30, 11)))); + value.Match( + some: v => _numberSourceRectangles.AddRange( + GetNumberSourceRectangles(v, isHeal: false) + .Select(x => new Rectangle(_numberSpritesOffset + x.Location, x.Size))), + none: () => _numberSourceRectangles.Add(new Rectangle(_numberSpritesOffset + new Point(92, 0), new Point(30, 11)))); - _healthBarSourceRectangle = GetHealthBarSourceRectangle(percentHealth); - _healthBarSourceRectangle = new Rectangle(_healthBarSpritesOffset + _healthBarSourceRectangle.Location, _healthBarSourceRectangle.Size); - } + _healthBarSourceRectangle = GetHealthBarSourceRectangle(percentHealth); + _healthBarSourceRectangle = new Rectangle(_healthBarSpritesOffset + _healthBarSourceRectangle.Location, _healthBarSourceRectangle.Size); + } + + public void SetHealth(int value, int percentHealth, Action doneCallback = null) + { + Visible = true; + _isMiss = false; + _doneCallback = doneCallback; + _frameOffset = 0; + + _numberSourceRectangles.Clear(); + _numberSourceRectangles.AddRange( + GetNumberSourceRectangles(value, isHeal: true) + .Select(x => new Rectangle(_numberSpritesOffset + x.Location, x.Size))); + + _healthBarSourceRectangle = GetHealthBarSourceRectangle(percentHealth); + _healthBarSourceRectangle = new Rectangle(_healthBarSpritesOffset + _healthBarSourceRectangle.Location, _healthBarSourceRectangle.Size); + } - public void SetHealth(int value, int percentHealth, Action doneCallback = null) + public void Update(GameTime gameTime) + { + if (!Visible) return; + + _frameOffset += .1f; + if (_frameOffset > 4) { - Visible = true; - _isMiss = false; - _doneCallback = doneCallback; - _frameOffset = 0; - - _numberSourceRectangles.Clear(); - _numberSourceRectangles.AddRange( - GetNumberSourceRectangles(value, isHeal: true) - .Select(x => new Rectangle(_numberSpritesOffset + x.Location, x.Size))); - - _healthBarSourceRectangle = GetHealthBarSourceRectangle(percentHealth); - _healthBarSourceRectangle = new Rectangle(_healthBarSpritesOffset + _healthBarSourceRectangle.Location, _healthBarSourceRectangle.Size); + Visible = false; + _doneCallback?.Invoke(); } - public void Update(GameTime gameTime) + _healthBarPosition = new Vector2( + _parentReference.HorizontalCenter - _healthBarBackgroundSource.Width / 2f, + _parentReference.NameLabelY); + + if (_isMiss) { - if (!Visible) return; - - _frameOffset += .1f; - if (_frameOffset > 4) - { - Visible = false; - _doneCallback?.Invoke(); - } - - _healthBarPosition = new Vector2( - _parentReference.HorizontalCenter - _healthBarBackgroundSource.Width / 2f, - _parentReference.NameLabelY); - - if (_isMiss) - { - var xPos = _parentReference.HorizontalCenter - (_numberSourceRectangles[0].Width / 2f); - var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height * 2f; - _damageCounterPosition = new Vector2(xPos, yPos); - } - else - { - var digitCount = _numberSourceRectangles.Count; - var xPos = _parentReference.HorizontalCenter - (digitCount * DigitWidth / 2f); - var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height * 2f; - _damageCounterPosition = new Vector2(xPos, yPos); - } + var xPos = _parentReference.HorizontalCenter - (_numberSourceRectangles[0].Width / 2f); + var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height * 2f; + _damageCounterPosition = new Vector2(xPos, yPos); } - - public void DrawToSpriteBatch(SpriteBatch spriteBatch) + else { - if (!Visible) return; - - var numberNdx = 0; - foreach (var numberSource in _numberSourceRectangles) - { - spriteBatch.Draw(_sourceTexture, _damageCounterPosition + new Vector2(numberNdx * DigitWidth, 0), numberSource, Color.White); - numberNdx++; - } - - spriteBatch.Draw(_sourceTexture, _healthBarPosition, _healthBarBackgroundSource, Color.White); - spriteBatch.Draw(_sourceTexture, _healthBarPosition, _healthBarSourceRectangle, Color.White); + var digitCount = _numberSourceRectangles.Count; + var xPos = _parentReference.HorizontalCenter - (digitCount * DigitWidth / 2f); + var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height * 2f; + _damageCounterPosition = new Vector2(xPos, yPos); } + } + + public void DrawToSpriteBatch(SpriteBatch spriteBatch) + { + if (!Visible) return; - private static IEnumerable GetNumberSourceRectangles(int value, bool isHeal) + var numberNdx = 0; + foreach (var numberSource in _numberSourceRectangles) { - var yCoord = isHeal ? 11 : 0; - - var digits = value.ToString(); - for (int i = 0; i < digits.Length; ++i) - { - int next = int.Parse($"{digits[i]}"); - yield return new Rectangle(next * DigitWidth, yCoord, 8, 11); - } + spriteBatch.Draw(_sourceTexture, _damageCounterPosition + new Vector2(numberNdx * DigitWidth, 0), numberSource, Color.White); + numberNdx++; } - private static Rectangle GetHealthBarSourceRectangle(int percentHealth) + spriteBatch.Draw(_sourceTexture, _healthBarPosition, _healthBarBackgroundSource, Color.White); + spriteBatch.Draw(_sourceTexture, _healthBarPosition, _healthBarSourceRectangle, Color.White); + } + + private static IEnumerable GetNumberSourceRectangles(int value, bool isHeal) + { + var yCoord = isHeal ? 11 : 0; + + var digits = value.ToString(); + for (int i = 0; i < digits.Length; ++i) { - // width of health bar is 40 - // percent -> pixels: (percentHealth / 100) * 40 - const double HealthBarFactor = .4; - - if (percentHealth >= 50) - return new Rectangle(0, 7, (int)Math.Round(percentHealth * HealthBarFactor), 7); - else if (percentHealth >= 25) - return new Rectangle(0, 14, (int)Math.Round(percentHealth * HealthBarFactor), 7); - else - return new Rectangle(0, 21, (int)Math.Round(percentHealth * HealthBarFactor), 7); + int next = int.Parse($"{digits[i]}"); + yield return new Rectangle(next * DigitWidth, yCoord, 8, 11); } } - public interface IHealthBarRenderer + private static Rectangle GetHealthBarSourceRectangle(int percentHealth) { - bool Visible { get; } + // width of health bar is 40 + // percent -> pixels: (percentHealth / 100) * 40 + const double HealthBarFactor = .4; + + if (percentHealth >= 50) + return new Rectangle(0, 7, (int)Math.Round(percentHealth * HealthBarFactor), 7); + else if (percentHealth >= 25) + return new Rectangle(0, 14, (int)Math.Round(percentHealth * HealthBarFactor), 7); + else + return new Rectangle(0, 21, (int)Math.Round(percentHealth * HealthBarFactor), 7); + } +} + +public interface IHealthBarRenderer +{ + bool Visible { get; } - void SetDamage(Option value, int percentHealth, Action doneCallback = null); + void SetDamage(Option value, int percentHealth, Action doneCallback = null); - void SetHealth(int value, int percentHealth, Action doneCallback = null); + void SetHealth(int value, int percentHealth, Action doneCallback = null); - void Update(GameTime gameTime); + void Update(GameTime gameTime); - void DrawToSpriteBatch(SpriteBatch spriteBatch); - } + void DrawToSpriteBatch(SpriteBatch spriteBatch); } \ No newline at end of file diff --git a/EndlessClient/Rendering/IGameWindowRepository.cs b/EndlessClient/Rendering/IGameWindowRepository.cs index e2d5f912f..a11cf50ef 100644 --- a/EndlessClient/Rendering/IGameWindowRepository.cs +++ b/EndlessClient/Rendering/IGameWindowRepository.cs @@ -1,21 +1,20 @@ using AutomaticTypeMapper; using Microsoft.Xna.Framework; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +public interface IGameWindowRepository { - public interface IGameWindowRepository - { - GameWindow Window { get; set; } - } + GameWindow Window { get; set; } +} - public interface IGameWindowProvider - { - GameWindow Window { get; } - } +public interface IGameWindowProvider +{ + GameWindow Window { get; } +} - [AutoMappedType(IsSingleton = true)] - public class GameWindowRepository : IGameWindowProvider, IGameWindowRepository - { - public GameWindow Window { get; set; } - } +[AutoMappedType(IsSingleton = true)] +public class GameWindowRepository : IGameWindowProvider, IGameWindowRepository +{ + public GameWindow Window { get; set; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/IMapActor.cs b/EndlessClient/Rendering/IMapActor.cs index 058a69ea5..361b9854d 100644 --- a/EndlessClient/Rendering/IMapActor.cs +++ b/EndlessClient/Rendering/IMapActor.cs @@ -1,26 +1,25 @@ using EOLib.Domain.Spells; using Microsoft.Xna.Framework; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +public interface IMapActor { - public interface IMapActor - { - int NameLabelY { get; } + int NameLabelY { get; } - int HorizontalCenter { get; } + int HorizontalCenter { get; } - bool IsAlive { get; } + bool IsAlive { get; } - ISpellTargetable SpellTarget { get; } + ISpellTargetable SpellTarget { get; } - Rectangle DrawArea { get; } + Rectangle DrawArea { get; } - void ShowDamageCounter(int damage, int percentHealth, bool isHeal); + void ShowDamageCounter(int damage, int percentHealth, bool isHeal); - void ShowChatBubble(string text, bool isGroupChat = false); + void ShowChatBubble(string text, bool isGroupChat = false); - bool EffectIsPlaying(); + bool EffectIsPlaying(); - void PlayEffect(int effectId); - } + void PlayEffect(int effectId); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/ClickDispatcher.cs b/EndlessClient/Rendering/Map/ClickDispatcher.cs index 9d7025423..f5459b245 100644 --- a/EndlessClient/Rendering/Map/ClickDispatcher.cs +++ b/EndlessClient/Rendering/Map/ClickDispatcher.cs @@ -20,245 +20,244 @@ using DomainCharacter = EOLib.Domain.Character.Character; using DomainNPC = EOLib.Domain.NPC.NPC; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +public class ClickDispatcher : XNAControl, IClickDispatcher { - public class ClickDispatcher : XNAControl, IClickDispatcher + private readonly IHudControlProvider _hudControlProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IMapCellStateProvider _mapCellStateProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly INPCRendererProvider _npcRendererProvider; + private readonly ISpellSlotDataProvider _spellSlotDataProvider; + private readonly IContextMenuRepository _contextMenuRepository; + private readonly IMapObjectBoundsCalculator _mapObjectBoundsCalculator; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IMapInteractionController _mapInteractionController; + private readonly INPCInteractionController _npcInteractionController; + + public override Rectangle EventArea => new(0, 0, _clientWindowSizeProvider.Width, _clientWindowSizeProvider.Height); + + public ClickDispatcher(IHudControlProvider hudControlProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterProvider characterProvider, + IMapCellStateProvider mapCellStateProvider, + ICharacterRendererProvider characterRendererProvider, + INPCRendererProvider npcRendererProvider, + ISpellSlotDataProvider spellSlotDataProvider, + IContextMenuRepository contextMenuRepository, + + IMapObjectBoundsCalculator mapObjectBoundsCalculator, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + + IMapInteractionController mapInteractionController, + INPCInteractionController npcInteractionController) { - private readonly IHudControlProvider _hudControlProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IMapCellStateProvider _mapCellStateProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly INPCRendererProvider _npcRendererProvider; - private readonly ISpellSlotDataProvider _spellSlotDataProvider; - private readonly IContextMenuRepository _contextMenuRepository; - private readonly IMapObjectBoundsCalculator _mapObjectBoundsCalculator; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IMapInteractionController _mapInteractionController; - private readonly INPCInteractionController _npcInteractionController; - - public override Rectangle EventArea => new(0, 0, _clientWindowSizeProvider.Width, _clientWindowSizeProvider.Height); - - public ClickDispatcher(IHudControlProvider hudControlProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterProvider characterProvider, - IMapCellStateProvider mapCellStateProvider, - ICharacterRendererProvider characterRendererProvider, - INPCRendererProvider npcRendererProvider, - ISpellSlotDataProvider spellSlotDataProvider, - IContextMenuRepository contextMenuRepository, - - IMapObjectBoundsCalculator mapObjectBoundsCalculator, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - - IMapInteractionController mapInteractionController, - INPCInteractionController npcInteractionController) - { - _hudControlProvider = hudControlProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _characterProvider = characterProvider; - _mapCellStateProvider = mapCellStateProvider; - _characterRendererProvider = characterRendererProvider; - _npcRendererProvider = npcRendererProvider; - _spellSlotDataProvider = spellSlotDataProvider; - _contextMenuRepository = contextMenuRepository; - _mapObjectBoundsCalculator = mapObjectBoundsCalculator; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - - _mapInteractionController = mapInteractionController; - _npcInteractionController = npcInteractionController; - } + _hudControlProvider = hudControlProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _characterProvider = characterProvider; + _mapCellStateProvider = mapCellStateProvider; + _characterRendererProvider = characterRendererProvider; + _npcRendererProvider = npcRendererProvider; + _spellSlotDataProvider = spellSlotDataProvider; + _contextMenuRepository = contextMenuRepository; + _mapObjectBoundsCalculator = mapObjectBoundsCalculator; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + + _mapInteractionController = mapInteractionController; + _npcInteractionController = npcInteractionController; + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + _contextMenuRepository.ContextMenu.MatchSome(contextMenu => { - _contextMenuRepository.ContextMenu.MatchSome(contextMenu => - { - Game.Components.Remove(contextMenu); - contextMenu.Dispose(); + Game.Components.Remove(contextMenu); + contextMenu.Dispose(); - _contextMenuRepository.ContextMenu = Option.None(); - }); + _contextMenuRepository.ContextMenu = Option.None(); + }); - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - var cellState = _mapCellStateProvider.GetCellStateAt(mapRenderer.GridCoordinates); + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + var cellState = _mapCellStateProvider.GetCellStateAt(mapRenderer.GridCoordinates); - // map items should always get click priority so they can be picked up even when under a character/npc/other object - var mapItemPickupResult = CheckForMapItemClicks(cellState, eventArgs); - return CheckForEntityClicks(eventArgs) || CheckForTileClicks(cellState, eventArgs) || mapItemPickupResult; - } + // map items should always get click priority so they can be picked up even when under a character/npc/other object + var mapItemPickupResult = CheckForMapItemClicks(cellState, eventArgs); + return CheckForEntityClicks(eventArgs) || CheckForTileClicks(cellState, eventArgs) || mapItemPickupResult; + } - private bool CheckForMapItemClicks(IMapCellState cellState, MouseEventArgs eventArgs) - { - if (eventArgs.Button != MouseButton.Left) return false; + private bool CheckForMapItemClicks(IMapCellState cellState, MouseEventArgs eventArgs) + { + if (eventArgs.Button != MouseButton.Left) return false; - if (cellState.Items.Any()) - _mapInteractionController.LeftClick(cellState); + if (cellState.Items.Any()) + _mapInteractionController.LeftClick(cellState); - return cellState.Items.Any(); - } + return cellState.Items.Any(); + } - private bool CheckForEntityClicks(MouseEventArgs eventArgs) + private bool CheckForEntityClicks(MouseEventArgs eventArgs) + { + var entities = new List(_currentMapStateProvider.Characters); + entities.Add(_characterProvider.MainCharacter); + entities.AddRange(_currentMapStateProvider.NPCs); + entities.AddRange(_currentMapProvider.CurrentMap.Signs); + entities.AddRange(_currentMapProvider.CurrentMap + .GetTileSpecs(TileSpec.Board1, TileSpec.Board2, TileSpec.Board3, TileSpec.Board4, + TileSpec.Board5, TileSpec.Board6, TileSpec.Board7, TileSpec.Board8, + TileSpec.Jukebox) + .Select(x => new TileSpecMapEntity(x.X, x.Y))); + + entities.Sort((a, b) => { - var entities = new List(_currentMapStateProvider.Characters); - entities.Add(_characterProvider.MainCharacter); - entities.AddRange(_currentMapStateProvider.NPCs); - entities.AddRange(_currentMapProvider.CurrentMap.Signs); - entities.AddRange(_currentMapProvider.CurrentMap - .GetTileSpecs(TileSpec.Board1, TileSpec.Board2, TileSpec.Board3, TileSpec.Board4, - TileSpec.Board5, TileSpec.Board6, TileSpec.Board7, TileSpec.Board8, - TileSpec.Jukebox) - .Select(x => new TileSpecMapEntity(x.X, x.Y))); - - entities.Sort((a, b) => - { - return (a.Y * _currentMapProvider.CurrentMap.Properties.Width + a.X) - .CompareTo(b.Y * _currentMapProvider.CurrentMap.Properties.Width + b.X) * -1; - }); + return (a.Y * _currentMapProvider.CurrentMap.Properties.Width + a.X) + .CompareTo(b.Y * _currentMapProvider.CurrentMap.Properties.Width + b.X) * -1; + }); - foreach (var entity in entities) - { - var bounds = GetEntityBounds(entity); + foreach (var entity in entities) + { + var bounds = GetEntityBounds(entity); - if (bounds.Contains(eventArgs.Position)) + if (bounds.Contains(eventArgs.Position)) + { + if (DispatchClickToEntity(entity, eventArgs)) { - if (DispatchClickToEntity(entity, eventArgs)) - { - _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator) - .CancelClickToWalk(); - return true; - } + _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator) + .CancelClickToWalk(); + return true; } } - - return false; } - private bool CheckForTileClicks(IMapCellState cellState, MouseEventArgs eventArgs) - { - if (eventArgs.Button == MouseButton.Left) - { - _mapInteractionController.LeftClick(cellState); - return true; - } - - return false; - } + return false; + } - private bool DispatchClickToEntity(IMapEntity entity, MouseEventArgs eventArgs) + private bool CheckForTileClicks(IMapCellState cellState, MouseEventArgs eventArgs) + { + if (eventArgs.Button == MouseButton.Left) { - return entity switch - { - DomainCharacter c => HandleCharacterClick(c, eventArgs.Button), - DomainNPC n => eventArgs.Button == MouseButton.Left && HandleNPCClick(n, eventArgs.Position), - SignMapEntity s => eventArgs.Button == MouseButton.Left && HandleSignClick(s), - TileSpecMapEntity ts => eventArgs.Button == MouseButton.Left && HandleTileSpecClick(ts), - _ => throw new ArgumentException() - }; + _mapInteractionController.LeftClick(cellState); + return true; } - private Rectangle GetEntityBounds(IMapEntity entity) + return false; + } + + private bool DispatchClickToEntity(IMapEntity entity, MouseEventArgs eventArgs) + { + return entity switch { - return entity switch - { - DomainCharacter c => GetCharacterRendererArea(c.ID), - DomainNPC n => GetNPCRendererArea(n.Index), - SignMapEntity or TileSpecMapEntity => GetObjectBounds(entity), - _ => throw new ArgumentException() - }; - } + DomainCharacter c => HandleCharacterClick(c, eventArgs.Button), + DomainNPC n => eventArgs.Button == MouseButton.Left && HandleNPCClick(n, eventArgs.Position), + SignMapEntity s => eventArgs.Button == MouseButton.Left && HandleSignClick(s), + TileSpecMapEntity ts => eventArgs.Button == MouseButton.Left && HandleTileSpecClick(ts), + _ => throw new ArgumentException() + }; + } - private Rectangle GetCharacterRendererArea(int characterId) + private Rectangle GetEntityBounds(IMapEntity entity) + { + return entity switch { - return _characterRendererProvider.MainCharacterRenderer.Match( - some: mcr => mcr.Character.ID == characterId ? mcr.DrawArea : RendererDrawAreaOrEmpty(characterId), - none: () => RendererDrawAreaOrEmpty(characterId)); + DomainCharacter c => GetCharacterRendererArea(c.ID), + DomainNPC n => GetNPCRendererArea(n.Index), + SignMapEntity or TileSpecMapEntity => GetObjectBounds(entity), + _ => throw new ArgumentException() + }; + } - Rectangle RendererDrawAreaOrEmpty(int id) => _characterRendererProvider.CharacterRenderers.ContainsKey(characterId) - ? _characterRendererProvider.CharacterRenderers[characterId].DrawArea - : Rectangle.Empty; - } + private Rectangle GetCharacterRendererArea(int characterId) + { + return _characterRendererProvider.MainCharacterRenderer.Match( + some: mcr => mcr.Character.ID == characterId ? mcr.DrawArea : RendererDrawAreaOrEmpty(characterId), + none: () => RendererDrawAreaOrEmpty(characterId)); - private Rectangle GetNPCRendererArea(int npcIndex) - { - return _npcRendererProvider.NPCRenderers.ContainsKey(npcIndex) - ? _npcRendererProvider.NPCRenderers[npcIndex].DrawArea + Rectangle RendererDrawAreaOrEmpty(int id) => _characterRendererProvider.CharacterRenderers.ContainsKey(characterId) + ? _characterRendererProvider.CharacterRenderers[characterId].DrawArea : Rectangle.Empty; - } + } - private Rectangle GetObjectBounds(IMapEntity entity) - { - var gfx = _currentMapProvider.CurrentMap.GFX[MapLayer.Objects][entity.Y, entity.X]; - return gfx > 0 - ? _mapObjectBoundsCalculator.GetMapObjectBounds(entity.X, entity.Y, gfx) - // if there is no map object GFX at the sign's position, use the default tile coordinates - : new Rectangle( - _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(entity.X, entity.Y).ToPoint(), - new Point(64, 32)); - } + private Rectangle GetNPCRendererArea(int npcIndex) + { + return _npcRendererProvider.NPCRenderers.ContainsKey(npcIndex) + ? _npcRendererProvider.NPCRenderers[npcIndex].DrawArea + : Rectangle.Empty; + } - private bool HandleCharacterClick(DomainCharacter c, MouseButton button) - { - switch (button) - { - case MouseButton.Left: return _mapInteractionController.LeftClick(c); - case MouseButton.Right: _mapInteractionController.RightClick(c); break; - default: return false; - } + private Rectangle GetObjectBounds(IMapEntity entity) + { + var gfx = _currentMapProvider.CurrentMap.GFX[MapLayer.Objects][entity.Y, entity.X]; + return gfx > 0 + ? _mapObjectBoundsCalculator.GetMapObjectBounds(entity.X, entity.Y, gfx) + // if there is no map object GFX at the sign's position, use the default tile coordinates + : new Rectangle( + _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(entity.X, entity.Y).ToPoint(), + new Point(64, 32)); + } - return true; + private bool HandleCharacterClick(DomainCharacter c, MouseButton button) + { + switch (button) + { + case MouseButton.Left: return _mapInteractionController.LeftClick(c); + case MouseButton.Right: _mapInteractionController.RightClick(c); break; + default: return false; } - private bool HandleNPCClick(DomainNPC n, Point currentMousePosition) - { - var renderer = _npcRendererProvider.NPCRenderers[n.Index]; + return true; + } - if (_spellSlotDataProvider.SpellIsPrepared) - { - _mapInteractionController.LeftClick(n); - } - else if (renderer.IsClickablePixel(currentMousePosition)) - { - _npcInteractionController.ShowNPCDialog(n); - } + private bool HandleNPCClick(DomainNPC n, Point currentMousePosition) + { + var renderer = _npcRendererProvider.NPCRenderers[n.Index]; - return true; + if (_spellSlotDataProvider.SpellIsPrepared) + { + _mapInteractionController.LeftClick(n); } - - private bool HandleSignClick(SignMapEntity s) + else if (renderer.IsClickablePixel(currentMousePosition)) { - var cellState = new MapCellState - { - Sign = Option.Some(new Sign(s)), - Coordinate = new MapCoordinate(s.X, s.Y) - }; - - _mapInteractionController.LeftClick(cellState); - - return true; + _npcInteractionController.ShowNPCDialog(n); } - private bool HandleTileSpecClick(TileSpecMapEntity ts) + return true; + } + + private bool HandleSignClick(SignMapEntity s) + { + var cellState = new MapCellState { - var cellState = new MapCellState - { - Coordinate = new MapCoordinate(ts.X, ts.Y), - TileSpec = _currentMapProvider.CurrentMap.Tiles[ts.Y, ts.X] - }; + Sign = Option.Some(new Sign(s)), + Coordinate = new MapCoordinate(s.X, s.Y) + }; - _mapInteractionController.LeftClick(cellState); + _mapInteractionController.LeftClick(cellState); - return false; - } + return true; } - public interface IClickDispatcher : IGameComponent + private bool HandleTileSpecClick(TileSpecMapEntity ts) { - int DrawOrder { get; set; } + var cellState = new MapCellState + { + Coordinate = new MapCoordinate(ts.X, ts.Y), + TileSpec = _currentMapProvider.CurrentMap.Tiles[ts.Y, ts.X] + }; + + _mapInteractionController.LeftClick(cellState); + + return false; } +} + +public interface IClickDispatcher : IGameComponent +{ + int DrawOrder { get; set; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs b/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs index 1fd6e2c43..77ddc36f7 100644 --- a/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs +++ b/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs @@ -7,79 +7,78 @@ using EOLib.Domain.Character; using EOLib.Domain.Map; -namespace EndlessClient.Rendering.Map -{ - [AutoMappedType] - public class ClickDispatcherFactory : IClickDispatcherFactory - { - private readonly IHudControlProvider _hudControlProvider; +namespace EndlessClient.Rendering.Map; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IMapCellStateProvider _mapCellStateProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly INPCRendererProvider _npcRendererProvider; - private readonly ISpellSlotDataProvider _spellSlotDataProvider; - private readonly IContextMenuRepository _contextMenuRepository; - private readonly IMapObjectBoundsCalculator _mapObjectBoundsCalculator; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IMapInteractionController _mapInteractionController; - private readonly INPCInteractionController _npcInteractionController; +[AutoMappedType] +public class ClickDispatcherFactory : IClickDispatcherFactory +{ + private readonly IHudControlProvider _hudControlProvider; - public ClickDispatcherFactory(IHudControlProvider hudControlProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterProvider characterProvider, - IMapCellStateProvider mapCellStateProvider, - ICharacterRendererProvider characterRendererProvider, - INPCRendererProvider npcRendererProvider, - ISpellSlotDataProvider spellSlotDataProvider, - IContextMenuRepository contextMenuRepository, - IMapObjectBoundsCalculator mapObjectBoundsCalculator, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IMapInteractionController mapInteractionController, - INPCInteractionController npcInteractionController) - { - _hudControlProvider = hudControlProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _characterProvider = characterProvider; - _mapCellStateProvider = mapCellStateProvider; - _characterRendererProvider = characterRendererProvider; - _npcRendererProvider = npcRendererProvider; - _spellSlotDataProvider = spellSlotDataProvider; - _contextMenuRepository = contextMenuRepository; - _mapObjectBoundsCalculator = mapObjectBoundsCalculator; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _mapInteractionController = mapInteractionController; - _npcInteractionController = npcInteractionController; - } + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IMapCellStateProvider _mapCellStateProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly INPCRendererProvider _npcRendererProvider; + private readonly ISpellSlotDataProvider _spellSlotDataProvider; + private readonly IContextMenuRepository _contextMenuRepository; + private readonly IMapObjectBoundsCalculator _mapObjectBoundsCalculator; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IMapInteractionController _mapInteractionController; + private readonly INPCInteractionController _npcInteractionController; - public IClickDispatcher Create() - { - return new ClickDispatcher(_hudControlProvider, - _clientWindowSizeProvider, - _currentMapProvider, - _currentMapStateProvider, - _characterProvider, - _mapCellStateProvider, - _characterRendererProvider, - _npcRendererProvider, - _spellSlotDataProvider, - _contextMenuRepository, - _mapObjectBoundsCalculator, - _gridDrawCoordinateCalculator, - _mapInteractionController, - _npcInteractionController); - } + public ClickDispatcherFactory(IHudControlProvider hudControlProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterProvider characterProvider, + IMapCellStateProvider mapCellStateProvider, + ICharacterRendererProvider characterRendererProvider, + INPCRendererProvider npcRendererProvider, + ISpellSlotDataProvider spellSlotDataProvider, + IContextMenuRepository contextMenuRepository, + IMapObjectBoundsCalculator mapObjectBoundsCalculator, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IMapInteractionController mapInteractionController, + INPCInteractionController npcInteractionController) + { + _hudControlProvider = hudControlProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _characterProvider = characterProvider; + _mapCellStateProvider = mapCellStateProvider; + _characterRendererProvider = characterRendererProvider; + _npcRendererProvider = npcRendererProvider; + _spellSlotDataProvider = spellSlotDataProvider; + _contextMenuRepository = contextMenuRepository; + _mapObjectBoundsCalculator = mapObjectBoundsCalculator; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _mapInteractionController = mapInteractionController; + _npcInteractionController = npcInteractionController; } - public interface IClickDispatcherFactory + public IClickDispatcher Create() { - IClickDispatcher Create(); + return new ClickDispatcher(_hudControlProvider, + _clientWindowSizeProvider, + _currentMapProvider, + _currentMapStateProvider, + _characterProvider, + _mapCellStateProvider, + _characterRendererProvider, + _npcRendererProvider, + _spellSlotDataProvider, + _contextMenuRepository, + _mapObjectBoundsCalculator, + _gridDrawCoordinateCalculator, + _mapInteractionController, + _npcInteractionController); } +} + +public interface IClickDispatcherFactory +{ + IClickDispatcher Create(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs b/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs index 52fc59fd5..68b1a0e58 100644 --- a/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs +++ b/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs @@ -12,143 +12,142 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +[AutoMappedType(IsSingleton = true)] +public class DynamicMapObjectUpdater : IDynamicMapObjectUpdater { - [AutoMappedType(IsSingleton = true)] - public class DynamicMapObjectUpdater : IDynamicMapObjectUpdater + private const int DOOR_CLOSE_TIME_MS = 3000; + + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IConfigurationProvider _configurationProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly ISfxPlayer _sfxPlayer; + + private readonly List<(Warp Door, DateTime OpenTime)> _cachedDoorState; + private IMapFile _cachedMap; + private List _ambientSounds; + + public DynamicMapObjectUpdater(ICharacterProvider characterProvider, + ICharacterRendererProvider characterRendererProvider, + ICurrentMapStateRepository currentMapStateRepository, + ICurrentMapProvider currentMapProvider, + IConfigurationProvider configurationProvider, + IUserInputProvider userInputProvider, + ISfxPlayer sfxPlayer) { - private const int DOOR_CLOSE_TIME_MS = 3000; - - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IConfigurationProvider _configurationProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly ISfxPlayer _sfxPlayer; - - private readonly List<(Warp Door, DateTime OpenTime)> _cachedDoorState; - private IMapFile _cachedMap; - private List _ambientSounds; - - public DynamicMapObjectUpdater(ICharacterProvider characterProvider, - ICharacterRendererProvider characterRendererProvider, - ICurrentMapStateRepository currentMapStateRepository, - ICurrentMapProvider currentMapProvider, - IConfigurationProvider configurationProvider, - IUserInputProvider userInputProvider, - ISfxPlayer sfxPlayer) - { - _characterProvider = characterProvider; - _characterRendererProvider = characterRendererProvider; - _currentMapStateRepository = currentMapStateRepository; - _currentMapProvider = currentMapProvider; - _configurationProvider = configurationProvider; - _userInputProvider = userInputProvider; - _sfxPlayer = sfxPlayer; - - _cachedDoorState = new List<(Warp Door, DateTime OpenTime)>(); - _ambientSounds = new List(); - } + _characterProvider = characterProvider; + _characterRendererProvider = characterRendererProvider; + _currentMapStateRepository = currentMapStateRepository; + _currentMapProvider = currentMapProvider; + _configurationProvider = configurationProvider; + _userInputProvider = userInputProvider; + _sfxPlayer = sfxPlayer; + + _cachedDoorState = new List<(Warp Door, DateTime OpenTime)>(); + _ambientSounds = new List(); + } - public void UpdateMapObjects(GameTime gameTime) + public void UpdateMapObjects(GameTime gameTime) + { + // todo: this should probably be part of currentMapStateRepository instead of tracked here + if (_cachedMap != _currentMapProvider.CurrentMap) { - // todo: this should probably be part of currentMapStateRepository instead of tracked here - if (_cachedMap != _currentMapProvider.CurrentMap) - { - _ambientSounds = new List(_currentMapProvider.CurrentMap.GetTileSpecs(TileSpec.AmbientSource)); - _cachedMap = _currentMapProvider.CurrentMap; - } + _ambientSounds = new List(_currentMapProvider.CurrentMap.GetTileSpecs(TileSpec.AmbientSource)); + _cachedMap = _currentMapProvider.CurrentMap; + } - var now = DateTime.Now; - OpenNewDoors(now); - CloseExpiredDoors(now); + var now = DateTime.Now; + OpenNewDoors(now); + CloseExpiredDoors(now); - UpdateAmbientNoiseVolume(); + UpdateAmbientNoiseVolume(); - HideStackedCharacterNames(); - } + HideStackedCharacterNames(); + } - private void OpenNewDoors(DateTime now) + private void OpenNewDoors(DateTime now) + { + var newDoors = _currentMapStateRepository.OpenDoors.Where(x => _cachedDoorState.All(d => d.Door != x)); + foreach (var door in newDoors) { - var newDoors = _currentMapStateRepository.OpenDoors.Where(x => _cachedDoorState.All(d => d.Door != x)); - foreach (var door in newDoors) - { - _cachedDoorState.Add((door, now)); - _sfxPlayer.PlaySfx(SoundEffectID.DoorOpen); - } + _cachedDoorState.Add((door, now)); + _sfxPlayer.PlaySfx(SoundEffectID.DoorOpen); } + } - private void CloseExpiredDoors(DateTime now) + private void CloseExpiredDoors(DateTime now) + { + var expiredDoors = _cachedDoorState.Where(x => (now - x.OpenTime).TotalMilliseconds > DOOR_CLOSE_TIME_MS).ToList(); + foreach (var door in expiredDoors) { - var expiredDoors = _cachedDoorState.Where(x => (now - x.OpenTime).TotalMilliseconds > DOOR_CLOSE_TIME_MS).ToList(); - foreach (var door in expiredDoors) + _cachedDoorState.Remove(door); + if (_currentMapStateRepository.OpenDoors.Contains(door.Door)) { - _cachedDoorState.Remove(door); - if (_currentMapStateRepository.OpenDoors.Contains(door.Door)) - { - _currentMapStateRepository.OpenDoors.Remove(door.Door); - _sfxPlayer.PlaySfx(SoundEffectID.DoorClose); - } + _currentMapStateRepository.OpenDoors.Remove(door.Door); + _sfxPlayer.PlaySfx(SoundEffectID.DoorClose); } } + } - private void UpdateAmbientNoiseVolume() + private void UpdateAmbientNoiseVolume() + { + if (_cachedMap.Properties.AmbientNoise <= 0 || !_configurationProvider.SoundEnabled) + return; + + // the algorithm in EO main seems to scale volume with distance to the closest ambient source + // distance is the sum of the components of the vector from character position to closest ambient source + // this is scaled from 0-25, with 0 being on top of the tile and 25 being too far away to hear the ambient sound from it + var props = _characterProvider.MainCharacter.RenderProperties; + var charCoord = props.CurrentAction == CharacterActionState.Walking ? props.DestinationCoordinates() : props.Coordinates(); + var shortestDistance = int.MaxValue; + foreach (var coordinate in _ambientSounds) { - if (_cachedMap.Properties.AmbientNoise <= 0 || !_configurationProvider.SoundEnabled) - return; - - // the algorithm in EO main seems to scale volume with distance to the closest ambient source - // distance is the sum of the components of the vector from character position to closest ambient source - // this is scaled from 0-25, with 0 being on top of the tile and 25 being too far away to hear the ambient sound from it - var props = _characterProvider.MainCharacter.RenderProperties; - var charCoord = props.CurrentAction == CharacterActionState.Walking ? props.DestinationCoordinates() : props.Coordinates(); - var shortestDistance = int.MaxValue; - foreach (var coordinate in _ambientSounds) - { - var distance = Math.Abs(charCoord.X - coordinate.X) + Math.Abs(charCoord.Y - coordinate.Y); - if (distance < shortestDistance) - shortestDistance = distance; - } - _sfxPlayer.SetLoopingSfxVolume(Math.Max((25 - shortestDistance) / 25f, 0)); + var distance = Math.Abs(charCoord.X - coordinate.X) + Math.Abs(charCoord.Y - coordinate.Y); + if (distance < shortestDistance) + shortestDistance = distance; } + _sfxPlayer.SetLoopingSfxVolume(Math.Max((25 - shortestDistance) / 25f, 0)); + } - private void HideStackedCharacterNames() - { - var characters = _characterRendererProvider.CharacterRenderers.Values - .Where(x => x.DrawArea.Contains(_userInputProvider.CurrentMouseState.Position)) - .GroupBy(x => x.Character.RenderProperties.Coordinates()); + private void HideStackedCharacterNames() + { + var characters = _characterRendererProvider.CharacterRenderers.Values + .Where(x => x.DrawArea.Contains(_userInputProvider.CurrentMouseState.Position)) + .GroupBy(x => x.Character.RenderProperties.Coordinates()); - foreach (var grouping in characters) + foreach (var grouping in characters) + { + if (grouping.Count() > 1) { - if (grouping.Count() > 1) + var isFirst = true; + foreach (var character in grouping.Reverse()) { - var isFirst = true; - foreach (var character in grouping.Reverse()) + if (isFirst) { - if (isFirst) - { - character.ShowName(); - } - else - { - character.HideName(); - } - - isFirst = false; - } - } - else - { - foreach (var character in grouping) character.ShowName(); + } + else + { + character.HideName(); + } + + isFirst = false; } } + else + { + foreach (var character in grouping) + character.ShowName(); + } } } +} - public interface IDynamicMapObjectUpdater - { - void UpdateMapObjects(GameTime gameTime); - } +public interface IDynamicMapObjectUpdater +{ + void UpdateMapObjects(GameTime gameTime); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs b/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs index 0182979a0..ed116105e 100644 --- a/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs +++ b/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs @@ -1,9 +1,8 @@ using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +public interface IMapItemGraphicProvider { - public interface IMapItemGraphicProvider - { - Texture2D GetItemGraphic(int id, int amount); - } + Texture2D GetItemGraphic(int id, int amount); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs b/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs index 7e29d6466..da21e211c 100644 --- a/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs +++ b/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs @@ -1,9 +1,8 @@ using EOLib.IO.Map; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +public interface IMapRenderDistanceCalculator { - public interface IMapRenderDistanceCalculator - { - MapRenderBounds CalculateRenderBounds(EOLib.Domain.Character.Character character, IMapFile currentMap); - } + MapRenderBounds CalculateRenderBounds(EOLib.Domain.Character.Character character, IMapFile currentMap); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/IMapRenderer.cs b/EndlessClient/Rendering/Map/IMapRenderer.cs index 00db8ffe2..8e2e5f870 100644 --- a/EndlessClient/Rendering/Map/IMapRenderer.cs +++ b/EndlessClient/Rendering/Map/IMapRenderer.cs @@ -1,24 +1,23 @@ using EOLib.Domain.Map; using Microsoft.Xna.Framework; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +public interface IMapRenderer : IGameComponent, IDrawable { - public interface IMapRenderer : IGameComponent, IDrawable - { - MapCoordinate GridCoordinates { get; } + MapCoordinate GridCoordinates { get; } - bool MouseOver { get; } + bool MouseOver { get; } - void StartMapTransition(); + void StartMapTransition(); - void StartEarthquake(int strength); + void StartEarthquake(int strength); - void RedrawGroundLayer(); + void RedrawGroundLayer(); - void RenderEffect(MapCoordinate location, int effectId); + void RenderEffect(MapCoordinate location, int effectId); - void AnimateMouseClick(); + void AnimateMouseClick(); - void ClearTransientRenderables(); - } + void ClearTransientRenderables(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapChangedActions.cs b/EndlessClient/Rendering/Map/MapChangedActions.cs index 984c225f8..074746873 100644 --- a/EndlessClient/Rendering/Map/MapChangedActions.cs +++ b/EndlessClient/Rendering/Map/MapChangedActions.cs @@ -18,238 +18,237 @@ using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using System.Linq; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +[MappedType(BaseType = typeof(IMapChangedActions))] +[MappedType(BaseType = typeof(IMapChangedNotifier))] +public class MapChangedActions : IMapChangedNotifier, IMapChangedActions { - [MappedType(BaseType = typeof(IMapChangedActions))] - [MappedType(BaseType = typeof(IMapChangedNotifier))] - public class MapChangedActions : IMapChangedNotifier, IMapChangedActions - { - private readonly ICharacterStateCache _characterStateCache; - private readonly INPCStateCache _npcStateCache; - private readonly INPCSpriteDataCache _npcSpriteDataCache; - private readonly ICharacterRendererRepository _characterRendererRepository; - private readonly INPCRendererRepository _npcRendererRepository; - private readonly IENFFileProvider _enfFileProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IConfigurationProvider _configurationProvider; - private readonly IActiveDialogProvider _dialogProvider; - private readonly IMfxPlayer _mfxPlayer; - private readonly ISfxPlayer _sfxPlayer; - private readonly IChatController _chatController; - - public MapChangedActions(ICharacterStateCache characterStateCache, - INPCStateCache npcStateCache, - INPCSpriteDataCache npcSpriteDataCache, - ICharacterRendererRepository characterRendererRepository, - INPCRendererRepository npcRendererRepository, - IENFFileProvider enfFileProvider, - IHudControlProvider hudControlProvider, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateRepository currentMapStateRepository, - IConfigurationProvider configurationProvider, - IActiveDialogProvider dialogProvider, - IMfxPlayer mfxPlayer, - ISfxPlayer sfxPlayer, - IChatController chatController) - { - _characterStateCache = characterStateCache; - _npcStateCache = npcStateCache; - _npcSpriteDataCache = npcSpriteDataCache; - _characterRendererRepository = characterRendererRepository; - _npcRendererRepository = npcRendererRepository; - _enfFileProvider = enfFileProvider; - _hudControlProvider = hudControlProvider; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _currentMapProvider = currentMapProvider; - _currentMapStateRepository = currentMapStateRepository; - _configurationProvider = configurationProvider; - _dialogProvider = dialogProvider; - _mfxPlayer = mfxPlayer; - _sfxPlayer = sfxPlayer; - _chatController = chatController; - } + private readonly ICharacterStateCache _characterStateCache; + private readonly INPCStateCache _npcStateCache; + private readonly INPCSpriteDataCache _npcSpriteDataCache; + private readonly ICharacterRendererRepository _characterRendererRepository; + private readonly INPCRendererRepository _npcRendererRepository; + private readonly IENFFileProvider _enfFileProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IConfigurationProvider _configurationProvider; + private readonly IActiveDialogProvider _dialogProvider; + private readonly IMfxPlayer _mfxPlayer; + private readonly ISfxPlayer _sfxPlayer; + private readonly IChatController _chatController; + + public MapChangedActions(ICharacterStateCache characterStateCache, + INPCStateCache npcStateCache, + INPCSpriteDataCache npcSpriteDataCache, + ICharacterRendererRepository characterRendererRepository, + INPCRendererRepository npcRendererRepository, + IENFFileProvider enfFileProvider, + IHudControlProvider hudControlProvider, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateRepository currentMapStateRepository, + IConfigurationProvider configurationProvider, + IActiveDialogProvider dialogProvider, + IMfxPlayer mfxPlayer, + ISfxPlayer sfxPlayer, + IChatController chatController) + { + _characterStateCache = characterStateCache; + _npcStateCache = npcStateCache; + _npcSpriteDataCache = npcSpriteDataCache; + _characterRendererRepository = characterRendererRepository; + _npcRendererRepository = npcRendererRepository; + _enfFileProvider = enfFileProvider; + _hudControlProvider = hudControlProvider; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _currentMapProvider = currentMapProvider; + _currentMapStateRepository = currentMapStateRepository; + _configurationProvider = configurationProvider; + _dialogProvider = dialogProvider; + _mfxPlayer = mfxPlayer; + _sfxPlayer = sfxPlayer; + _chatController = chatController; + } - public void ActiveCharacterEnterMapForLogin() - { - ShowMapNameIfAvailable(differentMapID: true); - ShowMapTransition(showMapTransition: true); - PlayBackgroundMusic(differentMapID: true); - PlayAmbientNoise(differentMapID: true); - ShowPkWarning(differentMapId: true); - } + public void ActiveCharacterEnterMapForLogin() + { + ShowMapNameIfAvailable(differentMapID: true); + ShowMapTransition(showMapTransition: true); + PlayBackgroundMusic(differentMapID: true); + PlayAmbientNoise(differentMapID: true); + ShowPkWarning(differentMapId: true); + } - public void NotifyMapChanged(WarpEffect warpAnimation, bool differentMapID) - { - StopAllAnimations(); - ClearCharacterRenderersAndCache(); - ClearNPCRenderersAndCache(); - ClearOpenDoors(); - ShowMapNameIfAvailable(differentMapID); - ShowPkWarning(differentMapID); - ShowMapTransition(differentMapID); - ShowWarpBubbles(warpAnimation); - PlayBackgroundMusic(differentMapID); - PlayAmbientNoise(differentMapID); - - if (!differentMapID) - RedrawGroundLayer(); - - CloseAllDialogs(); - - _chatController.ClearAndWarnIfJailAndGlobal(); - } + public void NotifyMapChanged(WarpEffect warpAnimation, bool differentMapID) + { + StopAllAnimations(); + ClearCharacterRenderersAndCache(); + ClearNPCRenderersAndCache(); + ClearOpenDoors(); + ShowMapNameIfAvailable(differentMapID); + ShowPkWarning(differentMapID); + ShowMapTransition(differentMapID); + ShowWarpBubbles(warpAnimation); + PlayBackgroundMusic(differentMapID); + PlayAmbientNoise(differentMapID); + + if (!differentMapID) + RedrawGroundLayer(); - public void NotifyMapMutation() - { - ClearOpenDoors(); + CloseAllDialogs(); - ShowMapTransition(showMapTransition: true); + _chatController.ClearAndWarnIfJailAndGlobal(); + } - RedrawGroundLayer(); + public void NotifyMapMutation() + { + ClearOpenDoors(); - var localChatData = new ChatData(ChatTab.Local, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), _localizedStringFinder.GetString(EOResourceID.SERVER_MESSAGE_MAP_MUTATION), ChatIcon.Exclamation, ChatColor.Server); - var systemChatData = new ChatData(ChatTab.System, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), _localizedStringFinder.GetString(EOResourceID.SERVER_MESSAGE_MAP_MUTATION), ChatIcon.Exclamation, ChatColor.Server); - _chatRepository.AllChat[ChatTab.Local].Add(localChatData); - _chatRepository.AllChat[ChatTab.System].Add(systemChatData); + ShowMapTransition(showMapTransition: true); - _sfxPlayer.PlaySfx(SoundEffectID.MapMutation); - } + RedrawGroundLayer(); - private void StopAllAnimations() - { - var characterAnimator = _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator); - characterAnimator.StopAllCharacterAnimations(); + var localChatData = new ChatData(ChatTab.Local, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), _localizedStringFinder.GetString(EOResourceID.SERVER_MESSAGE_MAP_MUTATION), ChatIcon.Exclamation, ChatColor.Server); + var systemChatData = new ChatData(ChatTab.System, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), _localizedStringFinder.GetString(EOResourceID.SERVER_MESSAGE_MAP_MUTATION), ChatIcon.Exclamation, ChatColor.Server); + _chatRepository.AllChat[ChatTab.Local].Add(localChatData); + _chatRepository.AllChat[ChatTab.System].Add(systemChatData); - var npcAnimator = _hudControlProvider.GetComponent(HudControlIdentifier.NPCAnimator); - npcAnimator.StopAllAnimations(); - } + _sfxPlayer.PlaySfx(SoundEffectID.MapMutation); + } - private void ClearCharacterRenderersAndCache() - { - _characterRendererRepository.MainCharacterRenderer.MatchSome(x => x.StopShout()); + private void StopAllAnimations() + { + var characterAnimator = _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator); + characterAnimator.StopAllCharacterAnimations(); - foreach (var characterRenderer in _characterRendererRepository.CharacterRenderers) - characterRenderer.Value.Dispose(); - _characterRendererRepository.CharacterRenderers.Clear(); - _characterStateCache.ClearAllOtherCharacterStates(); - } + var npcAnimator = _hudControlProvider.GetComponent(HudControlIdentifier.NPCAnimator); + npcAnimator.StopAllAnimations(); + } - private void ClearNPCRenderersAndCache() - { - var currentMapNpcGraphics = _currentMapStateRepository.NPCs.Select(x => _enfFileProvider.ENFFile[x.ID].Graphic).ToList(); - var priorMapNpcGraphics = _npcRendererRepository.NPCRenderers.Select(x => _enfFileProvider.ENFFile[x.Value.NPC.ID].Graphic); + private void ClearCharacterRenderersAndCache() + { + _characterRendererRepository.MainCharacterRenderer.MatchSome(x => x.StopShout()); - foreach (var evict in priorMapNpcGraphics.Except(currentMapNpcGraphics)) - _npcSpriteDataCache.MarkForEviction(evict); + foreach (var characterRenderer in _characterRendererRepository.CharacterRenderers) + characterRenderer.Value.Dispose(); + _characterRendererRepository.CharacterRenderers.Clear(); + _characterStateCache.ClearAllOtherCharacterStates(); + } - foreach (var unevict in currentMapNpcGraphics) - _npcSpriteDataCache.UnmarkForEviction(unevict); + private void ClearNPCRenderersAndCache() + { + var currentMapNpcGraphics = _currentMapStateRepository.NPCs.Select(x => _enfFileProvider.ENFFile[x.ID].Graphic).ToList(); + var priorMapNpcGraphics = _npcRendererRepository.NPCRenderers.Select(x => _enfFileProvider.ENFFile[x.Value.NPC.ID].Graphic); - foreach (var npcRenderer in _npcRendererRepository.NPCRenderers) - npcRenderer.Value.Dispose(); - _npcRendererRepository.NPCRenderers.Clear(); - _npcStateCache.Reset(); - } + foreach (var evict in priorMapNpcGraphics.Except(currentMapNpcGraphics)) + _npcSpriteDataCache.MarkForEviction(evict); - private void ClearOpenDoors() - { - _currentMapStateRepository.OpenDoors.Clear(); - } + foreach (var unevict in currentMapNpcGraphics) + _npcSpriteDataCache.UnmarkForEviction(unevict); - private void ShowMapNameIfAvailable(bool differentMapID) - { - if (!differentMapID || string.IsNullOrWhiteSpace(_currentMapProvider.CurrentMap.Properties.Name)) - return; + foreach (var npcRenderer in _npcRendererRepository.NPCRenderers) + npcRenderer.Value.Dispose(); + _npcRendererRepository.NPCRenderers.Clear(); + _npcStateCache.Reset(); + } - var message = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_YOU_ENTERED); - message = string.Format(message + " {0}", _currentMapProvider.CurrentMap.Properties.Name); + private void ClearOpenDoors() + { + _currentMapStateRepository.OpenDoors.Clear(); + } - var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.NoteLeftArrow); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } + private void ShowMapNameIfAvailable(bool differentMapID) + { + if (!differentMapID || string.IsNullOrWhiteSpace(_currentMapProvider.CurrentMap.Properties.Name)) + return; - private void ShowPkWarning(bool differentMapId) - { - if (!differentMapId || !_currentMapProvider.CurrentMap.Properties.PKAvailable) - return; + var message = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_YOU_ENTERED); + message = string.Format(message + " {0}", _currentMapProvider.CurrentMap.Properties.Name); - var message = _localizedStringFinder.GetString(EOResourceID.CAUTION_THIS_IS_A_PK_ZONE); - var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.NoteLeftArrow); - _chatRepository.AllChat[ChatTab.System].Add(chatData); + var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.NoteLeftArrow); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } - _sfxPlayer.PlaySfx(SoundEffectID.EnterPkMap); - } + private void ShowPkWarning(bool differentMapId) + { + if (!differentMapId || !_currentMapProvider.CurrentMap.Properties.PKAvailable) + return; - private void ShowMapTransition(bool showMapTransition) - { - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - mapRenderer.ClearTransientRenderables(); + var message = _localizedStringFinder.GetString(EOResourceID.CAUTION_THIS_IS_A_PK_ZONE); + var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.NoteLeftArrow); + _chatRepository.AllChat[ChatTab.System].Add(chatData); - if (showMapTransition) - { - mapRenderer.StartMapTransition(); - } - } + _sfxPlayer.PlaySfx(SoundEffectID.EnterPkMap); + } - private void ShowWarpBubbles(WarpEffect animation) - { - _characterRendererRepository.MainCharacterRenderer.MatchSome(r => - { - if (animation == WarpEffect.Admin) - r.PlayEffect((int)HardCodedEffect.WarpArrive); - }); - } + private void ShowMapTransition(bool showMapTransition) + { + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + mapRenderer.ClearTransientRenderables(); - private void RedrawGroundLayer() + if (showMapTransition) { - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - mapRenderer.RedrawGroundLayer(); + mapRenderer.StartMapTransition(); } + } - private void PlayBackgroundMusic(bool differentMapID) + private void ShowWarpBubbles(WarpEffect animation) + { + _characterRendererRepository.MainCharacterRenderer.MatchSome(r => { - if (!_configurationProvider.MusicEnabled || !differentMapID) - return; - - var music = _currentMapProvider.CurrentMap.Properties.Music; - var musicControl = _currentMapProvider.CurrentMap.Properties.Control; - if (music > 0) - _mfxPlayer.PlayBackgroundMusic(_currentMapProvider.CurrentMap.Properties.Music, musicControl); - else - _mfxPlayer.StopBackgroundMusic(); - } + if (animation == WarpEffect.Admin) + r.PlayEffect((int)HardCodedEffect.WarpArrive); + }); + } - private void PlayAmbientNoise(bool differentMapID) - { - if (!_configurationProvider.SoundEnabled || !differentMapID) - return; - - var noise = _currentMapProvider.CurrentMap.Properties.AmbientNoise; - if (noise > 0) - { - _sfxPlayer.StopLoopingSfx(); - _sfxPlayer.PlayLoopingSfx((SoundEffectID)noise); - } - else - _sfxPlayer.StopLoopingSfx(); - } + private void RedrawGroundLayer() + { + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + mapRenderer.RedrawGroundLayer(); + } - private void CloseAllDialogs() + private void PlayBackgroundMusic(bool differentMapID) + { + if (!_configurationProvider.MusicEnabled || !differentMapID) + return; + + var music = _currentMapProvider.CurrentMap.Properties.Music; + var musicControl = _currentMapProvider.CurrentMap.Properties.Control; + if (music > 0) + _mfxPlayer.PlayBackgroundMusic(_currentMapProvider.CurrentMap.Properties.Music, musicControl); + else + _mfxPlayer.StopBackgroundMusic(); + } + + private void PlayAmbientNoise(bool differentMapID) + { + if (!_configurationProvider.SoundEnabled || !differentMapID) + return; + + var noise = _currentMapProvider.CurrentMap.Properties.AmbientNoise; + if (noise > 0) { - foreach (var dlg in _dialogProvider.ActiveDialogs) - dlg.MatchSome(x => ((BaseEODialog)x).Close()); + _sfxPlayer.StopLoopingSfx(); + _sfxPlayer.PlayLoopingSfx((SoundEffectID)noise); } + else + _sfxPlayer.StopLoopingSfx(); } - public interface IMapChangedActions + private void CloseAllDialogs() { - void ActiveCharacterEnterMapForLogin(); + foreach (var dlg in _dialogProvider.ActiveDialogs) + dlg.MatchSome(x => ((BaseEODialog)x).Close()); } +} + +public interface IMapChangedActions +{ + void ActiveCharacterEnterMapForLogin(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs b/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs index a5049694a..bf1e7ab44 100644 --- a/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs +++ b/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs @@ -8,121 +8,120 @@ using EOLib.Graphics; using System.Collections.Generic; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +[MappedType(BaseType = typeof(IMapEntityRendererProvider), IsSingleton = true)] +public class MapEntityRendererProvider : IMapEntityRendererProvider { - [MappedType(BaseType = typeof(IMapEntityRendererProvider), IsSingleton = true)] - public class MapEntityRendererProvider : IMapEntityRendererProvider - { - public IMapEntityRenderer GroundRenderer { get; } + public IMapEntityRenderer GroundRenderer { get; } - public IReadOnlyList BaseRenderers { get; } + public IReadOnlyList BaseRenderers { get; } - public IReadOnlyList MapEntityRenderers { get; } + public IReadOnlyList MapEntityRenderers { get; } - public MapEntityRendererProvider(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - ICurrentMapStateProvider currentMapStateProvider, - IMapItemGraphicProvider mapItemGraphicProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - IConfigurationProvider configurationProvider, - ICharacterRendererProvider characterRendererProvider, - INPCRendererProvider npcRendererProvider) - { - GroundRenderer = - new GroundLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider); + public MapEntityRendererProvider(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + ICurrentMapStateProvider currentMapStateProvider, + IMapItemGraphicProvider mapItemGraphicProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + IConfigurationProvider configurationProvider, + ICharacterRendererProvider characterRendererProvider, + INPCRendererProvider npcRendererProvider) + { + GroundRenderer = + new GroundLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider); - BaseRenderers = new List - { - new AnimatedGroundLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new MapItemLayerRenderer(characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - currentMapStateProvider, - mapItemGraphicProvider) - }; + BaseRenderers = new List + { + new AnimatedGroundLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new MapItemLayerRenderer(characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + currentMapStateProvider, + mapItemGraphicProvider) + }; - MapEntityRenderers = new List - { - new ShadowLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - configurationProvider), - new OverlayLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new MapObjectLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - currentMapStateProvider), - new MainCharacterEntityRenderer(characterProvider, - characterRendererProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - transparent: false), - new DownWallLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - currentMapStateProvider), - new RightWallLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - currentMapStateProvider), - new OtherCharacterEntityRenderer(characterProvider, - characterRendererProvider, - currentMapStateProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new NPCEntityRenderer(characterProvider, + MapEntityRenderers = new List + { + new ShadowLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + configurationProvider), + new OverlayLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new MapObjectLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + currentMapStateProvider), + new MainCharacterEntityRenderer(characterProvider, + characterRendererProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + transparent: false), + new DownWallLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider, - npcRendererProvider, currentMapStateProvider), - new Overlay2LayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new RoofLayerRenderer(nativeGraphicsManager, + new RightWallLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + currentMapStateProvider), + new OtherCharacterEntityRenderer(characterProvider, + characterRendererProvider, + currentMapStateProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new NPCEntityRenderer(characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + npcRendererProvider, + currentMapStateProvider), + new Overlay2LayerRenderer(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider), - new RoofLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new OnTopLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new MainCharacterEntityRenderer(characterProvider, - characterRendererProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - transparent: true) - }; - } + new RoofLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new RoofLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new OnTopLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new MainCharacterEntityRenderer(characterProvider, + characterRendererProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + transparent: true) + }; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs b/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs index ef4fab820..d5b9799fc 100644 --- a/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs +++ b/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs @@ -4,34 +4,33 @@ using EOLib.IO.Repositories; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +[AutoMappedType] +public class MapItemGraphicProvider : IMapItemGraphicProvider { - [AutoMappedType] - public class MapItemGraphicProvider : IMapItemGraphicProvider + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEIFFileProvider _eifFileProvider; + + public MapItemGraphicProvider(INativeGraphicsManager nativeGraphicsManager, IEIFFileProvider eifFileProvider) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEIFFileProvider _eifFileProvider; + _nativeGraphicsManager = nativeGraphicsManager; + _eifFileProvider = eifFileProvider; + } - public MapItemGraphicProvider(INativeGraphicsManager nativeGraphicsManager, IEIFFileProvider eifFileProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _eifFileProvider = eifFileProvider; - } + public Texture2D GetItemGraphic(int id, int amount) + { + var item = _eifFileProvider.EIFFile[id]; - public Texture2D GetItemGraphic(int id, int amount) + if (item.Type == ItemType.Money) { - var item = _eifFileProvider.EIFFile[id]; - - if (item.Type == ItemType.Money) - { - var gfx = amount >= 100000 ? 4 : ( - amount >= 10000 ? 3 : ( - amount >= 100 ? 2 : ( - amount >= 2 ? 1 : 0))); - return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 269 + 2 * gfx, true); - } - - return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 2 * item.Graphic - 1, true); + var gfx = amount >= 100000 ? 4 : ( + amount >= 10000 ? 3 : ( + amount >= 100 ? 2 : ( + amount >= 2 ? 1 : 0))); + return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 269 + 2 * gfx, true); } + + return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 2 * item.Graphic - 1, true); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs b/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs index 1a6625b4a..fdeb30b07 100644 --- a/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs +++ b/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs @@ -5,40 +5,39 @@ using Microsoft.Xna.Framework; using System.Linq; -namespace EndlessClient.Rendering.Map -{ - [AutoMappedType] - public class MapObjectBoundsCalculator : IMapObjectBoundsCalculator - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICharacterProvider _characterProvider; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; +namespace EndlessClient.Rendering.Map; - public MapObjectBoundsCalculator(INativeGraphicsManager nativeGraphicsManager, - ICharacterProvider characterProvider, - IRenderOffsetCalculator renderOffsetCalculator, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) - { - _nativeGraphicsManager = nativeGraphicsManager; - _characterProvider = characterProvider; - _renderOffsetCalculator = renderOffsetCalculator; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - } +[AutoMappedType] +public class MapObjectBoundsCalculator : IMapObjectBoundsCalculator +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICharacterProvider _characterProvider; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - public Rectangle GetMapObjectBounds(int gridX, int gridY, int gfxNum) - { - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapObjects, gfxNum, transparent: true); - var drawPosition = _gridDrawCoordinateCalculator.CalculateDrawCoordinatesFromGridUnits(gridX, gridY); - // see: MapObjectLayerRenderer - // todo: more centralized way of representing this - drawPosition -= new Vector2(gfx.Width / 2, gfx.Height - 32); - return gfx.Bounds.WithPosition(drawPosition); - } + public MapObjectBoundsCalculator(INativeGraphicsManager nativeGraphicsManager, + ICharacterProvider characterProvider, + IRenderOffsetCalculator renderOffsetCalculator, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) + { + _nativeGraphicsManager = nativeGraphicsManager; + _characterProvider = characterProvider; + _renderOffsetCalculator = renderOffsetCalculator; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; } - public interface IMapObjectBoundsCalculator + public Rectangle GetMapObjectBounds(int gridX, int gridY, int gfxNum) { - Rectangle GetMapObjectBounds(int gridX, int gridY, int gfxNum); + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapObjects, gfxNum, transparent: true); + var drawPosition = _gridDrawCoordinateCalculator.CalculateDrawCoordinatesFromGridUnits(gridX, gridY); + // see: MapObjectLayerRenderer + // todo: more centralized way of representing this + drawPosition -= new Vector2(gfx.Width / 2, gfx.Height - 32); + return gfx.Bounds.WithPosition(drawPosition); } +} + +public interface IMapObjectBoundsCalculator +{ + Rectangle GetMapObjectBounds(int gridX, int gridY, int gfxNum); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapRenderBounds.cs b/EndlessClient/Rendering/Map/MapRenderBounds.cs index cfc199502..229186a9c 100644 --- a/EndlessClient/Rendering/Map/MapRenderBounds.cs +++ b/EndlessClient/Rendering/Map/MapRenderBounds.cs @@ -1,19 +1,18 @@ -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +public struct MapRenderBounds { - public struct MapRenderBounds - { - public int FirstRow { get; private set; } - public int LastRow { get; private set; } - public int FirstCol { get; private set; } - public int LastCol { get; private set; } + public int FirstRow { get; private set; } + public int LastRow { get; private set; } + public int FirstCol { get; private set; } + public int LastCol { get; private set; } - public MapRenderBounds(int firstRow, int lastRow, int firstCol, int lastCol) - : this() - { - FirstRow = firstRow; - LastRow = lastRow; - FirstCol = firstCol; - LastCol = lastCol; - } + public MapRenderBounds(int firstRow, int lastRow, int firstCol, int lastCol) + : this() + { + FirstRow = firstRow; + LastRow = lastRow; + FirstCol = firstCol; + LastCol = lastCol; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs b/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs index 85a850863..f62eb6b93 100644 --- a/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs +++ b/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs @@ -2,30 +2,29 @@ using EOLib.IO.Map; using System; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +[AutoMappedType] +public class MapRenderDistanceCalculator : IMapRenderDistanceCalculator { - [AutoMappedType] - public class MapRenderDistanceCalculator : IMapRenderDistanceCalculator - { - private const int DEFAULT_BOUNDS_DISTANCE = 22; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private const int DEFAULT_BOUNDS_DISTANCE = 22; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - public MapRenderDistanceCalculator(IClientWindowSizeProvider clientWindowSizeProvider) - { - _clientWindowSizeProvider = clientWindowSizeProvider; - } + public MapRenderDistanceCalculator(IClientWindowSizeProvider clientWindowSizeProvider) + { + _clientWindowSizeProvider = clientWindowSizeProvider; + } - public MapRenderBounds CalculateRenderBounds(EOLib.Domain.Character.Character character, IMapFile currentMap) - { - var boundsDistanceX = (int)Math.Ceiling((_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Width / 640.0 : 1) * DEFAULT_BOUNDS_DISTANCE); - var boundsDistanceY = (int)Math.Ceiling((_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Width / 320.0 : 1) * DEFAULT_BOUNDS_DISTANCE); + public MapRenderBounds CalculateRenderBounds(EOLib.Domain.Character.Character character, IMapFile currentMap) + { + var boundsDistanceX = (int)Math.Ceiling((_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Width / 640.0 : 1) * DEFAULT_BOUNDS_DISTANCE); + var boundsDistanceY = (int)Math.Ceiling((_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Width / 320.0 : 1) * DEFAULT_BOUNDS_DISTANCE); - var firstRow = Math.Max(character.RenderProperties.MapY - boundsDistanceY, 0); - var lastRow = Math.Min(character.RenderProperties.MapY + boundsDistanceY, currentMap.Properties.Height); - var firstCol = Math.Max(character.RenderProperties.MapX - boundsDistanceX, 0); - var lastCol = Math.Min(character.RenderProperties.MapX + boundsDistanceX, currentMap.Properties.Width); + var firstRow = Math.Max(character.RenderProperties.MapY - boundsDistanceY, 0); + var lastRow = Math.Min(character.RenderProperties.MapY + boundsDistanceY, currentMap.Properties.Height); + var firstCol = Math.Max(character.RenderProperties.MapX - boundsDistanceX, 0); + var lastCol = Math.Min(character.RenderProperties.MapX + boundsDistanceX, currentMap.Properties.Width); - return new MapRenderBounds(firstRow, lastRow, firstCol, lastCol); - } + return new MapRenderBounds(firstRow, lastRow, firstCol, lastCol); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapRenderLayer.cs b/EndlessClient/Rendering/Map/MapRenderLayer.cs index 52478bc5c..22fdd3e36 100644 --- a/EndlessClient/Rendering/Map/MapRenderLayer.cs +++ b/EndlessClient/Rendering/Map/MapRenderLayer.cs @@ -1,20 +1,19 @@ -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +public enum MapRenderLayer { - public enum MapRenderLayer - { - Ground, - Item, - Overlay, - Shadows, - MainCharacter, - DownWall, - RightWall, - Objects, - OtherCharacters, - Npc, - Overlay2, - Roof, - OnTop, - MainCharacterTransparent - } + Ground, + Item, + Overlay, + Shadows, + MainCharacter, + DownWall, + RightWall, + Objects, + OtherCharacters, + Npc, + Overlay2, + Roof, + OnTop, + MainCharacterTransparent } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapRenderer.cs b/EndlessClient/Rendering/Map/MapRenderer.cs index 60c66eaaa..23185857a 100644 --- a/EndlessClient/Rendering/Map/MapRenderer.cs +++ b/EndlessClient/Rendering/Map/MapRenderer.cs @@ -18,567 +18,566 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +public class MapRenderer : DrawableGameComponent, IMapRenderer { - public class MapRenderer : DrawableGameComponent, IMapRenderer + private const double TRANSITION_TIME_MS = 60.0; + + private readonly object _rt_locker_ = new object(); + + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IEffectRendererFactory _effectRendererFactory; + private readonly IMapEntityRendererProvider _mapEntityRendererProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IContentProvider _contentProvider; + private readonly IMapRenderDistanceCalculator _mapRenderDistanceCalculator; + private readonly ICharacterRendererUpdater _characterRendererUpdater; + private readonly INPCRendererUpdater _npcRendererUpdater; + private readonly IDynamicMapObjectUpdater _dynamicMapObjectUpdater; + private readonly IConfigurationProvider _configurationProvider; + private readonly IMouseCursorRenderer _mouseCursorRenderer; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + + private RenderTarget2D _mapBaseTarget, _mapObjectTarget; + private SpriteBatch _sb; + private MapTransitionState _mapTransitionState = MapTransitionState.Default; + private IReadOnlyList _lastMapChecksum; + private bool _groundDrawn; + + private Option _quakeState; + + private IDictionary _mapGridEffectRenderers; + + public bool MouseOver { - private const double TRANSITION_TIME_MS = 60.0; - - private readonly object _rt_locker_ = new object(); - - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IEffectRendererFactory _effectRendererFactory; - private readonly IMapEntityRendererProvider _mapEntityRendererProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IContentProvider _contentProvider; - private readonly IMapRenderDistanceCalculator _mapRenderDistanceCalculator; - private readonly ICharacterRendererUpdater _characterRendererUpdater; - private readonly INPCRendererUpdater _npcRendererUpdater; - private readonly IDynamicMapObjectUpdater _dynamicMapObjectUpdater; - private readonly IConfigurationProvider _configurationProvider; - private readonly IMouseCursorRenderer _mouseCursorRenderer; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - - private RenderTarget2D _mapBaseTarget, _mapObjectTarget; - private SpriteBatch _sb; - private MapTransitionState _mapTransitionState = MapTransitionState.Default; - private IReadOnlyList _lastMapChecksum; - private bool _groundDrawn; - - private Option _quakeState; - - private IDictionary _mapGridEffectRenderers; - - public bool MouseOver + get { - get - { - var ms = Mouse.GetState(); - return Game.IsActive && ms.X > 0 && ms.Y > 0 && - ms.X < _clientWindowSizeRepository.Width && - ms.Y < (_clientWindowSizeRepository.Resizable ? _clientWindowSizeRepository.Height : _clientWindowSizeRepository.Height * 2 / 3); - } + var ms = Mouse.GetState(); + return Game.IsActive && ms.X > 0 && ms.Y > 0 && + ms.X < _clientWindowSizeRepository.Width && + ms.Y < (_clientWindowSizeRepository.Resizable ? _clientWindowSizeRepository.Height : _clientWindowSizeRepository.Height * 2 / 3); } + } - public MapCoordinate GridCoordinates => _mouseCursorRenderer.GridCoordinates; - - public MapRenderer(IEndlessGame endlessGame, - IRenderTargetFactory renderTargetFactory, - IEffectRendererFactory effectRendererFactory, - IMapEntityRendererProvider mapEntityRendererProvider, - ICharacterProvider characterProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - IContentProvider contentProvider, - IMapRenderDistanceCalculator mapRenderDistanceCalculator, - ICharacterRendererUpdater characterRendererUpdater, - INPCRendererUpdater npcRendererUpdater, - IDynamicMapObjectUpdater dynamicMapObjectUpdater, - IConfigurationProvider configurationProvider, - IMouseCursorRenderer mouseCursorRenderer, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeRepository clientWindowSizeRepository, - IFixedTimeStepRepository fixedTimeStepRepository) - : base((Game)endlessGame) - { - _renderTargetFactory = renderTargetFactory; - _effectRendererFactory = effectRendererFactory; - _mapEntityRendererProvider = mapEntityRendererProvider; - _characterProvider = characterProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _contentProvider = contentProvider; - _mapRenderDistanceCalculator = mapRenderDistanceCalculator; - _characterRendererUpdater = characterRendererUpdater; - _npcRendererUpdater = npcRendererUpdater; - _dynamicMapObjectUpdater = dynamicMapObjectUpdater; - _configurationProvider = configurationProvider; - _mouseCursorRenderer = mouseCursorRenderer; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _clientWindowSizeRepository = clientWindowSizeRepository; - _fixedTimeStepRepository = fixedTimeStepRepository; - _mapGridEffectRenderers = new Dictionary(); - } + public MapCoordinate GridCoordinates => _mouseCursorRenderer.GridCoordinates; + + public MapRenderer(IEndlessGame endlessGame, + IRenderTargetFactory renderTargetFactory, + IEffectRendererFactory effectRendererFactory, + IMapEntityRendererProvider mapEntityRendererProvider, + ICharacterProvider characterProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + IContentProvider contentProvider, + IMapRenderDistanceCalculator mapRenderDistanceCalculator, + ICharacterRendererUpdater characterRendererUpdater, + INPCRendererUpdater npcRendererUpdater, + IDynamicMapObjectUpdater dynamicMapObjectUpdater, + IConfigurationProvider configurationProvider, + IMouseCursorRenderer mouseCursorRenderer, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeRepository clientWindowSizeRepository, + IFixedTimeStepRepository fixedTimeStepRepository) + : base((Game)endlessGame) + { + _renderTargetFactory = renderTargetFactory; + _effectRendererFactory = effectRendererFactory; + _mapEntityRendererProvider = mapEntityRendererProvider; + _characterProvider = characterProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _contentProvider = contentProvider; + _mapRenderDistanceCalculator = mapRenderDistanceCalculator; + _characterRendererUpdater = characterRendererUpdater; + _npcRendererUpdater = npcRendererUpdater; + _dynamicMapObjectUpdater = dynamicMapObjectUpdater; + _configurationProvider = configurationProvider; + _mouseCursorRenderer = mouseCursorRenderer; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _clientWindowSizeRepository = clientWindowSizeRepository; + _fixedTimeStepRepository = fixedTimeStepRepository; + _mapGridEffectRenderers = new Dictionary(); + } - public override void Initialize() - { - _clientWindowSizeRepository.GameWindowSizeChanged += ResizeGameWindow; + public override void Initialize() + { + _clientWindowSizeRepository.GameWindowSizeChanged += ResizeGameWindow; - _mapBaseTarget = _renderTargetFactory.CreateRenderTarget(); - _mapObjectTarget = _renderTargetFactory.CreateRenderTarget(); - _sb = new SpriteBatch(Game.GraphicsDevice); + _mapBaseTarget = _renderTargetFactory.CreateRenderTarget(); + _mapObjectTarget = _renderTargetFactory.CreateRenderTarget(); + _sb = new SpriteBatch(Game.GraphicsDevice); - _mouseCursorRenderer.Initialize(); + _mouseCursorRenderer.Initialize(); - DrawOrder = -10; + DrawOrder = -10; - base.Initialize(); - } + base.Initialize(); + } - public override void Update(GameTime gameTime) + public override void Update(GameTime gameTime) + { + if (_currentMapStateProvider.IsSleepWarp) return; + + if (_lastMapChecksum == null || !_lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) { - if (_currentMapStateProvider.IsSleepWarp) return; + // The dimensions of the map are 0-based in the properties. Adjust to 1-based for RT creation + var widthPlus1 = _currentMapProvider.CurrentMap.Properties.Width + 1; + var heightPlus1 = _currentMapProvider.CurrentMap.Properties.Height + 1; - if (_lastMapChecksum == null || !_lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) + lock (_rt_locker_) { - // The dimensions of the map are 0-based in the properties. Adjust to 1-based for RT creation - var widthPlus1 = _currentMapProvider.CurrentMap.Properties.Width + 1; - var heightPlus1 = _currentMapProvider.CurrentMap.Properties.Height + 1; - - lock (_rt_locker_) - { - _mapBaseTarget.Dispose(); - _mapBaseTarget = _renderTargetFactory.CreateRenderTarget( - (widthPlus1 + heightPlus1) * 32, - (widthPlus1 + heightPlus1) * 16); - _groundDrawn = false; - } + _mapBaseTarget.Dispose(); + _mapBaseTarget = _renderTargetFactory.CreateRenderTarget( + (widthPlus1 + heightPlus1) * 32, + (widthPlus1 + heightPlus1) * 16); + _groundDrawn = false; } + } - if (Visible) - { - _characterRendererUpdater.UpdateCharacters(gameTime); - _npcRendererUpdater.UpdateNPCs(gameTime); - _dynamicMapObjectUpdater.UpdateMapObjects(gameTime); + if (Visible) + { + _characterRendererUpdater.UpdateCharacters(gameTime); + _npcRendererUpdater.UpdateNPCs(gameTime); + _dynamicMapObjectUpdater.UpdateMapObjects(gameTime); - if (MouseOver) - _mouseCursorRenderer.Update(gameTime); + if (MouseOver) + _mouseCursorRenderer.Update(gameTime); - UpdateQuakeState(); + UpdateQuakeState(); - foreach (var target in _mapGridEffectRenderers.Values) - target.Update(); + foreach (var target in _mapGridEffectRenderers.Values) + target.Update(); - if (_fixedTimeStepRepository.IsWalkUpdateFrame || _mapTransitionState.StartTime.HasValue) - { - DrawGroundLayerToRenderTarget(); + if (_fixedTimeStepRepository.IsWalkUpdateFrame || _mapTransitionState.StartTime.HasValue) + { + DrawGroundLayerToRenderTarget(); - if (_fixedTimeStepRepository.IsWalkUpdateFrame) - { - DrawMapToRenderTarget(); - } + if (_fixedTimeStepRepository.IsWalkUpdateFrame) + { + DrawMapToRenderTarget(); } } + } - _lastMapChecksum = _currentMapProvider.CurrentMap.Properties.Checksum; + _lastMapChecksum = _currentMapProvider.CurrentMap.Properties.Checksum; - base.Update(gameTime); - } + base.Update(gameTime); + } + + public override void Draw(GameTime gameTime) + { + if (!Visible) + return; - public override void Draw(GameTime gameTime) + if (_currentMapStateProvider.IsSleepWarp) { - if (!Visible) - return; + lock (_rt_locker_) + { + GraphicsDevice.SetRenderTarget(_mapBaseTarget); + GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); + GraphicsDevice.SetRenderTarget(null); + } - if (_currentMapStateProvider.IsSleepWarp) + _sb.Begin(); + _sb.Draw(_mapBaseTarget, new Vector2(0, 0), Color.White); + _sb.DrawString(_contentProvider.Fonts[Constants.FontSize08], "zzzzz..", new Vector2(_clientWindowSizeRepository.Width / 2 - 15, _clientWindowSizeRepository.Height / 3), Color.White); + _sb.End(); + + // This implementation relies on MapWarpTime being reset in InputHandlerBase + _currentMapStateProvider.MapWarpTime.MatchSome(x => { - lock (_rt_locker_) + if ((DateTime.Now - x).TotalSeconds >= 5) { - GraphicsDevice.SetRenderTarget(_mapBaseTarget); - GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); - GraphicsDevice.SetRenderTarget(null); + _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), 1); } + }); + } + else + { + DrawToSpriteBatch(_sb, gameTime); + } - _sb.Begin(); - _sb.Draw(_mapBaseTarget, new Vector2(0, 0), Color.White); - _sb.DrawString(_contentProvider.Fonts[Constants.FontSize08], "zzzzz..", new Vector2(_clientWindowSizeRepository.Width / 2 - 15, _clientWindowSizeRepository.Height / 3), Color.White); - _sb.End(); + base.Draw(gameTime); + } - // This implementation relies on MapWarpTime being reset in InputHandlerBase - _currentMapStateProvider.MapWarpTime.MatchSome(x => - { - if ((DateTime.Now - x).TotalSeconds >= 5) - { - _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), 1); - } - }); - } - else - { - DrawToSpriteBatch(_sb, gameTime); - } + public void StartMapTransition() + { + _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), 1); + } - base.Draw(gameTime); - } + public void StartEarthquake(int strength) + { + _quakeState = Option.Some(new MapQuakeState(strength)); + } - public void StartMapTransition() - { - _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), 1); - } + public void RedrawGroundLayer() + { + _lastMapChecksum = null; + _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now - new TimeSpan(0, 5, 0)), 255); + } - public void StartEarthquake(int strength) + public void RenderEffect(MapCoordinate coordinate, int effectId) + { + if (!_mapGridEffectRenderers.ContainsKey(coordinate)) { - _quakeState = Option.Some(new MapQuakeState(strength)); + var renderer = _effectRendererFactory.Create(); + _mapGridEffectRenderers[coordinate] = renderer; } - public void RedrawGroundLayer() + if (_mapGridEffectRenderers[coordinate].State == EffectState.Stopped) { - _lastMapChecksum = null; - _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now - new TimeSpan(0, 5, 0)), 255); + _mapGridEffectRenderers[coordinate].PlayEffect(effectId + 1, coordinate); } - - public void RenderEffect(MapCoordinate coordinate, int effectId) + else { - if (!_mapGridEffectRenderers.ContainsKey(coordinate)) - { - var renderer = _effectRendererFactory.Create(); - _mapGridEffectRenderers[coordinate] = renderer; - } - - if (_mapGridEffectRenderers[coordinate].State == EffectState.Stopped) - { - _mapGridEffectRenderers[coordinate].PlayEffect(effectId + 1, coordinate); - } - else - { - _mapGridEffectRenderers[coordinate].QueueEffect(effectId + 1, coordinate); - } + _mapGridEffectRenderers[coordinate].QueueEffect(effectId + 1, coordinate); } + } - public void AnimateMouseClick() => _mouseCursorRenderer.AnimateClick(); + public void AnimateMouseClick() => _mouseCursorRenderer.AnimateClick(); - public void ClearTransientRenderables() - { - _mapGridEffectRenderers.Clear(); - _mouseCursorRenderer.ClearTransientRenderables(); - } + public void ClearTransientRenderables() + { + _mapGridEffectRenderers.Clear(); + _mouseCursorRenderer.ClearTransientRenderables(); + } - private void UpdateQuakeState() + private void UpdateQuakeState() + { + // when quake: + // 1. determine offset target + // 2. incrementally make offset approach closer to the target offset + // 3. when offset target reached, determine new target (random based on magnitude) + // 4. flip direction + // 5. keep going until specific number of "direction flips" has elapsed + + _quakeState.MatchSome(q => { - // when quake: - // 1. determine offset target - // 2. incrementally make offset approach closer to the target offset - // 3. when offset target reached, determine new target (random based on magnitude) - // 4. flip direction - // 5. keep going until specific number of "direction flips" has elapsed - - _quakeState.MatchSome(q => - { - var next = q.NextOffset(); + var next = q.NextOffset(); - if (next.OffsetReached) - next = next.NextState(); + if (next.OffsetReached) + next = next.NextState(); - _quakeState = next.Done - ? Option.None() - : Option.Some(next); - }); - } + _quakeState = next.Done + ? Option.None() + : Option.Some(next); + }); + } - private void DrawGroundLayerToRenderTarget() - { - if (_groundDrawn && !_mapTransitionState.StartTime.HasValue && _lastMapChecksum == _currentMapProvider.CurrentMap.Properties.Checksum) - return; + private void DrawGroundLayerToRenderTarget() + { + if (_groundDrawn && !_mapTransitionState.StartTime.HasValue && _lastMapChecksum == _currentMapProvider.CurrentMap.Properties.Checksum) + return; - _groundDrawn = true; + _groundDrawn = true; - lock (_rt_locker_) - { - GraphicsDevice.SetRenderTarget(_mapBaseTarget); - _sb.Begin(); + lock (_rt_locker_) + { + GraphicsDevice.SetRenderTarget(_mapBaseTarget); + _sb.Begin(); - var renderBounds = new MapRenderBounds(0, _currentMapProvider.CurrentMap.Properties.Height, - 0, _currentMapProvider.CurrentMap.Properties.Width); + var renderBounds = new MapRenderBounds(0, _currentMapProvider.CurrentMap.Properties.Height, + 0, _currentMapProvider.CurrentMap.Properties.Width); - var transitionComplete = true; - for (var row = renderBounds.FirstRow; row <= renderBounds.LastRow; row++) + var transitionComplete = true; + for (var row = renderBounds.FirstRow; row <= renderBounds.LastRow; row++) + { + for (var col = renderBounds.FirstCol; col <= renderBounds.LastCol; ++col) { - for (var col = renderBounds.FirstCol; col <= renderBounds.LastCol; ++col) - { - var alpha = GetAlphaForCoordinates(col, row, _characterProvider.MainCharacter); - transitionComplete &= alpha == 255; - - if (_mapEntityRendererProvider.GroundRenderer.CanRender(row, col)) - _mapEntityRendererProvider.GroundRenderer.RenderElementAt(_sb, row, col, alpha); - } + var alpha = GetAlphaForCoordinates(col, row, _characterProvider.MainCharacter); + transitionComplete &= alpha == 255; + + if (_mapEntityRendererProvider.GroundRenderer.CanRender(row, col)) + _mapEntityRendererProvider.GroundRenderer.RenderElementAt(_sb, row, col, alpha); } + } - if (transitionComplete) - _mapTransitionState = new MapTransitionState(Option.None(), 0); + if (transitionComplete) + _mapTransitionState = new MapTransitionState(Option.None(), 0); - _sb.End(); - GraphicsDevice.SetRenderTarget(null); - } + _sb.End(); + GraphicsDevice.SetRenderTarget(null); } + } + + private void DrawMapToRenderTarget() + { + var immutableCharacter = _characterProvider.MainCharacter; + var gfxToRenderLast = new SortedList>(); - private void DrawMapToRenderTarget() + lock (_rt_locker_) { - var immutableCharacter = _characterProvider.MainCharacter; - var gfxToRenderLast = new SortedList>(); + GraphicsDevice.SetRenderTarget(_mapObjectTarget); + GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); - lock (_rt_locker_) - { - GraphicsDevice.SetRenderTarget(_mapObjectTarget); - GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); + _sb.Begin(); - _sb.Begin(); + var renderBounds = _mapRenderDistanceCalculator.CalculateRenderBounds(immutableCharacter, _currentMapProvider.CurrentMap); - var renderBounds = _mapRenderDistanceCalculator.CalculateRenderBounds(immutableCharacter, _currentMapProvider.CurrentMap); + var hitKeys = new HashSet(); - var hitKeys = new HashSet(); + // render the grid diagonally. hack that fixes some layering issues due to not using a depth buffer for layers + // a better solution would be to use a depth buffer like eomap-js + for (var rowStart = renderBounds.FirstRow; rowStart <= renderBounds.LastRow; rowStart++) + { + var row = rowStart; + var col = renderBounds.FirstCol; + + if (!hitKeys.Add(new MapCoordinate(col, row))) + continue; - // render the grid diagonally. hack that fixes some layering issues due to not using a depth buffer for layers - // a better solution would be to use a depth buffer like eomap-js - for (var rowStart = renderBounds.FirstRow; rowStart <= renderBounds.LastRow; rowStart++) + while (row >= 0) { - var row = rowStart; - var col = renderBounds.FirstCol; + RenderGridSpace(row, col); - if (!hitKeys.Add(new MapCoordinate(col, row))) - continue; + row--; + col++; + } + } - while (row >= 0) - { - RenderGridSpace(row, col); + for (var colStart = renderBounds.FirstCol; colStart <= renderBounds.LastCol; colStart++) + { + var row = renderBounds.LastRow; + var col = colStart; - row--; - col++; - } - } + if (!hitKeys.Add(new MapCoordinate(col, row))) + continue; - for (var colStart = renderBounds.FirstCol; colStart <= renderBounds.LastCol; colStart++) + while (col <= renderBounds.LastCol) { - var row = renderBounds.LastRow; - var col = colStart; - - if (!hitKeys.Add(new MapCoordinate(col, row))) - continue; - - while (col <= renderBounds.LastCol) - { - RenderGridSpace(row, col); - row--; - col++; - } + RenderGridSpace(row, col); + row--; + col++; } + } - foreach (var kvp in gfxToRenderLast) + foreach (var kvp in gfxToRenderLast) + { + foreach (var (pointKey, renderer) in kvp.Value) { - foreach (var (pointKey, renderer) in kvp.Value) - { - var alpha = GetAlphaForCoordinates(pointKey.X, pointKey.Y, immutableCharacter); - renderer.RenderElementAt(_sb, pointKey.Y, pointKey.X, alpha); - } + var alpha = GetAlphaForCoordinates(pointKey.X, pointKey.Y, immutableCharacter); + renderer.RenderElementAt(_sb, pointKey.Y, pointKey.X, alpha); } - - _sb.End(); - GraphicsDevice.SetRenderTarget(null); } - void RenderGridSpace(int row, int col) + _sb.End(); + GraphicsDevice.SetRenderTarget(null); + } + + void RenderGridSpace(int row, int col) + { + var alpha = GetAlphaForCoordinates(col, row, immutableCharacter); + + for (int i = 0; i < _mapEntityRendererProvider.MapEntityRenderers.Count; i++) { - var alpha = GetAlphaForCoordinates(col, row, immutableCharacter); + var renderer = _mapEntityRendererProvider.MapEntityRenderers[i]; + + if (!renderer.CanRender(row, col)) + continue; - for (int i = 0; i < _mapEntityRendererProvider.MapEntityRenderers.Count; i++) + if (renderer.ShouldRenderLast) { - var renderer = _mapEntityRendererProvider.MapEntityRenderers[i]; - - if (!renderer.CanRender(row, col)) - continue; - - if (renderer.ShouldRenderLast) - { - var renderLaterKey = new MapCoordinate(col, row); - if (gfxToRenderLast.ContainsKey(renderer.RenderLayer)) - gfxToRenderLast[renderer.RenderLayer].Add((renderLaterKey, renderer)); - else - gfxToRenderLast.Add(renderer.RenderLayer, new List<(MapCoordinate, IMapEntityRenderer)> { (renderLaterKey, renderer) }); - } + var renderLaterKey = new MapCoordinate(col, row); + if (gfxToRenderLast.ContainsKey(renderer.RenderLayer)) + gfxToRenderLast[renderer.RenderLayer].Add((renderLaterKey, renderer)); else - renderer.RenderElementAt(_sb, row, col, alpha); + gfxToRenderLast.Add(renderer.RenderLayer, new List<(MapCoordinate, IMapEntityRenderer)> { (renderLaterKey, renderer) }); } + else + renderer.RenderElementAt(_sb, row, col, alpha); } } + } - private void DrawToSpriteBatch(SpriteBatch spriteBatch, GameTime gameTime) - { - spriteBatch.Begin(); - - var drawLoc = _gridDrawCoordinateCalculator.CalculateGroundLayerRenderTargetDrawCoordinates(); - var offset = _quakeState.Map(GetOffset).ValueOr(0); + private void DrawToSpriteBatch(SpriteBatch spriteBatch, GameTime gameTime) + { + spriteBatch.Begin(); - lock (_rt_locker_) - { - spriteBatch.Draw(_mapBaseTarget, drawLoc + new Vector2(offset, 0), Color.White); - DrawBaseLayers(spriteBatch); + var drawLoc = _gridDrawCoordinateCalculator.CalculateGroundLayerRenderTargetDrawCoordinates(); + var offset = _quakeState.Map(GetOffset).ValueOr(0); - _mouseCursorRenderer.Draw(spriteBatch, new Vector2(offset, 0)); + lock (_rt_locker_) + { + spriteBatch.Draw(_mapBaseTarget, drawLoc + new Vector2(offset, 0), Color.White); + DrawBaseLayers(spriteBatch); - spriteBatch.Draw(_mapObjectTarget, new Vector2(offset, 0), Color.White); + _mouseCursorRenderer.Draw(spriteBatch, new Vector2(offset, 0)); - foreach (var target in _mapGridEffectRenderers.Values) - { - target.DrawBehindTarget(spriteBatch); - target.DrawInFrontOfTarget(spriteBatch); - } + spriteBatch.Draw(_mapObjectTarget, new Vector2(offset, 0), Color.White); - spriteBatch.End(); + foreach (var target in _mapGridEffectRenderers.Values) + { + target.DrawBehindTarget(spriteBatch); + target.DrawInFrontOfTarget(spriteBatch); } - static float GetOffset(MapQuakeState quakeState) => quakeState.Offset; + spriteBatch.End(); } - private void DrawBaseLayers(SpriteBatch spriteBatch) - { - var offset = _quakeState.Map(GetOffset).ValueOr(0); + static float GetOffset(MapQuakeState quakeState) => quakeState.Offset; + } - var renderBounds = _mapRenderDistanceCalculator.CalculateRenderBounds(_characterProvider.MainCharacter, _currentMapProvider.CurrentMap); + private void DrawBaseLayers(SpriteBatch spriteBatch) + { + var offset = _quakeState.Map(GetOffset).ValueOr(0); - for (var row = renderBounds.FirstRow; row <= renderBounds.LastRow; row++) + var renderBounds = _mapRenderDistanceCalculator.CalculateRenderBounds(_characterProvider.MainCharacter, _currentMapProvider.CurrentMap); + + for (var row = renderBounds.FirstRow; row <= renderBounds.LastRow; row++) + { + for (var col = renderBounds.FirstCol; col <= renderBounds.LastCol; ++col) { - for (var col = renderBounds.FirstCol; col <= renderBounds.LastCol; ++col) - { - var alpha = GetAlphaForCoordinates(col, row, _characterProvider.MainCharacter); + var alpha = GetAlphaForCoordinates(col, row, _characterProvider.MainCharacter); - for (int i = 0; i < _mapEntityRendererProvider.BaseRenderers.Count; i++) - { - var renderer = _mapEntityRendererProvider.BaseRenderers[i]; - if (renderer.CanRender(row, col)) - renderer.RenderElementAt(spriteBatch, row, col, alpha, new Vector2(offset, 0)); - } + for (int i = 0; i < _mapEntityRendererProvider.BaseRenderers.Count; i++) + { + var renderer = _mapEntityRendererProvider.BaseRenderers[i]; + if (renderer.CanRender(row, col)) + renderer.RenderElementAt(spriteBatch, row, col, alpha, new Vector2(offset, 0)); } } - - static float GetOffset(MapQuakeState quakeState) => quakeState.Offset; } - private int GetAlphaForCoordinates(int objX, int objY, EOLib.Domain.Character.Character character) + static float GetOffset(MapQuakeState quakeState) => quakeState.Offset; + } + + private int GetAlphaForCoordinates(int objX, int objY, EOLib.Domain.Character.Character character) + { + if (!_configurationProvider.ShowTransition) { - if (!_configurationProvider.ShowTransition) - { - _mapTransitionState = new MapTransitionState(Option.None(), 0); - return 255; - } + _mapTransitionState = new MapTransitionState(Option.None(), 0); + return 255; + } - //get the farther away of X or Y coordinate for the map object - var metric = Math.Max(Math.Abs(objX - character.RenderProperties.MapX), - Math.Abs(objY - character.RenderProperties.MapY)); + //get the farther away of X or Y coordinate for the map object + var metric = Math.Max(Math.Abs(objX - character.RenderProperties.MapX), + Math.Abs(objY - character.RenderProperties.MapY)); - int alpha = 0; - if (!_mapTransitionState.StartTime.HasValue || - metric < _mapTransitionState.TransitionMetric || - _mapTransitionState.TransitionMetric == 0) - { - alpha = 255; - } - else if (metric == _mapTransitionState.TransitionMetric) - { - alpha = _mapTransitionState.StartTime.Map(HandleStartTime).ValueOr(alpha); - } - else - alpha = 0; + int alpha = 0; + if (!_mapTransitionState.StartTime.HasValue || + metric < _mapTransitionState.TransitionMetric || + _mapTransitionState.TransitionMetric == 0) + { + alpha = 255; + } + else if (metric == _mapTransitionState.TransitionMetric) + { + alpha = _mapTransitionState.StartTime.Map(HandleStartTime).ValueOr(alpha); + } + else + alpha = 0; - return alpha; + return alpha; - int HandleStartTime(DateTime startTime) - { - var ms = (DateTime.Now - startTime).TotalMilliseconds; + int HandleStartTime(DateTime startTime) + { + var ms = (DateTime.Now - startTime).TotalMilliseconds; - if (ms / TRANSITION_TIME_MS >= 1) - _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), _mapTransitionState.TransitionMetric + 1); + if (ms / TRANSITION_TIME_MS >= 1) + _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), _mapTransitionState.TransitionMetric + 1); - return (int)Math.Round(ms / TRANSITION_TIME_MS * 255); - } + return (int)Math.Round(ms / TRANSITION_TIME_MS * 255); } + } - private void ResizeGameWindow(object sender, EventArgs e) + private void ResizeGameWindow(object sender, EventArgs e) + { + lock (_rt_locker_) { - lock (_rt_locker_) - { - _mapObjectTarget.Dispose(); - _mapObjectTarget = _renderTargetFactory.CreateRenderTarget(_clientWindowSizeRepository.Width, _clientWindowSizeRepository.Height); - } + _mapObjectTarget.Dispose(); + _mapObjectTarget = _renderTargetFactory.CreateRenderTarget(_clientWindowSizeRepository.Width, _clientWindowSizeRepository.Height); } + } - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) + { + if (disposing) { - if (disposing) + lock (_rt_locker_) { - lock (_rt_locker_) - { - _mapBaseTarget.Dispose(); - _mapObjectTarget.Dispose(); - } - _sb.Dispose(); - _mouseCursorRenderer.Dispose(); - - _npcRendererUpdater.Dispose(); - _characterRendererUpdater.Dispose(); + _mapBaseTarget.Dispose(); + _mapObjectTarget.Dispose(); } + _sb.Dispose(); + _mouseCursorRenderer.Dispose(); - base.Dispose(disposing); + _npcRendererUpdater.Dispose(); + _characterRendererUpdater.Dispose(); } + + base.Dispose(disposing); } +} - internal struct MapTransitionState - { - internal static MapTransitionState Default => new MapTransitionState(Option.None(), 0); +internal struct MapTransitionState +{ + internal static MapTransitionState Default => new MapTransitionState(Option.None(), 0); - internal Option StartTime { get; } + internal Option StartTime { get; } - internal int TransitionMetric { get; } + internal int TransitionMetric { get; } - internal MapTransitionState(Option startTime, int transitionMetric) - : this() - { - StartTime = startTime; - TransitionMetric = transitionMetric; - } - } - - internal struct MapQuakeState + internal MapTransitionState(Option startTime, int transitionMetric) + : this() { - private static readonly Random _random = new Random(); + StartTime = startTime; + TransitionMetric = transitionMetric; + } +} - internal static MapQuakeState Default => new MapQuakeState(); +internal struct MapQuakeState +{ + private static readonly Random _random = new Random(); - internal int Magnitude { get; } + internal static MapQuakeState Default => new MapQuakeState(); - internal float Offset { get; } + internal int Magnitude { get; } - internal float OffsetTarget { get; } + internal float Offset { get; } - internal bool OffsetReached => Math.Abs(Offset) >= Math.Abs(OffsetTarget); + internal float OffsetTarget { get; } - internal int Flips { get; } + internal bool OffsetReached => Math.Abs(Offset) >= Math.Abs(OffsetTarget); - internal int FlipsMax => Magnitude == 0 ? 0 : 10 + Magnitude * 2; + internal int Flips { get; } - internal bool Done => Flips >= FlipsMax; + internal int FlipsMax => Magnitude == 0 ? 0 : 10 + Magnitude * 2; - internal MapQuakeState(int magnitude) - : this(magnitude, 0, 0) { } + internal bool Done => Flips >= FlipsMax; - private MapQuakeState(int magnitude, float offset, int flips) - : this(magnitude, offset, NewOffsetTarget(magnitude), flips) { } + internal MapQuakeState(int magnitude) + : this(magnitude, 0, 0) { } - private MapQuakeState(int magnitude, float offset, float offsetTarget, int flips) - { - Magnitude = magnitude; - Offset = offset; - OffsetTarget = offsetTarget; - Flips = flips; - } + private MapQuakeState(int magnitude, float offset, int flips) + : this(magnitude, offset, NewOffsetTarget(magnitude), flips) { } - internal MapQuakeState NextOffset() - { - var nextOffset = Offset + OffsetTarget / 4f; - return new MapQuakeState(Magnitude, nextOffset, OffsetTarget, Flips); - } + private MapQuakeState(int magnitude, float offset, float offsetTarget, int flips) + { + Magnitude = magnitude; + Offset = offset; + OffsetTarget = offsetTarget; + Flips = flips; + } - internal MapQuakeState NextState() - { - var flip = -OffsetTarget / Math.Abs(OffsetTarget); - var offset = OffsetTarget + 1 * flip; - var nextOffsetTarget = NewOffsetTarget(Magnitude) * flip; + internal MapQuakeState NextOffset() + { + var nextOffset = Offset + OffsetTarget / 4f; + return new MapQuakeState(Magnitude, nextOffset, OffsetTarget, Flips); + } - return new MapQuakeState(Magnitude, offset, nextOffsetTarget, Flips + 1); - } + internal MapQuakeState NextState() + { + var flip = -OffsetTarget / Math.Abs(OffsetTarget); + var offset = OffsetTarget + 1 * flip; + var nextOffsetTarget = NewOffsetTarget(Magnitude) * flip; - private static float NewOffsetTarget(int magnitude) => 16 + 3 * _random.Next(0, (int)(magnitude * 1.5)); + return new MapQuakeState(Magnitude, offset, nextOffsetTarget, Flips + 1); } + + private static float NewOffsetTarget(int magnitude) => 16 + 3 * _random.Next(0, (int)(magnitude * 1.5)); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MiniMapRenderer.cs b/EndlessClient/Rendering/Map/MiniMapRenderer.cs index 56cdbc24b..8ffc6ccac 100644 --- a/EndlessClient/Rendering/Map/MiniMapRenderer.cs +++ b/EndlessClient/Rendering/Map/MiniMapRenderer.cs @@ -11,273 +11,272 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering.Map +namespace EndlessClient.Rendering.Map; + +public class MiniMapRenderer : XNAControl { - public class MiniMapRenderer : XNAControl + private const int TileWidth = 28; + private const int TileHeight = 14; + + private enum MiniMapGfx { - private const int TileWidth = 28; - private const int TileHeight = 14; + UpLine = 0, + LeftLine = 1, + Corner = 2, + Solid = 3, //wall or obstacle + Green = 4, //other player + Red = 5, //attackable npc + Orange = 6, //you! + Blue = 7, //tile that you can interact with + Purple = 8, //npc + NUM_GRIDS = 9, + } - private enum MiniMapGfx - { - UpLine = 0, - LeftLine = 1, - Corner = 2, - Solid = 3, //wall or obstacle - Green = 4, //other player - Red = 5, //attackable npc - Orange = 6, //you! - Blue = 7, //tile that you can interact with - Purple = 8, //npc - NUM_GRIDS = 9, - } + private readonly object _rt_locker_ = new object(); + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly Texture2D _miniMapTexture; + + private RenderTarget2D _miniMapTarget; + private IReadOnlyList _lastMapChecksum; + + public MiniMapRenderer(INativeGraphicsManager nativeGraphicsManager, + IRenderTargetFactory renderTargetFactory, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterProvider characterProvider, + IENFFileProvider enfFileProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) + { + _renderTargetFactory = renderTargetFactory; + _clientWindowSizeProvider = clientWindowSizeProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _characterProvider = characterProvider; + _enfFileProvider = enfFileProvider; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _miniMapTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 45, true); + } - private readonly object _rt_locker_ = new object(); - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly Texture2D _miniMapTexture; - - private RenderTarget2D _miniMapTarget; - private IReadOnlyList _lastMapChecksum; - - public MiniMapRenderer(INativeGraphicsManager nativeGraphicsManager, - IRenderTargetFactory renderTargetFactory, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterProvider characterProvider, - IENFFileProvider enfFileProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) - { - _renderTargetFactory = renderTargetFactory; - _clientWindowSizeProvider = clientWindowSizeProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _characterProvider = characterProvider; - _enfFileProvider = enfFileProvider; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _miniMapTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 45, true); - } + public override void Initialize() + { + Visible = true; + DrawOrder = 0; - public override void Initialize() - { - Visible = true; - DrawOrder = 0; + base.Initialize(); + } - base.Initialize(); - } + protected override bool ShouldDraw() + { + return _currentMapStateProvider.ShowMiniMap && base.ShouldDraw(); + } - protected override bool ShouldDraw() + protected override void OnUpdateControl(GameTime gameTime) + { + if (_lastMapChecksum == null || !_lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) { - return _currentMapStateProvider.ShowMiniMap && base.ShouldDraw(); - } + // The dimensions of the map are 0-based in the properties. Adjust to 1-based for RT creation + var widthPlus1 = _currentMapProvider.CurrentMap.Properties.Width + 1; + var heightPlus1 = _currentMapProvider.CurrentMap.Properties.Height + 1; - protected override void OnUpdateControl(GameTime gameTime) - { - if (_lastMapChecksum == null || !_lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) + lock (_rt_locker_) { - // The dimensions of the map are 0-based in the properties. Adjust to 1-based for RT creation - var widthPlus1 = _currentMapProvider.CurrentMap.Properties.Width + 1; - var heightPlus1 = _currentMapProvider.CurrentMap.Properties.Height + 1; - - lock (_rt_locker_) - { - _miniMapTarget?.Dispose(); - _miniMapTarget = _renderTargetFactory.CreateRenderTarget( - (widthPlus1 + heightPlus1) * TileWidth, - (widthPlus1 + heightPlus1) * TileHeight); - } - - DrawFixedMapElementsToRenderTarget(); + _miniMapTarget?.Dispose(); + _miniMapTarget = _renderTargetFactory.CreateRenderTarget( + (widthPlus1 + heightPlus1) * TileWidth, + (widthPlus1 + heightPlus1) * TileHeight); } - _lastMapChecksum = _currentMapProvider.CurrentMap.Properties.Checksum; - - base.OnUpdateControl(gameTime); + DrawFixedMapElementsToRenderTarget(); } - protected override void OnDrawControl(GameTime gameTime) - { - lock (_rt_locker_) - { - _spriteBatch.Begin(); - - var baseTargetDrawLoc = _gridDrawCoordinateCalculator.CalculateGroundLayerRenderTargetDrawCoordinates(isMiniMap: true, TileWidth, TileHeight); - _spriteBatch.Draw(_miniMapTarget, baseTargetDrawLoc, Color.White); + _lastMapChecksum = _currentMapProvider.CurrentMap.Properties.Checksum; - var entities = new IMapEntity[] { _characterProvider.MainCharacter } - .Concat(_currentMapStateProvider.Characters) - .Concat(_currentMapStateProvider.NPCs); - - foreach (var entity in entities) - { - var loc = GetMiniMapDrawCoordinates(entity.X, entity.Y); - var miniMapRectSrc = GetSourceRectangleForEntity(entity); - DrawGridBox(loc, null, miniMapRectSrc); - } + base.OnUpdateControl(gameTime); + } - _spriteBatch.End(); - } + protected override void OnDrawControl(GameTime gameTime) + { + lock (_rt_locker_) + { + _spriteBatch.Begin(); - base.OnDrawControl(gameTime); - } + var baseTargetDrawLoc = _gridDrawCoordinateCalculator.CalculateGroundLayerRenderTargetDrawCoordinates(isMiniMap: true, TileWidth, TileHeight); + _spriteBatch.Draw(_miniMapTarget, baseTargetDrawLoc, Color.White); - private (MiniMapGfx? EdgeGfx, Rectangle SourceRect) GetSourceRectangleForGridSpace(int col, int row) - { - var tileSpec = _currentMapProvider.CurrentMap.Tiles[row, col]; + var entities = new IMapEntity[] { _characterProvider.MainCharacter } + .Concat(_currentMapStateProvider.Characters) + .Concat(_currentMapStateProvider.NPCs); - switch (tileSpec) + foreach (var entity in entities) { - case TileSpec.Wall: - case TileSpec.FakeWall: - return (GetEdge(), GetSourceRect(MiniMapGfx.Solid)); - case TileSpec.BankVault: - case TileSpec.ChairAll: - case TileSpec.ChairDown: - case TileSpec.ChairLeft: - case TileSpec.ChairRight: - case TileSpec.ChairUp: - case TileSpec.ChairDownRight: - case TileSpec.ChairUpLeft: - case TileSpec.Chest: - case TileSpec.JammedDoor: - // Unknown TileSpecs 10-15 have been confirmed in the vanilla client to show a Blue ! on the minimap - case (TileSpec)10: - case (TileSpec)11: - case (TileSpec)12: - case (TileSpec)13: - case (TileSpec)14: - case (TileSpec)15: - return (GetEdge(), GetSourceRect(MiniMapGfx.Blue)); - case TileSpec.MapEdge: - return (null, Rectangle.Empty); + var loc = GetMiniMapDrawCoordinates(entity.X, entity.Y); + var miniMapRectSrc = GetSourceRectangleForEntity(entity); + DrawGridBox(loc, null, miniMapRectSrc); } - if (_currentMapProvider.CurrentMap.Warps[row, col] != null) - { - var doorType = _currentMapProvider.CurrentMap.Warps[row, col].DoorType; - return (GetEdge(), GetSourceRect(doorType != DoorSpec.NoDoor ? MiniMapGfx.Blue : MiniMapGfx.UpLine)); - } + _spriteBatch.End(); + } + + base.OnDrawControl(gameTime); + } - return (GetEdge(), Rectangle.Empty); + private (MiniMapGfx? EdgeGfx, Rectangle SourceRect) GetSourceRectangleForGridSpace(int col, int row) + { + var tileSpec = _currentMapProvider.CurrentMap.Tiles[row, col]; - MiniMapGfx? GetEdge() - { - if (tileSpec == TileSpec.MapEdge) - return null; - - var tiles = _currentMapProvider.CurrentMap.Tiles; - - if (col - 1 >= 0 && tiles[row, col - 1] == TileSpec.MapEdge && - row - 1 >= 0 && tiles[row - 1, col] == TileSpec.MapEdge) - return null; - else if (col == 0 || (col - 1 >= 0 && tiles[row, col - 1] == TileSpec.MapEdge)) - return MiniMapGfx.UpLine; - else if (row == 0 || (row - 1 >= 0 && tiles[row - 1, col] == TileSpec.MapEdge)) - return MiniMapGfx.LeftLine; - else - return MiniMapGfx.Corner; - } + switch (tileSpec) + { + case TileSpec.Wall: + case TileSpec.FakeWall: + return (GetEdge(), GetSourceRect(MiniMapGfx.Solid)); + case TileSpec.BankVault: + case TileSpec.ChairAll: + case TileSpec.ChairDown: + case TileSpec.ChairLeft: + case TileSpec.ChairRight: + case TileSpec.ChairUp: + case TileSpec.ChairDownRight: + case TileSpec.ChairUpLeft: + case TileSpec.Chest: + case TileSpec.JammedDoor: + // Unknown TileSpecs 10-15 have been confirmed in the vanilla client to show a Blue ! on the minimap + case (TileSpec)10: + case (TileSpec)11: + case (TileSpec)12: + case (TileSpec)13: + case (TileSpec)14: + case (TileSpec)15: + return (GetEdge(), GetSourceRect(MiniMapGfx.Blue)); + case TileSpec.MapEdge: + return (null, Rectangle.Empty); } - private Rectangle GetSourceRectangleForEntity(IMapEntity mapEntity) + if (_currentMapProvider.CurrentMap.Warps[row, col] != null) { - if (_characterProvider.MainCharacter == mapEntity) - { - return GetSourceRect(MiniMapGfx.Orange); - } + var doorType = _currentMapProvider.CurrentMap.Warps[row, col].DoorType; + return (GetEdge(), GetSourceRect(doorType != DoorSpec.NoDoor ? MiniMapGfx.Blue : MiniMapGfx.UpLine)); + } - return mapEntity switch - { - EOLib.Domain.NPC.NPC n => GetNPCSourceRectangle(n), - EOLib.Domain.Character.Character c => GetSourceRect(MiniMapGfx.Green), - _ => Rectangle.Empty - }; + return (GetEdge(), Rectangle.Empty); - Rectangle GetNPCSourceRectangle(EOLib.Domain.NPC.NPC npc) - { - var npcType = _enfFileProvider.ENFFile[npc.ID].Type; - return GetSourceRect(npcType == NPCType.Aggressive || npcType == NPCType.Passive ? MiniMapGfx.Red : MiniMapGfx.Purple); - } + MiniMapGfx? GetEdge() + { + if (tileSpec == TileSpec.MapEdge) + return null; + + var tiles = _currentMapProvider.CurrentMap.Tiles; + + if (col - 1 >= 0 && tiles[row, col - 1] == TileSpec.MapEdge && + row - 1 >= 0 && tiles[row - 1, col] == TileSpec.MapEdge) + return null; + else if (col == 0 || (col - 1 >= 0 && tiles[row, col - 1] == TileSpec.MapEdge)) + return MiniMapGfx.UpLine; + else if (row == 0 || (row - 1 >= 0 && tiles[row - 1, col] == TileSpec.MapEdge)) + return MiniMapGfx.LeftLine; + else + return MiniMapGfx.Corner; } + } - private void DrawFixedMapElementsToRenderTarget() + private Rectangle GetSourceRectangleForEntity(IMapEntity mapEntity) + { + if (_characterProvider.MainCharacter == mapEntity) { - if (_lastMapChecksum != null && _lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) - return; - - GraphicsDevice.SetRenderTarget(_miniMapTarget); - GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); - _spriteBatch.Begin(); - - // the height is used to offset the 0 point of the grid, which is TileHeight units per tile in the height of the map - var height = _currentMapProvider.CurrentMap.Properties.Height + 1; + return GetSourceRect(MiniMapGfx.Orange); + } - for (int row = 0; row <= _currentMapProvider.CurrentMap.Properties.Height; ++row) - { - for (int col = 0; col <= _currentMapProvider.CurrentMap.Properties.Width; ++col) - { - var drawLoc = _gridDrawCoordinateCalculator.CalculateRawRenderCoordinatesFromGridUnits(col, row, TileWidth, TileHeight) + new Vector2(TileHeight * height, 0); - var (edgeGfx, miniMapRectSrc) = GetSourceRectangleForGridSpace(col, row); - DrawGridBox(drawLoc, edgeGfx, miniMapRectSrc); - } - } + return mapEntity switch + { + EOLib.Domain.NPC.NPC n => GetNPCSourceRectangle(n), + EOLib.Domain.Character.Character c => GetSourceRect(MiniMapGfx.Green), + _ => Rectangle.Empty + }; - _spriteBatch.End(); - GraphicsDevice.SetRenderTarget(null); + Rectangle GetNPCSourceRectangle(EOLib.Domain.NPC.NPC npc) + { + var npcType = _enfFileProvider.ENFFile[npc.ID].Type; + return GetSourceRect(npcType == NPCType.Aggressive || npcType == NPCType.Passive ? MiniMapGfx.Red : MiniMapGfx.Purple); } + } - private void DrawGridBox(Vector2 loc, MiniMapGfx? edgeGfx, Rectangle gridSpaceSourceRect) - { - if (edgeGfx != null) - { - var src = gridSpaceSourceRect.Equals(Rectangle.Empty) - ? GetSourceRect(MiniMapGfx.UpLine) - : gridSpaceSourceRect; + private void DrawFixedMapElementsToRenderTarget() + { + if (_lastMapChecksum != null && _lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) + return; - _spriteBatch.Draw(_miniMapTexture, loc, - new Rectangle((int)edgeGfx * src.Width, 0, src.Width, src.Height), - Color.FromNonPremultiplied(255, 255, 255, 128)); - } + GraphicsDevice.SetRenderTarget(_miniMapTarget); + GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); + _spriteBatch.Begin(); + + // the height is used to offset the 0 point of the grid, which is TileHeight units per tile in the height of the map + var height = _currentMapProvider.CurrentMap.Properties.Height + 1; - if (!gridSpaceSourceRect.IsEmpty) + for (int row = 0; row <= _currentMapProvider.CurrentMap.Properties.Height; ++row) + { + for (int col = 0; col <= _currentMapProvider.CurrentMap.Properties.Width; ++col) { - _spriteBatch.Draw(_miniMapTexture, loc, gridSpaceSourceRect, Color.FromNonPremultiplied(255, 255, 255, 128)); + var drawLoc = _gridDrawCoordinateCalculator.CalculateRawRenderCoordinatesFromGridUnits(col, row, TileWidth, TileHeight) + new Vector2(TileHeight * height, 0); + var (edgeGfx, miniMapRectSrc) = GetSourceRectangleForGridSpace(col, row); + DrawGridBox(drawLoc, edgeGfx, miniMapRectSrc); } } - private Vector2 GetMiniMapDrawCoordinates(int x, int y) - { - var widthFactor = _clientWindowSizeProvider.Width / 2; - var heightFactor = _clientWindowSizeProvider.Resizable - ? _clientWindowSizeProvider.Height / 2 // 144 = 480 * .45, viewport height factor - : _clientWindowSizeProvider.Height * 3 / 10 - 2; + _spriteBatch.End(); + GraphicsDevice.SetRenderTarget(null); + } - var tileWidthFactor = TileWidth / 2; - var tileHeightFactor = TileHeight / 2; + private void DrawGridBox(Vector2 loc, MiniMapGfx? edgeGfx, Rectangle gridSpaceSourceRect) + { + if (edgeGfx != null) + { + var src = gridSpaceSourceRect.Equals(Rectangle.Empty) + ? GetSourceRect(MiniMapGfx.UpLine) + : gridSpaceSourceRect; - return new Vector2(x * tileWidthFactor - y * tileWidthFactor + widthFactor, - y * tileHeightFactor + x * tileHeightFactor + heightFactor) - GetCharacterOffset(); + _spriteBatch.Draw(_miniMapTexture, loc, + new Rectangle((int)edgeGfx * src.Width, 0, src.Width, src.Height), + Color.FromNonPremultiplied(255, 255, 255, 128)); } - private Rectangle GetSourceRect(MiniMapGfx gfx) + if (!gridSpaceSourceRect.IsEmpty) { - var delta = _miniMapTexture.Width / (int)MiniMapGfx.NUM_GRIDS; - return new Rectangle((int)gfx * delta, 0, delta, _miniMapTexture.Height); + _spriteBatch.Draw(_miniMapTexture, loc, gridSpaceSourceRect, Color.FromNonPremultiplied(255, 255, 255, 128)); } + } - private Vector2 GetCharacterOffset() - { - var tileWidthFactor = TileWidth / 2; - var tileHeightFactor = TileHeight / 2; + private Vector2 GetMiniMapDrawCoordinates(int x, int y) + { + var widthFactor = _clientWindowSizeProvider.Width / 2; + var heightFactor = _clientWindowSizeProvider.Resizable + ? _clientWindowSizeProvider.Height / 2 // 144 = 480 * .45, viewport height factor + : _clientWindowSizeProvider.Height * 3 / 10 - 2; - var (cx, cy) = (_characterProvider.MainCharacter.X, _characterProvider.MainCharacter.Y); - return new Vector2(cx * tileWidthFactor - cy * tileWidthFactor, cx * tileHeightFactor + cy * tileHeightFactor); - } + var tileWidthFactor = TileWidth / 2; + var tileHeightFactor = TileHeight / 2; + + return new Vector2(x * tileWidthFactor - y * tileWidthFactor + widthFactor, + y * tileHeightFactor + x * tileHeightFactor + heightFactor) - GetCharacterOffset(); + } + + private Rectangle GetSourceRect(MiniMapGfx gfx) + { + var delta = _miniMapTexture.Width / (int)MiniMapGfx.NUM_GRIDS; + return new Rectangle((int)gfx * delta, 0, delta, _miniMapTexture.Height); + } + + private Vector2 GetCharacterOffset() + { + var tileWidthFactor = TileWidth / 2; + var tileHeightFactor = TileHeight / 2; + + var (cx, cy) = (_characterProvider.MainCharacter.X, _characterProvider.MainCharacter.Y); + return new Vector2(cx * tileWidthFactor - cy * tileWidthFactor, cx * tileHeightFactor + cy * tileHeightFactor); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs b/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs index 2bccedcba..2eadef11f 100644 --- a/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs +++ b/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs @@ -5,54 +5,53 @@ using EOLib.Graphics; using EOLib.IO.Repositories; -namespace EndlessClient.Rendering.Map -{ - [AutoMappedType] - public class MiniMapRendererFactory : IMiniMapRendererFactory - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IRenderTargetFactory _renderTargetFactory; +namespace EndlessClient.Rendering.Map; - public MiniMapRendererFactory(INativeGraphicsManager nativeGraphicsManager, - IRenderTargetFactory renderTargetFactory, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterProvider characterProvider, - IENFFileProvider enfFileProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) - { - _nativeGraphicsManager = nativeGraphicsManager; - _clientWindowSizeProvider = clientWindowSizeProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _characterProvider = characterProvider; - _enfFileProvider = enfFileProvider; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _renderTargetFactory = renderTargetFactory; - } +[AutoMappedType] +public class MiniMapRendererFactory : IMiniMapRendererFactory +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IRenderTargetFactory _renderTargetFactory; - public MiniMapRenderer Create() - { - return new MiniMapRenderer(_nativeGraphicsManager, - _renderTargetFactory, - _clientWindowSizeProvider, - _currentMapProvider, - _currentMapStateProvider, - _characterProvider, - _enfFileProvider, - _gridDrawCoordinateCalculator); - } + public MiniMapRendererFactory(INativeGraphicsManager nativeGraphicsManager, + IRenderTargetFactory renderTargetFactory, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterProvider characterProvider, + IENFFileProvider enfFileProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) + { + _nativeGraphicsManager = nativeGraphicsManager; + _clientWindowSizeProvider = clientWindowSizeProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _characterProvider = characterProvider; + _enfFileProvider = enfFileProvider; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _renderTargetFactory = renderTargetFactory; } - public interface IMiniMapRendererFactory + public MiniMapRenderer Create() { - MiniMapRenderer Create(); + return new MiniMapRenderer(_nativeGraphicsManager, + _renderTargetFactory, + _clientWindowSizeProvider, + _currentMapProvider, + _currentMapStateProvider, + _characterProvider, + _enfFileProvider, + _gridDrawCoordinateCalculator); } +} + +public interface IMiniMapRendererFactory +{ + MiniMapRenderer Create(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs index f431effcb..ef919192d 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs @@ -5,82 +5,81 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public abstract class BaseMapEntityRenderer : IMapEntityRenderer { - public abstract class BaseMapEntityRenderer : IMapEntityRenderer - { - private static readonly Dictionary _layerOffsets; + private static readonly Dictionary _layerOffsets; - private static DateTime _lastFrameTime = DateTime.Now; - protected static int _frameIndex = 0; + private static DateTime _lastFrameTime = DateTime.Now; + protected static int _frameIndex = 0; - static BaseMapEntityRenderer() + static BaseMapEntityRenderer() + { + _layerOffsets = new Dictionary { - _layerOffsets = new Dictionary - { - { MapRenderLayer.Ground, Point.Zero }, - { MapRenderLayer.Item, new Point(0, 16) }, - { MapRenderLayer.Objects, new Point(-2, -2) }, - { MapRenderLayer.Overlay, new Point(-2, -2) }, - { MapRenderLayer.DownWall, new Point(0, -1) }, - { MapRenderLayer.RightWall, new Point(32, -1) }, - { MapRenderLayer.Roof, new Point(-32, -64) }, - { MapRenderLayer.OnTop, new Point(-32, -32) }, - { MapRenderLayer.Shadows, new Point(-24, -12) }, - { MapRenderLayer.Overlay2, new Point(-2, -2) }, - { MapRenderLayer.MainCharacter, Point.Zero }, - }; - } + { MapRenderLayer.Ground, Point.Zero }, + { MapRenderLayer.Item, new Point(0, 16) }, + { MapRenderLayer.Objects, new Point(-2, -2) }, + { MapRenderLayer.Overlay, new Point(-2, -2) }, + { MapRenderLayer.DownWall, new Point(0, -1) }, + { MapRenderLayer.RightWall, new Point(32, -1) }, + { MapRenderLayer.Roof, new Point(-32, -64) }, + { MapRenderLayer.OnTop, new Point(-32, -32) }, + { MapRenderLayer.Shadows, new Point(-24, -12) }, + { MapRenderLayer.Overlay2, new Point(-2, -2) }, + { MapRenderLayer.MainCharacter, Point.Zero }, + }; + } - protected readonly ICharacterProvider _characterProvider; - protected readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + protected readonly ICharacterProvider _characterProvider; + protected readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - public abstract MapRenderLayer RenderLayer { get; } + public abstract MapRenderLayer RenderLayer { get; } - public bool ShouldRenderLast => RenderLayer == MapRenderLayer.Overlay2 || RenderLayer == MapRenderLayer.MainCharacterTransparent; + public bool ShouldRenderLast => RenderLayer == MapRenderLayer.Overlay2 || RenderLayer == MapRenderLayer.MainCharacterTransparent; - protected abstract int RenderDistance { get; } + protected abstract int RenderDistance { get; } - protected BaseMapEntityRenderer(ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _characterProvider = characterProvider; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _clientWindowSizeProvider = clientWindowSizeProvider; - } + protected BaseMapEntityRenderer(ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _characterProvider = characterProvider; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _clientWindowSizeProvider = clientWindowSizeProvider; + } - public virtual bool CanRender(int row, int col) - { - if (!ElementExistsAt(row, col)) - return false; + public virtual bool CanRender(int row, int col) + { + if (!ElementExistsAt(row, col)) + return false; - var props = _characterProvider.MainCharacter.RenderProperties; + var props = _characterProvider.MainCharacter.RenderProperties; - var rowDelta = Math.Abs(props.MapY - row); - var colDelta = Math.Abs(props.MapX - col); + var rowDelta = Math.Abs(props.MapY - row); + var colDelta = Math.Abs(props.MapX - col); - var renderDistanceScaledX = (int)Math.Ceiling(_clientWindowSizeProvider.Width / 640.0 * RenderDistance); - var renderDistanceScaledY = (int)Math.Ceiling(_clientWindowSizeProvider.Height / 480.0 * RenderDistance); + var renderDistanceScaledX = (int)Math.Ceiling(_clientWindowSizeProvider.Width / 640.0 * RenderDistance); + var renderDistanceScaledY = (int)Math.Ceiling(_clientWindowSizeProvider.Height / 480.0 * RenderDistance); - return rowDelta <= renderDistanceScaledX && colDelta <= renderDistanceScaledY; - } + return rowDelta <= renderDistanceScaledX && colDelta <= renderDistanceScaledY; + } - protected abstract bool ElementExistsAt(int row, int col); + protected abstract bool ElementExistsAt(int row, int col); - public virtual void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + public virtual void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + if ((DateTime.Now - _lastFrameTime).TotalMilliseconds > 600) { - if ((DateTime.Now - _lastFrameTime).TotalMilliseconds > 600) - { - _lastFrameTime = DateTime.Now; - _frameIndex = (_frameIndex + 1) % 4; - } + _lastFrameTime = DateTime.Now; + _frameIndex = (_frameIndex + 1) % 4; } + } - protected virtual Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) - { - return _gridDrawCoordinateCalculator.CalculateDrawCoordinatesFromGridUnits(gridX, gridY) + _layerOffsets[RenderLayer].ToVector2(); - } + protected virtual Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) + { + return _gridDrawCoordinateCalculator.CalculateDrawCoordinatesFromGridUnits(gridX, gridY) + _layerOffsets[RenderLayer].ToVector2(); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs index 17182a148..d9c68e5fd 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs @@ -6,101 +6,100 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public class GroundLayerRenderer : BaseMapEntityRenderer { - public class GroundLayerRenderer : BaseMapEntityRenderer - { - protected const int ANIMATED_TILE_MIN_WIDTH = 128; + protected const int ANIMATED_TILE_MIN_WIDTH = 128; - protected readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; + protected readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; - public override MapRenderLayer RenderLayer => MapRenderLayer.Ground; + public override MapRenderLayer RenderLayer => MapRenderLayer.Ground; - protected override int RenderDistance => 10; + protected override int RenderDistance => 10; - public GroundLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - } + public GroundLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + } - protected override Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) - { - // the height is used to offset the 0 point of the grid, which is 32 units per tile in the height of the map - var height = CurrentMap.Properties.Height; - var offset = new Vector2(32 * height, 0); + protected override Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) + { + // the height is used to offset the 0 point of the grid, which is 32 units per tile in the height of the map + var height = CurrentMap.Properties.Height; + var offset = new Vector2(32 * height, 0); - var basePosition = _gridDrawCoordinateCalculator.CalculateRawRenderCoordinatesFromGridUnits(gridX, gridY); - return basePosition + offset; - } + var basePosition = _gridDrawCoordinateCalculator.CalculateRawRenderCoordinatesFromGridUnits(gridX, gridY); + return basePosition + offset; + } + + public override bool CanRender(int row, int col) => ElementExistsAt(row, col); + + protected override bool ElementExistsAt(int row, int col) + { + return (CurrentMap.Properties.FillTile > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) || + CurrentMap.GFX[MapLayer.GroundTile][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + base.RenderElementAt(spriteBatch, row, col, alpha); - public override bool CanRender(int row, int col) => ElementExistsAt(row, col); + var pos = GetDrawCoordinatesFromGridUnits(col, row); - protected override bool ElementExistsAt(int row, int col) + int tileGFX; + Texture2D tileTexture; + if ((tileGFX = CurrentMap.Properties.FillTile) > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) { - return (CurrentMap.Properties.FillTile > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) || - CurrentMap.GFX[MapLayer.GroundTile][row, col] > 0; + tileTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileGFX, true); } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + else if ((tileGFX = CurrentMap.GFX[MapLayer.GroundTile][row, col]) > 0) + { + tileTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileGFX, true); + } + else { - base.RenderElementAt(spriteBatch, row, col, alpha); - - var pos = GetDrawCoordinatesFromGridUnits(col, row); - - int tileGFX; - Texture2D tileTexture; - if ((tileGFX = CurrentMap.Properties.FillTile) > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) - { - tileTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileGFX, true); - } - else if ((tileGFX = CurrentMap.GFX[MapLayer.GroundTile][row, col]) > 0) - { - tileTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileGFX, true); - } - else - { - return; - } - - var src = tileTexture.Width >= ANIMATED_TILE_MIN_WIDTH - ? new Rectangle?(new Rectangle((tileTexture.Width / 4) * _frameIndex, 0, tileTexture.Width / 4, tileTexture.Height)) - : null; - spriteBatch.Draw(tileTexture, pos + additionalOffset, src, Color.FromNonPremultiplied(255, 255, 255, alpha)); + return; } - protected IMapFile CurrentMap => _currentMapProvider.CurrentMap; + var src = tileTexture.Width >= ANIMATED_TILE_MIN_WIDTH + ? new Rectangle?(new Rectangle((tileTexture.Width / 4) * _frameIndex, 0, tileTexture.Width / 4, tileTexture.Height)) + : null; + spriteBatch.Draw(tileTexture, pos + additionalOffset, src, Color.FromNonPremultiplied(255, 255, 255, alpha)); } - public class AnimatedGroundLayerRenderer : GroundLayerRenderer + protected IMapFile CurrentMap => _currentMapProvider.CurrentMap; +} + +public class AnimatedGroundLayerRenderer : GroundLayerRenderer +{ + public AnimatedGroundLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) { - public AnimatedGroundLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - } + } - protected override bool ElementExistsAt(int row, int col) - { - int tileId; - var tileExists = ((tileId = CurrentMap.Properties.FillTile) > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) || - (tileId = CurrentMap.GFX[MapLayer.GroundTile][row, col]) > 0; + protected override bool ElementExistsAt(int row, int col) + { + int tileId; + var tileExists = ((tileId = CurrentMap.Properties.FillTile) > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) || + (tileId = CurrentMap.GFX[MapLayer.GroundTile][row, col]) > 0; - return tileExists && _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileId, true).Width >= ANIMATED_TILE_MIN_WIDTH; - } + return tileExists && _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileId, true).Width >= ANIMATED_TILE_MIN_WIDTH; + } - protected override Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) - { - return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(gridX, gridY); - } + protected override Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) + { + return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(gridX, gridY); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs index 9315a11a5..4d0ee8a12 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs @@ -3,16 +3,15 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public interface IMapEntityRenderer { - public interface IMapEntityRenderer - { - MapRenderLayer RenderLayer { get; } + MapRenderLayer RenderLayer { get; } - bool ShouldRenderLast { get; } + bool ShouldRenderLast { get; } - bool CanRender(int row, int col); + bool CanRender(int row, int col); - void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalPixelOffset = default); - } + void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalPixelOffset = default); } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs index 90c1e5422..cac29588d 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs @@ -1,14 +1,13 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public interface IMapEntityRendererProvider { - public interface IMapEntityRendererProvider - { - IMapEntityRenderer GroundRenderer { get; } + IMapEntityRenderer GroundRenderer { get; } - IReadOnlyList BaseRenderers { get; } + IReadOnlyList BaseRenderers { get; } - IReadOnlyList MapEntityRenderers { get; } - } + IReadOnlyList MapEntityRenderers { get; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs index f45bc97d2..d0f5e3627 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs @@ -5,49 +5,48 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public class MainCharacterEntityRenderer : BaseMapEntityRenderer { - public class MainCharacterEntityRenderer : BaseMapEntityRenderer - { - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly bool _transparent; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly bool _transparent; - public MainCharacterEntityRenderer(ICharacterProvider characterProvider, - ICharacterRendererProvider characterRendererProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - bool transparent) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _characterRendererProvider = characterRendererProvider; - _transparent = transparent; - } + public MainCharacterEntityRenderer(ICharacterProvider characterProvider, + ICharacterRendererProvider characterRendererProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + bool transparent) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _characterRendererProvider = characterRendererProvider; + _transparent = transparent; + } - public override MapRenderLayer RenderLayer => - _transparent ? MapRenderLayer.MainCharacterTransparent : MapRenderLayer.MainCharacter; + public override MapRenderLayer RenderLayer => + _transparent ? MapRenderLayer.MainCharacterTransparent : MapRenderLayer.MainCharacter; - protected override int RenderDistance => 1; + protected override int RenderDistance => 1; - protected override bool ElementExistsAt(int row, int col) + protected override bool ElementExistsAt(int row, int col) + { + var rp = _characterProvider.MainCharacter.RenderProperties; + if (rp.CurrentAction != CharacterActionState.Walking) { - var rp = _characterProvider.MainCharacter.RenderProperties; - if (rp.CurrentAction != CharacterActionState.Walking) - { - return row == rp.MapY && col == rp.MapX; - } - else - { - return row == rp.GetDestinationY() && col == rp.GetDestinationX(); - } + return row == rp.MapY && col == rp.MapX; } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + else { - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => - { - cr.Transparent = _transparent; - cr.DrawToSpriteBatch(spriteBatch); - }); + return row == rp.GetDestinationY() && col == rp.GetDestinationX(); } } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => + { + cr.Transparent = _transparent; + cr.DrawToSpriteBatch(spriteBatch); + }); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs index 8b7819708..a1f0403de 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs @@ -6,47 +6,46 @@ using System; using System.Linq; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public class MapItemLayerRenderer : BaseMapEntityRenderer { - public class MapItemLayerRenderer : BaseMapEntityRenderer - { - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IMapItemGraphicProvider _mapItemGraphicProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - public override MapRenderLayer RenderLayer => MapRenderLayer.Item; + public override MapRenderLayer RenderLayer => MapRenderLayer.Item; - protected override int RenderDistance => 16; + protected override int RenderDistance => 16; - public MapItemLayerRenderer(ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapStateProvider currentMapStateProvider, - IMapItemGraphicProvider mapItemGraphicProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _currentMapStateProvider = currentMapStateProvider; - _mapItemGraphicProvider = mapItemGraphicProvider; - } + public MapItemLayerRenderer(ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapStateProvider currentMapStateProvider, + IMapItemGraphicProvider mapItemGraphicProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _currentMapStateProvider = currentMapStateProvider; + _mapItemGraphicProvider = mapItemGraphicProvider; + } - protected override bool ElementExistsAt(int row, int col) - { - return _currentMapStateProvider.MapItems.ContainsKey(new MapCoordinate(col, row)); - } + protected override bool ElementExistsAt(int row, int col) + { + return _currentMapStateProvider.MapItems.ContainsKey(new MapCoordinate(col, row)); + } - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + var items = _currentMapStateProvider.MapItems[new MapCoordinate(col, row)]; + + foreach (var item in items.OrderBy(item => item.UniqueID)) { - var items = _currentMapStateProvider.MapItems[new MapCoordinate(col, row)]; - - foreach (var item in items.OrderBy(item => item.UniqueID)) - { - var itemPos = GetDrawCoordinatesFromGridUnits(col, row); - var itemTexture = _mapItemGraphicProvider.GetItemGraphic(item.ItemID, item.Amount); - - spriteBatch.Draw(itemTexture, - new Vector2(itemPos.X - (int)Math.Round(itemTexture.Width / 2.0), - itemPos.Y - (int)Math.Round(itemTexture.Height / 2.0)) + additionalOffset, - Color.FromNonPremultiplied(255, 255, 255, alpha)); - } + var itemPos = GetDrawCoordinatesFromGridUnits(col, row); + var itemTexture = _mapItemGraphicProvider.GetItemGraphic(item.ItemID, item.Amount); + + spriteBatch.Draw(itemTexture, + new Vector2(itemPos.X - (int)Math.Round(itemTexture.Width / 2.0), + itemPos.Y - (int)Math.Round(itemTexture.Height / 2.0)) + additionalOffset, + Color.FromNonPremultiplied(255, 255, 255, alpha)); } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs index 3677dffa8..36b8ec6b4 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs @@ -11,82 +11,81 @@ using System.Linq; using DomainCharacter = EOLib.Domain.Character.Character; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public class MapObjectLayerRenderer : BaseMapEntityRenderer { - public class MapObjectLayerRenderer : BaseMapEntityRenderer - { - private const int TIMED_SPIKE_DURATION_MS = 1000; + private const int TIMED_SPIKE_DURATION_MS = 1000; - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; - public override MapRenderLayer RenderLayer => MapRenderLayer.Objects; + public override MapRenderLayer RenderLayer => MapRenderLayer.Objects; - protected override int RenderDistance => 22; + protected override int RenderDistance => 22; - public MapObjectLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapStateProvider currentMapStateProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - } + public MapObjectLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapStateProvider currentMapStateProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + } - protected override bool ElementExistsAt(int row, int col) - { - return MapFile.GFX[MapLayer.Objects][row, col] > 0; - } + protected override bool ElementExistsAt(int row, int col) + { + return MapFile.GFX[MapLayer.Objects][row, col] > 0; + } - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + if (MapFile.Tiles[row, col] == TileSpec.SpikesTrap) { - if (MapFile.Tiles[row, col] == TileSpec.SpikesTrap) + var loc = new MapCoordinate(col, row); + var mainCharacterAt = CharacterAt(_characterProvider.MainCharacter, loc); + if (!mainCharacterAt && _currentMapStateProvider.Characters.ContainsKey(loc)) { - var loc = new MapCoordinate(col, row); - var mainCharacterAt = CharacterAt(_characterProvider.MainCharacter, loc); - if (!mainCharacterAt && _currentMapStateProvider.Characters.ContainsKey(loc)) - { - var anyOtherCharactersAt = _currentMapStateProvider.Characters[loc].Any(x => CharacterAt(x, loc)); - if (!anyOtherCharactersAt) - { - return; - } - } - else if (!mainCharacterAt) + var anyOtherCharactersAt = _currentMapStateProvider.Characters[loc].Any(x => CharacterAt(x, loc)); + if (!anyOtherCharactersAt) { return; } } - else if (MapFile.Tiles[row, col] == TileSpec.SpikesTimed) + else if (!mainCharacterAt) { - var shouldRender = _currentMapStateProvider.LastTimedSpikeEvent - .Map(time => (DateTime.Now - time).TotalMilliseconds <= TIMED_SPIKE_DURATION_MS) - .ValueOr(false); - if (!shouldRender) - return; + return; } + } + else if (MapFile.Tiles[row, col] == TileSpec.SpikesTimed) + { + var shouldRender = _currentMapStateProvider.LastTimedSpikeEvent + .Map(time => (DateTime.Now - time).TotalMilliseconds <= TIMED_SPIKE_DURATION_MS) + .ValueOr(false); + if (!shouldRender) + return; + } - int gfxNum = MapFile.GFX[MapLayer.Objects][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapObjects, gfxNum, true); + int gfxNum = MapFile.GFX[MapLayer.Objects][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapObjects, gfxNum, true); - var pos = GetDrawCoordinatesFromGridUnits(col, row); - pos -= new Vector2(gfx.Width / 2, gfx.Height - 32); + var pos = GetDrawCoordinatesFromGridUnits(col, row); + pos -= new Vector2(gfx.Width / 2, gfx.Height - 32); - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); + } - private IMapFile MapFile => _currentMapProvider.CurrentMap; + private IMapFile MapFile => _currentMapProvider.CurrentMap; - private static bool CharacterAt(DomainCharacter c, MapCoordinate tile) - { - return c.RenderProperties.CurrentAction != CharacterActionState.Walking - ? tile == c.RenderProperties.Coordinates() - : tile == c.RenderProperties.DestinationCoordinates(); - } + private static bool CharacterAt(DomainCharacter c, MapCoordinate tile) + { + return c.RenderProperties.CurrentAction != CharacterActionState.Walking + ? tile == c.RenderProperties.Coordinates() + : tile == c.RenderProperties.DestinationCoordinates(); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs index ac63c5438..2551ba8d5 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs @@ -6,51 +6,50 @@ using Microsoft.Xna.Framework.Graphics; using System.Linq; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public class NPCEntityRenderer : BaseMapEntityRenderer { - public class NPCEntityRenderer : BaseMapEntityRenderer + private readonly INPCRendererProvider _npcRendererProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + + public NPCEntityRenderer(ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + INPCRendererProvider npcRendererProvider, + ICurrentMapStateProvider currentMapStateProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) { - private readonly INPCRendererProvider _npcRendererProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - - public NPCEntityRenderer(ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - INPCRendererProvider npcRendererProvider, - ICurrentMapStateProvider currentMapStateProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _npcRendererProvider = npcRendererProvider; - _currentMapStateProvider = currentMapStateProvider; - } + _npcRendererProvider = npcRendererProvider; + _currentMapStateProvider = currentMapStateProvider; + } - public override MapRenderLayer RenderLayer => MapRenderLayer.Npc; + public override MapRenderLayer RenderLayer => MapRenderLayer.Npc; - protected override int RenderDistance => 16; + protected override int RenderDistance => 16; - protected override bool ElementExistsAt(int row, int col) - { - var coordinate = new MapCoordinate(col, row); - return _currentMapStateProvider.NPCs.ContainsKey(coordinate) || _npcRendererProvider.DyingNPCs.ContainsKey(coordinate); - } + protected override bool ElementExistsAt(int row, int col) + { + var coordinate = new MapCoordinate(col, row); + return _currentMapStateProvider.NPCs.ContainsKey(coordinate) || _npcRendererProvider.DyingNPCs.ContainsKey(coordinate); + } - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + var coordinate = new MapCoordinate(col, row); + var indicesToRender = _npcRendererProvider.DyingNPCs.ContainsKey(coordinate) + ? _currentMapStateProvider.NPCs.ContainsKey(coordinate) + ? Enumerable.Repeat(_npcRendererProvider.DyingNPCs[coordinate], 1).Concat(_currentMapStateProvider.NPCs[coordinate].Select(n => n.Index)) + : Enumerable.Repeat(_npcRendererProvider.DyingNPCs[coordinate], 1) + : _currentMapStateProvider.NPCs[coordinate].Select(n => n.Index); + + foreach (var index in indicesToRender) { - var coordinate = new MapCoordinate(col, row); - var indicesToRender = _npcRendererProvider.DyingNPCs.ContainsKey(coordinate) - ? _currentMapStateProvider.NPCs.ContainsKey(coordinate) - ? Enumerable.Repeat(_npcRendererProvider.DyingNPCs[coordinate], 1).Concat(_currentMapStateProvider.NPCs[coordinate].Select(n => n.Index)) - : Enumerable.Repeat(_npcRendererProvider.DyingNPCs[coordinate], 1) - : _currentMapStateProvider.NPCs[coordinate].Select(n => n.Index); - - foreach (var index in indicesToRender) - { - if (!_npcRendererProvider.NPCRenderers.ContainsKey(index) || - _npcRendererProvider.NPCRenderers[index] == null) - continue; - - _npcRendererProvider.NPCRenderers[index].DrawToSpriteBatch(spriteBatch); - } + if (!_npcRendererProvider.NPCRenderers.ContainsKey(index) || + _npcRendererProvider.NPCRenderers[index] == null) + continue; + + _npcRendererProvider.NPCRenderers[index].DrawToSpriteBatch(spriteBatch); } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs index 32a32620f..cce88a4dc 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs @@ -6,42 +6,41 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public class OnTopLayerRenderer : BaseMapEntityRenderer { - public class OnTopLayerRenderer : BaseMapEntityRenderer + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; + + public override MapRenderLayer RenderLayer => MapRenderLayer.OnTop; + + protected override int RenderDistance => 12; + + public OnTopLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + } + + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.OverlayTile][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - - public override MapRenderLayer RenderLayer => MapRenderLayer.OnTop; - - protected override int RenderDistance => 12; - - public OnTopLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - } - - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.OverlayTile][row, col] > 0; - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - int gfxNum = CurrentMap.GFX[MapLayer.OverlayTile][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, gfxNum, true); - - var pos = GetDrawCoordinatesFromGridUnits(col, row); - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } - - private IMapFile CurrentMap => _currentMapProvider.CurrentMap; + int gfxNum = CurrentMap.GFX[MapLayer.OverlayTile][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, gfxNum, true); + + var pos = GetDrawCoordinatesFromGridUnits(col, row); + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); } + + private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs index 25dd1a64e..ab6b1b444 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs @@ -6,45 +6,44 @@ using Microsoft.Xna.Framework.Graphics; using System.Linq; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public class OtherCharacterEntityRenderer : BaseMapEntityRenderer { - public class OtherCharacterEntityRenderer : BaseMapEntityRenderer + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + + public OtherCharacterEntityRenderer(ICharacterProvider characterProvider, + ICharacterRendererProvider characterRendererProvider, + ICurrentMapStateProvider currentMapStateProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) { - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - - public OtherCharacterEntityRenderer(ICharacterProvider characterProvider, - ICharacterRendererProvider characterRendererProvider, - ICurrentMapStateProvider currentMapStateProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _characterRendererProvider = characterRendererProvider; - _currentMapStateProvider = currentMapStateProvider; - } + _characterRendererProvider = characterRendererProvider; + _currentMapStateProvider = currentMapStateProvider; + } - public override MapRenderLayer RenderLayer => MapRenderLayer.OtherCharacters; + public override MapRenderLayer RenderLayer => MapRenderLayer.OtherCharacters; - protected override int RenderDistance => 16; + protected override int RenderDistance => 16; - protected override bool ElementExistsAt(int row, int col) - { - return _currentMapStateProvider.Characters.ContainsKey(new MapCoordinate(col, row)); - } + protected override bool ElementExistsAt(int row, int col) + { + return _currentMapStateProvider.Characters.ContainsKey(new MapCoordinate(col, row)); + } - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - var toRender = _currentMapStateProvider.Characters[new MapCoordinate(col, row)]; + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + var toRender = _currentMapStateProvider.Characters[new MapCoordinate(col, row)]; - foreach (var id in toRender.Select(x => x.ID)) - { - if (!_characterRendererProvider.CharacterRenderers.ContainsKey(id) || - _characterRendererProvider.CharacterRenderers[id] == null) - return; + foreach (var id in toRender.Select(x => x.ID)) + { + if (!_characterRendererProvider.CharacterRenderers.ContainsKey(id) || + _characterRendererProvider.CharacterRenderers[id] == null) + return; - _characterRendererProvider.CharacterRenderers[id].DrawToSpriteBatch(spriteBatch); - } + _characterRendererProvider.CharacterRenderers[id].DrawToSpriteBatch(spriteBatch); } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs index e23dc5240..3845c7d4f 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs @@ -6,44 +6,43 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers -{ - public class Overlay2LayerRenderer : BaseMapEntityRenderer - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; +namespace EndlessClient.Rendering.MapEntityRenderers; - public override MapRenderLayer RenderLayer => MapRenderLayer.Overlay2; +public class Overlay2LayerRenderer : BaseMapEntityRenderer +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; - protected override int RenderDistance => 12; + public override MapRenderLayer RenderLayer => MapRenderLayer.Overlay2; - public Overlay2LayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - } + protected override int RenderDistance => 12; - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.Overlay2][row, col] > 0; - } + public Overlay2LayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + } - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - int gfxNum = CurrentMap.GFX[MapLayer.Overlay2][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapOverlay, gfxNum, true); + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.Overlay2][row, col] > 0; + } - var pos = GetDrawCoordinatesFromGridUnits(col, row); - pos -= new Vector2((float)System.Math.Floor(gfx.Width / 2f), gfx.Height - 32); + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + int gfxNum = CurrentMap.GFX[MapLayer.Overlay2][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapOverlay, gfxNum, true); - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } + var pos = GetDrawCoordinatesFromGridUnits(col, row); + pos -= new Vector2((float)System.Math.Floor(gfx.Width / 2f), gfx.Height - 32); - private IMapFile CurrentMap => _currentMapProvider.CurrentMap; + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); } + + private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs index b6ff7111e..ad170a8ce 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs @@ -6,44 +6,43 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers -{ - public class OverlayLayerRenderer : BaseMapEntityRenderer - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; +namespace EndlessClient.Rendering.MapEntityRenderers; - public override MapRenderLayer RenderLayer => MapRenderLayer.Overlay; +public class OverlayLayerRenderer : BaseMapEntityRenderer +{ + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; - protected override int RenderDistance => 14; + public override MapRenderLayer RenderLayer => MapRenderLayer.Overlay; - public OverlayLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - } + protected override int RenderDistance => 14; - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.OverlayObjects][row, col] > 0; - } + public OverlayLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + } - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - int gfxNum = CurrentMap.GFX[MapLayer.OverlayObjects][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapOverlay, gfxNum, true); + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.OverlayObjects][row, col] > 0; + } - var pos = GetDrawCoordinatesFromGridUnits(col, row); - pos -= new Vector2(gfx.Width / 2, gfx.Height - 32); + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + int gfxNum = CurrentMap.GFX[MapLayer.OverlayObjects][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapOverlay, gfxNum, true); - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } + var pos = GetDrawCoordinatesFromGridUnits(col, row); + pos -= new Vector2(gfx.Width / 2, gfx.Height - 32); - private IMapFile CurrentMap => _currentMapProvider.CurrentMap; + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); } + + private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs index b42cff2e9..ada554756 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs @@ -6,42 +6,41 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public class RoofLayerRenderer : BaseMapEntityRenderer { - public class RoofLayerRenderer : BaseMapEntityRenderer + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; + + public override MapRenderLayer RenderLayer => MapRenderLayer.Roof; + + protected override int RenderDistance => 12; + + public RoofLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + } + + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.Roof][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - - public override MapRenderLayer RenderLayer => MapRenderLayer.Roof; - - protected override int RenderDistance => 12; - - public RoofLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - } - - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.Roof][row, col] > 0; - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - int gfxNum = CurrentMap.GFX[MapLayer.Roof][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapWallTop, gfxNum, true); - - var pos = GetDrawCoordinatesFromGridUnits(col, row); - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } - - private IMapFile CurrentMap => _currentMapProvider.CurrentMap; + int gfxNum = CurrentMap.GFX[MapLayer.Roof][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapWallTop, gfxNum, true); + + var pos = GetDrawCoordinatesFromGridUnits(col, row); + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); } + + private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs index d6ca67d0f..64d45c991 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs @@ -7,52 +7,51 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public class ShadowLayerRenderer : BaseMapEntityRenderer { - public class ShadowLayerRenderer : BaseMapEntityRenderer + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IConfigurationProvider _configurationProvider; + + public override MapRenderLayer RenderLayer => MapRenderLayer.Shadows; + + protected override int RenderDistance => 16; + + public ShadowLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + IConfigurationProvider configurationProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + _configurationProvider = configurationProvider; + } + + public override bool CanRender(int row, int col) + { + return _configurationProvider.ShowShadows && base.CanRender(row, col); + } + + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.Shadow][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IConfigurationProvider _configurationProvider; - - public override MapRenderLayer RenderLayer => MapRenderLayer.Shadows; - - protected override int RenderDistance => 16; - - public ShadowLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - IConfigurationProvider configurationProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - _configurationProvider = configurationProvider; - } - - public override bool CanRender(int row, int col) - { - return _configurationProvider.ShowShadows && base.CanRender(row, col); - } - - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.Shadow][row, col] > 0; - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - int gfxNum = CurrentMap.GFX[MapLayer.Shadow][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.Shadows, gfxNum, true); - - var pos = GetDrawCoordinatesFromGridUnits(col, row); - pos = new Vector2(pos.X - 32, pos.Y); - - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, 255 / 5)); - } - - private IMapFile CurrentMap => _currentMapProvider.CurrentMap; + int gfxNum = CurrentMap.GFX[MapLayer.Shadow][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.Shadows, gfxNum, true); + + var pos = GetDrawCoordinatesFromGridUnits(col, row); + pos = new Vector2(pos.X - 32, pos.Y); + + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, 255 / 5)); } + + private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs index eb8687289..6d5260106 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs @@ -7,105 +7,104 @@ using Microsoft.Xna.Framework.Graphics; using System.Linq; -namespace EndlessClient.Rendering.MapEntityRenderers +namespace EndlessClient.Rendering.MapEntityRenderers; + +public abstract class WallLayerRendererBase : BaseMapEntityRenderer { - public abstract class WallLayerRendererBase : BaseMapEntityRenderer - { - private const int WALL_FRAME_WIDTH = 68; - - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - - protected override int RenderDistance => 20; - - protected WallLayerRendererBase(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapStateProvider currentMapStateProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - } - - protected void DrawWall(SpriteBatch spriteBatch, int row, int col, int alpha, int gfxNum, Vector2 additionalOffset = default) - { - if (_currentMapStateProvider.OpenDoors.Any(openDoor => openDoor.X == col && openDoor.Y == row)) - gfxNum++; - - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapWalls, gfxNum, true); - - var gfxWidthDelta = gfx.Width / 4; - var src = gfx.Width > WALL_FRAME_WIDTH - ? new Rectangle?(new Rectangle(gfxWidthDelta * _frameIndex, 0, gfxWidthDelta, gfx.Height)) - : null; - - var pos = GetDrawCoordinatesFromGridUnits(col, row); - pos -= new Vector2(32, gfx.Height - 32); - - spriteBatch.Draw(gfx, pos + additionalOffset, src, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } - - protected IMapFile CurrentMap => _currentMapProvider.CurrentMap; - } + private const int WALL_FRAME_WIDTH = 68; - public class DownWallLayerRenderer : WallLayerRendererBase - { - public override MapRenderLayer RenderLayer => MapRenderLayer.DownWall; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + + protected override int RenderDistance => 20; - public DownWallLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + protected WallLayerRendererBase(INativeGraphicsManager nativeGraphicsManager, ICurrentMapProvider currentMapProvider, ICharacterProvider characterProvider, IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, IClientWindowSizeProvider clientWindowSizeProvider, ICurrentMapStateProvider currentMapStateProvider) - : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider, currentMapStateProvider) - { - } - - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.WallRowsDown][row, col] > 0; - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - base.RenderElementAt(spriteBatch, row, col, alpha, additionalOffset); - - var gfxNum = CurrentMap.GFX[MapLayer.WallRowsDown][row, col]; - DrawWall(spriteBatch, row, col, alpha, gfxNum, additionalOffset); - } + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; } - public class RightWallLayerRenderer : WallLayerRendererBase + protected void DrawWall(SpriteBatch spriteBatch, int row, int col, int alpha, int gfxNum, Vector2 additionalOffset = default) { - public override MapRenderLayer RenderLayer => MapRenderLayer.RightWall; - - public RightWallLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapStateProvider currentMapStateProvider) - : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider, currentMapStateProvider) - { - } - - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.WallRowsRight][row, col] > 0; - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - base.RenderElementAt(spriteBatch, row, col, alpha, additionalOffset); - - var gfxNum = CurrentMap.GFX[MapLayer.WallRowsRight][row, col]; - DrawWall(spriteBatch, row, col, alpha, gfxNum, additionalOffset); - } + if (_currentMapStateProvider.OpenDoors.Any(openDoor => openDoor.X == col && openDoor.Y == row)) + gfxNum++; + + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapWalls, gfxNum, true); + + var gfxWidthDelta = gfx.Width / 4; + var src = gfx.Width > WALL_FRAME_WIDTH + ? new Rectangle?(new Rectangle(gfxWidthDelta * _frameIndex, 0, gfxWidthDelta, gfx.Height)) + : null; + + var pos = GetDrawCoordinatesFromGridUnits(col, row); + pos -= new Vector2(32, gfx.Height - 32); + + spriteBatch.Draw(gfx, pos + additionalOffset, src, Color.FromNonPremultiplied(255, 255, 255, alpha)); + } + + protected IMapFile CurrentMap => _currentMapProvider.CurrentMap; +} + +public class DownWallLayerRenderer : WallLayerRendererBase +{ + public override MapRenderLayer RenderLayer => MapRenderLayer.DownWall; + + public DownWallLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapStateProvider currentMapStateProvider) + : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider, currentMapStateProvider) + { + } + + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.WallRowsDown][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + base.RenderElementAt(spriteBatch, row, col, alpha, additionalOffset); + + var gfxNum = CurrentMap.GFX[MapLayer.WallRowsDown][row, col]; + DrawWall(spriteBatch, row, col, alpha, gfxNum, additionalOffset); + } +} + +public class RightWallLayerRenderer : WallLayerRendererBase +{ + public override MapRenderLayer RenderLayer => MapRenderLayer.RightWall; + + public RightWallLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapStateProvider currentMapStateProvider) + : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider, currentMapStateProvider) + { + } + + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.WallRowsRight][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + base.RenderElementAt(spriteBatch, row, col, alpha, additionalOffset); + + var gfxNum = CurrentMap.GFX[MapLayer.WallRowsRight][row, col]; + DrawWall(spriteBatch, row, col, alpha, gfxNum, additionalOffset); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs b/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs index c6dfe7e0d..0350ebe36 100644 --- a/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs @@ -4,64 +4,63 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata +namespace EndlessClient.Rendering.Metadata; + +[AutoMappedType(IsSingleton = true)] +public class EffectMetadataProvider : IMetadataProvider { - [AutoMappedType(IsSingleton = true)] - public class EffectMetadataProvider : IMetadataProvider - { - public IReadOnlyDictionary DefaultMetadata => _metadata; + public IReadOnlyDictionary DefaultMetadata => _metadata; - private readonly Dictionary _metadata; - private readonly IGFXMetadataLoader _metadataLoader; + private readonly Dictionary _metadata; + private readonly IGFXMetadataLoader _metadataLoader; - public EffectMetadataProvider(IGFXMetadataLoader metadataLoader) + public EffectMetadataProvider(IGFXMetadataLoader metadataLoader) + { + // source: https://docs.google.com/spreadsheets/d/1DQgN4r2cH6HA2ydn4M6CpUJlClWXXBemosYP57k_o5I/edit#gid=0 + // todo: flickering effects are off-by-one. Fix metadata in the GFX (EndlessClient.Binaries), here, and in EffectSpriteInfo where a -1 is applied to the random choice + _metadata = new Dictionary { - // source: https://docs.google.com/spreadsheets/d/1DQgN4r2cH6HA2ydn4M6CpUJlClWXXBemosYP57k_o5I/edit#gid=0 - // todo: flickering effects are off-by-one. Fix metadata in the GFX (EndlessClient.Binaries), here, and in EffectSpriteInfo where a -1 is applied to the random choice - _metadata = new Dictionary - { - { 1, new EffectMetadata(true, true, true, SoundEffectID.PotionOfFlamesEffect, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // small fire - { 2, new EffectMetadata(false, false, true, SoundEffectID.PotionOfLoveEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // hearts - { 3, new EffectMetadata(false, true, true, SoundEffectID.AdminWarp, 8, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin warp - { 4, new EffectMetadata(false, false, true, SoundEffectID.AdminWarp, 8, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin warp 2 - { 5, new EffectMetadata(false, false, true, SoundEffectID.PotionOfFireworksEffect, 7, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // celebrate - { 6, new EffectMetadata(false, true, true, SoundEffectID.PotionOfSparklesEffect, 5, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // schwing - { 7, new EffectMetadata(true, false, false, SoundEffectID.PotionOfEvilTerrorEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // evil - { 8, new EffectMetadata(true, false, false, SoundEffectID.PotionOfEvilTerrorEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // terror - { 9, new EffectMetadata(true, false, false, SoundEffectID.Water, 6, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // water splash - { 10, new EffectMetadata(false, true, true, SoundEffectID.Heal, 5, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // heal - { 11, new EffectMetadata(false, false, true, SoundEffectID.Thunder, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // small thunder - { 12, new EffectMetadata(false, false, true, 0, 4, 8, 0, 0, EffectAnimationType.Static, null, null, null) }, // snow - { 13, new EffectMetadata(true, true, false, SoundEffectID.UltimaBlastSpell, 4, 3, 0, 0, EffectAnimationType.Static, null, null, null) }, // ultima - { 14, new EffectMetadata(true, true, false, SoundEffectID.PotionOfFlamesEffect, 6, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // fire ball - { 15, new EffectMetadata(false, true, true, SoundEffectID.ShieldSpell, 6, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // shield - { 16, new EffectMetadata(true, false, true, SoundEffectID.RingOfFireSpell, 4, 3, 0, 0, EffectAnimationType.Static, null, null, null) }, // ring of fire - { 17, new EffectMetadata(false, true, true, SoundEffectID.IceBlastSpell1, 7, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // ice blast - { 18, new EffectMetadata(false, false, true, SoundEffectID.EnergyBallSpell, 7, 1, 0, 0, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(-10), null, null) }, // energy ball - { 19, new EffectMetadata(true, true, true, SoundEffectID.WhirlSpell, 4, 2, 0, -10, EffectAnimationType.Position, null, new PositionOffsetEffectMetadata(new[] { -20, 0, 20, 0 }, new[] { 0, 14, 0, -14 }), null) }, // whirl / tornado - { 20, new EffectMetadata(false, true, false, SoundEffectID.AuraSpell, 5, 3, 0, -12, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // aura - { 21, new EffectMetadata(false, false, true, SoundEffectID.BouldersSpell, 7, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // boulders - { 22, new EffectMetadata(true, true, false, SoundEffectID.HeavenSpell, 5, 4, 0, -114, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // heaven - { 23, new EffectMetadata(true, true, false, SoundEffectID.IceBlastSpell2, 6, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // blue flame - { 24, new EffectMetadata(true, true, false, SoundEffectID.HeavenSpell, 5, 4, 0, -114, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // dark beam - { 25, new EffectMetadata(false, false, true, SoundEffectID.AdminHide, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin hide - { 26, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark hand - { 27, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark skull - { 28, new EffectMetadata(false, false, true, SoundEffectID.FireBlastSpell, 4, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // fire blast - { 29, new EffectMetadata(false, false, true, SoundEffectID.TentaclesSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // tentacles - { 30, new EffectMetadata(true, false, true, SoundEffectID.PowerWindSpell, 6, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // power wind - { 31, new EffectMetadata(true, false, true, SoundEffectID.MagicWhirlSpell, 15, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // magic whirl - { 32, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 6, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark bite - { 33, new EffectMetadata(true, true, false, SoundEffectID.AuraSpell, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // shell - { 34, new EffectMetadata(true, true, false, SoundEffectID.EnergyBallSpell, 5, 1, 0, -44, EffectAnimationType.Static, null, null, null) } // green flame - }; - _metadataLoader = metadataLoader; - } + { 1, new EffectMetadata(true, true, true, SoundEffectID.PotionOfFlamesEffect, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // small fire + { 2, new EffectMetadata(false, false, true, SoundEffectID.PotionOfLoveEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // hearts + { 3, new EffectMetadata(false, true, true, SoundEffectID.AdminWarp, 8, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin warp + { 4, new EffectMetadata(false, false, true, SoundEffectID.AdminWarp, 8, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin warp 2 + { 5, new EffectMetadata(false, false, true, SoundEffectID.PotionOfFireworksEffect, 7, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // celebrate + { 6, new EffectMetadata(false, true, true, SoundEffectID.PotionOfSparklesEffect, 5, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // schwing + { 7, new EffectMetadata(true, false, false, SoundEffectID.PotionOfEvilTerrorEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // evil + { 8, new EffectMetadata(true, false, false, SoundEffectID.PotionOfEvilTerrorEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // terror + { 9, new EffectMetadata(true, false, false, SoundEffectID.Water, 6, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // water splash + { 10, new EffectMetadata(false, true, true, SoundEffectID.Heal, 5, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // heal + { 11, new EffectMetadata(false, false, true, SoundEffectID.Thunder, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // small thunder + { 12, new EffectMetadata(false, false, true, 0, 4, 8, 0, 0, EffectAnimationType.Static, null, null, null) }, // snow + { 13, new EffectMetadata(true, true, false, SoundEffectID.UltimaBlastSpell, 4, 3, 0, 0, EffectAnimationType.Static, null, null, null) }, // ultima + { 14, new EffectMetadata(true, true, false, SoundEffectID.PotionOfFlamesEffect, 6, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // fire ball + { 15, new EffectMetadata(false, true, true, SoundEffectID.ShieldSpell, 6, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // shield + { 16, new EffectMetadata(true, false, true, SoundEffectID.RingOfFireSpell, 4, 3, 0, 0, EffectAnimationType.Static, null, null, null) }, // ring of fire + { 17, new EffectMetadata(false, true, true, SoundEffectID.IceBlastSpell1, 7, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // ice blast + { 18, new EffectMetadata(false, false, true, SoundEffectID.EnergyBallSpell, 7, 1, 0, 0, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(-10), null, null) }, // energy ball + { 19, new EffectMetadata(true, true, true, SoundEffectID.WhirlSpell, 4, 2, 0, -10, EffectAnimationType.Position, null, new PositionOffsetEffectMetadata(new[] { -20, 0, 20, 0 }, new[] { 0, 14, 0, -14 }), null) }, // whirl / tornado + { 20, new EffectMetadata(false, true, false, SoundEffectID.AuraSpell, 5, 3, 0, -12, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // aura + { 21, new EffectMetadata(false, false, true, SoundEffectID.BouldersSpell, 7, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // boulders + { 22, new EffectMetadata(true, true, false, SoundEffectID.HeavenSpell, 5, 4, 0, -114, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // heaven + { 23, new EffectMetadata(true, true, false, SoundEffectID.IceBlastSpell2, 6, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // blue flame + { 24, new EffectMetadata(true, true, false, SoundEffectID.HeavenSpell, 5, 4, 0, -114, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // dark beam + { 25, new EffectMetadata(false, false, true, SoundEffectID.AdminHide, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin hide + { 26, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark hand + { 27, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark skull + { 28, new EffectMetadata(false, false, true, SoundEffectID.FireBlastSpell, 4, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // fire blast + { 29, new EffectMetadata(false, false, true, SoundEffectID.TentaclesSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // tentacles + { 30, new EffectMetadata(true, false, true, SoundEffectID.PowerWindSpell, 6, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // power wind + { 31, new EffectMetadata(true, false, true, SoundEffectID.MagicWhirlSpell, 15, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // magic whirl + { 32, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 6, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark bite + { 33, new EffectMetadata(true, true, false, SoundEffectID.AuraSpell, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // shell + { 34, new EffectMetadata(true, true, false, SoundEffectID.EnergyBallSpell, 5, 1, 0, -44, EffectAnimationType.Static, null, null, null) } // green flame + }; + _metadataLoader = metadataLoader; + } - public EffectMetadata GetValueOrDefault(int graphic) - { - return _metadataLoader.GetMetadata(graphic) - .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : EffectMetadata.Default); - } + public EffectMetadata GetValueOrDefault(int graphic) + { + return _metadataLoader.GetMetadata(graphic) + .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : EffectMetadata.Default); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs b/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs index 0456b8f54..6ece51a9c 100644 --- a/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs +++ b/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs @@ -8,63 +8,62 @@ using System.Collections.Generic; using System.Text; -namespace EndlessClient.Rendering.Metadata +namespace EndlessClient.Rendering.Metadata; + +[AutoMappedType(IsSingleton = true)] +public class GFXMetadataLoader : IGFXMetadataLoader { - [AutoMappedType(IsSingleton = true)] - public class GFXMetadataLoader : IGFXMetadataLoader - { - private readonly IPEFileCollection _peFileCollection; - private readonly Dictionary> _cache; + private readonly IPEFileCollection _peFileCollection; + private readonly Dictionary> _cache; - private static readonly Dictionary _mapper; + private static readonly Dictionary _mapper; - static GFXMetadataLoader() + static GFXMetadataLoader() + { + _mapper = new Dictionary { - _mapper = new Dictionary - { - { typeof(EffectMetadata), GFXTypes.Spells }, - { typeof(NPCMetadata), GFXTypes.NPC }, - { typeof(ShieldMetadata), GFXTypes.MaleBack }, - { typeof(HatMetadata), GFXTypes.MaleHat }, - { typeof(WeaponMetadata), GFXTypes.MaleWeapons } - }; - } + { typeof(EffectMetadata), GFXTypes.Spells }, + { typeof(NPCMetadata), GFXTypes.NPC }, + { typeof(ShieldMetadata), GFXTypes.MaleBack }, + { typeof(HatMetadata), GFXTypes.MaleHat }, + { typeof(WeaponMetadata), GFXTypes.MaleWeapons } + }; + } - public GFXMetadataLoader(IPEFileCollection peFileCollection) - { - _peFileCollection = peFileCollection; - _cache = new Dictionary>(); - } + public GFXMetadataLoader(IPEFileCollection peFileCollection) + { + _peFileCollection = peFileCollection; + _cache = new Dictionary>(); + } - public Option GetMetadata(int graphic) - where TMetadata : class, IGFXMetadata - { - if (graphic == 0 || !_mapper.TryGetValue(typeof(TMetadata), out var gfxType)) - return Option.None(); + public Option GetMetadata(int graphic) + where TMetadata : class, IGFXMetadata + { + if (graphic == 0 || !_mapper.TryGetValue(typeof(TMetadata), out var gfxType)) + return Option.None(); - if (!_cache.ContainsKey(gfxType)) - _cache.Add(gfxType, new Dictionary()); - else if (_cache[gfxType].ContainsKey(graphic)) - return Option.Some(_cache[gfxType][graphic] as TMetadata).NotNull(); + if (!_cache.ContainsKey(gfxType)) + _cache.Add(gfxType, new Dictionary()); + else if (_cache[gfxType].ContainsKey(graphic)) + return Option.Some(_cache[gfxType][graphic] as TMetadata).NotNull(); - try - { - var rawMetadata = _peFileCollection[gfxType].GetResourceByID(ResourceType.RCData, graphic); - var metadataString = Encoding.Unicode.GetString(rawMetadata); - _cache[gfxType].Add(graphic, JsonConvert.DeserializeObject(metadataString)); + try + { + var rawMetadata = _peFileCollection[gfxType].GetResourceByID(ResourceType.RCData, graphic); + var metadataString = Encoding.Unicode.GetString(rawMetadata); + _cache[gfxType].Add(graphic, JsonConvert.DeserializeObject(metadataString)); - return (_cache[gfxType][graphic] as TMetadata).SomeNotNull(); - } - catch - { - return Option.None(); - } + return (_cache[gfxType][graphic] as TMetadata).SomeNotNull(); + } + catch + { + return Option.None(); } } +} - public interface IGFXMetadataLoader - { - Option GetMetadata(int graphic) - where TMetadata : class, IGFXMetadata; - } +public interface IGFXMetadataLoader +{ + Option GetMetadata(int graphic) + where TMetadata : class, IGFXMetadata; } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs b/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs index d1c783103..6f90b3ac0 100644 --- a/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs @@ -2,68 +2,67 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata +namespace EndlessClient.Rendering.Metadata; + +[AutoMappedType(IsSingleton = true)] +public class HatMetadataProvider : IMetadataProvider { - [AutoMappedType(IsSingleton = true)] - public class HatMetadataProvider : IMetadataProvider - { - public IReadOnlyDictionary DefaultMetadata => _metadata; + public IReadOnlyDictionary DefaultMetadata => _metadata; - private readonly Dictionary _metadata; - private readonly IGFXMetadataLoader _metadataLoader; + private readonly Dictionary _metadata; + private readonly IGFXMetadataLoader _metadataLoader; - public HatMetadataProvider(IGFXMetadataLoader metadataLoader) + public HatMetadataProvider(IGFXMetadataLoader metadataLoader) + { + _metadata = new Dictionary { - _metadata = new Dictionary - { - { 7, new HatMetadata(HatMaskType.FaceMask) }, // bandana - { 8, new HatMetadata(HatMaskType.FaceMask) }, // bandana - { 9, new HatMetadata(HatMaskType.FaceMask) }, // bandana - { 10, new HatMetadata(HatMaskType.FaceMask) }, // bandana - { 11, new HatMetadata(HatMaskType.FaceMask) }, // bandana - { 12, new HatMetadata(HatMaskType.FaceMask) }, // purple scarf - { 13, new HatMetadata(HatMaskType.FaceMask) }, // red scarf - { 14, new HatMetadata(HatMaskType.FaceMask) }, // black scarf - { 15, new HatMetadata(HatMaskType.FaceMask) }, // dragon mask + { 7, new HatMetadata(HatMaskType.FaceMask) }, // bandana + { 8, new HatMetadata(HatMaskType.FaceMask) }, // bandana + { 9, new HatMetadata(HatMaskType.FaceMask) }, // bandana + { 10, new HatMetadata(HatMaskType.FaceMask) }, // bandana + { 11, new HatMetadata(HatMaskType.FaceMask) }, // bandana + { 12, new HatMetadata(HatMaskType.FaceMask) }, // purple scarf + { 13, new HatMetadata(HatMaskType.FaceMask) }, // red scarf + { 14, new HatMetadata(HatMaskType.FaceMask) }, // black scarf + { 15, new HatMetadata(HatMaskType.FaceMask) }, // dragon mask - { 16, new HatMetadata(HatMaskType.HideHair) }, // black hood - { 17, new HatMetadata(HatMaskType.HideHair) }, // brown hood - { 18, new HatMetadata(HatMaskType.HideHair) }, // blue hood - { 19, new HatMetadata(HatMaskType.HideHair) }, // green hood - { 20, new HatMetadata(HatMaskType.HideHair) }, // red hood - { 21, new HatMetadata(HatMaskType.HideHair) }, // chainmail hat + { 16, new HatMetadata(HatMaskType.HideHair) }, // black hood + { 17, new HatMetadata(HatMaskType.HideHair) }, // brown hood + { 18, new HatMetadata(HatMaskType.HideHair) }, // blue hood + { 19, new HatMetadata(HatMaskType.HideHair) }, // green hood + { 20, new HatMetadata(HatMaskType.HideHair) }, // red hood + { 21, new HatMetadata(HatMaskType.HideHair) }, // chainmail hat - { 25, new HatMetadata(HatMaskType.HideHair) }, // horned hat - { 26, new HatMetadata(HatMaskType.HideHair) }, // merchant hat - { 28, new HatMetadata(HatMaskType.HideHair) }, // helmy - { 30, new HatMetadata(HatMaskType.HideHair) }, // eloff helmet - { 31, new HatMetadata(HatMaskType.HideHair) }, // air hat + { 25, new HatMetadata(HatMaskType.HideHair) }, // horned hat + { 26, new HatMetadata(HatMaskType.HideHair) }, // merchant hat + { 28, new HatMetadata(HatMaskType.HideHair) }, // helmy + { 30, new HatMetadata(HatMaskType.HideHair) }, // eloff helmet + { 31, new HatMetadata(HatMaskType.HideHair) }, // air hat - { 32, new HatMetadata(HatMaskType.FaceMask) }, // frog head - { 33, new HatMetadata(HatMaskType.FaceMask) }, // pilotte + { 32, new HatMetadata(HatMaskType.FaceMask) }, // frog head + { 33, new HatMetadata(HatMaskType.FaceMask) }, // pilotte - { 34, new HatMetadata(HatMaskType.HideHair) }, // beruta - { 35, new HatMetadata(HatMaskType.HideHair) }, // pirate hat - { 36, new HatMetadata(HatMaskType.HideHair) }, // lotus helmet - { 37, new HatMetadata(HatMaskType.HideHair) }, // kitty hat - { 38, new HatMetadata(HatMaskType.HideHair) }, // hula hula hat + { 34, new HatMetadata(HatMaskType.HideHair) }, // beruta + { 35, new HatMetadata(HatMaskType.HideHair) }, // pirate hat + { 36, new HatMetadata(HatMaskType.HideHair) }, // lotus helmet + { 37, new HatMetadata(HatMaskType.HideHair) }, // kitty hat + { 38, new HatMetadata(HatMaskType.HideHair) }, // hula hula hat - { 40, new HatMetadata(HatMaskType.HideHair) }, // gob helm - { 41, new HatMetadata(HatMaskType.HideHair) }, // horned gob helm - { 44, new HatMetadata(HatMaskType.HideHair) }, // helmet of darkness - { 46, new HatMetadata(HatMaskType.HideHair) }, // flad hat - { 47, new HatMetadata(HatMaskType.HideHair) }, // cook hat + { 40, new HatMetadata(HatMaskType.HideHair) }, // gob helm + { 41, new HatMetadata(HatMaskType.HideHair) }, // horned gob helm + { 44, new HatMetadata(HatMaskType.HideHair) }, // helmet of darkness + { 46, new HatMetadata(HatMaskType.HideHair) }, // flad hat + { 47, new HatMetadata(HatMaskType.HideHair) }, // cook hat - { 48, new HatMetadata(HatMaskType.FaceMask) }, // glasses - { 50, new HatMetadata(HatMaskType.FaceMask) }, // medic cap - }; - _metadataLoader = metadataLoader; - } + { 48, new HatMetadata(HatMaskType.FaceMask) }, // glasses + { 50, new HatMetadata(HatMaskType.FaceMask) }, // medic cap + }; + _metadataLoader = metadataLoader; + } - public HatMetadata GetValueOrDefault(int graphic) - { - return _metadataLoader.GetMetadata(graphic) - .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : HatMetadata.Default); - } + public HatMetadata GetValueOrDefault(int graphic) + { + return _metadataLoader.GetMetadata(graphic) + .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : HatMetadata.Default); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/IMetadataProvider.cs b/EndlessClient/Rendering/Metadata/IMetadataProvider.cs index f7075edab..84c5501fd 100644 --- a/EndlessClient/Rendering/Metadata/IMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/IMetadataProvider.cs @@ -1,13 +1,12 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata +namespace EndlessClient.Rendering.Metadata; + +public interface IMetadataProvider + where TMetadata : IGFXMetadata { - public interface IMetadataProvider - where TMetadata : IGFXMetadata - { - IReadOnlyDictionary DefaultMetadata { get; } + IReadOnlyDictionary DefaultMetadata { get; } - TMetadata GetValueOrDefault(int graphic); - } + TMetadata GetValueOrDefault(int graphic); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs b/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs index 1d529de90..4414e5de4 100644 --- a/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs @@ -3,47 +3,46 @@ using EndlessClient.Rendering.Effects; using Newtonsoft.Json; -namespace EndlessClient.Rendering.Metadata.Models +namespace EndlessClient.Rendering.Metadata.Models; + +[Record] +public sealed partial class EffectMetadata : IGFXMetadata { - [Record] - public sealed partial class EffectMetadata : IGFXMetadata - { - public static EffectMetadata Default { get; } = new Builder { HasInFrontLayer = true, Loops = 2, Frames = 4, AnimationType = EffectAnimationType.Static }.ToImmutable(); + public static EffectMetadata Default { get; } = new Builder { HasInFrontLayer = true, Loops = 2, Frames = 4, AnimationType = EffectAnimationType.Static }.ToImmutable(); - [JsonProperty("hasLayer0")] - public bool HasBehindLayer { get; } + [JsonProperty("hasLayer0")] + public bool HasBehindLayer { get; } - [JsonProperty("hasLayer1")] - public bool HasTransparentLayer { get; } + [JsonProperty("hasLayer1")] + public bool HasTransparentLayer { get; } - [JsonProperty("hasLayer2")] - public bool HasInFrontLayer { get; } + [JsonProperty("hasLayer2")] + public bool HasInFrontLayer { get; } - [JsonProperty("sfx")] - public SoundEffectID SoundEffect { get; } + [JsonProperty("sfx")] + public SoundEffectID SoundEffect { get; } - [JsonProperty("frames")] - public int Frames { get; } + [JsonProperty("frames")] + public int Frames { get; } - [JsonProperty("loops")] - public int Loops { get; } + [JsonProperty("loops")] + public int Loops { get; } - [JsonProperty("xOffset")] - public int OffsetX { get; } + [JsonProperty("xOffset")] + public int OffsetX { get; } - [JsonProperty("yOffset")] - public int OffsetY { get; } + [JsonProperty("yOffset")] + public int OffsetY { get; } - [JsonProperty("type")] - public EffectAnimationType AnimationType { get; } + [JsonProperty("type")] + public EffectAnimationType AnimationType { get; } - [JsonProperty("verticalSlidingData")] - public VerticalSlidingEffectMetadata VerticalSlidingMetadata { get; } + [JsonProperty("verticalSlidingData")] + public VerticalSlidingEffectMetadata VerticalSlidingMetadata { get; } - [JsonProperty("positionData")] - public PositionOffsetEffectMetadata PositionOffsetMetadata { get; } + [JsonProperty("positionData")] + public PositionOffsetEffectMetadata PositionOffsetMetadata { get; } - [JsonProperty("flickeringData")] - public RandomFlickeringEffectMetadata RandomFlickeringMetadata { get; } - } + [JsonProperty("flickeringData")] + public RandomFlickeringEffectMetadata RandomFlickeringMetadata { get; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs b/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs index afff2bc1d..ca4011e8d 100644 --- a/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs @@ -1,6 +1,5 @@ -namespace EndlessClient.Rendering.Metadata.Models +namespace EndlessClient.Rendering.Metadata.Models; + +public interface IGFXMetadata { - public interface IGFXMetadata - { - } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs b/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs index 4cbe72b7d..33cbe1485 100644 --- a/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs @@ -1,29 +1,28 @@ using Amadevus.RecordGenerator; using Newtonsoft.Json; -namespace EndlessClient.Rendering.Metadata.Models +namespace EndlessClient.Rendering.Metadata.Models; + +[Record] +public sealed partial class NPCMetadata : IGFXMetadata { - [Record] - public sealed partial class NPCMetadata : IGFXMetadata - { - public static NPCMetadata Default { get; } = new Builder().ToImmutable(); + public static NPCMetadata Default { get; } = new Builder().ToImmutable(); - [JsonProperty("xOffset")] - public int OffsetX { get; } + [JsonProperty("xOffset")] + public int OffsetX { get; } - [JsonProperty("yOffset")] - public int OffsetY { get; } + [JsonProperty("yOffset")] + public int OffsetY { get; } - [JsonProperty("xAttackOffset")] - public int AttackOffsetX { get; } + [JsonProperty("xAttackOffset")] + public int AttackOffsetX { get; } - [JsonProperty("yAttackOffset")] - public int AttackOffsetY { get; } + [JsonProperty("yAttackOffset")] + public int AttackOffsetY { get; } - [JsonProperty("hasAnimation")] - public bool HasStandingFrameAnimation { get; } + [JsonProperty("hasAnimation")] + public bool HasStandingFrameAnimation { get; } - [JsonProperty("nameHeight")] - public int NameLabelOffset { get; } - } + [JsonProperty("nameHeight")] + public int NameLabelOffset { get; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs b/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs index b6009357f..0eca0a32e 100644 --- a/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs @@ -2,200 +2,199 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata +namespace EndlessClient.Rendering.Metadata; + +[AutoMappedType(IsSingleton = true)] +public class NPCMetadataProvider : IMetadataProvider { - [AutoMappedType(IsSingleton = true)] - public class NPCMetadataProvider : IMetadataProvider - { - public IReadOnlyDictionary DefaultMetadata => _metadata; + public IReadOnlyDictionary DefaultMetadata => _metadata; - private readonly Dictionary _metadata; - private readonly IGFXMetadataLoader _metadataLoader; + private readonly Dictionary _metadata; + private readonly IGFXMetadataLoader _metadataLoader; - public NPCMetadataProvider(IGFXMetadataLoader metadataLoader) + public NPCMetadataProvider(IGFXMetadataLoader metadataLoader) + { + // source: https://docs.google.com/spreadsheets/d/1GMo3c2xcPW5Uv3pOsaIS2EwtVA_N0Qfwo9TCTDibUoI/edit#gid=0 + _metadata = new Dictionary { - // source: https://docs.google.com/spreadsheets/d/1GMo3c2xcPW5Uv3pOsaIS2EwtVA_N0Qfwo9TCTDibUoI/edit#gid=0 - _metadata = new Dictionary - { - { 1, new NPCMetadata(0, 16, 0, 0, false, 4) }, // crow - { 2, new NPCMetadata(0, 18, -6, -3, false, 0) }, // rat - { 3, new NPCMetadata(0, 16, -8, -4, false, 0) }, // slime - { 4, new NPCMetadata(0, 18, -8, -4, false, 50) }, // mummy - { 5, new NPCMetadata(-2, 7, -8, -4, false, 20) }, // fox - { 6, new NPCMetadata(0, 8, -6, -3, false, 10) }, // snake - { 7, new NPCMetadata(-2, 6, -4, -2, false, 12) }, // goat - { 8, new NPCMetadata(0, 0, -2, -1, false, 75) }, // centaur - { 9, new NPCMetadata(-4, 6, -4, -2, false, 30) }, // undeath - { 10, new NPCMetadata(1, -1, -6, -3, false, 8) }, // spider - { 11, new NPCMetadata(0, 5, -4, -2, false, 40) }, // barbarian - { 12, new NPCMetadata(0, 15, -6, -3, false, 33) }, // cactus - { 13, new NPCMetadata(0, 13, 2, -2, false, 10) }, // penguin - { 14, new NPCMetadata(-4, 10, -2, -4, false, 53) }, // cyclops - { 15, new NPCMetadata(-1, 17, 0, 0, false, 40) }, // shop bob - { 16, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton - { 17, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton captain - { 18, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton sword - { 19, new NPCMetadata(0, 11, -6, -3, false, 49) }, // wingo - { 20, new NPCMetadata(0, 7, 0, 0, false, 40) }, // juweller - { 21, new NPCMetadata(-2, 17, -10, -5, false, 40) }, // pirate npc 1 - { 22, new NPCMetadata(0, 11, 0, 0, true, 45) }, // witch - { 23, new NPCMetadata(0, 17, 0, 0, false, 40) }, // babs - { 24, new NPCMetadata(0, 17, 0, 0, false, 40) }, // pirate npc 2 - { 25, new NPCMetadata(0, 6, 0, 0, true, 50) }, // blacksmith - { 26, new NPCMetadata(-2, 11, -6, -3, false, 0) }, // crab🦀 - { 27, new NPCMetadata(0, 9, 0, 0, true, 12) }, // remi - { 28, new NPCMetadata(-4, 16, 0, 0, true, 42) }, // guild bob - { 29, new NPCMetadata(0, 7, -6, -3, false, 0) }, // vyercil - { 30, new NPCMetadata(-10, 13, -8, -4, false, 42) }, // reaper - { 31, new NPCMetadata(0, 13, -8, -4, false, 42) }, // chaos spawn - { 32, new NPCMetadata(0, 17, 0, 0, false, 40) }, // blue hair npc - { 33, new NPCMetadata(0, 17, 0, 0, false, 40) }, // beard npc - { 34, new NPCMetadata(0, 17, 0, 0, false, 40) }, // long hair npc - { 35, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard red - { 36, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard purple - { 37, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard green - { 38, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // green blob - { 39, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // pink blob - { 40, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // red blob - { 41, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // cyan blob - { 42, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // orange blob - { 43, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // yellow blob - { 44, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // blue blob - { 45, new NPCMetadata(-1, 12, -6, -3, false, 40) }, // horse - { 46, new NPCMetadata(-3, 10, -6, -3, false, 42) }, // unicorn - { 47, new NPCMetadata(0, 10, -6, -3, false, 66) }, // birdman - { 48, new NPCMetadata(6, 10, -6, -3, false, 66) }, // birdman winged - { 49, new NPCMetadata(-9, 13, -6, -3, false, 68) }, // birdman captain - { 50, new NPCMetadata(4, 10, -6, -3, true, 82) }, // flying birdman - { 51, new NPCMetadata(0, 13, -10, -5, true, 59) }, // hell guardian - { 52, new NPCMetadata(0, 1, -4, -2, true, 48) }, // wolfman - { 53, new NPCMetadata(-2, 17, 0, 0, false, 40) }, // mommy npc - { 54, new NPCMetadata(0, 14, 0, 0, false, 28) }, // kid npc - { 55, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog green - { 56, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog turqoise - { 57, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog red - { 58, new NPCMetadata(0, 18, -8, -4, true, 42) }, // hornet - { 59, new NPCMetadata(0, 16, -8, -4, true, 44) }, // bat - { 60, new NPCMetadata(-3, 6, -6, -3, false, 10) }, // wurm - { 61, new NPCMetadata(0, 0, -12, -6, false, 10) }, // worm - { 62, new NPCMetadata(-3, 11, -8, -4, false, 10) }, // ant - { 63, new NPCMetadata(-3, 11, -8, -4, false, 10) }, // ant soldier - { 64, new NPCMetadata(0, 15, -12, -6, true, 41) }, // teawk - { 65, new NPCMetadata(3, 12, -8, -4, false, 23) }, // batmaso - { 66, new NPCMetadata(-1, 8, -10, -5, false, 53) }, // jesaur - { 67, new NPCMetadata(0, 12, -4, -2, false, 28) }, // hedgehog - { 68, new NPCMetadata(0, 6, -4, -2, false, 93) }, // ice golem - { 69, new NPCMetadata(0, 20, 0, 0, true, 48) }, // ice gem - { 70, new NPCMetadata(-1, 17, -8, -4, false, 18) }, // gnome - { 71, new NPCMetadata(-2, 10, -6, -3, false, 24) }, // gnome rider - { 72, new NPCMetadata(1, 14, 0, 0, false, 20) }, // rock - { 73, new NPCMetadata(-3, 13, -8, -4, false, 55) }, // golem - { 74, new NPCMetadata(0, 16, -4, -2, false, 22) }, // mushroom - { 75, new NPCMetadata(-1, 17, -6, -3, true, 37) }, // teawcus - { 76, new NPCMetadata(-1, 16, -4, -2, false, 41) }, // hula man - { 77, new NPCMetadata(-2, 10, 0, 0, false, 14) }, // snail - { 78, new NPCMetadata(-2, 10, 0, 0, false, 14) }, // bowtie snail - { 79, new NPCMetadata(0, 15, 0, 0, true, 41) }, // geggime - { 80, new NPCMetadata(0, 5, -8, -4, false, 31) }, // ewak - { 81, new NPCMetadata(-3, 15, -6, -3, true, 44) }, // azuorph - { 82, new NPCMetadata(-2, 18, 0, 0, false, 40) }, // sword guy npc - { 83, new NPCMetadata(-2, 17, 0, 0, false, 40) }, // purple hair npc - { 84, new NPCMetadata(-2, 18, 0, 0, false, 40) }, // green hair girl npc - { 85, new NPCMetadata(0, 18, -10, -5, true, 50) }, // wraith - { 86, new NPCMetadata(-2, 14, 0, 0, true, 43) }, // priest - { 87, new NPCMetadata(-4, 11, -8, -4, false, 40) }, // ninja - { 88, new NPCMetadata(1, 12, -10, -5, false, 54) }, // orc - { 89, new NPCMetadata(0, -4, 0, 0, true, 43) }, // octo - { 90, new NPCMetadata(1, 6, -8, -4, true, 54) }, // octo tentacle - { 91, new NPCMetadata(-14, 14, -3, -2, false, 64) }, // anundo leader - { 92, new NPCMetadata(0, 13, -6, -4, false, 21) }, // carnivo - { 93, new NPCMetadata(-9, 14, 0, 0, true, 55) }, // old king - { 94, new NPCMetadata(-9, 14, 0, 0, true, 50) }, // green hair king - { 95, new NPCMetadata(-7, 9, 0, 0, false, 32) }, // goblin - { 96, new NPCMetadata(-1, 18, -6, -3, true, 46) }, // optica - { 97, new NPCMetadata(-2, 14, -4, -2, false, 46) }, // bogo man - { 98, new NPCMetadata(-1, 20, -8, -4, true, 50) }, // butterfly - { 99, new NPCMetadata(0, 17, -6, -3, true, 68) }, // cursed mask - { 100, new NPCMetadata(0, 17, -6, -3, false, 30) }, // red imp - { 101, new NPCMetadata(0, 17, -6, -3, false, 30) }, // grey imp - { 102, new NPCMetadata(0, 15, 0, 0, true, 84) }, // vine tentacle - { 103, new NPCMetadata(0, 16, -10, -5, false, 48) }, // headless hunter - { 104, new NPCMetadata(0, 15, -8, -4, false, 60) }, // swamp monster - { 105, new NPCMetadata(0, 15, -8, -4, true, 70) }, // twin demons - { 106, new NPCMetadata(0, 13, -6, -3, false, 30) }, // dwarf - { 107, new NPCMetadata(-31, 4, -4, -2, false, 138) }, // apozen - { 108, new NPCMetadata(0, 6, -10, -5, false, 12) }, // mimic - { 109, new NPCMetadata(-2, 16, 0, 0, false, 43) }, // panda master npc - { 110, new NPCMetadata(-2, 17, -6, -3, true, 59) }, // crane - { 111, new NPCMetadata(0, 17, -6, -3, true, 17) }, // cyto 053 - { 112, new NPCMetadata(4, 6, -6, -3, true, 30) }, // sav 109 - { 113, new NPCMetadata(1, 7, 0, 0, false, 6) }, // robo tile - { 114, new NPCMetadata(0, 17, -4, -2, true, 44) }, // proto - { 115, new NPCMetadata(-6, 16, -6, -3, true, 42) }, // princess - { 116, new NPCMetadata(0, 18, 0, 0, true, 40) }, // scientist npc - { 117, new NPCMetadata(-2, 15, 0, 0, true, 32) }, // mechanic npc - { 118, new NPCMetadata(-6, 15, -4, -2, true, 47) }, // wise man - { 119, new NPCMetadata(-1, 13, -6, -3, false, 15) }, // sheep - { 120, new NPCMetadata(-3, 19, -8, -4, false, 19) }, // biter - { 121, new NPCMetadata(-1, 16, -2, -1, true, 10) }, // blocto - { 122, new NPCMetadata(0, 18, -8, -4, true, 58) }, // puppet - { 123, new NPCMetadata(0, 4, 0, 0, false, 65) }, // king wurm - { 124, new NPCMetadata(-4, 9, -10, -5, false, 71) }, // gnoll - { 125, new NPCMetadata(0, 0, 0, 0, false, 88) }, // bone spider - { 126, new NPCMetadata(0, 20, -10, -5, true, 58) }, // hell flyer - { 127, new NPCMetadata(-4, 12, -14, -5, true, 36) }, // shaman - { 128, new NPCMetadata(-5, 17, -4, -2, false, 36) }, // war bear - { 129, new NPCMetadata(0, 7, 0, 0, true, 32) }, // shark - { 130, new NPCMetadata(0, 15, -10, -5, false, 5) }, // turtle - { 131, new NPCMetadata(-1, 16, -8, -4, false, 16) }, // doll - { 132, new NPCMetadata(-2, 5, -8, -4, false, 40) }, // dark magician - { 133, new NPCMetadata(-2, 5, -6, -3, false, 47) }, // yeti - { 134, new NPCMetadata(0, 18, -10, -5, true, 80) }, // banshee - { 135, new NPCMetadata(0, 18, 0, 5, false, 41) }, // drone flyer - { 136, new NPCMetadata(-2, 19, -4, -2, false, 22) }, // butter - { 137, new NPCMetadata(0, 18, -8, -4, false, 45) }, // funky hair npc - { 138, new NPCMetadata(0, 18, -6, -3, false, 26) }, // flombie - { 139, new NPCMetadata(0, 17, -6, -3, false, 32) }, // gator - { 140, new NPCMetadata(0, 18, -2, -1, true, 65) }, // phoenix - { 141, new NPCMetadata(0, 16, -6, -3, false, 25) }, // bale - { 142, new NPCMetadata(0, 18, -2, -1, true, 20) }, // espring - { 143, new NPCMetadata(0, 16, -6, -3, false, 40) }, // old italian man npc - { 144, new NPCMetadata(-3, 8, 0, 0, false, 52) }, // rotveig - { 145, new NPCMetadata(0, 19, -6, -3, false, 48) }, // booba amazon npc - { 146, new NPCMetadata(0, 19, -6, -3, false, 69) }, // cacadem - { 147, new NPCMetadata(0, 10, 0, 0, false, 32) }, // flowie - { 148, new NPCMetadata(-4, 16, -6, -3, true, 37) }, // nutviper - { 149, new NPCMetadata(2, 6, 0, 0, false, 98) }, // dragon - { 150, new NPCMetadata(-1, 18, -6, -3, false, 48) }, // flyman - { 151, new NPCMetadata(-2, 1, -2, 1, false, 18) }, // vitamin - { 152, new NPCMetadata(0, 10, -8, -2, false, 27) }, // onigiri - { 153, new NPCMetadata(-2, 13, -6, -9, false, 39) }, // rabther - { 154, new NPCMetadata(0, 15, -6, -3, false, 13) }, // piglet - { 155, new NPCMetadata(0, 16, -6, -3, false, 18) }, // piglet with baby - { 156, new NPCMetadata(0, 15, -6, -3, false, 32) }, // tenba - { 157, new NPCMetadata(0, 6, -8, -4, true, 58) }, // funky hair cyborg - { 158, new NPCMetadata(0, 15, 0, 0, true, 74) }, // drummer - { 159, new NPCMetadata(-11, 18, 0, 0, true, 57) }, // guitarist - { 160, new NPCMetadata(-4, 18, 0, 0, true, 45) }, // wise man guitar - { 161, new NPCMetadata(0, 0, 0, 0, true, 65) }, // piano panda - { 162, new NPCMetadata(-1, 10, -8, -4, false, 15) }, // mini army - { 163, new NPCMetadata(0, 8, -6, -3, false, 12) }, // artist - { 164, new NPCMetadata(0, 15, -8, -4, false, 10) }, // hamster - { 165, new NPCMetadata(0, 13, 0, 0, false, 10) }, // mole - { 166, new NPCMetadata(0, 18, 0, 0, true, 32) }, // fish - { 167, new NPCMetadata(0, 14, -6, -3, false, 22) }, // lizzy - { 168, new NPCMetadata(0, 15, -8, -4, false, 15) }, // ape - { 169, new NPCMetadata(0, 4, -8, -4, false, 19) }, // taraduda - { 170, new NPCMetadata(0, 19, -8, -4, false, 17) }, // monkey - { 171, new NPCMetadata(0, 0, 0, 0, false, 0) }, // ancient wraith - }; - _metadataLoader = metadataLoader; - } + { 1, new NPCMetadata(0, 16, 0, 0, false, 4) }, // crow + { 2, new NPCMetadata(0, 18, -6, -3, false, 0) }, // rat + { 3, new NPCMetadata(0, 16, -8, -4, false, 0) }, // slime + { 4, new NPCMetadata(0, 18, -8, -4, false, 50) }, // mummy + { 5, new NPCMetadata(-2, 7, -8, -4, false, 20) }, // fox + { 6, new NPCMetadata(0, 8, -6, -3, false, 10) }, // snake + { 7, new NPCMetadata(-2, 6, -4, -2, false, 12) }, // goat + { 8, new NPCMetadata(0, 0, -2, -1, false, 75) }, // centaur + { 9, new NPCMetadata(-4, 6, -4, -2, false, 30) }, // undeath + { 10, new NPCMetadata(1, -1, -6, -3, false, 8) }, // spider + { 11, new NPCMetadata(0, 5, -4, -2, false, 40) }, // barbarian + { 12, new NPCMetadata(0, 15, -6, -3, false, 33) }, // cactus + { 13, new NPCMetadata(0, 13, 2, -2, false, 10) }, // penguin + { 14, new NPCMetadata(-4, 10, -2, -4, false, 53) }, // cyclops + { 15, new NPCMetadata(-1, 17, 0, 0, false, 40) }, // shop bob + { 16, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton + { 17, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton captain + { 18, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton sword + { 19, new NPCMetadata(0, 11, -6, -3, false, 49) }, // wingo + { 20, new NPCMetadata(0, 7, 0, 0, false, 40) }, // juweller + { 21, new NPCMetadata(-2, 17, -10, -5, false, 40) }, // pirate npc 1 + { 22, new NPCMetadata(0, 11, 0, 0, true, 45) }, // witch + { 23, new NPCMetadata(0, 17, 0, 0, false, 40) }, // babs + { 24, new NPCMetadata(0, 17, 0, 0, false, 40) }, // pirate npc 2 + { 25, new NPCMetadata(0, 6, 0, 0, true, 50) }, // blacksmith + { 26, new NPCMetadata(-2, 11, -6, -3, false, 0) }, // crab🦀 + { 27, new NPCMetadata(0, 9, 0, 0, true, 12) }, // remi + { 28, new NPCMetadata(-4, 16, 0, 0, true, 42) }, // guild bob + { 29, new NPCMetadata(0, 7, -6, -3, false, 0) }, // vyercil + { 30, new NPCMetadata(-10, 13, -8, -4, false, 42) }, // reaper + { 31, new NPCMetadata(0, 13, -8, -4, false, 42) }, // chaos spawn + { 32, new NPCMetadata(0, 17, 0, 0, false, 40) }, // blue hair npc + { 33, new NPCMetadata(0, 17, 0, 0, false, 40) }, // beard npc + { 34, new NPCMetadata(0, 17, 0, 0, false, 40) }, // long hair npc + { 35, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard red + { 36, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard purple + { 37, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard green + { 38, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // green blob + { 39, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // pink blob + { 40, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // red blob + { 41, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // cyan blob + { 42, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // orange blob + { 43, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // yellow blob + { 44, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // blue blob + { 45, new NPCMetadata(-1, 12, -6, -3, false, 40) }, // horse + { 46, new NPCMetadata(-3, 10, -6, -3, false, 42) }, // unicorn + { 47, new NPCMetadata(0, 10, -6, -3, false, 66) }, // birdman + { 48, new NPCMetadata(6, 10, -6, -3, false, 66) }, // birdman winged + { 49, new NPCMetadata(-9, 13, -6, -3, false, 68) }, // birdman captain + { 50, new NPCMetadata(4, 10, -6, -3, true, 82) }, // flying birdman + { 51, new NPCMetadata(0, 13, -10, -5, true, 59) }, // hell guardian + { 52, new NPCMetadata(0, 1, -4, -2, true, 48) }, // wolfman + { 53, new NPCMetadata(-2, 17, 0, 0, false, 40) }, // mommy npc + { 54, new NPCMetadata(0, 14, 0, 0, false, 28) }, // kid npc + { 55, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog green + { 56, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog turqoise + { 57, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog red + { 58, new NPCMetadata(0, 18, -8, -4, true, 42) }, // hornet + { 59, new NPCMetadata(0, 16, -8, -4, true, 44) }, // bat + { 60, new NPCMetadata(-3, 6, -6, -3, false, 10) }, // wurm + { 61, new NPCMetadata(0, 0, -12, -6, false, 10) }, // worm + { 62, new NPCMetadata(-3, 11, -8, -4, false, 10) }, // ant + { 63, new NPCMetadata(-3, 11, -8, -4, false, 10) }, // ant soldier + { 64, new NPCMetadata(0, 15, -12, -6, true, 41) }, // teawk + { 65, new NPCMetadata(3, 12, -8, -4, false, 23) }, // batmaso + { 66, new NPCMetadata(-1, 8, -10, -5, false, 53) }, // jesaur + { 67, new NPCMetadata(0, 12, -4, -2, false, 28) }, // hedgehog + { 68, new NPCMetadata(0, 6, -4, -2, false, 93) }, // ice golem + { 69, new NPCMetadata(0, 20, 0, 0, true, 48) }, // ice gem + { 70, new NPCMetadata(-1, 17, -8, -4, false, 18) }, // gnome + { 71, new NPCMetadata(-2, 10, -6, -3, false, 24) }, // gnome rider + { 72, new NPCMetadata(1, 14, 0, 0, false, 20) }, // rock + { 73, new NPCMetadata(-3, 13, -8, -4, false, 55) }, // golem + { 74, new NPCMetadata(0, 16, -4, -2, false, 22) }, // mushroom + { 75, new NPCMetadata(-1, 17, -6, -3, true, 37) }, // teawcus + { 76, new NPCMetadata(-1, 16, -4, -2, false, 41) }, // hula man + { 77, new NPCMetadata(-2, 10, 0, 0, false, 14) }, // snail + { 78, new NPCMetadata(-2, 10, 0, 0, false, 14) }, // bowtie snail + { 79, new NPCMetadata(0, 15, 0, 0, true, 41) }, // geggime + { 80, new NPCMetadata(0, 5, -8, -4, false, 31) }, // ewak + { 81, new NPCMetadata(-3, 15, -6, -3, true, 44) }, // azuorph + { 82, new NPCMetadata(-2, 18, 0, 0, false, 40) }, // sword guy npc + { 83, new NPCMetadata(-2, 17, 0, 0, false, 40) }, // purple hair npc + { 84, new NPCMetadata(-2, 18, 0, 0, false, 40) }, // green hair girl npc + { 85, new NPCMetadata(0, 18, -10, -5, true, 50) }, // wraith + { 86, new NPCMetadata(-2, 14, 0, 0, true, 43) }, // priest + { 87, new NPCMetadata(-4, 11, -8, -4, false, 40) }, // ninja + { 88, new NPCMetadata(1, 12, -10, -5, false, 54) }, // orc + { 89, new NPCMetadata(0, -4, 0, 0, true, 43) }, // octo + { 90, new NPCMetadata(1, 6, -8, -4, true, 54) }, // octo tentacle + { 91, new NPCMetadata(-14, 14, -3, -2, false, 64) }, // anundo leader + { 92, new NPCMetadata(0, 13, -6, -4, false, 21) }, // carnivo + { 93, new NPCMetadata(-9, 14, 0, 0, true, 55) }, // old king + { 94, new NPCMetadata(-9, 14, 0, 0, true, 50) }, // green hair king + { 95, new NPCMetadata(-7, 9, 0, 0, false, 32) }, // goblin + { 96, new NPCMetadata(-1, 18, -6, -3, true, 46) }, // optica + { 97, new NPCMetadata(-2, 14, -4, -2, false, 46) }, // bogo man + { 98, new NPCMetadata(-1, 20, -8, -4, true, 50) }, // butterfly + { 99, new NPCMetadata(0, 17, -6, -3, true, 68) }, // cursed mask + { 100, new NPCMetadata(0, 17, -6, -3, false, 30) }, // red imp + { 101, new NPCMetadata(0, 17, -6, -3, false, 30) }, // grey imp + { 102, new NPCMetadata(0, 15, 0, 0, true, 84) }, // vine tentacle + { 103, new NPCMetadata(0, 16, -10, -5, false, 48) }, // headless hunter + { 104, new NPCMetadata(0, 15, -8, -4, false, 60) }, // swamp monster + { 105, new NPCMetadata(0, 15, -8, -4, true, 70) }, // twin demons + { 106, new NPCMetadata(0, 13, -6, -3, false, 30) }, // dwarf + { 107, new NPCMetadata(-31, 4, -4, -2, false, 138) }, // apozen + { 108, new NPCMetadata(0, 6, -10, -5, false, 12) }, // mimic + { 109, new NPCMetadata(-2, 16, 0, 0, false, 43) }, // panda master npc + { 110, new NPCMetadata(-2, 17, -6, -3, true, 59) }, // crane + { 111, new NPCMetadata(0, 17, -6, -3, true, 17) }, // cyto 053 + { 112, new NPCMetadata(4, 6, -6, -3, true, 30) }, // sav 109 + { 113, new NPCMetadata(1, 7, 0, 0, false, 6) }, // robo tile + { 114, new NPCMetadata(0, 17, -4, -2, true, 44) }, // proto + { 115, new NPCMetadata(-6, 16, -6, -3, true, 42) }, // princess + { 116, new NPCMetadata(0, 18, 0, 0, true, 40) }, // scientist npc + { 117, new NPCMetadata(-2, 15, 0, 0, true, 32) }, // mechanic npc + { 118, new NPCMetadata(-6, 15, -4, -2, true, 47) }, // wise man + { 119, new NPCMetadata(-1, 13, -6, -3, false, 15) }, // sheep + { 120, new NPCMetadata(-3, 19, -8, -4, false, 19) }, // biter + { 121, new NPCMetadata(-1, 16, -2, -1, true, 10) }, // blocto + { 122, new NPCMetadata(0, 18, -8, -4, true, 58) }, // puppet + { 123, new NPCMetadata(0, 4, 0, 0, false, 65) }, // king wurm + { 124, new NPCMetadata(-4, 9, -10, -5, false, 71) }, // gnoll + { 125, new NPCMetadata(0, 0, 0, 0, false, 88) }, // bone spider + { 126, new NPCMetadata(0, 20, -10, -5, true, 58) }, // hell flyer + { 127, new NPCMetadata(-4, 12, -14, -5, true, 36) }, // shaman + { 128, new NPCMetadata(-5, 17, -4, -2, false, 36) }, // war bear + { 129, new NPCMetadata(0, 7, 0, 0, true, 32) }, // shark + { 130, new NPCMetadata(0, 15, -10, -5, false, 5) }, // turtle + { 131, new NPCMetadata(-1, 16, -8, -4, false, 16) }, // doll + { 132, new NPCMetadata(-2, 5, -8, -4, false, 40) }, // dark magician + { 133, new NPCMetadata(-2, 5, -6, -3, false, 47) }, // yeti + { 134, new NPCMetadata(0, 18, -10, -5, true, 80) }, // banshee + { 135, new NPCMetadata(0, 18, 0, 5, false, 41) }, // drone flyer + { 136, new NPCMetadata(-2, 19, -4, -2, false, 22) }, // butter + { 137, new NPCMetadata(0, 18, -8, -4, false, 45) }, // funky hair npc + { 138, new NPCMetadata(0, 18, -6, -3, false, 26) }, // flombie + { 139, new NPCMetadata(0, 17, -6, -3, false, 32) }, // gator + { 140, new NPCMetadata(0, 18, -2, -1, true, 65) }, // phoenix + { 141, new NPCMetadata(0, 16, -6, -3, false, 25) }, // bale + { 142, new NPCMetadata(0, 18, -2, -1, true, 20) }, // espring + { 143, new NPCMetadata(0, 16, -6, -3, false, 40) }, // old italian man npc + { 144, new NPCMetadata(-3, 8, 0, 0, false, 52) }, // rotveig + { 145, new NPCMetadata(0, 19, -6, -3, false, 48) }, // booba amazon npc + { 146, new NPCMetadata(0, 19, -6, -3, false, 69) }, // cacadem + { 147, new NPCMetadata(0, 10, 0, 0, false, 32) }, // flowie + { 148, new NPCMetadata(-4, 16, -6, -3, true, 37) }, // nutviper + { 149, new NPCMetadata(2, 6, 0, 0, false, 98) }, // dragon + { 150, new NPCMetadata(-1, 18, -6, -3, false, 48) }, // flyman + { 151, new NPCMetadata(-2, 1, -2, 1, false, 18) }, // vitamin + { 152, new NPCMetadata(0, 10, -8, -2, false, 27) }, // onigiri + { 153, new NPCMetadata(-2, 13, -6, -9, false, 39) }, // rabther + { 154, new NPCMetadata(0, 15, -6, -3, false, 13) }, // piglet + { 155, new NPCMetadata(0, 16, -6, -3, false, 18) }, // piglet with baby + { 156, new NPCMetadata(0, 15, -6, -3, false, 32) }, // tenba + { 157, new NPCMetadata(0, 6, -8, -4, true, 58) }, // funky hair cyborg + { 158, new NPCMetadata(0, 15, 0, 0, true, 74) }, // drummer + { 159, new NPCMetadata(-11, 18, 0, 0, true, 57) }, // guitarist + { 160, new NPCMetadata(-4, 18, 0, 0, true, 45) }, // wise man guitar + { 161, new NPCMetadata(0, 0, 0, 0, true, 65) }, // piano panda + { 162, new NPCMetadata(-1, 10, -8, -4, false, 15) }, // mini army + { 163, new NPCMetadata(0, 8, -6, -3, false, 12) }, // artist + { 164, new NPCMetadata(0, 15, -8, -4, false, 10) }, // hamster + { 165, new NPCMetadata(0, 13, 0, 0, false, 10) }, // mole + { 166, new NPCMetadata(0, 18, 0, 0, true, 32) }, // fish + { 167, new NPCMetadata(0, 14, -6, -3, false, 22) }, // lizzy + { 168, new NPCMetadata(0, 15, -8, -4, false, 15) }, // ape + { 169, new NPCMetadata(0, 4, -8, -4, false, 19) }, // taraduda + { 170, new NPCMetadata(0, 19, -8, -4, false, 17) }, // monkey + { 171, new NPCMetadata(0, 0, 0, 0, false, 0) }, // ancient wraith + }; + _metadataLoader = metadataLoader; + } - public NPCMetadata GetValueOrDefault(int graphic) - { - return _metadataLoader.GetMetadata(graphic) - .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : NPCMetadata.Default); - } + public NPCMetadata GetValueOrDefault(int graphic) + { + return _metadataLoader.GetMetadata(graphic) + .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : NPCMetadata.Default); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs b/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs index b5fbab4ac..6199e292f 100644 --- a/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs @@ -2,35 +2,34 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata +namespace EndlessClient.Rendering.Metadata; + +[AutoMappedType(IsSingleton = true)] +public class ShieldMetadataProvider : IMetadataProvider { - [AutoMappedType(IsSingleton = true)] - public class ShieldMetadataProvider : IMetadataProvider - { - public IReadOnlyDictionary DefaultMetadata => _metadata; + public IReadOnlyDictionary DefaultMetadata => _metadata; - private readonly Dictionary _metadata; - private readonly IGFXMetadataLoader _metadataLoader; + private readonly Dictionary _metadata; + private readonly IGFXMetadataLoader _metadataLoader; - public ShieldMetadataProvider(IGFXMetadataLoader metadataLoader) + public ShieldMetadataProvider(IGFXMetadataLoader metadataLoader) + { + _metadata = new Dictionary { - _metadata = new Dictionary - { - { 10, new ShieldMetadata(true) }, // good wings - { 11, new ShieldMetadata(true) }, // bag - { 14, new ShieldMetadata(true) }, // normal arrows - { 15, new ShieldMetadata(true) }, // frost arrows - { 16, new ShieldMetadata(true) }, // fire arrows - { 18, new ShieldMetadata(true) }, // good force wings - { 19, new ShieldMetadata(true) }, // fire force wings - }; - _metadataLoader = metadataLoader; - } + { 10, new ShieldMetadata(true) }, // good wings + { 11, new ShieldMetadata(true) }, // bag + { 14, new ShieldMetadata(true) }, // normal arrows + { 15, new ShieldMetadata(true) }, // frost arrows + { 16, new ShieldMetadata(true) }, // fire arrows + { 18, new ShieldMetadata(true) }, // good force wings + { 19, new ShieldMetadata(true) }, // fire force wings + }; + _metadataLoader = metadataLoader; + } - public ShieldMetadata GetValueOrDefault(int graphic) - { - return _metadataLoader.GetMetadata(graphic) - .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : ShieldMetadata.Default); - } + public ShieldMetadata GetValueOrDefault(int graphic) + { + return _metadataLoader.GetMetadata(graphic) + .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : ShieldMetadata.Default); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs b/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs index 5aa1bf734..20a3264c1 100644 --- a/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs @@ -3,103 +3,102 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata +namespace EndlessClient.Rendering.Metadata; + +[AutoMappedType(IsSingleton = true)] +public class WeaponMetadataProvider : IMetadataProvider { - [AutoMappedType(IsSingleton = true)] - public class WeaponMetadataProvider : IMetadataProvider - { - public IReadOnlyDictionary DefaultMetadata => _metadata; + public IReadOnlyDictionary DefaultMetadata => _metadata; - private readonly Dictionary _metadata; - private readonly IGFXMetadataLoader _metadataLoader; + private readonly Dictionary _metadata; + private readonly IGFXMetadataLoader _metadataLoader; - public WeaponMetadataProvider(IGFXMetadataLoader metadataLoader) + public WeaponMetadataProvider(IGFXMetadataLoader metadataLoader) + { + _metadata = new Dictionary { - _metadata = new Dictionary - { - { 0, new WeaponMetadata(null, new[] { SoundEffectID.PunchAttack }, false) }, // fist - { 1, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // wood axe - { 2, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // sai - { 3, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dragon blade - { 4, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dagger - { 5, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // spear - { 6, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // saber - { 7, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // staff - { 8, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // book - { 9, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // mace - { 10, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // spirit star - { 11, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // throw axe - { 12, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dark katana - { 13, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // short sword - { 14, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // broadsword - { 15, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // broom - { 16, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ninchackus - { 17, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ancient star - { 18, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle axe - { 19, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ancient sword - { 20, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // luna staff - { 21, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lance - { 22, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // aura staff - { 23, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // forest staff - { 24, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // normal sword - { 25, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // jewel staff - { 26, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // thor's hammer - { 27, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // light katana - { 28, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // polearm - { 29, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // sickle - { 30, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // trident - { 31, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // warlock sword - { 32, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // whip - { 33, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ultima - { 34, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ice blade - { 35, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gold defender - { 36, new WeaponMetadata(4, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lotus sword - { 37, new WeaponMetadata(4, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // cristal sword - { 38, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // killing edge - { 39, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // dark blade - { 40, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // reaper scyth - { 41, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // crescent staff - { 42, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // bow - { 43, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // xbow - { 44, new WeaponMetadata(8, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // reaper - { 45, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // hockey stick - { 46, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // twin blades - { 47, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lefor mace - { 48, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // cava staff - { 49, new WeaponMetadata(0, new[] { SoundEffectID.Harp1,SoundEffectID.Harp2,SoundEffectID.Harp3}, true) }, // harp - { 50, new WeaponMetadata(0, new[] { SoundEffectID.Guitar1,SoundEffectID.Guitar2, SoundEffectID.Guitar3 }, true) }, // guitar - { 51, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle spear - { 52, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // flail - { 53, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // war axe - { 54, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gastro - { 55, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // ablo staff - { 56, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fluon sword - { 57, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // rapier - { 58, new WeaponMetadata(0, new[] { SoundEffectID.Gun }, true) }, // gun - { 59, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // knob staff - { 60, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fladdat staff - { 61, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gabrasto - { 62, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle spear 2 - { 63, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lens of truth - { 64, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // chopper - { 65, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // adger - { 66, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // chains - { 67, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // mitova - { 68, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // merhawk - { 69, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // kontra - { 70, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // jack spear - { 71, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // bazar staff - { 72, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // saw blade - { 73, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // scav bow - { 74, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fan - }; - _metadataLoader = metadataLoader; - } + { 0, new WeaponMetadata(null, new[] { SoundEffectID.PunchAttack }, false) }, // fist + { 1, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // wood axe + { 2, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // sai + { 3, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dragon blade + { 4, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dagger + { 5, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // spear + { 6, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // saber + { 7, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // staff + { 8, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // book + { 9, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // mace + { 10, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // spirit star + { 11, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // throw axe + { 12, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dark katana + { 13, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // short sword + { 14, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // broadsword + { 15, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // broom + { 16, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ninchackus + { 17, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ancient star + { 18, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle axe + { 19, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ancient sword + { 20, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // luna staff + { 21, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lance + { 22, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // aura staff + { 23, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // forest staff + { 24, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // normal sword + { 25, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // jewel staff + { 26, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // thor's hammer + { 27, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // light katana + { 28, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // polearm + { 29, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // sickle + { 30, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // trident + { 31, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // warlock sword + { 32, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // whip + { 33, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ultima + { 34, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ice blade + { 35, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gold defender + { 36, new WeaponMetadata(4, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lotus sword + { 37, new WeaponMetadata(4, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // cristal sword + { 38, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // killing edge + { 39, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // dark blade + { 40, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // reaper scyth + { 41, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // crescent staff + { 42, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // bow + { 43, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // xbow + { 44, new WeaponMetadata(8, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // reaper + { 45, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // hockey stick + { 46, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // twin blades + { 47, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lefor mace + { 48, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // cava staff + { 49, new WeaponMetadata(0, new[] { SoundEffectID.Harp1,SoundEffectID.Harp2,SoundEffectID.Harp3}, true) }, // harp + { 50, new WeaponMetadata(0, new[] { SoundEffectID.Guitar1,SoundEffectID.Guitar2, SoundEffectID.Guitar3 }, true) }, // guitar + { 51, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle spear + { 52, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // flail + { 53, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // war axe + { 54, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gastro + { 55, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // ablo staff + { 56, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fluon sword + { 57, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // rapier + { 58, new WeaponMetadata(0, new[] { SoundEffectID.Gun }, true) }, // gun + { 59, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // knob staff + { 60, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fladdat staff + { 61, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gabrasto + { 62, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle spear 2 + { 63, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lens of truth + { 64, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // chopper + { 65, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // adger + { 66, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // chains + { 67, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // mitova + { 68, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // merhawk + { 69, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // kontra + { 70, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // jack spear + { 71, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // bazar staff + { 72, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // saw blade + { 73, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // scav bow + { 74, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fan + }; + _metadataLoader = metadataLoader; + } - public WeaponMetadata GetValueOrDefault(int graphic) - { - return _metadataLoader.GetMetadata(graphic) - .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : WeaponMetadata.Default); - } + public WeaponMetadata GetValueOrDefault(int graphic) + { + return _metadataLoader.GetMetadata(graphic) + .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : WeaponMetadata.Default); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MouseCursorRenderer.cs b/EndlessClient/Rendering/MouseCursorRenderer.cs index f311a3a5b..9f04a642c 100644 --- a/EndlessClient/Rendering/MouseCursorRenderer.cs +++ b/EndlessClient/Rendering/MouseCursorRenderer.cs @@ -17,302 +17,301 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +public class MouseCursorRenderer : XNAControl, IMouseCursorRenderer { - public class MouseCursorRenderer : XNAControl, IMouseCursorRenderer + private enum CursorIndex { - private enum CursorIndex - { - Standard = 0, - HoverNormal = 1, - HoverItem = 2, - ClickFirstFrame = 3, - ClickSecondFrame = 4, - NumberOfFramesInSheet = 5 - } + Standard = 0, + HoverNormal = 1, + HoverItem = 2, + ClickFirstFrame = 3, + ClickSecondFrame = 4, + NumberOfFramesInSheet = 5 + } - private readonly Rectangle SingleCursorFrameArea; - - private readonly Texture2D _mouseCursorTexture; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IMapCellStateProvider _mapCellStateProvider; - private readonly IItemStringService _itemStringService; - private readonly IItemNameColorService _itemNameColorService; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly IContextMenuProvider _contextMenuProvider; - - private readonly XNALabel _mapItemText; - - private int _gridX, _gridY; - private CursorIndex _cursorIndex; - private bool _shouldDrawCursor; - - private Option _startClickTime; - private CursorIndex _clickFrame; - private int _clickAlpha; - private Option _clickCoordinate; - - public MapCoordinate GridCoordinates => new MapCoordinate(_gridX, _gridY); - - public MouseCursorRenderer(INativeGraphicsManager nativeGraphicsManager, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IMapCellStateProvider mapCellStateProvider, - IItemStringService itemStringService, - IItemNameColorService itemNameColorService, - IEIFFileProvider eifFileProvider, - ICurrentMapProvider currentMapProvider, - IUserInputProvider userInputProvider, - IActiveDialogProvider activeDialogProvider, - IContextMenuProvider contextMenuProvider) + private readonly Rectangle SingleCursorFrameArea; + + private readonly Texture2D _mouseCursorTexture; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IMapCellStateProvider _mapCellStateProvider; + private readonly IItemStringService _itemStringService; + private readonly IItemNameColorService _itemNameColorService; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly IContextMenuProvider _contextMenuProvider; + + private readonly XNALabel _mapItemText; + + private int _gridX, _gridY; + private CursorIndex _cursorIndex; + private bool _shouldDrawCursor; + + private Option _startClickTime; + private CursorIndex _clickFrame; + private int _clickAlpha; + private Option _clickCoordinate; + + public MapCoordinate GridCoordinates => new MapCoordinate(_gridX, _gridY); + + public MouseCursorRenderer(INativeGraphicsManager nativeGraphicsManager, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IMapCellStateProvider mapCellStateProvider, + IItemStringService itemStringService, + IItemNameColorService itemNameColorService, + IEIFFileProvider eifFileProvider, + ICurrentMapProvider currentMapProvider, + IUserInputProvider userInputProvider, + IActiveDialogProvider activeDialogProvider, + IContextMenuProvider contextMenuProvider) + { + _mouseCursorTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 24, true); + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _mapCellStateProvider = mapCellStateProvider; + _itemStringService = itemStringService; + _itemNameColorService = itemNameColorService; + _eifFileProvider = eifFileProvider; + _currentMapProvider = currentMapProvider; + _userInputProvider = userInputProvider; + _activeDialogProvider = activeDialogProvider; + _contextMenuProvider = contextMenuProvider; + + SingleCursorFrameArea = new Rectangle(0, 0, + _mouseCursorTexture.Width / (int)CursorIndex.NumberOfFramesInSheet, + _mouseCursorTexture.Height); + DrawArea = SingleCursorFrameArea; + + _mapItemText = new XNALabel(Constants.FontSize09) { - _mouseCursorTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 24, true); - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _mapCellStateProvider = mapCellStateProvider; - _itemStringService = itemStringService; - _itemNameColorService = itemNameColorService; - _eifFileProvider = eifFileProvider; - _currentMapProvider = currentMapProvider; - _userInputProvider = userInputProvider; - _activeDialogProvider = activeDialogProvider; - _contextMenuProvider = contextMenuProvider; - - SingleCursorFrameArea = new Rectangle(0, 0, - _mouseCursorTexture.Width / (int)CursorIndex.NumberOfFramesInSheet, - _mouseCursorTexture.Height); - DrawArea = SingleCursorFrameArea; - - _mapItemText = new XNALabel(Constants.FontSize09) - { - Visible = false, - Text = string.Empty, - ForeColor = Color.White, - AutoSize = false, - DrawOrder = 10 //todo: make a better provider for draw orders (see also HudControlsFactory) - }; - - _clickCoordinate = Option.None(); - } + Visible = false, + Text = string.Empty, + ForeColor = Color.White, + AutoSize = false, + DrawOrder = 10 //todo: make a better provider for draw orders (see also HudControlsFactory) + }; + + _clickCoordinate = Option.None(); + } - public override void Initialize() - { - _mapItemText.AddControlToDefaultGame(); - } + public override void Initialize() + { + _mapItemText.AddControlToDefaultGame(); + } - #region Update and Helpers + #region Update and Helpers - public override void Update(GameTime gameTime) - { - // prevents updates if there is a dialog - if (!ShouldUpdate() || _activeDialogProvider.ActiveDialogs.Any(x => x.HasValue) || - _contextMenuProvider.ContextMenu.HasValue) - return; + public override void Update(GameTime gameTime) + { + // prevents updates if there is a dialog + if (!ShouldUpdate() || _activeDialogProvider.ActiveDialogs.Any(x => x.HasValue) || + _contextMenuProvider.ContextMenu.HasValue) + return; - var gridPosition = _gridDrawCoordinateCalculator.CalculateGridCoordinatesFromDrawLocation(_userInputProvider.CurrentMouseState.Position.ToVector2()); - _gridX = gridPosition.X; - _gridY = gridPosition.Y; + var gridPosition = _gridDrawCoordinateCalculator.CalculateGridCoordinatesFromDrawLocation(_userInputProvider.CurrentMouseState.Position.ToVector2()); + _gridX = gridPosition.X; + _gridY = gridPosition.Y; - UpdateDrawPostionBasedOnGridPosition(); + UpdateDrawPostionBasedOnGridPosition(); - var cellState = _mapCellStateProvider.GetCellStateAt(_gridX, _gridY); - UpdateCursorSourceRectangle(cellState); - } + var cellState = _mapCellStateProvider.GetCellStateAt(_gridX, _gridY); + UpdateCursorSourceRectangle(cellState); + } - private void UpdateDrawPostionBasedOnGridPosition() + private void UpdateDrawPostionBasedOnGridPosition() + { + var drawPosition = _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(_gridX, _gridY); + DrawArea = new Rectangle((int)drawPosition.X, + (int)drawPosition.Y, + DrawArea.Width, + DrawArea.Height); + } + + private void UpdateCursorSourceRectangle(IMapCellState cellState) + { + _shouldDrawCursor = true; + _cursorIndex = CursorIndex.Standard; + if (cellState.Character.HasValue || cellState.NPC.HasValue) + _cursorIndex = CursorIndex.HoverNormal; + else if (cellState.Sign.HasValue) + _shouldDrawCursor = false; + else if (cellState.Items.Any()) { - var drawPosition = _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(_gridX, _gridY); - DrawArea = new Rectangle((int)drawPosition.X, - (int)drawPosition.Y, - DrawArea.Width, - DrawArea.Height); + _cursorIndex = CursorIndex.HoverItem; + UpdateMapItemLabel(Option.Some(cellState.Items.First())); } + else if (cellState.TileSpec != TileSpec.None) + UpdateCursorIndexForTileSpec(cellState.TileSpec); - private void UpdateCursorSourceRectangle(IMapCellState cellState) - { - _shouldDrawCursor = true; - _cursorIndex = CursorIndex.Standard; - if (cellState.Character.HasValue || cellState.NPC.HasValue) - _cursorIndex = CursorIndex.HoverNormal; - else if (cellState.Sign.HasValue) - _shouldDrawCursor = false; - else if (cellState.Items.Any()) - { - _cursorIndex = CursorIndex.HoverItem; - UpdateMapItemLabel(Option.Some(cellState.Items.First())); - } - else if (cellState.TileSpec != TileSpec.None) - UpdateCursorIndexForTileSpec(cellState.TileSpec); + if (!cellState.Items.Any()) + UpdateMapItemLabel(Option.None()); - if (!cellState.Items.Any()) - UpdateMapItemLabel(Option.None()); + if (_mapItemText.Visible) + { + //relative to cursor DrawPosition, since this control is a parent of MapItemText + _mapItemText.DrawPosition = new Vector2(DrawArea.X + 32 - _mapItemText.ActualWidth / 2f, + DrawArea.Y + -_mapItemText.ActualHeight - 4); + } - if (_mapItemText.Visible) + _startClickTime.MatchSome(st => { - //relative to cursor DrawPosition, since this control is a parent of MapItemText - _mapItemText.DrawPosition = new Vector2(DrawArea.X + 32 - _mapItemText.ActualWidth / 2f, - DrawArea.Y + -_mapItemText.ActualHeight - 4); - } + _clickAlpha -= 5; - _startClickTime.MatchSome(st => + if (st.ElapsedMilliseconds > 350) { - _clickAlpha -= 5; + _startClickTime = Option.Some(Stopwatch.StartNew()); + _clickFrame++; - if (st.ElapsedMilliseconds > 350) + if (_clickFrame != CursorIndex.ClickFirstFrame && _clickFrame != CursorIndex.ClickSecondFrame) { - _startClickTime = Option.Some(Stopwatch.StartNew()); - _clickFrame++; - - if (_clickFrame != CursorIndex.ClickFirstFrame && _clickFrame != CursorIndex.ClickSecondFrame) - { - _clickFrame = CursorIndex.Standard; - _startClickTime = Option.None(); - _clickCoordinate = Option.None(); - } + _clickFrame = CursorIndex.Standard; + _startClickTime = Option.None(); + _clickCoordinate = Option.None(); } - }); - } + } + }); + } - private void UpdateMapItemLabel(Option item) - { - item.Match( - some: i => - { - var data = _eifFileProvider.EIFFile[i.ItemID]; - var text = _itemStringService.GetStringForMapDisplay(data, i.Amount); + private void UpdateMapItemLabel(Option item) + { + item.Match( + some: i => + { + var data = _eifFileProvider.EIFFile[i.ItemID]; + var text = _itemStringService.GetStringForMapDisplay(data, i.Amount); - if (!_mapItemText.Visible || _mapItemText.Text != text) - { - _mapItemText.Visible = true; - _mapItemText.Text = text; - _mapItemText.ResizeBasedOnText(); - _mapItemText.ForeColor = _itemNameColorService.GetColorForMapDisplay(data); - } - }, - none: () => + if (!_mapItemText.Visible || _mapItemText.Text != text) { - _mapItemText.Visible = false; - _mapItemText.Text = string.Empty; - }); - } + _mapItemText.Visible = true; + _mapItemText.Text = text; + _mapItemText.ResizeBasedOnText(); + _mapItemText.ForeColor = _itemNameColorService.GetColorForMapDisplay(data); + } + }, + none: () => + { + _mapItemText.Visible = false; + _mapItemText.Text = string.Empty; + }); + } - private void UpdateCursorIndexForTileSpec(TileSpec tileSpec) + private void UpdateCursorIndexForTileSpec(TileSpec tileSpec) + { + switch (tileSpec) { - switch (tileSpec) - { - case TileSpec.Wall: - case TileSpec.JammedDoor: - case TileSpec.MapEdge: - case TileSpec.FakeWall: - case TileSpec.VultTypo: - _shouldDrawCursor = false; - break; - case TileSpec.Chest: - case TileSpec.BankVault: - case TileSpec.ChairDown: - case TileSpec.ChairLeft: - case TileSpec.ChairRight: - case TileSpec.ChairUp: - case TileSpec.ChairDownRight: - case TileSpec.ChairUpLeft: - case TileSpec.ChairAll: - case TileSpec.Board1: - case TileSpec.Board2: - case TileSpec.Board3: - case TileSpec.Board4: - case TileSpec.Board5: - case TileSpec.Board6: - case TileSpec.Board7: - case TileSpec.Board8: - case TileSpec.Jukebox: - _cursorIndex = CursorIndex.HoverNormal; - break; - case TileSpec.NPCBoundary: - case TileSpec.Jump: - case TileSpec.Water: - case TileSpec.Arena: - case TileSpec.AmbientSource: - case TileSpec.SpikesStatic: - case TileSpec.SpikesTrap: - case TileSpec.SpikesTimed: - case TileSpec.None: - _cursorIndex = CursorIndex.Standard; - break; - default: - _cursorIndex = CursorIndex.HoverNormal; - break; - } + case TileSpec.Wall: + case TileSpec.JammedDoor: + case TileSpec.MapEdge: + case TileSpec.FakeWall: + case TileSpec.VultTypo: + _shouldDrawCursor = false; + break; + case TileSpec.Chest: + case TileSpec.BankVault: + case TileSpec.ChairDown: + case TileSpec.ChairLeft: + case TileSpec.ChairRight: + case TileSpec.ChairUp: + case TileSpec.ChairDownRight: + case TileSpec.ChairUpLeft: + case TileSpec.ChairAll: + case TileSpec.Board1: + case TileSpec.Board2: + case TileSpec.Board3: + case TileSpec.Board4: + case TileSpec.Board5: + case TileSpec.Board6: + case TileSpec.Board7: + case TileSpec.Board8: + case TileSpec.Jukebox: + _cursorIndex = CursorIndex.HoverNormal; + break; + case TileSpec.NPCBoundary: + case TileSpec.Jump: + case TileSpec.Water: + case TileSpec.Arena: + case TileSpec.AmbientSource: + case TileSpec.SpikesStatic: + case TileSpec.SpikesTrap: + case TileSpec.SpikesTimed: + case TileSpec.None: + _cursorIndex = CursorIndex.Standard; + break; + default: + _cursorIndex = CursorIndex.HoverNormal; + break; } + } + + #endregion - #endregion + public void Draw(SpriteBatch spriteBatch, Vector2 additionalOffset) + { + if (_contextMenuProvider.ContextMenu.HasValue) + return; - public void Draw(SpriteBatch spriteBatch, Vector2 additionalOffset) + if (_shouldDrawCursor && _gridX >= 0 && _gridY >= 0 && + _gridX <= _currentMapProvider.CurrentMap.Properties.Width && + _gridY <= _currentMapProvider.CurrentMap.Properties.Height) { - if (_contextMenuProvider.ContextMenu.HasValue) - return; + spriteBatch.Draw(_mouseCursorTexture, + DrawPosition + additionalOffset, + new Rectangle(SingleCursorFrameArea.Width * (int)_cursorIndex, + 0, + SingleCursorFrameArea.Width, + SingleCursorFrameArea.Height), + Color.White); + } - if (_shouldDrawCursor && _gridX >= 0 && _gridY >= 0 && - _gridX <= _currentMapProvider.CurrentMap.Properties.Width && - _gridY <= _currentMapProvider.CurrentMap.Properties.Height) + if (_startClickTime.HasValue) + { + _clickCoordinate.MatchSome(c => { + var position = _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c); spriteBatch.Draw(_mouseCursorTexture, - DrawPosition + additionalOffset, - new Rectangle(SingleCursorFrameArea.Width * (int)_cursorIndex, - 0, - SingleCursorFrameArea.Width, - SingleCursorFrameArea.Height), - Color.White); - } - - if (_startClickTime.HasValue) - { - _clickCoordinate.MatchSome(c => - { - var position = _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c); - spriteBatch.Draw(_mouseCursorTexture, - position + additionalOffset, - SingleCursorFrameArea.WithPosition(new Vector2(SingleCursorFrameArea.Width * (int)_clickFrame, 0)), - Color.FromNonPremultiplied(255, 255, 255, _clickAlpha)); - }); - } + position + additionalOffset, + SingleCursorFrameArea.WithPosition(new Vector2(SingleCursorFrameArea.Width * (int)_clickFrame, 0)), + Color.FromNonPremultiplied(255, 255, 255, _clickAlpha)); + }); } + } - public void AnimateClick() - { - if (_startClickTime.HasValue) - return; + public void AnimateClick() + { + if (_startClickTime.HasValue) + return; - _startClickTime = Option.Some(Stopwatch.StartNew()); - _clickFrame = CursorIndex.ClickFirstFrame; - _clickAlpha = 200; - _clickCoordinate = Option.Some(new MapCoordinate(_gridX, _gridY)); - } + _startClickTime = Option.Some(Stopwatch.StartNew()); + _clickFrame = CursorIndex.ClickFirstFrame; + _clickAlpha = 200; + _clickCoordinate = Option.Some(new MapCoordinate(_gridX, _gridY)); + } - public void ClearTransientRenderables() - { - _mapItemText.Visible = false; - _startClickTime = Option.None(); - } + public void ClearTransientRenderables() + { + _mapItemText.Visible = false; + _startClickTime = Option.None(); + } - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - _spriteBatch.Dispose(); - _mapItemText.Dispose(); - } + _spriteBatch.Dispose(); + _mapItemText.Dispose(); } } +} - public interface IMouseCursorRenderer : IXNAControl, IDisposable - { - MapCoordinate GridCoordinates { get; } +public interface IMouseCursorRenderer : IXNAControl, IDisposable +{ + MapCoordinate GridCoordinates { get; } - void Draw(SpriteBatch spriteBatch, Vector2 additionalOffset); + void Draw(SpriteBatch spriteBatch, Vector2 additionalOffset); - void AnimateClick(); + void AnimateClick(); - void ClearTransientRenderables(); - } + void ClearTransientRenderables(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/INPCRenderer.cs b/EndlessClient/Rendering/NPC/INPCRenderer.cs index 654c13446..238154a37 100644 --- a/EndlessClient/Rendering/NPC/INPCRenderer.cs +++ b/EndlessClient/Rendering/NPC/INPCRenderer.cs @@ -2,18 +2,17 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.NPC +namespace EndlessClient.Rendering.NPC; + +public interface INPCRenderer : IDrawable, IUpdateable, IGameComponent, IDisposable, IMapActor { - public interface INPCRenderer : IDrawable, IUpdateable, IGameComponent, IDisposable, IMapActor - { - EOLib.Domain.NPC.NPC NPC { get; set; } + EOLib.Domain.NPC.NPC NPC { get; set; } - bool IsDead { get; } + bool IsDead { get; } - bool IsClickablePixel(Point currentMousePosition); + bool IsClickablePixel(Point currentMousePosition); - void DrawToSpriteBatch(SpriteBatch spriteBatch); + void DrawToSpriteBatch(SpriteBatch spriteBatch); - void StartDying(); - } + void StartDying(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCActions.cs b/EndlessClient/Rendering/NPC/NPCActions.cs index 1a150be36..a8ef0ab5a 100644 --- a/EndlessClient/Rendering/NPC/NPCActions.cs +++ b/EndlessClient/Rendering/NPC/NPCActions.cs @@ -11,158 +11,157 @@ using EOLib.Localization; using Optional; -namespace EndlessClient.Rendering.NPC +namespace EndlessClient.Rendering.NPC; + +[AutoMappedType] +public class NPCActions : INPCActionNotifier { - [AutoMappedType] - public class NPCActions : INPCActionNotifier + private readonly IHudControlProvider _hudControlProvider; + private readonly INPCStateCache _npcStateCache; + private readonly INPCRendererRepository _npcRendererRepository; + private readonly ICharacterRendererRepository _characterRendererRepository; + private readonly IChatBubbleActions _chatBubbleActions; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IESFFileProvider _esfFileProvider; + private readonly ISfxPlayer _sfxPlayer; + + public NPCActions(IHudControlProvider hudControlProvider, + INPCStateCache npcStateCache, + INPCRendererRepository npcRendererRepository, + ICharacterRendererRepository characterRendererRepository, + IChatBubbleActions chatBubbleActions, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + IEIFFileProvider eifFileProvider, + IESFFileProvider esfFileProvider, + ISfxPlayer sfxPlayer) { - private readonly IHudControlProvider _hudControlProvider; - private readonly INPCStateCache _npcStateCache; - private readonly INPCRendererRepository _npcRendererRepository; - private readonly ICharacterRendererRepository _characterRendererRepository; - private readonly IChatBubbleActions _chatBubbleActions; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IESFFileProvider _esfFileProvider; - private readonly ISfxPlayer _sfxPlayer; - - public NPCActions(IHudControlProvider hudControlProvider, - INPCStateCache npcStateCache, - INPCRendererRepository npcRendererRepository, - ICharacterRendererRepository characterRendererRepository, - IChatBubbleActions chatBubbleActions, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - IEIFFileProvider eifFileProvider, - IESFFileProvider esfFileProvider, - ISfxPlayer sfxPlayer) - { - _hudControlProvider = hudControlProvider; - _npcStateCache = npcStateCache; - _npcRendererRepository = npcRendererRepository; - _characterRendererRepository = characterRendererRepository; - _chatBubbleActions = chatBubbleActions; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _eifFileProvider = eifFileProvider; - _esfFileProvider = esfFileProvider; - _sfxPlayer = sfxPlayer; - } + _hudControlProvider = hudControlProvider; + _npcStateCache = npcStateCache; + _npcRendererRepository = npcRendererRepository; + _characterRendererRepository = characterRendererRepository; + _chatBubbleActions = chatBubbleActions; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _eifFileProvider = eifFileProvider; + _esfFileProvider = esfFileProvider; + _sfxPlayer = sfxPlayer; + } - public void StartNPCWalkAnimation(int npcIndex) - { - if (!_hudControlProvider.IsInGame) - return; + public void StartNPCWalkAnimation(int npcIndex) + { + if (!_hudControlProvider.IsInGame) + return; - Animator.StartWalkAnimation(npcIndex); - } + Animator.StartWalkAnimation(npcIndex); + } - public void StartNPCAttackAnimation(int npcIndex) - { - if (!_hudControlProvider.IsInGame) - return; + public void StartNPCAttackAnimation(int npcIndex) + { + if (!_hudControlProvider.IsInGame) + return; - Animator.StartAttackAnimation(npcIndex); + Animator.StartAttackAnimation(npcIndex); - _sfxPlayer.PlaySfx(SoundEffectID.PunchAttack); - } + _sfxPlayer.PlaySfx(SoundEffectID.PunchAttack); + } - public void RemoveNPCFromView(int npcIndex, int playerId, Option spellId, Option damage, bool showDeathAnimation) - { - //possible that the server might send a packet for the npc to be removed by the map switch is completed - if (!_hudControlProvider.IsInGame) - return; + public void RemoveNPCFromView(int npcIndex, int playerId, Option spellId, Option damage, bool showDeathAnimation) + { + //possible that the server might send a packet for the npc to be removed by the map switch is completed + if (!_hudControlProvider.IsInGame) + return; - var hasRenderer = _npcRendererRepository.NPCRenderers.ContainsKey(npcIndex); + var hasRenderer = _npcRendererRepository.NPCRenderers.ContainsKey(npcIndex); - _npcStateCache.RemoveStateByIndex(npcIndex); + _npcStateCache.RemoveStateByIndex(npcIndex); - if (hasRenderer) - { - var renderer = _npcRendererRepository.NPCRenderers[npcIndex]; + if (hasRenderer) + { + var renderer = _npcRendererRepository.NPCRenderers[npcIndex]; - if (!showDeathAnimation) - { - renderer.Dispose(); - _npcRendererRepository.NPCRenderers.Remove(npcIndex); - } - else - { - renderer.StartDying(); - _npcRendererRepository.DyingNPCs[new MapCoordinate(renderer.NPC.X, renderer.NPC.Y)] = npcIndex; - - damage.MatchSome(d => renderer.ShowDamageCounter(d, 0, isHeal: false)); - } + if (!showDeathAnimation) + { + renderer.Dispose(); + _npcRendererRepository.NPCRenderers.Remove(npcIndex); } - - spellId.MatchSome(spell => + else { - if (hasRenderer) - { - var graphic = _esfFileProvider.ESFFile[spell].Graphic; - _npcRendererRepository.NPCRenderers[npcIndex].PlayEffect(graphic); - } + renderer.StartDying(); + _npcRendererRepository.DyingNPCs[new MapCoordinate(renderer.NPC.X, renderer.NPC.Y)] = npcIndex; - ShoutSpellCast(playerId); - }); - } - - public void ShowNPCSpeechBubble(int npcIndex, string message) - { - _chatBubbleActions.ShowChatBubbleForNPC(npcIndex, message); + damage.MatchSome(d => renderer.ShowDamageCounter(d, 0, isHeal: false)); + } } - public void NPCTakeDamage(int npcIndex, int fromPlayerId, int damageToNpc, int npcPctHealth, Option spellId) + spellId.MatchSome(spell => { - var hasRenderer = _npcRendererRepository.NPCRenderers.ContainsKey(npcIndex); - if (hasRenderer) - _npcRendererRepository.NPCRenderers[npcIndex].ShowDamageCounter(damageToNpc, npcPctHealth, isHeal: false); - - spellId.MatchSome(spell => { - if (hasRenderer) - { - var renderer = _npcRendererRepository.NPCRenderers[npcIndex]; + var graphic = _esfFileProvider.ESFFile[spell].Graphic; + _npcRendererRepository.NPCRenderers[npcIndex].PlayEffect(graphic); + } - var graphic = _esfFileProvider.ESFFile[spell].Graphic; - renderer.PlayEffect(graphic); - } + ShoutSpellCast(playerId); + }); + } - ShoutSpellCast(fromPlayerId); - }); - } + public void ShowNPCSpeechBubble(int npcIndex, string message) + { + _chatBubbleActions.ShowChatBubbleForNPC(npcIndex, message); + } - public void NPCDropItem(MapItem item) - { - // todo: not sure if it is better to do this here in a notifier or modify the chat repository in the packet handler - // however, I don't want to introduce a dependency on localized text in the packet handler - var itemName = _eifFileProvider.EIFFile[item.ItemID].Name; - var chatData = new ChatData(ChatTab.System, - string.Empty, - $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_THE_NPC_DROPPED)} {item.Amount} {itemName}", - ChatIcon.DownArrow); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } + public void NPCTakeDamage(int npcIndex, int fromPlayerId, int damageToNpc, int npcPctHealth, Option spellId) + { + var hasRenderer = _npcRendererRepository.NPCRenderers.ContainsKey(npcIndex); + + if (hasRenderer) + _npcRendererRepository.NPCRenderers[npcIndex].ShowDamageCounter(damageToNpc, npcPctHealth, isHeal: false); - private void ShoutSpellCast(int playerId) + spellId.MatchSome(spell => { - _characterRendererRepository.MainCharacterRenderer.Match( - some: r => - { - if (r.Character.ID == playerId) - r.ShoutSpellCast(); - else if (_characterRendererRepository.CharacterRenderers.ContainsKey(playerId)) - _characterRendererRepository.CharacterRenderers[playerId].ShoutSpellCast(); - }, - none: () => - { - if (_characterRendererRepository.CharacterRenderers.ContainsKey(playerId)) - _characterRendererRepository.CharacterRenderers[playerId].ShoutSpellCast(); - }); - } + if (hasRenderer) + { + var renderer = _npcRendererRepository.NPCRenderers[npcIndex]; + + var graphic = _esfFileProvider.ESFFile[spell].Graphic; + renderer.PlayEffect(graphic); + } - private INPCAnimator Animator => _hudControlProvider.GetComponent(HudControlIdentifier.NPCAnimator); + ShoutSpellCast(fromPlayerId); + }); } + + public void NPCDropItem(MapItem item) + { + // todo: not sure if it is better to do this here in a notifier or modify the chat repository in the packet handler + // however, I don't want to introduce a dependency on localized text in the packet handler + var itemName = _eifFileProvider.EIFFile[item.ItemID].Name; + var chatData = new ChatData(ChatTab.System, + string.Empty, + $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_THE_NPC_DROPPED)} {item.Amount} {itemName}", + ChatIcon.DownArrow); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } + + private void ShoutSpellCast(int playerId) + { + _characterRendererRepository.MainCharacterRenderer.Match( + some: r => + { + if (r.Character.ID == playerId) + r.ShoutSpellCast(); + else if (_characterRendererRepository.CharacterRenderers.ContainsKey(playerId)) + _characterRendererRepository.CharacterRenderers[playerId].ShoutSpellCast(); + }, + none: () => + { + if (_characterRendererRepository.CharacterRenderers.ContainsKey(playerId)) + _characterRendererRepository.CharacterRenderers[playerId].ShoutSpellCast(); + }); + } + + private INPCAnimator Animator => _hudControlProvider.GetComponent(HudControlIdentifier.NPCAnimator); } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCAnimator.cs b/EndlessClient/Rendering/NPC/NPCAnimator.cs index 77124741a..db118c5ba 100644 --- a/EndlessClient/Rendering/NPC/NPCAnimator.cs +++ b/EndlessClient/Rendering/NPC/NPCAnimator.cs @@ -8,139 +8,138 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.NPC +namespace EndlessClient.Rendering.NPC; + +public class NPCAnimator : GameComponent, INPCAnimator { - public class NPCAnimator : GameComponent, INPCAnimator - { - private const int TICKS_PER_ACTION_FRAME = 8; // 8 x10ms ticks per action frame + private const int TICKS_PER_ACTION_FRAME = 8; // 8 x10ms ticks per action frame - private readonly List _npcStartWalkingTimes; - private readonly List _npcStartAttackingTimes; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + private readonly List _npcStartWalkingTimes; + private readonly List _npcStartAttackingTimes; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - public NPCAnimator(IEndlessGameProvider gameProvider, - ICurrentMapStateRepository currentMapStateRepository, - IFixedTimeStepRepository fixedTimeStepRepository) - : base((Game)gameProvider.Game) - { - _currentMapStateRepository = currentMapStateRepository; - _fixedTimeStepRepository = fixedTimeStepRepository; - _npcStartWalkingTimes = new List(); - _npcStartAttackingTimes = new List(); - } + public NPCAnimator(IEndlessGameProvider gameProvider, + ICurrentMapStateRepository currentMapStateRepository, + IFixedTimeStepRepository fixedTimeStepRepository) + : base((Game)gameProvider.Game) + { + _currentMapStateRepository = currentMapStateRepository; + _fixedTimeStepRepository = fixedTimeStepRepository; + _npcStartWalkingTimes = new List(); + _npcStartAttackingTimes = new List(); + } - public override void Update(GameTime gameTime) - { - AnimateNPCWalking(); - AnimateNPCAttacking(); + public override void Update(GameTime gameTime) + { + AnimateNPCWalking(); + AnimateNPCAttacking(); - base.Update(gameTime); - } + base.Update(gameTime); + } - public void StartWalkAnimation(int npcIndex) - { - if (_npcStartWalkingTimes.Any(x => x.UniqueID == npcIndex)) - return; + public void StartWalkAnimation(int npcIndex) + { + if (_npcStartWalkingTimes.Any(x => x.UniqueID == npcIndex)) + return; - var startWalkingTimeAndID = new RenderFrameActionTime(npcIndex, _fixedTimeStepRepository.TickCount); + var startWalkingTimeAndID = new RenderFrameActionTime(npcIndex, _fixedTimeStepRepository.TickCount); - _npcStartWalkingTimes.Add(startWalkingTimeAndID); - } + _npcStartWalkingTimes.Add(startWalkingTimeAndID); + } - public void StartAttackAnimation(int npcIndex) - { - if (_npcStartAttackingTimes.Any(x => x.UniqueID == npcIndex)) - return; + public void StartAttackAnimation(int npcIndex) + { + if (_npcStartAttackingTimes.Any(x => x.UniqueID == npcIndex)) + return; - var startAttackingTimeAndID = new RenderFrameActionTime(npcIndex, _fixedTimeStepRepository.TickCount); + var startAttackingTimeAndID = new RenderFrameActionTime(npcIndex, _fixedTimeStepRepository.TickCount); - _npcStartAttackingTimes.Add(startAttackingTimeAndID); - } + _npcStartAttackingTimes.Add(startAttackingTimeAndID); + } - public void StopAllAnimations() - { - _npcStartWalkingTimes.Clear(); - } + public void StopAllAnimations() + { + _npcStartWalkingTimes.Clear(); + } - private void AnimateNPCWalking() + private void AnimateNPCWalking() + { + var npcsDoneWalking = new List(); + foreach (var pair in _npcStartWalkingTimes) { - var npcsDoneWalking = new List(); - foreach (var pair in _npcStartWalkingTimes) + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_ACTION_FRAME) { - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_ACTION_FRAME) - { - var npc = _currentMapStateRepository.NPCs.SingleOrNone(x => x.Index == pair.UniqueID); - - npc.Match( - some: n => - { - var nextFrameNPC = AnimateOneWalkFrame(n); - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - - if (nextFrameNPC.Frame == NPCFrame.Standing) - npcsDoneWalking.Add(pair); - - _currentMapStateRepository.NPCs.Remove(n); - _currentMapStateRepository.NPCs.Add(nextFrameNPC); - }, - none: () => npcsDoneWalking.Add(pair)); - } - } + var npc = _currentMapStateRepository.NPCs.SingleOrNone(x => x.Index == pair.UniqueID); + + npc.Match( + some: n => + { + var nextFrameNPC = AnimateOneWalkFrame(n); + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + + if (nextFrameNPC.Frame == NPCFrame.Standing) + npcsDoneWalking.Add(pair); - _npcStartWalkingTimes.RemoveAll(npcsDoneWalking.Contains); + _currentMapStateRepository.NPCs.Remove(n); + _currentMapStateRepository.NPCs.Add(nextFrameNPC); + }, + none: () => npcsDoneWalking.Add(pair)); + } } - private void AnimateNPCAttacking() + _npcStartWalkingTimes.RemoveAll(npcsDoneWalking.Contains); + } + + private void AnimateNPCAttacking() + { + var npcsDoneAttacking = new List(); + foreach (var pair in _npcStartAttackingTimes) { - var npcsDoneAttacking = new List(); - foreach (var pair in _npcStartAttackingTimes) + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_ACTION_FRAME) { - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_ACTION_FRAME) - { - var npc = _currentMapStateRepository.NPCs.SingleOrNone(x => x.Index == pair.UniqueID); + var npc = _currentMapStateRepository.NPCs.SingleOrNone(x => x.Index == pair.UniqueID); - npc.Match( - some: n => - { - var nextFrameNPC = n.WithNextAttackFrame(); - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + npc.Match( + some: n => + { + var nextFrameNPC = n.WithNextAttackFrame(); + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - if (nextFrameNPC.Frame == NPCFrame.Standing) - npcsDoneAttacking.Add(pair); + if (nextFrameNPC.Frame == NPCFrame.Standing) + npcsDoneAttacking.Add(pair); - _currentMapStateRepository.NPCs.Remove(n); - _currentMapStateRepository.NPCs.Add(nextFrameNPC); + _currentMapStateRepository.NPCs.Remove(n); + _currentMapStateRepository.NPCs.Add(nextFrameNPC); - }, - none: () => npcsDoneAttacking.Add(pair)); - } + }, + none: () => npcsDoneAttacking.Add(pair)); } - - _npcStartAttackingTimes.RemoveAll(npcsDoneAttacking.Contains); } - private static EOLib.Domain.NPC.NPC AnimateOneWalkFrame(EOLib.Domain.NPC.NPC npc) - { - var nextFrameNPC = npc.WithNextWalkFrame(); + _npcStartAttackingTimes.RemoveAll(npcsDoneAttacking.Contains); + } - if (nextFrameNPC.IsActing(NPCActionState.Standing)) - { - nextFrameNPC = nextFrameNPC - .WithX(nextFrameNPC.GetDestinationX()) - .WithY(nextFrameNPC.GetDestinationY()); - } + private static EOLib.Domain.NPC.NPC AnimateOneWalkFrame(EOLib.Domain.NPC.NPC npc) + { + var nextFrameNPC = npc.WithNextWalkFrame(); - return nextFrameNPC; + if (nextFrameNPC.IsActing(NPCActionState.Standing)) + { + nextFrameNPC = nextFrameNPC + .WithX(nextFrameNPC.GetDestinationX()) + .WithY(nextFrameNPC.GetDestinationY()); } + + return nextFrameNPC; } +} - public interface INPCAnimator : IGameComponent - { - void StartWalkAnimation(int npcIndex); +public interface INPCAnimator : IGameComponent +{ + void StartWalkAnimation(int npcIndex); - void StartAttackAnimation(int npcIndex); + void StartAttackAnimation(int npcIndex); - void StopAllAnimations(); - } + void StopAllAnimations(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCCache.cs b/EndlessClient/Rendering/NPC/NPCCache.cs index 65c527286..caa4a7830 100644 --- a/EndlessClient/Rendering/NPC/NPCCache.cs +++ b/EndlessClient/Rendering/NPC/NPCCache.cs @@ -1,55 +1,54 @@ using AutomaticTypeMapper; using System.Collections.Generic; -namespace EndlessClient.Rendering.NPC +namespace EndlessClient.Rendering.NPC; + +[MappedType(BaseType = typeof(INPCStateCache), IsSingleton = true)] +public class NPCStateCache : INPCStateCache { - [MappedType(BaseType = typeof(INPCStateCache), IsSingleton = true)] - public class NPCStateCache : INPCStateCache + private readonly Dictionary _npcStates; + + public IReadOnlyDictionary NPCStates => _npcStates; + + public NPCStateCache() { - private readonly Dictionary _npcStates; - - public IReadOnlyDictionary NPCStates => _npcStates; - - public NPCStateCache() - { - _npcStates = new Dictionary(); - } - - public bool HasNPCStateWithIndex(int index) - { - return _npcStates.ContainsKey(index) && _npcStates[index] != null; - } - - public void UpdateNPCState(int index, EOLib.Domain.NPC.NPC npc) - { - if (!_npcStates.ContainsKey(index)) - _npcStates.Add(index, npc); - else - _npcStates[index] = npc; - } - - public void RemoveStateByIndex(int index) - { - if (_npcStates.ContainsKey(index)) - _npcStates.Remove(index); - } - - public void Reset() - { - _npcStates.Clear(); - } + _npcStates = new Dictionary(); } - public interface INPCStateCache + public bool HasNPCStateWithIndex(int index) { - IReadOnlyDictionary NPCStates { get; } - - bool HasNPCStateWithIndex(int index); + return _npcStates.ContainsKey(index) && _npcStates[index] != null; + } - void UpdateNPCState(int index, EOLib.Domain.NPC.NPC npc); + public void UpdateNPCState(int index, EOLib.Domain.NPC.NPC npc) + { + if (!_npcStates.ContainsKey(index)) + _npcStates.Add(index, npc); + else + _npcStates[index] = npc; + } - void RemoveStateByIndex(int index); + public void RemoveStateByIndex(int index) + { + if (_npcStates.ContainsKey(index)) + _npcStates.Remove(index); + } - void Reset(); + public void Reset() + { + _npcStates.Clear(); } +} + +public interface INPCStateCache +{ + IReadOnlyDictionary NPCStates { get; } + + bool HasNPCStateWithIndex(int index); + + void UpdateNPCState(int index, EOLib.Domain.NPC.NPC npc); + + void RemoveStateByIndex(int index); + + void Reset(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRenderer.cs b/EndlessClient/Rendering/NPC/NPCRenderer.cs index 56befc44e..0d990b932 100644 --- a/EndlessClient/Rendering/NPC/NPCRenderer.cs +++ b/EndlessClient/Rendering/NPC/NPCRenderer.cs @@ -18,330 +18,329 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering.NPC +namespace EndlessClient.Rendering.NPC; + +public class NPCRenderer : DrawableGameComponent, INPCRenderer { - public class NPCRenderer : DrawableGameComponent, INPCRenderer - { - private static readonly object _rt_locker_ = new object(); + private static readonly object _rt_locker_ = new object(); - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly INPCSpriteSheet _npcSpriteSheet; - private readonly INPCSpriteDataCache _npcSpriteDataCache; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IHealthBarRendererFactory _healthBarRendererFactory; - private readonly IChatBubbleFactory _chatBubbleFactory; - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IUserInputProvider _userInputProvider; - private readonly IEffectRenderer _effectRenderer; - private readonly IHealthBarRenderer _healthBarRenderer; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly INPCSpriteSheet _npcSpriteSheet; + private readonly INPCSpriteDataCache _npcSpriteDataCache; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IHealthBarRendererFactory _healthBarRendererFactory; + private readonly IChatBubbleFactory _chatBubbleFactory; + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IUserInputProvider _userInputProvider; + private readonly IEffectRenderer _effectRenderer; + private readonly IHealthBarRenderer _healthBarRenderer; - private RenderTarget2D _npcRenderTarget; - private SpriteBatch _spriteBatch; + private RenderTarget2D _npcRenderTarget; + private SpriteBatch _spriteBatch; - private DateTime _lastStandingAnimation; - private int _fadeAwayAlpha; - private bool _isDying, _isBlankSprite; + private DateTime _lastStandingAnimation; + private int _fadeAwayAlpha; + private bool _isDying, _isBlankSprite; - private XNALabel _nameLabel; - private IChatBubble _chatBubble; + private XNALabel _nameLabel; + private IChatBubble _chatBubble; - public int NameLabelY { get; private set; } + public int NameLabelY { get; private set; } - public int HorizontalCenter { get; private set; } + public int HorizontalCenter { get; private set; } - public bool IsAlive => !_isDying && !IsDead; + public bool IsAlive => !_isDying && !IsDead; - public Rectangle DrawArea { get; private set; } + public Rectangle DrawArea { get; private set; } - public EOLib.Domain.NPC.NPC NPC { get; set; } + public EOLib.Domain.NPC.NPC NPC { get; set; } - public ISpellTargetable SpellTarget => NPC; + public ISpellTargetable SpellTarget => NPC; - public bool IsDead { get; private set; } + public bool IsDead { get; private set; } - public Rectangle EffectTargetArea { get; private set; } + public Rectangle EffectTargetArea { get; private set; } - public NPCRenderer(IEndlessGameProvider endlessGameProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - IENFFileProvider enfFileProvider, - INPCSpriteSheet npcSpriteSheet, - INPCSpriteDataCache npcSpriteDataCache, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IHealthBarRendererFactory healthBarRendererFactory, - IChatBubbleFactory chatBubbleFactory, - IRenderTargetFactory renderTargetFactory, - IUserInputProvider userInputProvider, - IEffectRendererFactory effectRendererFactory, - EOLib.Domain.NPC.NPC initialNPC) - : base((Game)endlessGameProvider.Game) - { - NPC = initialNPC; - _clientWindowSizeProvider = clientWindowSizeProvider; - _enfFileProvider = enfFileProvider; - _npcSpriteSheet = npcSpriteSheet; - _npcSpriteDataCache = npcSpriteDataCache; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _healthBarRendererFactory = healthBarRendererFactory; - _chatBubbleFactory = chatBubbleFactory; - _renderTargetFactory = renderTargetFactory; - _userInputProvider = userInputProvider; - _effectRenderer = effectRendererFactory.Create(); - - DrawArea = GetStandingFrameRectangle(); - - _lastStandingAnimation = DateTime.Now; - _fadeAwayAlpha = 255; - - _clientWindowSizeProvider.GameWindowSizeChanged += RecreateRenderTarget; - - _healthBarRenderer = _healthBarRendererFactory.CreateHealthBarRenderer(this); - } + public NPCRenderer(IEndlessGameProvider endlessGameProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + IENFFileProvider enfFileProvider, + INPCSpriteSheet npcSpriteSheet, + INPCSpriteDataCache npcSpriteDataCache, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IHealthBarRendererFactory healthBarRendererFactory, + IChatBubbleFactory chatBubbleFactory, + IRenderTargetFactory renderTargetFactory, + IUserInputProvider userInputProvider, + IEffectRendererFactory effectRendererFactory, + EOLib.Domain.NPC.NPC initialNPC) + : base((Game)endlessGameProvider.Game) + { + NPC = initialNPC; + _clientWindowSizeProvider = clientWindowSizeProvider; + _enfFileProvider = enfFileProvider; + _npcSpriteSheet = npcSpriteSheet; + _npcSpriteDataCache = npcSpriteDataCache; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _healthBarRendererFactory = healthBarRendererFactory; + _chatBubbleFactory = chatBubbleFactory; + _renderTargetFactory = renderTargetFactory; + _userInputProvider = userInputProvider; + _effectRenderer = effectRendererFactory.Create(); + + DrawArea = GetStandingFrameRectangle(); + + _lastStandingAnimation = DateTime.Now; + _fadeAwayAlpha = 255; + + _clientWindowSizeProvider.GameWindowSizeChanged += RecreateRenderTarget; + + _healthBarRenderer = _healthBarRendererFactory.CreateHealthBarRenderer(this); + } - public override void Initialize() + public override void Initialize() + { + UpdateDrawAreas(); + + _nameLabel = new XNALabel(Constants.FontSize08pt5) { - UpdateDrawAreas(); - - _nameLabel = new XNALabel(Constants.FontSize08pt5) - { - Visible = false, - TextWidth = 89, - TextAlign = LabelAlignment.MiddleCenter, - ForeColor = Color.White, - AutoSize = true, - Text = _enfFileProvider.ENFFile[NPC.ID].Name, - DrawOrder = 30, - KeepInClientWindowBounds = false, - }; - _nameLabel.Initialize(); - - if (!_nameLabel.Game.Components.Contains(_nameLabel)) - _nameLabel.Game.Components.Add(_nameLabel); + Visible = false, + TextWidth = 89, + TextAlign = LabelAlignment.MiddleCenter, + ForeColor = Color.White, + AutoSize = true, + Text = _enfFileProvider.ENFFile[NPC.ID].Name, + DrawOrder = 30, + KeepInClientWindowBounds = false, + }; + _nameLabel.Initialize(); - _nameLabel.DrawPosition = GetNameLabelPosition(); + if (!_nameLabel.Game.Components.Contains(_nameLabel)) + _nameLabel.Game.Components.Add(_nameLabel); - lock (_rt_locker_) - _npcRenderTarget = _renderTargetFactory.CreateRenderTarget(); + _nameLabel.DrawPosition = GetNameLabelPosition(); - _spriteBatch = new SpriteBatch(Game.GraphicsDevice); + lock (_rt_locker_) + _npcRenderTarget = _renderTargetFactory.CreateRenderTarget(); - var graphic = _enfFileProvider.ENFFile[NPC.ID].Graphic; - _npcSpriteDataCache.Populate(graphic); - _isBlankSprite = _npcSpriteDataCache.IsBlankSprite(graphic); + _spriteBatch = new SpriteBatch(Game.GraphicsDevice); - base.Initialize(); - } + var graphic = _enfFileProvider.ENFFile[NPC.ID].Graphic; + _npcSpriteDataCache.Populate(graphic); + _isBlankSprite = _npcSpriteDataCache.IsBlankSprite(graphic); - public override void Update(GameTime gameTime) - { - if (!Visible) return; - - UpdateDrawAreas(); - UpdateStandingFrameAnimation(); - UpdateDeadState(); - DrawToRenderTarget(); - - var currentMousePosition = _userInputProvider.CurrentMouseState.Position; - - if (DrawArea.Contains(currentMousePosition)) - { - var chatBubbleIsVisible = _chatBubble != null && _chatBubble.Visible; - _nameLabel.Visible = !_healthBarRenderer.Visible && !chatBubbleIsVisible && !_isDying && IsClickablePixel(currentMousePosition); - _nameLabel.DrawPosition = GetNameLabelPosition(); - } - else - { - _nameLabel.Visible = false; - } - - _effectRenderer.Update(); - _healthBarRenderer.Update(gameTime); - - base.Update(gameTime); - } + base.Initialize(); + } - public bool IsClickablePixel(Point currentMousePosition) - { - var cachedTexture = _npcSpriteDataCache.GetData(_enfFileProvider.ENFFile[NPC.ID].Graphic, NPC.Frame); - if (!_isBlankSprite && cachedTexture.Length > 0 && _npcRenderTarget.Bounds.Contains(currentMousePosition)) - { - var currentFrame = _npcSpriteSheet.GetNPCTexture(_enfFileProvider.ENFFile[NPC.ID].Graphic, NPC.Frame, NPC.Direction); + public override void Update(GameTime gameTime) + { + if (!Visible) return; - var adjustedPos = currentMousePosition - DrawArea.Location; - var pixel = cachedTexture[adjustedPos.Y * currentFrame.Width + adjustedPos.X]; + UpdateDrawAreas(); + UpdateStandingFrameAnimation(); + UpdateDeadState(); + DrawToRenderTarget(); - return pixel.A > 0; - } + var currentMousePosition = _userInputProvider.CurrentMouseState.Position; - return true; + if (DrawArea.Contains(currentMousePosition)) + { + var chatBubbleIsVisible = _chatBubble != null && _chatBubble.Visible; + _nameLabel.Visible = !_healthBarRenderer.Visible && !chatBubbleIsVisible && !_isDying && IsClickablePixel(currentMousePosition); + _nameLabel.DrawPosition = GetNameLabelPosition(); } - - public void DrawToSpriteBatch(SpriteBatch spriteBatch) + else { - if (!Visible) return; + _nameLabel.Visible = false; + } - _effectRenderer.DrawBehindTarget(spriteBatch); - if (_npcRenderTarget != null) - spriteBatch.Draw(_npcRenderTarget, Vector2.Zero, Color.White); - _effectRenderer.DrawInFrontOfTarget(spriteBatch); + _effectRenderer.Update(); + _healthBarRenderer.Update(gameTime); - _healthBarRenderer.DrawToSpriteBatch(spriteBatch); - } + base.Update(gameTime); + } - public void StartDying() + public bool IsClickablePixel(Point currentMousePosition) + { + var cachedTexture = _npcSpriteDataCache.GetData(_enfFileProvider.ENFFile[NPC.ID].Graphic, NPC.Frame); + if (!_isBlankSprite && cachedTexture.Length > 0 && _npcRenderTarget.Bounds.Contains(currentMousePosition)) { - _isDying = true; - } + var currentFrame = _npcSpriteSheet.GetNPCTexture(_enfFileProvider.ENFFile[NPC.ID].Graphic, NPC.Frame, NPC.Direction); - public void ShowDamageCounter(int damage, int percentHealth, bool isHeal) - { - var optionalDamage = damage.SomeWhen(d => d > 0); - _healthBarRenderer.SetDamage(optionalDamage, percentHealth, ShowChatBubble); - _chatBubble?.Hide(); + var adjustedPos = currentMousePosition - DrawArea.Location; + var pixel = cachedTexture[adjustedPos.Y * currentFrame.Width + adjustedPos.X]; - void ShowChatBubble() => _chatBubble?.Show(); + return pixel.A > 0; } - public void ShowChatBubble(string message, bool isGroupChat) - { - if (_chatBubble == null) - _chatBubble = _chatBubbleFactory.CreateChatBubble(this); - _chatBubble.SetMessage(message, isGroupChat: false); - } + return true; + } - #region Effects + public void DrawToSpriteBatch(SpriteBatch spriteBatch) + { + if (!Visible) return; - public bool EffectIsPlaying() - { - return _effectRenderer.State == EffectState.Playing; - } + _effectRenderer.DrawBehindTarget(spriteBatch); + if (_npcRenderTarget != null) + spriteBatch.Draw(_npcRenderTarget, Vector2.Zero, Color.White); + _effectRenderer.DrawInFrontOfTarget(spriteBatch); - public void PlayEffect(int graphic) - { - _effectRenderer.PlayEffect(graphic, this); - } + _healthBarRenderer.DrawToSpriteBatch(spriteBatch); + } + + public void StartDying() + { + _isDying = true; + } + + public void ShowDamageCounter(int damage, int percentHealth, bool isHeal) + { + var optionalDamage = damage.SomeWhen(d => d > 0); + _healthBarRenderer.SetDamage(optionalDamage, percentHealth, ShowChatBubble); + _chatBubble?.Hide(); + + void ShowChatBubble() => _chatBubble?.Show(); + } - #endregion + public void ShowChatBubble(string message, bool isGroupChat) + { + if (_chatBubble == null) + _chatBubble = _chatBubbleFactory.CreateChatBubble(this); + _chatBubble.SetMessage(message, isGroupChat: false); + } - private Rectangle GetStandingFrameRectangle() + #region Effects + + public bool EffectIsPlaying() + { + return _effectRenderer.State == EffectState.Playing; + } + + public void PlayEffect(int graphic) + { + _effectRenderer.PlayEffect(graphic, this); + } + + #endregion + + private Rectangle GetStandingFrameRectangle() + { + var data = _enfFileProvider.ENFFile[NPC.ID]; + var baseFrame = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPCFrame.Standing, EODirection.Down); + return new Rectangle(0, 0, baseFrame.Width, baseFrame.Height); + } + + private void UpdateDrawAreas() + { + var data = _enfFileProvider.ENFFile[NPC.ID]; + var frameTexture = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPC.Frame, NPC.Direction); + var metaData = _npcSpriteSheet.GetNPCMetadata(data.Graphic); + + var isUpOrRight = NPC.IsFacing(EODirection.Up, EODirection.Right) ? -1 : 1; + var isDownOrRight = NPC.IsFacing(EODirection.Down, EODirection.Right) ? -1 : 1; + + int metaDataOffsetX, metaDataOffsetY; + if (NPC.Frame == NPCFrame.Attack2) { - var data = _enfFileProvider.ENFFile[NPC.ID]; - var baseFrame = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPCFrame.Standing, EODirection.Down); - return new Rectangle(0, 0, baseFrame.Width, baseFrame.Height); + metaDataOffsetX = metaData.AttackOffsetX * isUpOrRight + (metaData.OffsetX * isUpOrRight); + metaDataOffsetY = metaData.AttackOffsetY * isDownOrRight - metaData.OffsetY; } - - private void UpdateDrawAreas() + else { - var data = _enfFileProvider.ENFFile[NPC.ID]; - var frameTexture = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPC.Frame, NPC.Direction); - var metaData = _npcSpriteSheet.GetNPCMetadata(data.Graphic); - - var isUpOrRight = NPC.IsFacing(EODirection.Up, EODirection.Right) ? -1 : 1; - var isDownOrRight = NPC.IsFacing(EODirection.Down, EODirection.Right) ? -1 : 1; - - int metaDataOffsetX, metaDataOffsetY; - if (NPC.Frame == NPCFrame.Attack2) - { - metaDataOffsetX = metaData.AttackOffsetX * isUpOrRight + (metaData.OffsetX * isUpOrRight); - metaDataOffsetY = metaData.AttackOffsetY * isDownOrRight - metaData.OffsetY; - } - else - { - metaDataOffsetX = metaData.OffsetX * isUpOrRight; - metaDataOffsetY = -metaData.OffsetY; - } - - var renderCoordinates = _gridDrawCoordinateCalculator.CalculateDrawCoordinates(NPC) + - new Vector2(metaDataOffsetX - frameTexture.Width / 2, metaDataOffsetY - (frameTexture.Height - 23)); - DrawArea = frameTexture.Bounds.WithPosition(renderCoordinates); - - var horizontalOffset = _npcSpriteSheet.GetNPCMetadata(data.Graphic).OffsetX * (NPC.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1); - HorizontalCenter = DrawArea.X + (DrawArea.Width / 2) + horizontalOffset; - - var nameLabelGridCoordinates = _gridDrawCoordinateCalculator.CalculateDrawCoordinates(NPC.WithX(NPC.X - 1).WithY(NPC.Y - 1)); - NameLabelY = (int)nameLabelGridCoordinates.Y - metaData.NameLabelOffset; - - EffectTargetArea = DrawArea.WithSize(DrawArea.Width + horizontalOffset * 2, DrawArea.Height); + metaDataOffsetX = metaData.OffsetX * isUpOrRight; + metaDataOffsetY = -metaData.OffsetY; } - private void UpdateStandingFrameAnimation() - { - var now = DateTime.Now; + var renderCoordinates = _gridDrawCoordinateCalculator.CalculateDrawCoordinates(NPC) + + new Vector2(metaDataOffsetX - frameTexture.Width / 2, metaDataOffsetY - (frameTexture.Height - 23)); + DrawArea = frameTexture.Bounds.WithPosition(renderCoordinates); - var data = _enfFileProvider.ENFFile[NPC.ID]; - var metaData = _npcSpriteSheet.GetNPCMetadata(data.Graphic); + var horizontalOffset = _npcSpriteSheet.GetNPCMetadata(data.Graphic).OffsetX * (NPC.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1); + HorizontalCenter = DrawArea.X + (DrawArea.Width / 2) + horizontalOffset; - if (!metaData.HasStandingFrameAnimation - || !NPC.IsActing(NPCActionState.Standing) - || (now - _lastStandingAnimation).TotalMilliseconds < 250) - return; + var nameLabelGridCoordinates = _gridDrawCoordinateCalculator.CalculateDrawCoordinates(NPC.WithX(NPC.X - 1).WithY(NPC.Y - 1)); + NameLabelY = (int)nameLabelGridCoordinates.Y - metaData.NameLabelOffset; - _lastStandingAnimation = now; - NPC = NPC.WithFrame(NPC.Frame == NPCFrame.Standing ? NPCFrame.StandingFrame1 : NPCFrame.Standing); - } + EffectTargetArea = DrawArea.WithSize(DrawArea.Width + horizontalOffset * 2, DrawArea.Height); + } - private void UpdateDeadState() - { - if (!_isDying) return; + private void UpdateStandingFrameAnimation() + { + var now = DateTime.Now; - if (_fadeAwayAlpha >= 3) - _fadeAwayAlpha -= 3; - IsDead = _fadeAwayAlpha <= 0 && !EffectIsPlaying(); - } + var data = _enfFileProvider.ENFFile[NPC.ID]; + var metaData = _npcSpriteSheet.GetNPCMetadata(data.Graphic); - private void DrawToRenderTarget() - { - if (_npcRenderTarget == null) - return; + if (!metaData.HasStandingFrameAnimation + || !NPC.IsActing(NPCActionState.Standing) + || (now - _lastStandingAnimation).TotalMilliseconds < 250) + return; - var data = _enfFileProvider.ENFFile[NPC.ID]; - var texture = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPC.Frame, NPC.Direction); + _lastStandingAnimation = now; + NPC = NPC.WithFrame(NPC.Frame == NPCFrame.Standing ? NPCFrame.StandingFrame1 : NPCFrame.Standing); + } - var color = Color.FromNonPremultiplied(255, 255, 255, _fadeAwayAlpha); - var effects = NPC.IsFacing(EODirection.Left, EODirection.Down) ? SpriteEffects.None : SpriteEffects.FlipHorizontally; + private void UpdateDeadState() + { + if (!_isDying) return; - lock (_rt_locker_) - { - GraphicsDevice.SetRenderTarget(_npcRenderTarget); - GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 1, 0); + if (_fadeAwayAlpha >= 3) + _fadeAwayAlpha -= 3; + IsDead = _fadeAwayAlpha <= 0 && !EffectIsPlaying(); + } - _spriteBatch.Begin(); - _spriteBatch.Draw(texture, DrawArea, null, color, 0, Vector2.Zero, effects, 1); - _spriteBatch.End(); + private void DrawToRenderTarget() + { + if (_npcRenderTarget == null) + return; - GraphicsDevice.SetRenderTarget(null); - } - } + var data = _enfFileProvider.ENFFile[NPC.ID]; + var texture = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPC.Frame, NPC.Direction); + + var color = Color.FromNonPremultiplied(255, 255, 255, _fadeAwayAlpha); + var effects = NPC.IsFacing(EODirection.Left, EODirection.Down) ? SpriteEffects.None : SpriteEffects.FlipHorizontally; - private void RecreateRenderTarget(object sender, EventArgs e) + lock (_rt_locker_) { - lock (_rt_locker_) - { - _npcRenderTarget.Dispose(); - _npcRenderTarget = _renderTargetFactory.CreateRenderTarget(); - } + GraphicsDevice.SetRenderTarget(_npcRenderTarget); + GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 1, 0); + + _spriteBatch.Begin(); + _spriteBatch.Draw(texture, DrawArea, null, color, 0, Vector2.Zero, effects, 1); + _spriteBatch.End(); + + GraphicsDevice.SetRenderTarget(null); } + } - private Vector2 GetNameLabelPosition() + private void RecreateRenderTarget(object sender, EventArgs e) + { + lock (_rt_locker_) { - return new Vector2(HorizontalCenter - (_nameLabel.ActualWidth / 2f), NameLabelY); + _npcRenderTarget.Dispose(); + _npcRenderTarget = _renderTargetFactory.CreateRenderTarget(); } + } - protected override void Dispose(bool disposing) - { - if (disposing) - { - _nameLabel.Dispose(); - _chatBubble?.Dispose(); - _spriteBatch?.Dispose(); + private Vector2 GetNameLabelPosition() + { + return new Vector2(HorizontalCenter - (_nameLabel.ActualWidth / 2f), NameLabelY); + } - lock (_rt_locker_) - _npcRenderTarget?.Dispose(); + protected override void Dispose(bool disposing) + { + if (disposing) + { + _nameLabel.Dispose(); + _chatBubble?.Dispose(); + _spriteBatch?.Dispose(); - _clientWindowSizeProvider.GameWindowSizeChanged -= RecreateRenderTarget; - } + lock (_rt_locker_) + _npcRenderTarget?.Dispose(); - base.Dispose(disposing); + _clientWindowSizeProvider.GameWindowSizeChanged -= RecreateRenderTarget; } + + base.Dispose(disposing); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRendererFactory.cs b/EndlessClient/Rendering/NPC/NPCRendererFactory.cs index 882dab75b..e362038de 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererFactory.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererFactory.cs @@ -7,67 +7,66 @@ using EndlessClient.Rendering.Sprites; using EOLib.IO.Repositories; -namespace EndlessClient.Rendering.NPC -{ - [AutoMappedType] - public class NPCRendererFactory : INPCRendererFactory - { - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly INPCSpriteSheet _npcSpriteSheet; - private readonly INPCSpriteDataCache _npcSpriteDataCache; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IHealthBarRendererFactory _healthBarRendererFactory; - private readonly IChatBubbleFactory _chatBubbleFactory; - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IUserInputProvider _userInputProvider; - private readonly IEffectRendererFactory _effectRendererFactory; +namespace EndlessClient.Rendering.NPC; - public NPCRendererFactory(IEndlessGameProvider endlessGameProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - IENFFileProvider enfFileProvider, - INPCSpriteSheet npcSpriteSheet, - INPCSpriteDataCache npcSpriteDataCache, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IHealthBarRendererFactory healthBarRendererFactory, - IChatBubbleFactory chatBubbleFactory, - IRenderTargetFactory renderTargetFactory, - IUserInputProvider userInputProvider, - IEffectRendererFactory effectRendererFactory) - { - _endlessGameProvider = endlessGameProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - _enfFileProvider = enfFileProvider; - _npcSpriteSheet = npcSpriteSheet; - _npcSpriteDataCache = npcSpriteDataCache; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _healthBarRendererFactory = healthBarRendererFactory; - _chatBubbleFactory = chatBubbleFactory; - _renderTargetFactory = renderTargetFactory; - _userInputProvider = userInputProvider; - _effectRendererFactory = effectRendererFactory; - } +[AutoMappedType] +public class NPCRendererFactory : INPCRendererFactory +{ + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly INPCSpriteSheet _npcSpriteSheet; + private readonly INPCSpriteDataCache _npcSpriteDataCache; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IHealthBarRendererFactory _healthBarRendererFactory; + private readonly IChatBubbleFactory _chatBubbleFactory; + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IUserInputProvider _userInputProvider; + private readonly IEffectRendererFactory _effectRendererFactory; - public INPCRenderer CreateRendererFor(EOLib.Domain.NPC.NPC npc) - { - return new NPCRenderer(_endlessGameProvider, - _clientWindowSizeProvider, - _enfFileProvider, - _npcSpriteSheet, - _npcSpriteDataCache, - _gridDrawCoordinateCalculator, - _healthBarRendererFactory, - _chatBubbleFactory, - _renderTargetFactory, - _userInputProvider, - _effectRendererFactory, - npc); - } + public NPCRendererFactory(IEndlessGameProvider endlessGameProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + IENFFileProvider enfFileProvider, + INPCSpriteSheet npcSpriteSheet, + INPCSpriteDataCache npcSpriteDataCache, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IHealthBarRendererFactory healthBarRendererFactory, + IChatBubbleFactory chatBubbleFactory, + IRenderTargetFactory renderTargetFactory, + IUserInputProvider userInputProvider, + IEffectRendererFactory effectRendererFactory) + { + _endlessGameProvider = endlessGameProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + _enfFileProvider = enfFileProvider; + _npcSpriteSheet = npcSpriteSheet; + _npcSpriteDataCache = npcSpriteDataCache; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _healthBarRendererFactory = healthBarRendererFactory; + _chatBubbleFactory = chatBubbleFactory; + _renderTargetFactory = renderTargetFactory; + _userInputProvider = userInputProvider; + _effectRendererFactory = effectRendererFactory; } - public interface INPCRendererFactory + public INPCRenderer CreateRendererFor(EOLib.Domain.NPC.NPC npc) { - INPCRenderer CreateRendererFor(EOLib.Domain.NPC.NPC npc); + return new NPCRenderer(_endlessGameProvider, + _clientWindowSizeProvider, + _enfFileProvider, + _npcSpriteSheet, + _npcSpriteDataCache, + _gridDrawCoordinateCalculator, + _healthBarRendererFactory, + _chatBubbleFactory, + _renderTargetFactory, + _userInputProvider, + _effectRendererFactory, + npc); } +} + +public interface INPCRendererFactory +{ + INPCRenderer CreateRendererFor(EOLib.Domain.NPC.NPC npc); } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRendererRepository.cs b/EndlessClient/Rendering/NPC/NPCRendererRepository.cs index d6f93a73c..611913026 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererRepository.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererRepository.cs @@ -3,46 +3,45 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering.NPC +namespace EndlessClient.Rendering.NPC; + +public interface INPCRendererRepository : IDisposable { - public interface INPCRendererRepository : IDisposable - { - Dictionary NPCRenderers { get; set; } + Dictionary NPCRenderers { get; set; } - Dictionary DyingNPCs { get; set; } - } + Dictionary DyingNPCs { get; set; } +} - public interface INPCRendererProvider - { - IReadOnlyDictionary NPCRenderers { get; } +public interface INPCRendererProvider +{ + IReadOnlyDictionary NPCRenderers { get; } - IReadOnlyDictionary DyingNPCs { get; } - } + IReadOnlyDictionary DyingNPCs { get; } +} - [AutoMappedType(IsSingleton = true)] - public class NPCRendererRepository : INPCRendererRepository, INPCRendererProvider - { - public Dictionary NPCRenderers { get; set; } +[AutoMappedType(IsSingleton = true)] +public class NPCRendererRepository : INPCRendererRepository, INPCRendererProvider +{ + public Dictionary NPCRenderers { get; set; } - public Dictionary DyingNPCs { get; set; } + public Dictionary DyingNPCs { get; set; } - IReadOnlyDictionary INPCRendererProvider.NPCRenderers => NPCRenderers; + IReadOnlyDictionary INPCRendererProvider.NPCRenderers => NPCRenderers; - IReadOnlyDictionary INPCRendererProvider.DyingNPCs => DyingNPCs; + IReadOnlyDictionary INPCRendererProvider.DyingNPCs => DyingNPCs; - public NPCRendererRepository() - { - NPCRenderers = new Dictionary(); - DyingNPCs = new Dictionary(); - } + public NPCRendererRepository() + { + NPCRenderers = new Dictionary(); + DyingNPCs = new Dictionary(); + } - public void Dispose() - { - foreach (var renderer in NPCRenderers.Values) - renderer.Dispose(); - NPCRenderers.Clear(); + public void Dispose() + { + foreach (var renderer in NPCRenderers.Values) + renderer.Dispose(); + NPCRenderers.Clear(); - DyingNPCs.Clear(); - } + DyingNPCs.Clear(); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs b/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs index be61aa056..1f39ce3ca 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs @@ -5,129 +5,128 @@ using System; using System.Linq; -namespace EndlessClient.Rendering.NPC +namespace EndlessClient.Rendering.NPC; + +[AutoMappedType] +public class NPCRendererUpdater : INPCRendererUpdater { - [AutoMappedType] - public class NPCRendererUpdater : INPCRendererUpdater + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly INPCRendererRepository _npcRendererRepository; + private readonly INPCStateCache _npcStateCache; + private readonly INPCRendererFactory _npcRendererFactory; + + public NPCRendererUpdater(ICurrentMapStateProvider currentMapStateProvider, + INPCRendererRepository npcRendererRepository, + INPCStateCache npcStateCache, + INPCRendererFactory npcRendererFactory) { - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly INPCRendererRepository _npcRendererRepository; - private readonly INPCStateCache _npcStateCache; - private readonly INPCRendererFactory _npcRendererFactory; - - public NPCRendererUpdater(ICurrentMapStateProvider currentMapStateProvider, - INPCRendererRepository npcRendererRepository, - INPCStateCache npcStateCache, - INPCRendererFactory npcRendererFactory) - { - _currentMapStateProvider = currentMapStateProvider; - _npcRendererRepository = npcRendererRepository; - _npcStateCache = npcStateCache; - _npcRendererFactory = npcRendererFactory; - } + _currentMapStateProvider = currentMapStateProvider; + _npcRendererRepository = npcRendererRepository; + _npcStateCache = npcStateCache; + _npcRendererFactory = npcRendererFactory; + } - public void UpdateNPCs(GameTime gameTime) - { - CleanUpDeadNPCs(); - CleanUpRemovedNPCs(); - CreateAndCacheNPCRenderers(); - UpdateNPCRenderers(gameTime); - } + public void UpdateNPCs(GameTime gameTime) + { + CleanUpDeadNPCs(); + CleanUpRemovedNPCs(); + CreateAndCacheNPCRenderers(); + UpdateNPCRenderers(gameTime); + } - private void CleanUpDeadNPCs() + private void CleanUpDeadNPCs() + { + var deadNPCs = _npcRendererRepository.NPCRenderers.Values.Where(x => x.IsDead).ToList(); + if (!deadNPCs.Any()) + return; + + foreach (var npc in deadNPCs) { - var deadNPCs = _npcRendererRepository.NPCRenderers.Values.Where(x => x.IsDead).ToList(); - if (!deadNPCs.Any()) - return; - - foreach (var npc in deadNPCs) - { - npc.Dispose(); - _npcRendererRepository.NPCRenderers.Remove(npc.NPC.Index); - _npcRendererRepository.DyingNPCs.Remove(new MapCoordinate(npc.NPC.X, npc.NPC.Y)); - _npcStateCache.RemoveStateByIndex(npc.NPC.Index); - } + npc.Dispose(); + _npcRendererRepository.NPCRenderers.Remove(npc.NPC.Index); + _npcRendererRepository.DyingNPCs.Remove(new MapCoordinate(npc.NPC.X, npc.NPC.Y)); + _npcStateCache.RemoveStateByIndex(npc.NPC.Index); } + } + + private void CleanUpRemovedNPCs() + { + var removedNPCs = _npcRendererRepository.NPCRenderers.Values + .Where(x => x.IsAlive) + .Select(x => x.NPC.Index) + .Where(x => !_currentMapStateProvider.NPCs.Select(y => y.Index).Any(y => y == x)) + .ToList(); - private void CleanUpRemovedNPCs() + foreach (var index in removedNPCs) { - var removedNPCs = _npcRendererRepository.NPCRenderers.Values - .Where(x => x.IsAlive) - .Select(x => x.NPC.Index) - .Where(x => !_currentMapStateProvider.NPCs.Select(y => y.Index).Any(y => y == x)) - .ToList(); - - foreach (var index in removedNPCs) - { - if (!_npcRendererRepository.NPCRenderers.TryGetValue(index, out var renderer)) - continue; - - renderer.Dispose(); - _npcRendererRepository.NPCRenderers.Remove(index); - _npcStateCache.RemoveStateByIndex(index); - } + if (!_npcRendererRepository.NPCRenderers.TryGetValue(index, out var renderer)) + continue; + + renderer.Dispose(); + _npcRendererRepository.NPCRenderers.Remove(index); + _npcStateCache.RemoveStateByIndex(index); } + } - private void CreateAndCacheNPCRenderers() + private void CreateAndCacheNPCRenderers() + { + foreach (var npc in _currentMapStateProvider.NPCs) { - foreach (var npc in _currentMapStateProvider.NPCs) - { - _npcStateCache.HasNPCStateWithIndex(npc.Index) - .SomeWhen(b => b) - .Map(_ => _npcStateCache.NPCStates[npc.Index]) - .Match( - some: n => + _npcStateCache.HasNPCStateWithIndex(npc.Index) + .SomeWhen(b => b) + .Map(_ => _npcStateCache.NPCStates[npc.Index]) + .Match( + some: n => + { + if (n != npc) { - if (n != npc) - { - UpdateCachedNPC(npc); - } - }, - none: () => CreateAndCacheRendererForNPC(npc)); - } + UpdateCachedNPC(npc); + } + }, + none: () => CreateAndCacheRendererForNPC(npc)); } + } - private void CreateAndCacheRendererForNPC(EOLib.Domain.NPC.NPC npc) - { - _npcStateCache.UpdateNPCState(npc.Index, npc); - - var renderer = _npcRendererFactory.CreateRendererFor(npc); - renderer.Initialize(); - - if (_npcRendererRepository.NPCRenderers.ContainsKey(npc.Index) && - _npcRendererRepository.NPCRenderers[npc.Index] != null) - { - _npcRendererRepository.NPCRenderers[npc.Index].Dispose(); - _npcRendererRepository.NPCRenderers.Remove(npc.Index); - } + private void CreateAndCacheRendererForNPC(EOLib.Domain.NPC.NPC npc) + { + _npcStateCache.UpdateNPCState(npc.Index, npc); - _npcRendererRepository.NPCRenderers.Add(npc.Index, renderer); - } + var renderer = _npcRendererFactory.CreateRendererFor(npc); + renderer.Initialize(); - private void UpdateCachedNPC(EOLib.Domain.NPC.NPC npc) + if (_npcRendererRepository.NPCRenderers.ContainsKey(npc.Index) && + _npcRendererRepository.NPCRenderers[npc.Index] != null) { - if (_npcRendererRepository.NPCRenderers.ContainsKey(npc.Index)) - { - _npcRendererRepository.NPCRenderers[npc.Index].NPC = npc; - _npcStateCache.UpdateNPCState(npc.Index, npc); - } + _npcRendererRepository.NPCRenderers[npc.Index].Dispose(); + _npcRendererRepository.NPCRenderers.Remove(npc.Index); } - private void UpdateNPCRenderers(GameTime gameTime) - { - foreach (var renderer in _npcRendererRepository.NPCRenderers.Values) - renderer.Update(gameTime); - } + _npcRendererRepository.NPCRenderers.Add(npc.Index, renderer); + } - public void Dispose() + private void UpdateCachedNPC(EOLib.Domain.NPC.NPC npc) + { + if (_npcRendererRepository.NPCRenderers.ContainsKey(npc.Index)) { - _npcStateCache.Reset(); - _npcRendererRepository.Dispose(); + _npcRendererRepository.NPCRenderers[npc.Index].NPC = npc; + _npcStateCache.UpdateNPCState(npc.Index, npc); } } - public interface INPCRendererUpdater : IDisposable + private void UpdateNPCRenderers(GameTime gameTime) + { + foreach (var renderer in _npcRendererRepository.NPCRenderers.Values) + renderer.Update(gameTime); + } + + public void Dispose() { - void UpdateNPCs(GameTime gameTime); + _npcStateCache.Reset(); + _npcRendererRepository.Dispose(); } +} + +public interface INPCRendererUpdater : IDisposable +{ + void UpdateNPCs(GameTime gameTime); } \ No newline at end of file diff --git a/EndlessClient/Rendering/PlayerStatusIconRenderer.cs b/EndlessClient/Rendering/PlayerStatusIconRenderer.cs index 7b984422f..298d71f52 100644 --- a/EndlessClient/Rendering/PlayerStatusIconRenderer.cs +++ b/EndlessClient/Rendering/PlayerStatusIconRenderer.cs @@ -7,97 +7,96 @@ using System; using XNAControls; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +public sealed class PlayerStatusIconRenderer : XNAControl { - public sealed class PlayerStatusIconRenderer : XNAControl + [Flags] + private enum StatusIconType { - [Flags] - private enum StatusIconType - { - Weapon = 1, - Shield = 2, - Spell = 4, - PK = 8 - } + Weapon = 1, + Shield = 2, + Spell = 4, + PK = 8 + } - private static readonly StatusIconType[] _orderedValues = - { - StatusIconType.PK, - StatusIconType.Spell, - StatusIconType.Weapon, - StatusIconType.Shield - }; + private static readonly StatusIconType[] _orderedValues = + { + StatusIconType.PK, + StatusIconType.Spell, + StatusIconType.Weapon, + StatusIconType.Shield + }; - private readonly ICharacterProvider _characterProvider; - private readonly ISpellSlotDataProvider _spellSlotDataProvider; - private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ISpellSlotDataProvider _spellSlotDataProvider; + private readonly ICurrentMapProvider _currentMapProvider; - private readonly Texture2D _statusIcons; + private readonly Texture2D _statusIcons; - private StatusIconType _icons; + private StatusIconType _icons; - public PlayerStatusIconRenderer(INativeGraphicsManager nativeGraphicsManager, - ICharacterProvider characterProvider, - ISpellSlotDataProvider spellSlotDataProvider, - ICurrentMapProvider currentMapProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _characterProvider = characterProvider; - _spellSlotDataProvider = spellSlotDataProvider; - _currentMapProvider = currentMapProvider; + public PlayerStatusIconRenderer(INativeGraphicsManager nativeGraphicsManager, + ICharacterProvider characterProvider, + ISpellSlotDataProvider spellSlotDataProvider, + ICurrentMapProvider currentMapProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _characterProvider = characterProvider; + _spellSlotDataProvider = spellSlotDataProvider; + _currentMapProvider = currentMapProvider; - _statusIcons = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 46, true); + _statusIcons = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 46, true); - DrawPosition = new Vector2(14, clientWindowSizeProvider.Height - _statusIcons.Height - 3); - clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => DrawPosition = new Vector2(14, clientWindowSizeProvider.Height - _statusIcons.Height - 3); - } + DrawPosition = new Vector2(14, clientWindowSizeProvider.Height - _statusIcons.Height - 3); + clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => DrawPosition = new Vector2(14, clientWindowSizeProvider.Height - _statusIcons.Height - 3); + } - protected override void OnUpdateControl(GameTime gameTime) - { - var c = _characterProvider.MainCharacter; - - _icons = 0; - if (_currentMapProvider.CurrentMap.Properties.PKAvailable) - _icons |= StatusIconType.PK; - if (_spellSlotDataProvider.SelectedSpellSlot.HasValue) - _icons |= StatusIconType.Spell; - if (c.RenderProperties.WeaponGraphic > 0) - _icons |= StatusIconType.Weapon; - if (c.RenderProperties.ShieldGraphic > 0) - _icons |= StatusIconType.Shield; - - base.OnUpdateControl(gameTime); - } + protected override void OnUpdateControl(GameTime gameTime) + { + var c = _characterProvider.MainCharacter; + + _icons = 0; + if (_currentMapProvider.CurrentMap.Properties.PKAvailable) + _icons |= StatusIconType.PK; + if (_spellSlotDataProvider.SelectedSpellSlot.HasValue) + _icons |= StatusIconType.Spell; + if (c.RenderProperties.WeaponGraphic > 0) + _icons |= StatusIconType.Weapon; + if (c.RenderProperties.ShieldGraphic > 0) + _icons |= StatusIconType.Shield; + + base.OnUpdateControl(gameTime); + } - protected override void OnDrawControl(GameTime gt) - { - _spriteBatch.Begin(); + protected override void OnDrawControl(GameTime gt) + { + _spriteBatch.Begin(); - int extraOffset = 0; - foreach (var icon in _orderedValues) + int extraOffset = 0; + foreach (var icon in _orderedValues) + { + if ((_icons & icon) > 0) { - if ((_icons & icon) > 0) - { - _spriteBatch.Draw(_statusIcons, DrawPositionWithParentOffset + new Vector2(extraOffset, 0), GetSourceRectangle(icon), Color.FromNonPremultiplied(0x9e, 0x9f, 0x9e, 0xff)); - extraOffset += 24; - } + _spriteBatch.Draw(_statusIcons, DrawPositionWithParentOffset + new Vector2(extraOffset, 0), GetSourceRectangle(icon), Color.FromNonPremultiplied(0x9e, 0x9f, 0x9e, 0xff)); + extraOffset += 24; } + } - _spriteBatch.End(); + _spriteBatch.End(); - base.OnDrawControl(gt); - } + base.OnDrawControl(gt); + } - private Rectangle GetSourceRectangle(StatusIconType type) - { - var widthDelta = _statusIcons.Width / 4; - var heightDelta = _statusIcons.Height / 2; + private Rectangle GetSourceRectangle(StatusIconType type) + { + var widthDelta = _statusIcons.Width / 4; + var heightDelta = _statusIcons.Height / 2; - //convert from power of two 'flag' value to base 10 index - var index = (int)Math.Log((int)type, 2); + //convert from power of two 'flag' value to base 10 index + var index = (int)Math.Log((int)type, 2); - var xOffset = widthDelta * index; - return new Rectangle(xOffset, 0, widthDelta, heightDelta); - } + var xOffset = widthDelta * index; + return new Rectangle(xOffset, 0, widthDelta, heightDelta); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/PointComparer.cs b/EndlessClient/Rendering/PointComparer.cs index eadbb3f36..43ce7f645 100644 --- a/EndlessClient/Rendering/PointComparer.cs +++ b/EndlessClient/Rendering/PointComparer.cs @@ -1,17 +1,16 @@ using Microsoft.Xna.Framework; using System.Collections.Generic; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +public class PointComparer : IComparer { - public class PointComparer : IComparer + public int Compare(Point a, Point b) { - public int Compare(Point a, Point b) - { - if (a.Y < b.Y || a.X < b.X) - return -1; - if (a.Y > b.Y || a.X > b.X) - return 1; - return 0; - } + if (a.Y < b.Y || a.X < b.X) + return -1; + if (a.Y > b.Y || a.X > b.X) + return 1; + return 0; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/RenderFrameActionTime.cs b/EndlessClient/Rendering/RenderFrameActionTime.cs index a4ee2626b..3f32d6fa4 100644 --- a/EndlessClient/Rendering/RenderFrameActionTime.cs +++ b/EndlessClient/Rendering/RenderFrameActionTime.cs @@ -1,40 +1,39 @@ using System; -namespace EndlessClient.Rendering -{ - public class RenderFrameActionTime - { - private Action _sfxCallback; +namespace EndlessClient.Rendering; - public int UniqueID { get; private set; } +public class RenderFrameActionTime +{ + private Action _sfxCallback; - public ulong ActionTick { get; private set; } + public int UniqueID { get; private set; } - public bool Replay { get; private set; } + public ulong ActionTick { get; private set; } - public RenderFrameActionTime(int uniqueID, ulong ticks, Action sfxCallback = null) - { - UniqueID = uniqueID; - _sfxCallback = sfxCallback; - UpdateActionStartTime(ticks); - } + public bool Replay { get; private set; } - public void UpdateActionStartTime(ulong ticks) - { - ActionTick = ticks; - } + public RenderFrameActionTime(int uniqueID, ulong ticks, Action sfxCallback = null) + { + UniqueID = uniqueID; + _sfxCallback = sfxCallback; + UpdateActionStartTime(ticks); + } - public void SetReplay(Action sfxCallback = null) - { - _sfxCallback = sfxCallback; - Replay = true; - } + public void UpdateActionStartTime(ulong ticks) + { + ActionTick = ticks; + } - public void ClearReplay() - { - Replay = false; - } + public void SetReplay(Action sfxCallback = null) + { + _sfxCallback = sfxCallback; + Replay = true; + } - public void SoundEffect() => _sfxCallback?.Invoke(); + public void ClearReplay() + { + Replay = false; } + + public void SoundEffect() => _sfxCallback?.Invoke(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/RenderOffsetCalculator.cs b/EndlessClient/Rendering/RenderOffsetCalculator.cs index 6bbc5432a..47d44665e 100644 --- a/EndlessClient/Rendering/RenderOffsetCalculator.cs +++ b/EndlessClient/Rendering/RenderOffsetCalculator.cs @@ -5,93 +5,92 @@ using EOLib.Domain.Map; using EOLib.Domain.NPC; -namespace EndlessClient.Rendering +namespace EndlessClient.Rendering; + +[MappedType(BaseType = typeof(IRenderOffsetCalculator))] +public class RenderOffsetCalculator : IRenderOffsetCalculator { - [MappedType(BaseType = typeof(IRenderOffsetCalculator))] - public class RenderOffsetCalculator : IRenderOffsetCalculator + private const int WidthFactor = 32; + private const int HeightFactor = 16; + private const int WalkWidthFactor = WidthFactor / 4; + private const int WalkHeightFactor = HeightFactor / 4; + + public int CalculateOffsetX(CharacterRenderProperties properties) + { + return properties.MapX * WidthFactor - properties.MapY * WidthFactor + CalculateWalkAdjustX(properties); + } + + public int CalculateWalkAdjustX(CharacterRenderProperties properties) + { + var multiplier = properties.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; + var walkAdjust = properties.IsActing(CharacterActionState.Walking) ? WalkWidthFactor * properties.ActualWalkFrame : 0; + return walkAdjust * multiplier; + } + + public int CalculateOffsetY(CharacterRenderProperties properties) { - private const int WidthFactor = 32; - private const int HeightFactor = 16; - private const int WalkWidthFactor = WidthFactor / 4; - private const int WalkHeightFactor = HeightFactor / 4; - - public int CalculateOffsetX(CharacterRenderProperties properties) - { - return properties.MapX * WidthFactor - properties.MapY * WidthFactor + CalculateWalkAdjustX(properties); - } - - public int CalculateWalkAdjustX(CharacterRenderProperties properties) - { - var multiplier = properties.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; - var walkAdjust = properties.IsActing(CharacterActionState.Walking) ? WalkWidthFactor * properties.ActualWalkFrame : 0; - return walkAdjust * multiplier; - } - - public int CalculateOffsetY(CharacterRenderProperties properties) - { - return properties.MapX * HeightFactor + properties.MapY * HeightFactor + CalculateWalkAdjustY(properties); - } - - public int CalculateWalkAdjustY(CharacterRenderProperties properties) - { - var multiplier = properties.IsFacing(EODirection.Left, EODirection.Up) ? -1 : 1; - var walkAdjust = properties.IsActing(CharacterActionState.Walking) ? WalkHeightFactor * properties.ActualWalkFrame : 0; - return walkAdjust * multiplier; - } - - public int CalculateOffsetX(EOLib.Domain.NPC.NPC npc) - { - return npc.X * WidthFactor - npc.Y * WidthFactor + CalculateWalkAdjustX(npc); - } - - public int CalculateWalkAdjustX(EOLib.Domain.NPC.NPC npc) - { - var multiplier = npc.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; - var walkAdjust = npc.IsActing(NPCActionState.Walking) ? WalkWidthFactor * npc.GetWalkFrame() : 0; - - return walkAdjust * multiplier; - } - - public int CalculateOffsetY(EOLib.Domain.NPC.NPC npc) - { - return npc.X * HeightFactor + npc.Y * HeightFactor + CalculateWalkAdjustY(npc); - } - - public int CalculateWalkAdjustY(EOLib.Domain.NPC.NPC npc) - { - var multiplier = npc.IsFacing(EODirection.Left, EODirection.Up) ? -1 : 1; - var walkAdjust = npc.IsActing(NPCActionState.Walking) ? WalkHeightFactor * npc.GetWalkFrame() : 0; - - return walkAdjust * multiplier; - } - - public int CalculateOffsetX(MapCoordinate coordinate) - { - return coordinate.X * WidthFactor - coordinate.Y * WidthFactor; - } - - public int CalculateOffsetY(MapCoordinate coordinate) - { - return coordinate.X * HeightFactor + coordinate.Y * HeightFactor; - } + return properties.MapX * HeightFactor + properties.MapY * HeightFactor + CalculateWalkAdjustY(properties); } - public interface IRenderOffsetCalculator + public int CalculateWalkAdjustY(CharacterRenderProperties properties) { - int CalculateOffsetX(CharacterRenderProperties properties); - int CalculateWalkAdjustX(CharacterRenderProperties properties); + var multiplier = properties.IsFacing(EODirection.Left, EODirection.Up) ? -1 : 1; + var walkAdjust = properties.IsActing(CharacterActionState.Walking) ? WalkHeightFactor * properties.ActualWalkFrame : 0; + return walkAdjust * multiplier; + } + + public int CalculateOffsetX(EOLib.Domain.NPC.NPC npc) + { + return npc.X * WidthFactor - npc.Y * WidthFactor + CalculateWalkAdjustX(npc); + } + + public int CalculateWalkAdjustX(EOLib.Domain.NPC.NPC npc) + { + var multiplier = npc.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; + var walkAdjust = npc.IsActing(NPCActionState.Walking) ? WalkWidthFactor * npc.GetWalkFrame() : 0; + + return walkAdjust * multiplier; + } - int CalculateOffsetY(CharacterRenderProperties properties); - int CalculateWalkAdjustY(CharacterRenderProperties properties); + public int CalculateOffsetY(EOLib.Domain.NPC.NPC npc) + { + return npc.X * HeightFactor + npc.Y * HeightFactor + CalculateWalkAdjustY(npc); + } - int CalculateOffsetX(EOLib.Domain.NPC.NPC npc); - int CalculateWalkAdjustX(EOLib.Domain.NPC.NPC npc); + public int CalculateWalkAdjustY(EOLib.Domain.NPC.NPC npc) + { + var multiplier = npc.IsFacing(EODirection.Left, EODirection.Up) ? -1 : 1; + var walkAdjust = npc.IsActing(NPCActionState.Walking) ? WalkHeightFactor * npc.GetWalkFrame() : 0; - int CalculateOffsetY(EOLib.Domain.NPC.NPC npc); - int CalculateWalkAdjustY(EOLib.Domain.NPC.NPC npc); + return walkAdjust * multiplier; + } - int CalculateOffsetX(MapCoordinate coordinate); + public int CalculateOffsetX(MapCoordinate coordinate) + { + return coordinate.X * WidthFactor - coordinate.Y * WidthFactor; + } - int CalculateOffsetY(MapCoordinate coordinate); + public int CalculateOffsetY(MapCoordinate coordinate) + { + return coordinate.X * HeightFactor + coordinate.Y * HeightFactor; } +} + +public interface IRenderOffsetCalculator +{ + int CalculateOffsetX(CharacterRenderProperties properties); + int CalculateWalkAdjustX(CharacterRenderProperties properties); + + int CalculateOffsetY(CharacterRenderProperties properties); + int CalculateWalkAdjustY(CharacterRenderProperties properties); + + int CalculateOffsetX(EOLib.Domain.NPC.NPC npc); + int CalculateWalkAdjustX(EOLib.Domain.NPC.NPC npc); + + int CalculateOffsetY(EOLib.Domain.NPC.NPC npc); + int CalculateWalkAdjustY(EOLib.Domain.NPC.NPC npc); + + int CalculateOffsetX(MapCoordinate coordinate); + + int CalculateOffsetY(MapCoordinate coordinate); } \ No newline at end of file diff --git a/EndlessClient/Rendering/RendererRepositoryResetter.cs b/EndlessClient/Rendering/RendererRepositoryResetter.cs index 1a00ae3ab..996309c30 100644 --- a/EndlessClient/Rendering/RendererRepositoryResetter.cs +++ b/EndlessClient/Rendering/RendererRepositoryResetter.cs @@ -3,39 +3,38 @@ using EndlessClient.Rendering.Chat; using EndlessClient.Rendering.NPC; -namespace EndlessClient.Rendering -{ - [MappedType(BaseType = typeof(IRendererRepositoryResetter))] - public class RendererRepositoryResetter : IRendererRepositoryResetter - { - private readonly ICharacterRendererRepository _characterRendererRepository; - private readonly INPCRendererRepository _npcRendererRepository; - private readonly ICharacterStateCache _characterStateCache; - private readonly INPCStateCache _npcStateCache; +namespace EndlessClient.Rendering; - public RendererRepositoryResetter(ICharacterRendererRepository characterRendererRepository, - INPCRendererRepository npcRendererRepository, - ICharacterStateCache characterStateCache, - INPCStateCache npcStateCache) - { - _characterRendererRepository = characterRendererRepository; - _npcRendererRepository = npcRendererRepository; - _characterStateCache = characterStateCache; - _npcStateCache = npcStateCache; - } - - public void ResetRenderers() - { - _characterRendererRepository.Dispose(); - _npcRendererRepository.Dispose(); +[MappedType(BaseType = typeof(IRendererRepositoryResetter))] +public class RendererRepositoryResetter : IRendererRepositoryResetter +{ + private readonly ICharacterRendererRepository _characterRendererRepository; + private readonly INPCRendererRepository _npcRendererRepository; + private readonly ICharacterStateCache _characterStateCache; + private readonly INPCStateCache _npcStateCache; - _characterStateCache.Reset(); - _npcStateCache.Reset(); - } + public RendererRepositoryResetter(ICharacterRendererRepository characterRendererRepository, + INPCRendererRepository npcRendererRepository, + ICharacterStateCache characterStateCache, + INPCStateCache npcStateCache) + { + _characterRendererRepository = characterRendererRepository; + _npcRendererRepository = npcRendererRepository; + _characterStateCache = characterStateCache; + _npcStateCache = npcStateCache; } - public interface IRendererRepositoryResetter + public void ResetRenderers() { - void ResetRenderers(); + _characterRendererRepository.Dispose(); + _npcRendererRepository.Dispose(); + + _characterStateCache.Reset(); + _npcStateCache.Reset(); } +} + +public interface IRendererRepositoryResetter +{ + void ResetRenderers(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs b/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs index 90c79b724..39adf29d0 100644 --- a/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs +++ b/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs @@ -1,21 +1,20 @@ -namespace EndlessClient.Rendering.Sprites +namespace EndlessClient.Rendering.Sprites; + +public enum ArmorShieldSpriteType { - public enum ArmorShieldSpriteType - { - //dir1/dir2 - Standing = 1, //1/2 - ShieldItemOnBack_AttackingWithBow = 3, - WalkFrame1 = 3, //3/7 - WalkFrame2 = 4, //4/8 - WalkFrame3 = 5, //5/9 - WalkFrame4 = 6, //6/10 - SpellCast = 11, //11/12 - PunchFrame1 = 13, //13/15 - PunchFrame2 = 14, //14/16 + //dir1/dir2 + Standing = 1, //1/2 + ShieldItemOnBack_AttackingWithBow = 3, + WalkFrame1 = 3, //3/7 + WalkFrame2 = 4, //4/8 + WalkFrame3 = 5, //5/9 + WalkFrame4 = 6, //6/10 + SpellCast = 11, //11/12 + PunchFrame1 = 13, //13/15 + PunchFrame2 = 14, //14/16 - //not valid for shields: - SitChair = 17, //17/18 - SitGround = 19, //19/20 - Bow = 21, //21/22 - } + //not valid for shields: + SitChair = 17, //17/18 + SitGround = 19, //19/20 + Bow = 21, //21/22 } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/BootsSpriteType.cs b/EndlessClient/Rendering/Sprites/BootsSpriteType.cs index e06c886e3..34b0522cf 100644 --- a/EndlessClient/Rendering/Sprites/BootsSpriteType.cs +++ b/EndlessClient/Rendering/Sprites/BootsSpriteType.cs @@ -1,14 +1,13 @@ -namespace EndlessClient.Rendering.Sprites +namespace EndlessClient.Rendering.Sprites; + +public enum BootsSpriteType { - public enum BootsSpriteType - { - Standing = 1, //1/2 - WalkFrame1 = 3, //3/7 - WalkFrame2 = 4, //4/8 - WalkFrame3 = 5, //5/9 - WalkFrame4 = 6, //6/10 - Attack = 11, //11/12 - SitChair = 13, //13/14 - SitGround = 15, //15/16 - } + Standing = 1, //1/2 + WalkFrame1 = 3, //3/7 + WalkFrame2 = 4, //4/8 + WalkFrame3 = 5, //5/9 + WalkFrame4 = 6, //6/10 + Attack = 11, //11/12 + SitChair = 13, //13/14 + SitGround = 15, //15/16 } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs b/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs index e4f920f79..531a996ca 100644 --- a/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs +++ b/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs @@ -9,173 +9,102 @@ using System; using System.Linq; -namespace EndlessClient.Rendering.Sprites +namespace EndlessClient.Rendering.Sprites; + +[MappedType(BaseType = typeof(ICharacterSpriteCalculator))] +public class CharacterSpriteCalculator : ICharacterSpriteCalculator { - [MappedType(BaseType = typeof(ICharacterSpriteCalculator))] - public class CharacterSpriteCalculator : ICharacterSpriteCalculator + private readonly INativeGraphicsManager _gfxManager; + private readonly IMetadataProvider _shieldMetadataProvider; + private readonly IMetadataProvider _hatMetadataProvider; + private readonly IMetadataProvider _weaponMetadataProvider; + + public CharacterSpriteCalculator(INativeGraphicsManager gfxManager, + IMetadataProvider shieldMetadataProvider, + IMetadataProvider hatMetadataProvider, + IMetadataProvider weaponMetadataProvider) { - private readonly INativeGraphicsManager _gfxManager; - private readonly IMetadataProvider _shieldMetadataProvider; - private readonly IMetadataProvider _hatMetadataProvider; - private readonly IMetadataProvider _weaponMetadataProvider; - - public CharacterSpriteCalculator(INativeGraphicsManager gfxManager, - IMetadataProvider shieldMetadataProvider, - IMetadataProvider hatMetadataProvider, - IMetadataProvider weaponMetadataProvider) - { - _gfxManager = gfxManager; - _shieldMetadataProvider = shieldMetadataProvider; - _hatMetadataProvider = hatMetadataProvider; - _weaponMetadataProvider = weaponMetadataProvider; - } - - public ISpriteSheet GetBootsTexture(CharacterRenderProperties characterRenderProperties) - { - if (characterRenderProperties.BootsGraphic == 0) - return new EmptySpriteSheet(); - - var type = BootsSpriteType.Standing; - var currentAction = characterRenderProperties.CurrentAction; - if (currentAction == CharacterActionState.Emote && characterRenderProperties.SitState != SitState.Standing) - currentAction = CharacterActionState.Sitting; - - switch (currentAction) - { - case CharacterActionState.Walking: - switch (characterRenderProperties.RenderWalkFrame) - { - case 1: type = BootsSpriteType.WalkFrame1; break; - case 2: type = BootsSpriteType.WalkFrame2; break; - case 3: type = BootsSpriteType.WalkFrame3; break; - case 4: type = BootsSpriteType.WalkFrame4; break; - } - break; - case CharacterActionState.Attacking: - if (!BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame == 2 || - BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame == 1) - type = BootsSpriteType.Attack; - break; - case CharacterActionState.Sitting: - switch (characterRenderProperties.SitState) - { - case SitState.Chair: type = BootsSpriteType.SitChair; break; - case SitState.Floor: type = BootsSpriteType.SitGround; break; - } - break; - } - - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleShoes : GFXTypes.MaleShoes; + _gfxManager = gfxManager; + _shieldMetadataProvider = shieldMetadataProvider; + _hatMetadataProvider = hatMetadataProvider; + _weaponMetadataProvider = weaponMetadataProvider; + } - var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var baseBootGraphic = GetBaseBootGraphic(characterRenderProperties.BootsGraphic); - var gfxNumber = baseBootGraphic + (int)type + offset; + public ISpriteSheet GetBootsTexture(CharacterRenderProperties characterRenderProperties) + { + if (characterRenderProperties.BootsGraphic == 0) + return new EmptySpriteSheet(); - return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); - } + var type = BootsSpriteType.Standing; + var currentAction = characterRenderProperties.CurrentAction; + if (currentAction == CharacterActionState.Emote && characterRenderProperties.SitState != SitState.Standing) + currentAction = CharacterActionState.Sitting; - public ISpriteSheet GetArmorTexture(CharacterRenderProperties characterRenderProperties) + switch (currentAction) { - if (characterRenderProperties.ArmorGraphic == 0) - return new EmptySpriteSheet(); - - var type = ArmorShieldSpriteType.Standing; - var currentAction = characterRenderProperties.CurrentAction; - if (currentAction == CharacterActionState.Emote && characterRenderProperties.SitState != SitState.Standing) - currentAction = CharacterActionState.Sitting; - - switch (currentAction) - { - case CharacterActionState.Walking: - switch (characterRenderProperties.RenderWalkFrame) - { - case 1: type = ArmorShieldSpriteType.WalkFrame1; break; - case 2: type = ArmorShieldSpriteType.WalkFrame2; break; - case 3: type = ArmorShieldSpriteType.WalkFrame3; break; - case 4: type = ArmorShieldSpriteType.WalkFrame4; break; - } - break; - case CharacterActionState.Attacking: - if (BowIsEquipped(characterRenderProperties)) - { - switch (characterRenderProperties.RenderAttackFrame) - { - case 1: type = ArmorShieldSpriteType.Bow; break; - case 2: type = ArmorShieldSpriteType.Standing; break; - } - } - else - { - switch (characterRenderProperties.RenderAttackFrame) - { - case 1: type = ArmorShieldSpriteType.PunchFrame1; break; - case 2: type = ArmorShieldSpriteType.PunchFrame2; break; - } - } - break; - case CharacterActionState.SpellCast: - type = ArmorShieldSpriteType.SpellCast; - break; - case CharacterActionState.Sitting: - switch (characterRenderProperties.SitState) - { - case SitState.Chair: - type = ArmorShieldSpriteType.SitChair; - break; - case SitState.Floor: - type = ArmorShieldSpriteType.SitGround; - break; - } - break; - } - - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleArmor : GFXTypes.MaleArmor; - - var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var baseArmorValue = GetBaseArmorGraphic(characterRenderProperties.ArmorGraphic); - var gfxNumber = baseArmorValue + (int)type + offset; - - return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + case CharacterActionState.Walking: + switch (characterRenderProperties.RenderWalkFrame) + { + case 1: type = BootsSpriteType.WalkFrame1; break; + case 2: type = BootsSpriteType.WalkFrame2; break; + case 3: type = BootsSpriteType.WalkFrame3; break; + case 4: type = BootsSpriteType.WalkFrame4; break; + } + break; + case CharacterActionState.Attacking: + if (!BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame == 2 || + BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame == 1) + type = BootsSpriteType.Attack; + break; + case CharacterActionState.Sitting: + switch (characterRenderProperties.SitState) + { + case SitState.Chair: type = BootsSpriteType.SitChair; break; + case SitState.Floor: type = BootsSpriteType.SitGround; break; + } + break; } - public ISpriteSheet GetHatTexture(CharacterRenderProperties characterRenderProperties) - { - if (characterRenderProperties.HatGraphic == 0) - return new EmptySpriteSheet(); - - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleHat : GFXTypes.MaleHat; + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleShoes : GFXTypes.MaleShoes; - var offset = 2 * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var baseHatValue = GetBaseHatGraphic(characterRenderProperties.HatGraphic); - var gfxNumber = baseHatValue + 1 + offset; + var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var baseBootGraphic = GetBaseBootGraphic(characterRenderProperties.BootsGraphic); + var gfxNumber = baseBootGraphic + (int)type + offset; - var actualMetadata = _hatMetadataProvider.GetValueOrDefault(characterRenderProperties.HatGraphic); - return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, transparent: true, fullTransparent: actualMetadata.ClipMode != HatMaskType.Standard)); - } + return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + } - public ISpriteSheet GetShieldTexture(CharacterRenderProperties characterRenderProperties) - { - if (characterRenderProperties.ShieldGraphic == 0) - return new EmptySpriteSheet(); + public ISpriteSheet GetArmorTexture(CharacterRenderProperties characterRenderProperties) + { + if (characterRenderProperties.ArmorGraphic == 0) + return new EmptySpriteSheet(); - var type = ArmorShieldSpriteType.Standing; - var offset = GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var type = ArmorShieldSpriteType.Standing; + var currentAction = characterRenderProperties.CurrentAction; + if (currentAction == CharacterActionState.Emote && characterRenderProperties.SitState != SitState.Standing) + currentAction = CharacterActionState.Sitting; - // front shields have one size gfx, back arrows/wings have another size. - var actualMetadata = _shieldMetadataProvider.GetValueOrDefault(characterRenderProperties.ShieldGraphic); - if (!actualMetadata.IsShieldOnBack) - { - if (characterRenderProperties.CurrentAction == CharacterActionState.Walking) + switch (currentAction) + { + case CharacterActionState.Walking: + switch (characterRenderProperties.RenderWalkFrame) { - switch (characterRenderProperties.RenderWalkFrame) + case 1: type = ArmorShieldSpriteType.WalkFrame1; break; + case 2: type = ArmorShieldSpriteType.WalkFrame2; break; + case 3: type = ArmorShieldSpriteType.WalkFrame3; break; + case 4: type = ArmorShieldSpriteType.WalkFrame4; break; + } + break; + case CharacterActionState.Attacking: + if (BowIsEquipped(characterRenderProperties)) + { + switch (characterRenderProperties.RenderAttackFrame) { - case 1: type = ArmorShieldSpriteType.WalkFrame1; break; - case 2: type = ArmorShieldSpriteType.WalkFrame2; break; - case 3: type = ArmorShieldSpriteType.WalkFrame3; break; - case 4: type = ArmorShieldSpriteType.WalkFrame4; break; + case 1: type = ArmorShieldSpriteType.Bow; break; + case 2: type = ArmorShieldSpriteType.Standing; break; } } - else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking) + else { switch (characterRenderProperties.RenderAttackFrame) { @@ -183,352 +112,422 @@ public ISpriteSheet GetShieldTexture(CharacterRenderProperties characterRenderPr case 2: type = ArmorShieldSpriteType.PunchFrame2; break; } } - else if (characterRenderProperties.CurrentAction == CharacterActionState.SpellCast) + break; + case CharacterActionState.SpellCast: + type = ArmorShieldSpriteType.SpellCast; + break; + case CharacterActionState.Sitting: + switch (characterRenderProperties.SitState) { - type = ArmorShieldSpriteType.SpellCast; + case SitState.Chair: + type = ArmorShieldSpriteType.SitChair; + break; + case SitState.Floor: + type = ArmorShieldSpriteType.SitGround; + break; } - else if (characterRenderProperties.SitState != SitState.Standing) - { - return new EmptySpriteSheet(); - } - - offset *= GetOffsetBasedOnState(type); - } - else - { - //different gfx numbering scheme for shield items worn on the back: - // Standing = 1/2 - // Attacking = 3/4 - // Extra = 5 (unused?) - if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking) - type = ArmorShieldSpriteType.ShieldItemOnBack_AttackingWithBow; - } - - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleBack : GFXTypes.MaleBack; - - var baseShieldValue = GetBaseShieldGraphic(characterRenderProperties.ShieldGraphic); - var gfxNumber = baseShieldValue + (int)type + offset; - return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + break; } - public ISpriteSheet[] GetWeaponTextures(CharacterRenderProperties characterRenderProperties) - { - var retTextures = new ISpriteSheet[] { new EmptySpriteSheet(), new EmptySpriteSheet() }; - if (characterRenderProperties.WeaponGraphic == 0) - return retTextures; + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleArmor : GFXTypes.MaleArmor; - var type = WeaponSpriteType.Standing; - switch (characterRenderProperties.CurrentAction) - { - case CharacterActionState.Walking: - switch (characterRenderProperties.RenderWalkFrame) - { - case 1: type = WeaponSpriteType.WalkFrame1; break; - case 2: type = WeaponSpriteType.WalkFrame2; break; - case 3: type = WeaponSpriteType.WalkFrame3; break; - case 4: type = WeaponSpriteType.WalkFrame4; break; - } - break; - case CharacterActionState.Attacking: - if (BowIsEquipped(characterRenderProperties)) - { - switch (characterRenderProperties.RenderAttackFrame) - { - case 1: type = WeaponSpriteType.Shooting; break; - case 2: type = WeaponSpriteType.Standing; break; - } - } - else - { - switch (characterRenderProperties.RenderAttackFrame) - { - case 1: type = WeaponSpriteType.SwingFrame1; break; - case 2: - type = characterRenderProperties.Direction == EODirection.Down - || characterRenderProperties.Direction == EODirection.Right - ? WeaponSpriteType.SwingFrame2Spec : WeaponSpriteType.SwingFrame2; - break; - } - } - break; - case CharacterActionState.SpellCast: - type = WeaponSpriteType.SpellCast; - break; - case CharacterActionState.Sitting: - return retTextures; //no weapon when sitting - } + var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var baseArmorValue = GetBaseArmorGraphic(characterRenderProperties.ArmorGraphic); + var gfxNumber = baseArmorValue + (int)type + offset; - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleWeapons : GFXTypes.MaleWeapons; + return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + } - var baseWeaponValue = GetBaseWeaponGraphic(characterRenderProperties.WeaponGraphic); + public ISpriteSheet GetHatTexture(CharacterRenderProperties characterRenderProperties) + { + if (characterRenderProperties.HatGraphic == 0) + return new EmptySpriteSheet(); - if (type == WeaponSpriteType.SwingFrame2Spec) - { - // SwingFrame2Spec is rendered in front of the character - var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var gfxNumber = baseWeaponValue + (int)type + offset; - retTextures[0] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); - - // SwingFrame2 is rendered behind the character - type = WeaponSpriteType.SwingFrame2; - offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - gfxNumber = baseWeaponValue + (int)type + offset; - retTextures[1] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); - } - else - { - var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var gfxNumber = baseWeaponValue + (int)type + offset; + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleHat : GFXTypes.MaleHat; - retTextures[0] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); - } + var offset = 2 * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var baseHatValue = GetBaseHatGraphic(characterRenderProperties.HatGraphic); + var gfxNumber = baseHatValue + 1 + offset; - return retTextures; - } + var actualMetadata = _hatMetadataProvider.GetValueOrDefault(characterRenderProperties.HatGraphic); + return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, transparent: true, fullTransparent: actualMetadata.ClipMode != HatMaskType.Standard)); + } - public ISpriteSheet GetWeaponSlash(CharacterRenderProperties characterRenderProperties) - { - const int NUM_SLASHES = 9; + public ISpriteSheet GetShieldTexture(CharacterRenderProperties characterRenderProperties) + { + if (characterRenderProperties.ShieldGraphic == 0) + return new EmptySpriteSheet(); - var metadata = _weaponMetadataProvider.GetValueOrDefault(characterRenderProperties.WeaponGraphic); - if (!metadata.Slash.HasValue || metadata.Ranged || characterRenderProperties.RenderAttackFrame != 2) - return new EmptySpriteSheet(); + var type = ArmorShieldSpriteType.Standing; + var offset = GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var sheet = _gfxManager.TextureFromResource(GFXTypes.PostLoginUI, 40, transparent: true); - return new SpriteSheet(sheet, - new Rectangle(sheet.Width / 4 * (int)characterRenderProperties.Direction, - sheet.Height / NUM_SLASHES * metadata.Slash.Value, - sheet.Width / 4, - sheet.Height / NUM_SLASHES)); - } - - public ISpriteSheet GetSkinTexture(CharacterRenderProperties characterRenderProperties) + // front shields have one size gfx, back arrows/wings have another size. + var actualMetadata = _shieldMetadataProvider.GetValueOrDefault(characterRenderProperties.ShieldGraphic); + if (!actualMetadata.IsShieldOnBack) { - const int SheetRows = 7; - var sheetColumns = 4; - var gfxNum = 1; - - if (characterRenderProperties.CurrentAction == CharacterActionState.Walking && characterRenderProperties.RenderWalkFrame > 0) - { - gfxNum = 2; - sheetColumns = 16; - } - else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && characterRenderProperties.RenderAttackFrame > 0) + if (characterRenderProperties.CurrentAction == CharacterActionState.Walking) { - if (!BowIsEquipped(characterRenderProperties)) + switch (characterRenderProperties.RenderWalkFrame) { - gfxNum = 3; - sheetColumns = 8; + case 1: type = ArmorShieldSpriteType.WalkFrame1; break; + case 2: type = ArmorShieldSpriteType.WalkFrame2; break; + case 3: type = ArmorShieldSpriteType.WalkFrame3; break; + case 4: type = ArmorShieldSpriteType.WalkFrame4; break; } - else if (characterRenderProperties.RenderAttackFrame == 1) //only 1 frame of bow/gun animation + } + else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking) + { + switch (characterRenderProperties.RenderAttackFrame) { - gfxNum = 7; //4 columns in this one too + case 1: type = ArmorShieldSpriteType.PunchFrame1; break; + case 2: type = ArmorShieldSpriteType.PunchFrame2; break; } } else if (characterRenderProperties.CurrentAction == CharacterActionState.SpellCast) { - gfxNum = 4; + type = ArmorShieldSpriteType.SpellCast; } else if (characterRenderProperties.SitState != SitState.Standing) { - if (characterRenderProperties.SitState == SitState.Floor) gfxNum = 6; - else if (characterRenderProperties.SitState == SitState.Chair) gfxNum = 5; + return new EmptySpriteSheet(); } - var texture = _gfxManager.TextureFromResource(GFXTypes.SkinSprites, gfxNum, true); + offset *= GetOffsetBasedOnState(type); + } + else + { + //different gfx numbering scheme for shield items worn on the back: + // Standing = 1/2 + // Attacking = 3/4 + // Extra = 5 (unused?) + if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking) + type = ArmorShieldSpriteType.ShieldItemOnBack_AttackingWithBow; + } - var rotated = characterRenderProperties.Direction == EODirection.Left || - characterRenderProperties.Direction == EODirection.Up; + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleBack : GFXTypes.MaleBack; - var heightDelta = texture.Height / SheetRows; - var widthDelta = texture.Width / sheetColumns; - var sectionDelta = texture.Width / 4; + var baseShieldValue = GetBaseShieldGraphic(characterRenderProperties.ShieldGraphic); + var gfxNumber = baseShieldValue + (int)type + offset; + return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + } - var walkExtra = characterRenderProperties.RenderWalkFrame > 0 ? widthDelta * (characterRenderProperties.RenderWalkFrame - 1) : 0; - walkExtra = !BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame > 0 ? widthDelta * (characterRenderProperties.RenderAttackFrame - 1) : walkExtra; + public ISpriteSheet[] GetWeaponTextures(CharacterRenderProperties characterRenderProperties) + { + var retTextures = new ISpriteSheet[] { new EmptySpriteSheet(), new EmptySpriteSheet() }; + if (characterRenderProperties.WeaponGraphic == 0) + return retTextures; - // Fix offsets for skins - the source rectangles are not at an evenly spaced interval - if (characterRenderProperties.Gender == 1) - { - if (characterRenderProperties.CurrentAction == CharacterActionState.Walking && !rotated) + var type = WeaponSpriteType.Standing; + switch (characterRenderProperties.CurrentAction) + { + case CharacterActionState.Walking: + switch (characterRenderProperties.RenderWalkFrame) { - walkExtra += 1; + case 1: type = WeaponSpriteType.WalkFrame1; break; + case 2: type = WeaponSpriteType.WalkFrame2; break; + case 3: type = WeaponSpriteType.WalkFrame3; break; + case 4: type = WeaponSpriteType.WalkFrame4; break; } - else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && - characterRenderProperties.RenderAttackFrame == 1) + break; + case CharacterActionState.Attacking: + if (BowIsEquipped(characterRenderProperties)) { - // This condition needs some shifting, but this must be done in SkinRenderLocationCalculator since it is a shift of the loaded sprite + switch (characterRenderProperties.RenderAttackFrame) + { + case 1: type = WeaponSpriteType.Shooting; break; + case 2: type = WeaponSpriteType.Standing; break; + } } - } - else if (characterRenderProperties.Gender == 0) - { - if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && characterRenderProperties.RenderAttackFrame > 0) + else { - walkExtra += 1; + switch (characterRenderProperties.RenderAttackFrame) + { + case 1: type = WeaponSpriteType.SwingFrame1; break; + case 2: + type = characterRenderProperties.Direction == EODirection.Down + || characterRenderProperties.Direction == EODirection.Right + ? WeaponSpriteType.SwingFrame2Spec : WeaponSpriteType.SwingFrame2; + break; + } } - } + break; + case CharacterActionState.SpellCast: + type = WeaponSpriteType.SpellCast; + break; + case CharacterActionState.Sitting: + return retTextures; //no weapon when sitting + } - var sourceArea = new Rectangle( - characterRenderProperties.Gender * widthDelta * (sheetColumns / 2) + (rotated ? sectionDelta : 0) + walkExtra, - characterRenderProperties.Race * heightDelta, - widthDelta, - heightDelta); + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleWeapons : GFXTypes.MaleWeapons; - return new SpriteSheet(texture, sourceArea); - } + var baseWeaponValue = GetBaseWeaponGraphic(characterRenderProperties.WeaponGraphic); - public ISpriteSheet GetHairTexture(CharacterRenderProperties characterRenderProperties) + if (type == WeaponSpriteType.SwingFrame2Spec) + { + // SwingFrame2Spec is rendered in front of the character + var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var gfxNumber = baseWeaponValue + (int)type + offset; + retTextures[0] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + + // SwingFrame2 is rendered behind the character + type = WeaponSpriteType.SwingFrame2; + offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + gfxNumber = baseWeaponValue + (int)type + offset; + retTextures[1] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + } + else { - // Use dummy rectangle for no hair so hats are still correctly aligned - var hairStyle = characterRenderProperties.HairStyle == 0 ? 1 : characterRenderProperties.HairStyle; + var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var gfxNumber = baseWeaponValue + (int)type + offset; - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleHair : GFXTypes.MaleHair; - var offset = 2 * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var gfxNumber = GetBaseHairGraphic(hairStyle, characterRenderProperties.HairColor) + 2 + offset; + retTextures[0] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + } - var hairTexture = _gfxManager.TextureFromResource(gfxFile, gfxNumber, true); + return retTextures; + } - return characterRenderProperties.HairStyle == 0 - ? (ISpriteSheet)new EmptySpriteSheet(new Rectangle(0, 0, hairTexture.Width, hairTexture.Height)) - : new SpriteSheet(hairTexture); - } + public ISpriteSheet GetWeaponSlash(CharacterRenderProperties characterRenderProperties) + { + const int NUM_SLASHES = 9; + + var metadata = _weaponMetadataProvider.GetValueOrDefault(characterRenderProperties.WeaponGraphic); + if (!metadata.Slash.HasValue || metadata.Ranged || characterRenderProperties.RenderAttackFrame != 2) + return new EmptySpriteSheet(); + + var sheet = _gfxManager.TextureFromResource(GFXTypes.PostLoginUI, 40, transparent: true); + return new SpriteSheet(sheet, + new Rectangle(sheet.Width / 4 * (int)characterRenderProperties.Direction, + sheet.Height / NUM_SLASHES * metadata.Slash.Value, + sheet.Width / 4, + sheet.Height / NUM_SLASHES)); + } + + public ISpriteSheet GetSkinTexture(CharacterRenderProperties characterRenderProperties) + { + const int SheetRows = 7; + var sheetColumns = 4; + var gfxNum = 1; - public ISpriteSheet GetFaceTexture(CharacterRenderProperties characterRenderProperties) + if (characterRenderProperties.CurrentAction == CharacterActionState.Walking && characterRenderProperties.RenderWalkFrame > 0) { - if (characterRenderProperties.EmoteFrame < 0 || - characterRenderProperties.Emote == Emote.Trade || - characterRenderProperties.Emote == Emote.LevelUp) + gfxNum = 2; + sheetColumns = 16; + } + else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && characterRenderProperties.RenderAttackFrame > 0) + { + if (!BowIsEquipped(characterRenderProperties)) { - return new EmptySpriteSheet(); + gfxNum = 3; + sheetColumns = 8; } + else if (characterRenderProperties.RenderAttackFrame == 1) //only 1 frame of bow/gun animation + { + gfxNum = 7; //4 columns in this one too + } + } + else if (characterRenderProperties.CurrentAction == CharacterActionState.SpellCast) + { + gfxNum = 4; + } + else if (characterRenderProperties.SitState != SitState.Standing) + { + if (characterRenderProperties.SitState == SitState.Floor) gfxNum = 6; + else if (characterRenderProperties.SitState == SitState.Chair) gfxNum = 5; + } - //14 rows (7 female - 7 male) / 11 columns - const int ROWS = 14; - const int COLS = 11; + var texture = _gfxManager.TextureFromResource(GFXTypes.SkinSprites, gfxNum, true); - var texture = _gfxManager.TextureFromResource(GFXTypes.SkinSprites, 8, true); + var rotated = characterRenderProperties.Direction == EODirection.Left || + characterRenderProperties.Direction == EODirection.Up; - var widthDelta = texture.Width / COLS; - var heightDelta = texture.Height / ROWS; - var genderOffset = texture.Height / 2 * characterRenderProperties.Gender; - //'playful' is the last face in the gfx (ndx 10), even though it has enum value of 14 (ndx 13) - var emote = characterRenderProperties.Emote == Emote.Playful || - characterRenderProperties.Emote == Emote.Drunk - ? 10 : (int)characterRenderProperties.Emote - 1; + var heightDelta = texture.Height / SheetRows; + var widthDelta = texture.Width / sheetColumns; + var sectionDelta = texture.Width / 4; - var sourceRectangle = new Rectangle(widthDelta * emote, heightDelta * characterRenderProperties.Race + genderOffset, widthDelta, heightDelta); + var walkExtra = characterRenderProperties.RenderWalkFrame > 0 ? widthDelta * (characterRenderProperties.RenderWalkFrame - 1) : 0; + walkExtra = !BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame > 0 ? widthDelta * (characterRenderProperties.RenderAttackFrame - 1) : walkExtra; - return new SpriteSheet(texture, sourceRectangle); + // Fix offsets for skins - the source rectangles are not at an evenly spaced interval + if (characterRenderProperties.Gender == 1) + { + if (characterRenderProperties.CurrentAction == CharacterActionState.Walking && !rotated) + { + walkExtra += 1; + } + else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && + characterRenderProperties.RenderAttackFrame == 1) + { + // This condition needs some shifting, but this must be done in SkinRenderLocationCalculator since it is a shift of the loaded sprite + } } - - public ISpriteSheet GetEmoteTexture(CharacterRenderProperties characterRenderProperties) + else if (characterRenderProperties.Gender == 0) { - if (characterRenderProperties.Emote == 0 || characterRenderProperties.EmoteFrame < 0) - return new EmptySpriteSheet(); + if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && characterRenderProperties.RenderAttackFrame > 0) + { + walkExtra += 1; + } + } - const int NUM_EMOTES = 15; - const int NUM_FRAMES = 4; + var sourceArea = new Rectangle( + characterRenderProperties.Gender * widthDelta * (sheetColumns / 2) + (rotated ? sectionDelta : 0) + walkExtra, + characterRenderProperties.Race * heightDelta, + widthDelta, + heightDelta); - var emoteValue = Enum.GetName(typeof(Emote), characterRenderProperties.Emote) ?? ""; - var convertedValuesDictionary = Enum.GetNames(typeof(EmoteSpriteType)) - .ToDictionary(x => x, x => (EmoteSpriteType)Enum.Parse(typeof(EmoteSpriteType), x)); - var convertedEmote = (int)convertedValuesDictionary[emoteValue]; + return new SpriteSheet(texture, sourceArea); + } - var emoteTexture = _gfxManager.TextureFromResource(GFXTypes.PostLoginUI, 38, true); + public ISpriteSheet GetHairTexture(CharacterRenderProperties characterRenderProperties) + { + // Use dummy rectangle for no hair so hats are still correctly aligned + var hairStyle = characterRenderProperties.HairStyle == 0 ? 1 : characterRenderProperties.HairStyle; - var eachSet = emoteTexture.Width / NUM_EMOTES; - var eachFrame = emoteTexture.Width / (NUM_EMOTES * NUM_FRAMES); - var startX = convertedEmote * eachSet + characterRenderProperties.EmoteFrame * eachFrame; + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleHair : GFXTypes.MaleHair; + var offset = 2 * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var gfxNumber = GetBaseHairGraphic(hairStyle, characterRenderProperties.HairColor) + 2 + offset; - var emoteRect = new Rectangle(startX, 0, eachFrame, emoteTexture.Height); + var hairTexture = _gfxManager.TextureFromResource(gfxFile, gfxNumber, true); - return new SpriteSheet(emoteTexture, emoteRect); - } + return characterRenderProperties.HairStyle == 0 + ? (ISpriteSheet)new EmptySpriteSheet(new Rectangle(0, 0, hairTexture.Width, hairTexture.Height)) + : new SpriteSheet(hairTexture); + } - private int GetBaseBootGraphic(int bootsGraphic) + public ISpriteSheet GetFaceTexture(CharacterRenderProperties characterRenderProperties) + { + if (characterRenderProperties.EmoteFrame < 0 || + characterRenderProperties.Emote == Emote.Trade || + characterRenderProperties.Emote == Emote.LevelUp) { - return (bootsGraphic - 1) * 40; + return new EmptySpriteSheet(); } - private int GetBaseArmorGraphic(int armorGraphic) - { - return (armorGraphic - 1) * 50; - } + //14 rows (7 female - 7 male) / 11 columns + const int ROWS = 14; + const int COLS = 11; - private int GetBaseHatGraphic(int hatGraphic) - { - return (hatGraphic - 1) * 10; - } + var texture = _gfxManager.TextureFromResource(GFXTypes.SkinSprites, 8, true); - private int GetBaseShieldGraphic(int shieldGraphic) - { - return (shieldGraphic - 1) * 50; - } + var widthDelta = texture.Width / COLS; + var heightDelta = texture.Height / ROWS; + var genderOffset = texture.Height / 2 * characterRenderProperties.Gender; + //'playful' is the last face in the gfx (ndx 10), even though it has enum value of 14 (ndx 13) + var emote = characterRenderProperties.Emote == Emote.Playful || + characterRenderProperties.Emote == Emote.Drunk + ? 10 : (int)characterRenderProperties.Emote - 1; - private int GetBaseWeaponGraphic(int weaponGraphic) - { - return (weaponGraphic - 1) * 100; - } + var sourceRectangle = new Rectangle(widthDelta * emote, heightDelta * characterRenderProperties.Race + genderOffset, widthDelta, heightDelta); - private int GetBaseHairGraphic(int hairStyle, int hairColor) - { - return (hairStyle - 1) * 40 + hairColor * 4; - } + return new SpriteSheet(texture, sourceRectangle); + } - private int GetBaseOffsetFromDirection(EODirection direction) - { - return direction == EODirection.Down || - direction == EODirection.Right ? 0 : 1; - } + public ISpriteSheet GetEmoteTexture(CharacterRenderProperties characterRenderProperties) + { + if (characterRenderProperties.Emote == 0 || characterRenderProperties.EmoteFrame < 0) + return new EmptySpriteSheet(); - private int GetOffsetBasedOnState(BootsSpriteType type) - { - switch (type) - { - case BootsSpriteType.WalkFrame1: - case BootsSpriteType.WalkFrame2: - case BootsSpriteType.WalkFrame3: - case BootsSpriteType.WalkFrame4: - return 4; - } - return 1; - } + const int NUM_EMOTES = 15; + const int NUM_FRAMES = 4; + + var emoteValue = Enum.GetName(typeof(Emote), characterRenderProperties.Emote) ?? ""; + var convertedValuesDictionary = Enum.GetNames(typeof(EmoteSpriteType)) + .ToDictionary(x => x, x => (EmoteSpriteType)Enum.Parse(typeof(EmoteSpriteType), x)); + var convertedEmote = (int)convertedValuesDictionary[emoteValue]; - private int GetOffsetBasedOnState(ArmorShieldSpriteType type) + var emoteTexture = _gfxManager.TextureFromResource(GFXTypes.PostLoginUI, 38, true); + + var eachSet = emoteTexture.Width / NUM_EMOTES; + var eachFrame = emoteTexture.Width / (NUM_EMOTES * NUM_FRAMES); + var startX = convertedEmote * eachSet + characterRenderProperties.EmoteFrame * eachFrame; + + var emoteRect = new Rectangle(startX, 0, eachFrame, emoteTexture.Height); + + return new SpriteSheet(emoteTexture, emoteRect); + } + + private int GetBaseBootGraphic(int bootsGraphic) + { + return (bootsGraphic - 1) * 40; + } + + private int GetBaseArmorGraphic(int armorGraphic) + { + return (armorGraphic - 1) * 50; + } + + private int GetBaseHatGraphic(int hatGraphic) + { + return (hatGraphic - 1) * 10; + } + + private int GetBaseShieldGraphic(int shieldGraphic) + { + return (shieldGraphic - 1) * 50; + } + + private int GetBaseWeaponGraphic(int weaponGraphic) + { + return (weaponGraphic - 1) * 100; + } + + private int GetBaseHairGraphic(int hairStyle, int hairColor) + { + return (hairStyle - 1) * 40 + hairColor * 4; + } + + private int GetBaseOffsetFromDirection(EODirection direction) + { + return direction == EODirection.Down || + direction == EODirection.Right ? 0 : 1; + } + + private int GetOffsetBasedOnState(BootsSpriteType type) + { + switch (type) { - switch (type) - { - case ArmorShieldSpriteType.WalkFrame1: - case ArmorShieldSpriteType.WalkFrame2: - case ArmorShieldSpriteType.WalkFrame3: - case ArmorShieldSpriteType.WalkFrame4: - return 4; - case ArmorShieldSpriteType.PunchFrame1: - case ArmorShieldSpriteType.PunchFrame2: - return 2; - } - return 1; + case BootsSpriteType.WalkFrame1: + case BootsSpriteType.WalkFrame2: + case BootsSpriteType.WalkFrame3: + case BootsSpriteType.WalkFrame4: + return 4; } + return 1; + } - private int GetOffsetBasedOnState(WeaponSpriteType type) + private int GetOffsetBasedOnState(ArmorShieldSpriteType type) + { + switch (type) { - switch (type) - { - case WeaponSpriteType.WalkFrame1: - case WeaponSpriteType.WalkFrame2: - case WeaponSpriteType.WalkFrame3: - case WeaponSpriteType.WalkFrame4: - return 4; - case WeaponSpriteType.SwingFrame1: - case WeaponSpriteType.SwingFrame2: - return 2; - } - return 1; + case ArmorShieldSpriteType.WalkFrame1: + case ArmorShieldSpriteType.WalkFrame2: + case ArmorShieldSpriteType.WalkFrame3: + case ArmorShieldSpriteType.WalkFrame4: + return 4; + case ArmorShieldSpriteType.PunchFrame1: + case ArmorShieldSpriteType.PunchFrame2: + return 2; } + return 1; + } - private bool BowIsEquipped(CharacterRenderProperties characterRenderProperties) + private int GetOffsetBasedOnState(WeaponSpriteType type) + { + switch (type) { - return _weaponMetadataProvider.GetValueOrDefault(characterRenderProperties.WeaponGraphic).Ranged; + case WeaponSpriteType.WalkFrame1: + case WeaponSpriteType.WalkFrame2: + case WeaponSpriteType.WalkFrame3: + case WeaponSpriteType.WalkFrame4: + return 4; + case WeaponSpriteType.SwingFrame1: + case WeaponSpriteType.SwingFrame2: + return 2; } + return 1; + } + + private bool BowIsEquipped(CharacterRenderProperties characterRenderProperties) + { + return _weaponMetadataProvider.GetValueOrDefault(characterRenderProperties.WeaponGraphic).Ranged; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs b/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs index 12edf2cba..78ce76c8d 100644 --- a/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs +++ b/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs @@ -1,21 +1,20 @@ -namespace EndlessClient.Rendering.Sprites +namespace EndlessClient.Rendering.Sprites; + +public enum EmoteSpriteType { - public enum EmoteSpriteType - { - Happy = 0, - Sad = 1, - Surprised = 2, - Confused = 3, - Moon = 4, - Angry = 5, - Hearts = 6, - Depressed = 7, - Embarassed = 8, - Suicidal = 9, - Drunk = 10, - Trade = 11, - LevelUp = 12, - Playful = 13, - MusicNotes = 14, - } + Happy = 0, + Sad = 1, + Surprised = 2, + Confused = 3, + Moon = 4, + Angry = 5, + Hearts = 6, + Depressed = 7, + Embarassed = 8, + Suicidal = 9, + Drunk = 10, + Trade = 11, + LevelUp = 12, + Playful = 13, + MusicNotes = 14, } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs b/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs index 5d8308eaf..af18adf02 100644 --- a/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs @@ -2,30 +2,29 @@ using Microsoft.Xna.Framework.Graphics; using System.Linq; -namespace EndlessClient.Rendering.Sprites +namespace EndlessClient.Rendering.Sprites; + +public class EmptySpriteSheet : ISpriteSheet { - public class EmptySpriteSheet : ISpriteSheet - { - public bool HasTexture => false; - public Texture2D SheetTexture => null; - public Rectangle SourceRectangle { get; } + public bool HasTexture => false; + public Texture2D SheetTexture => null; + public Rectangle SourceRectangle { get; } - public EmptySpriteSheet() - : this(Rectangle.Empty) { } + public EmptySpriteSheet() + : this(Rectangle.Empty) { } - public EmptySpriteSheet(Rectangle sourceRectangle) - { - SourceRectangle = sourceRectangle; - } + public EmptySpriteSheet(Rectangle sourceRectangle) + { + SourceRectangle = sourceRectangle; + } - public T[] GetSourceTextureData() where T : struct - { - return Enumerable.Empty().ToArray(); - } + public T[] GetSourceTextureData() where T : struct + { + return Enumerable.Empty().ToArray(); + } - public Texture2D GetSourceTexture() - { - return SheetTexture; - } + public Texture2D GetSourceTexture() + { + return SheetTexture; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs b/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs index f50db921c..a6cfea869 100644 --- a/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs +++ b/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs @@ -1,19 +1,18 @@ using EOLib.Domain.Character; -namespace EndlessClient.Rendering.Sprites +namespace EndlessClient.Rendering.Sprites; + +public interface ICharacterSpriteCalculator { - public interface ICharacterSpriteCalculator - { - ISpriteSheet GetBootsTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetArmorTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetHatTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetShieldTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet[] GetWeaponTextures(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetWeaponSlash(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetBootsTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetArmorTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetHatTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetShieldTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet[] GetWeaponTextures(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetWeaponSlash(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetSkinTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetHairTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetFaceTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetEmoteTexture(CharacterRenderProperties characterRenderProperties); - } + ISpriteSheet GetSkinTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetHairTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetFaceTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetEmoteTexture(CharacterRenderProperties characterRenderProperties); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/ISpriteSheet.cs b/EndlessClient/Rendering/Sprites/ISpriteSheet.cs index 10e7863a6..34784ea20 100644 --- a/EndlessClient/Rendering/Sprites/ISpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/ISpriteSheet.cs @@ -1,18 +1,17 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Sprites +namespace EndlessClient.Rendering.Sprites; + +public interface ISpriteSheet { - public interface ISpriteSheet - { - bool HasTexture { get; } + bool HasTexture { get; } - Texture2D SheetTexture { get; } + Texture2D SheetTexture { get; } - Rectangle SourceRectangle { get; } + Rectangle SourceRectangle { get; } - T[] GetSourceTextureData() where T : struct; + T[] GetSourceTextureData() where T : struct; - Texture2D GetSourceTexture(); - } + Texture2D GetSourceTexture(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs b/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs index 5909e4f48..eb4007a53 100644 --- a/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs +++ b/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs @@ -6,113 +6,112 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.Sprites -{ - [AutoMappedType(IsSingleton = true)] - public class NPCSpriteDataCache : INPCSpriteDataCache - { - private const int CACHE_SIZE = 32; - - private readonly INPCSpriteSheet _npcSpriteSheet; +namespace EndlessClient.Rendering.Sprites; - private readonly Dictionary>> _spriteData; - private readonly List _lru; - private readonly HashSet _reclaimable; +[AutoMappedType(IsSingleton = true)] +public class NPCSpriteDataCache : INPCSpriteDataCache +{ + private const int CACHE_SIZE = 32; - public NPCSpriteDataCache(INPCSpriteSheet npcSpriteSheet) - { - _npcSpriteSheet = npcSpriteSheet; - _spriteData = new Dictionary>>(CACHE_SIZE); - _lru = new List(CACHE_SIZE); - _reclaimable = new HashSet(CACHE_SIZE); - } + private readonly INPCSpriteSheet _npcSpriteSheet; - public void Populate(int graphic) - { - if (_spriteData.ContainsKey(graphic)) - return; + private readonly Dictionary>> _spriteData; + private readonly List _lru; + private readonly HashSet _reclaimable; - if (_lru.Count >= CACHE_SIZE && _reclaimable.Count > 0) - { - // find and "reclaim" the first available candidate based on the order they were added to the LRU - // 'reclaimable' candidates are updated when the map changes - // candidates will never be NPCs that are on the current map - // a map with >= CACHE_SIZE different NPCs will cause problems here - for (int i = 0; i < _lru.Count; i++) - { - var candidate = _lru[i]; - if (_reclaimable.Contains(candidate)) - { - _spriteData.Remove(candidate); - _reclaimable.Remove(candidate); - _lru.RemoveAt(i); - break; - } - } - } + public NPCSpriteDataCache(INPCSpriteSheet npcSpriteSheet) + { + _npcSpriteSheet = npcSpriteSheet; + _spriteData = new Dictionary>>(CACHE_SIZE); + _lru = new List(CACHE_SIZE); + _reclaimable = new HashSet(CACHE_SIZE); + } - _spriteData[graphic] = new Dictionary>(); - _reclaimable.Remove(graphic); - _lru.Add(graphic); + public void Populate(int graphic) + { + if (_spriteData.ContainsKey(graphic)) + return; - foreach (NPCFrame frame in Enum.GetValues(typeof(NPCFrame))) + if (_lru.Count >= CACHE_SIZE && _reclaimable.Count > 0) + { + // find and "reclaim" the first available candidate based on the order they were added to the LRU + // 'reclaimable' candidates are updated when the map changes + // candidates will never be NPCs that are on the current map + // a map with >= CACHE_SIZE different NPCs will cause problems here + for (int i = 0; i < _lru.Count; i++) { - var text = _npcSpriteSheet.GetNPCTexture(graphic, frame, EODirection.Down); - var data = Array.Empty(); - - if (text != null) + var candidate = _lru[i]; + if (_reclaimable.Contains(candidate)) { - data = new Color[text.Width * text.Height]; - text.GetData(data); + _spriteData.Remove(candidate); + _reclaimable.Remove(candidate); + _lru.RemoveAt(i); + break; } - - _spriteData[graphic][frame] = data; } } - public void MarkForEviction(int graphic) - { - _reclaimable.Add(graphic); - } + _spriteData[graphic] = new Dictionary>(); + _reclaimable.Remove(graphic); + _lru.Add(graphic); - public void UnmarkForEviction(int graphic) + foreach (NPCFrame frame in Enum.GetValues(typeof(NPCFrame))) { - _reclaimable.Remove(graphic); - } + var text = _npcSpriteSheet.GetNPCTexture(graphic, frame, EODirection.Down); + var data = Array.Empty(); - public ReadOnlySpan GetData(int graphic, NPCFrame frame) - { - if (!_spriteData.ContainsKey(graphic)) + if (text != null) { - Populate(graphic); + data = new Color[text.Width * text.Height]; + text.GetData(data); } - return _spriteData[graphic][frame].Span; + _spriteData[graphic][frame] = data; } + } - public bool IsBlankSprite(int graphic) - { - if (!_spriteData.ContainsKey(graphic)) - { - Populate(graphic); - } + public void MarkForEviction(int graphic) + { + _reclaimable.Add(graphic); + } + + public void UnmarkForEviction(int graphic) + { + _reclaimable.Remove(graphic); + } - return _spriteData[graphic][NPCFrame.Standing].Span.ToArray().All(AlphaIsZero); + public ReadOnlySpan GetData(int graphic, NPCFrame frame) + { + if (!_spriteData.ContainsKey(graphic)) + { + Populate(graphic); } - private static bool AlphaIsZero(Color input) => input.A == 0; + return _spriteData[graphic][frame].Span; } - public interface INPCSpriteDataCache + public bool IsBlankSprite(int graphic) { - void Populate(int graphic); + if (!_spriteData.ContainsKey(graphic)) + { + Populate(graphic); + } + + return _spriteData[graphic][NPCFrame.Standing].Span.ToArray().All(AlphaIsZero); + } - void MarkForEviction(int graphic); + private static bool AlphaIsZero(Color input) => input.A == 0; +} - void UnmarkForEviction(int graphic); +public interface INPCSpriteDataCache +{ + void Populate(int graphic); - ReadOnlySpan GetData(int graphic, NPCFrame frame); + void MarkForEviction(int graphic); - bool IsBlankSprite(int graphic); - } + void UnmarkForEviction(int graphic); + + ReadOnlySpan GetData(int graphic, NPCFrame frame); + + bool IsBlankSprite(int graphic); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/NPCSpriteSheet.cs b/EndlessClient/Rendering/Sprites/NPCSpriteSheet.cs index 2c0d0ef27..392641645 100644 --- a/EndlessClient/Rendering/Sprites/NPCSpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/NPCSpriteSheet.cs @@ -6,68 +6,67 @@ using EOLib.Graphics; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Sprites +namespace EndlessClient.Rendering.Sprites; + +[AutoMappedType] +public class NPCSpriteSheet : INPCSpriteSheet { - [AutoMappedType] - public class NPCSpriteSheet : INPCSpriteSheet - { - private readonly INativeGraphicsManager _gfxManager; - private readonly IMetadataProvider _npcMetadataProvider; + private readonly INativeGraphicsManager _gfxManager; + private readonly IMetadataProvider _npcMetadataProvider; - public NPCSpriteSheet(INativeGraphicsManager gfxManager, - IMetadataProvider npcMetadataProvider) - { - _gfxManager = gfxManager; - _npcMetadataProvider = npcMetadataProvider; - } + public NPCSpriteSheet(INativeGraphicsManager gfxManager, + IMetadataProvider npcMetadataProvider) + { + _gfxManager = gfxManager; + _npcMetadataProvider = npcMetadataProvider; + } - public Texture2D GetNPCTexture(int baseGraphic, NPCFrame whichFrame, EODirection direction) + public Texture2D GetNPCTexture(int baseGraphic, NPCFrame whichFrame, EODirection direction) + { + int offset; + switch (whichFrame) { - int offset; - switch (whichFrame) - { - case NPCFrame.Standing: - offset = direction == EODirection.Down || direction == EODirection.Right ? 1 : 3; - break; - case NPCFrame.StandingFrame1: - offset = direction == EODirection.Down || direction == EODirection.Right ? 2 : 4; - break; - case NPCFrame.WalkFrame1: - offset = direction == EODirection.Down || direction == EODirection.Right ? 5 : 9; - break; - case NPCFrame.WalkFrame2: - offset = direction == EODirection.Down || direction == EODirection.Right ? 6 : 10; - break; - case NPCFrame.WalkFrame3: - offset = direction == EODirection.Down || direction == EODirection.Right ? 7 : 11; - break; - case NPCFrame.WalkFrame4: - offset = direction == EODirection.Down || direction == EODirection.Right ? 8 : 12; - break; - case NPCFrame.Attack1: - offset = direction == EODirection.Down || direction == EODirection.Right ? 13 : 15; - break; - case NPCFrame.Attack2: - offset = direction == EODirection.Down || direction == EODirection.Right ? 14 : 16; - break; - default: - return null; - } - - var baseGfx = (baseGraphic - 1) * 40; - return _gfxManager.TextureFromResource(GFXTypes.NPC, baseGfx + offset, true); + case NPCFrame.Standing: + offset = direction == EODirection.Down || direction == EODirection.Right ? 1 : 3; + break; + case NPCFrame.StandingFrame1: + offset = direction == EODirection.Down || direction == EODirection.Right ? 2 : 4; + break; + case NPCFrame.WalkFrame1: + offset = direction == EODirection.Down || direction == EODirection.Right ? 5 : 9; + break; + case NPCFrame.WalkFrame2: + offset = direction == EODirection.Down || direction == EODirection.Right ? 6 : 10; + break; + case NPCFrame.WalkFrame3: + offset = direction == EODirection.Down || direction == EODirection.Right ? 7 : 11; + break; + case NPCFrame.WalkFrame4: + offset = direction == EODirection.Down || direction == EODirection.Right ? 8 : 12; + break; + case NPCFrame.Attack1: + offset = direction == EODirection.Down || direction == EODirection.Right ? 13 : 15; + break; + case NPCFrame.Attack2: + offset = direction == EODirection.Down || direction == EODirection.Right ? 14 : 16; + break; + default: + return null; } - public NPCMetadata GetNPCMetadata(int graphic) - { - return _npcMetadataProvider.GetValueOrDefault(graphic); - } + var baseGfx = (baseGraphic - 1) * 40; + return _gfxManager.TextureFromResource(GFXTypes.NPC, baseGfx + offset, true); } - public interface INPCSpriteSheet + public NPCMetadata GetNPCMetadata(int graphic) { - Texture2D GetNPCTexture(int baseGraphic, NPCFrame whichFrame, EODirection direction); - - NPCMetadata GetNPCMetadata(int graphic); + return _npcMetadataProvider.GetValueOrDefault(graphic); } +} + +public interface INPCSpriteSheet +{ + Texture2D GetNPCTexture(int baseGraphic, NPCFrame whichFrame, EODirection direction); + + NPCMetadata GetNPCMetadata(int graphic); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/SpriteSheet.cs b/EndlessClient/Rendering/Sprites/SpriteSheet.cs index 4e44ea418..ab46df8a3 100644 --- a/EndlessClient/Rendering/Sprites/SpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/SpriteSheet.cs @@ -1,51 +1,50 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Sprites +namespace EndlessClient.Rendering.Sprites; + +public class SpriteSheet : ISpriteSheet { - public class SpriteSheet : ISpriteSheet - { - public bool HasTexture => true; + public bool HasTexture => true; - public Texture2D SheetTexture { get; } + public Texture2D SheetTexture { get; } - public Rectangle SourceRectangle { get; } + public Rectangle SourceRectangle { get; } - public SpriteSheet(Texture2D texture) - { - SheetTexture = texture; - SourceRectangle = new Rectangle(0, 0, texture.Width, texture.Height); - } + public SpriteSheet(Texture2D texture) + { + SheetTexture = texture; + SourceRectangle = new Rectangle(0, 0, texture.Width, texture.Height); + } - public SpriteSheet(Texture2D texture, Rectangle sourceArea) - { - SheetTexture = texture; - SourceRectangle = sourceArea; - } + public SpriteSheet(Texture2D texture, Rectangle sourceArea) + { + SheetTexture = texture; + SourceRectangle = sourceArea; + } - public T[] GetSourceTextureData() where T : struct - { - var data = new T[SourceRectangle.Width * SourceRectangle.Height]; - if (!SheetTexture.Bounds.Contains(SourceRectangle)) - return data; + public T[] GetSourceTextureData() where T : struct + { + var data = new T[SourceRectangle.Width * SourceRectangle.Height]; + if (!SheetTexture.Bounds.Contains(SourceRectangle)) + return data; - SheetTexture.GetData(0, SourceRectangle, data, 0, data.Length); + SheetTexture.GetData(0, SourceRectangle, data, 0, data.Length); - return data; - } + return data; + } - /// - /// Get a new texture containing the data from SheetTexture within the bounds of SourceRectangle. Must be disposed. - /// - /// New texture containing just the image specified by the SourceRectangle property. - public Texture2D GetSourceTexture() - { - var colorData = GetSourceTextureData(); + /// + /// Get a new texture containing the data from SheetTexture within the bounds of SourceRectangle. Must be disposed. + /// + /// New texture containing just the image specified by the SourceRectangle property. + public Texture2D GetSourceTexture() + { + var colorData = GetSourceTextureData(); - var retText = new Texture2D(SheetTexture.GraphicsDevice, SourceRectangle.Width, SourceRectangle.Height); - retText.SetData(colorData); + var retText = new Texture2D(SheetTexture.GraphicsDevice, SourceRectangle.Width, SourceRectangle.Height); + retText.SetData(colorData); - return retText; - } + return retText; } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/WeaponSpriteType.cs b/EndlessClient/Rendering/Sprites/WeaponSpriteType.cs index 2c75f97f5..1feb9532a 100644 --- a/EndlessClient/Rendering/Sprites/WeaponSpriteType.cs +++ b/EndlessClient/Rendering/Sprites/WeaponSpriteType.cs @@ -1,17 +1,16 @@ -namespace EndlessClient.Rendering.Sprites +namespace EndlessClient.Rendering.Sprites; + +public enum WeaponSpriteType { - public enum WeaponSpriteType - { - Standing = 1, //1/2 - WalkFrame1 = 3, //3/7 - WalkFrame2 = 4, //4/8 - WalkFrame3 = 5, //5/9 - WalkFrame4 = 6, //6/10 - SpellCast = 11, //11/12 - SwingFrame1 = 13, //13/15 - SwingFrame2 = 14, //14/16 - SwingFrame2Spec = 17, //17 - special frame rendered on top of the character in certain directions - //invalid for non-ranged weapons: - Shooting = 18, //18/19 AND 21/22 have same gfx - } + Standing = 1, //1/2 + WalkFrame1 = 3, //3/7 + WalkFrame2 = 4, //4/8 + WalkFrame3 = 5, //5/9 + WalkFrame4 = 6, //6/10 + SpellCast = 11, //11/12 + SwingFrame1 = 13, //13/15 + SwingFrame2 = 14, //14/16 + SwingFrame2Spec = 17, //17 - special frame rendered on top of the character in certain directions + //invalid for non-ranged weapons: + Shooting = 18, //18/19 AND 21/22 have same gfx } \ No newline at end of file diff --git a/EndlessClient/Services/FriendIgnoreListService.cs b/EndlessClient/Services/FriendIgnoreListService.cs index 6aa0ced90..466c75ca7 100644 --- a/EndlessClient/Services/FriendIgnoreListService.cs +++ b/EndlessClient/Services/FriendIgnoreListService.cs @@ -3,88 +3,87 @@ using System.IO; using System.Linq; -namespace EndlessClient.Services +namespace EndlessClient.Services; + +[AutoMappedType] +public class FriendIgnoreListService : IFriendIgnoreListService { - [AutoMappedType] - public class FriendIgnoreListService : IFriendIgnoreListService + public IReadOnlyList LoadList(string path) { - public IReadOnlyList LoadList(string path) - { - return Load(path); - } + return Load(path); + } - public void SaveFriends(string path, IReadOnlyList contents) - { - Save(isIgnore: false, path, contents); - } + public void SaveFriends(string path, IReadOnlyList contents) + { + Save(isIgnore: false, path, contents); + } - public void SaveIgnored(string path, IReadOnlyList contents) - { - Save(isIgnore: true, path, contents); - } + public void SaveIgnored(string path, IReadOnlyList contents) + { + Save(isIgnore: true, path, contents); + } - public void SaveNewFriend(string path, string name) - { - if (!File.Exists(path) || string.IsNullOrWhiteSpace(File.ReadAllText(path))) - Save(isIgnore: false, path, new[] { name }); - else - File.AppendAllLines(path, new[] { name }); - } + public void SaveNewFriend(string path, string name) + { + if (!File.Exists(path) || string.IsNullOrWhiteSpace(File.ReadAllText(path))) + Save(isIgnore: false, path, new[] { name }); + else + File.AppendAllLines(path, new[] { name }); + } - public void SaveNewIgnore(string path, string name) - { - if (!File.Exists(path) || string.IsNullOrWhiteSpace(File.ReadAllText(path))) - Save(isIgnore: true, path, new[] { name }); - else - File.AppendAllLines(path, new[] { name }); - } + public void SaveNewIgnore(string path, string name) + { + if (!File.Exists(path) || string.IsNullOrWhiteSpace(File.ReadAllText(path))) + Save(isIgnore: true, path, new[] { name }); + else + File.AppendAllLines(path, new[] { name }); + } - private static List Load(string fileName) + private static List Load(string fileName) + { + if (!File.Exists(fileName)) + return new List(); + + List allLines; + try { - if (!File.Exists(fileName)) - return new List(); - - List allLines; - try - { - allLines = new List(File.ReadAllLines(fileName)); - } - catch (IOException) - { - return new List(); - } - - allLines.RemoveAll(s => s.StartsWith("#") || string.IsNullOrWhiteSpace(s)); - - return allLines.Select(Capitalize).Distinct().ToList(); + allLines = new List(File.ReadAllLines(fileName)); } - - private static void Save(bool isIgnore, string fileName, IEnumerable lines) + catch (IOException) { - using (var sw = new StreamWriter(fileName)) - { - string friendOrIgnore = isIgnore ? "ignore" : "friend"; - sw.WriteLine($"# Endless Online 0.28 [ {friendOrIgnore} list ]\n"); - sw.WriteLine($"# List of {friendOrIgnore}{(isIgnore ? "d" : "")} characters, use a new line for each name\n\n"); - - foreach (string s in lines) - sw.WriteLine(Capitalize(s)); - } + return new List(); } - private static string Capitalize(string input) => char.ToUpper(input[0]) + input.Substring(1).ToLower(); + allLines.RemoveAll(s => s.StartsWith("#") || string.IsNullOrWhiteSpace(s)); + + return allLines.Select(Capitalize).Distinct().ToList(); } - public interface IFriendIgnoreListService + private static void Save(bool isIgnore, string fileName, IEnumerable lines) { - IReadOnlyList LoadList(string path); + using (var sw = new StreamWriter(fileName)) + { + string friendOrIgnore = isIgnore ? "ignore" : "friend"; + sw.WriteLine($"# Endless Online 0.28 [ {friendOrIgnore} list ]\n"); + sw.WriteLine($"# List of {friendOrIgnore}{(isIgnore ? "d" : "")} characters, use a new line for each name\n\n"); + + foreach (string s in lines) + sw.WriteLine(Capitalize(s)); + } + } - void SaveFriends(string path, IReadOnlyList contents); + private static string Capitalize(string input) => char.ToUpper(input[0]) + input.Substring(1).ToLower(); +} - void SaveIgnored(string path, IReadOnlyList contents); +public interface IFriendIgnoreListService +{ + IReadOnlyList LoadList(string path); - void SaveNewFriend(string path, string name); + void SaveFriends(string path, IReadOnlyList contents); - void SaveNewIgnore(string path, string name); - } + void SaveIgnored(string path, IReadOnlyList contents); + + void SaveNewFriend(string path, string name); + + void SaveNewIgnore(string path, string name); } \ No newline at end of file diff --git a/EndlessClient/Subscribers/ArenaEventSubscriber.cs b/EndlessClient/Subscribers/ArenaEventSubscriber.cs index d8cd83401..5eb1b54e5 100644 --- a/EndlessClient/Subscribers/ArenaEventSubscriber.cs +++ b/EndlessClient/Subscribers/ArenaEventSubscriber.cs @@ -13,95 +13,94 @@ using EOLib.Localization; using System.Collections.Generic; -namespace EndlessClient.Subscribers +namespace EndlessClient.Subscribers; + +[AutoMappedType] +public class ArenaEventSubscriber : IArenaNotifier { - [AutoMappedType] - public class ArenaEventSubscriber : IArenaNotifier + private readonly IHudControlProvider _hudControlProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IServerMessageHandler _serverMessageHandler; + + public ArenaEventSubscriber(IHudControlProvider hudControlProvider, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + IServerMessageHandler serverMessageHandler) { - private readonly IHudControlProvider _hudControlProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IServerMessageHandler _serverMessageHandler; + _hudControlProvider = hudControlProvider; + _currentMapProvider = currentMapProvider; + _characterProvider = characterProvider; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _serverMessageHandler = serverMessageHandler; + } - public ArenaEventSubscriber(IHudControlProvider hudControlProvider, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - IServerMessageHandler serverMessageHandler) - { - _hudControlProvider = hudControlProvider; - _currentMapProvider = currentMapProvider; - _characterProvider = characterProvider; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _serverMessageHandler = serverMessageHandler; - } + public void NotifyArenaBusy() + { + var message = _localizedStringFinder.GetString(EOResourceID.ARENA_ROUND_DELAYED_STILL_PLAYERS); + _serverMessageHandler.AddServerMessage(message, SoundEffectID.ArenaTickSound); + } - public void NotifyArenaBusy() - { - var message = _localizedStringFinder.GetString(EOResourceID.ARENA_ROUND_DELAYED_STILL_PLAYERS); - _serverMessageHandler.AddServerMessage(message, SoundEffectID.ArenaTickSound); - } + public void NotifyArenaStart(int players) + { + var message = _localizedStringFinder.GetString(EOResourceID.ARENA_PLAYERS_LAUNCHED); + _serverMessageHandler.AddServerMessage($"{players}{message}"); - public void NotifyArenaStart(int players) + var coord = _characterProvider.MainCharacter.RenderProperties.Coordinates(); + if (AdjacentToArenaTile(coord, _currentMapProvider.CurrentMap.Tiles)) { - var message = _localizedStringFinder.GetString(EOResourceID.ARENA_PLAYERS_LAUNCHED); - _serverMessageHandler.AddServerMessage($"{players}{message}"); - - var coord = _characterProvider.MainCharacter.RenderProperties.Coordinates(); - if (AdjacentToArenaTile(coord, _currentMapProvider.CurrentMap.Tiles)) - { - var periodicEmoter = _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler); - periodicEmoter.StartArenaBlockTimer(); - } + var periodicEmoter = _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler); + periodicEmoter.StartArenaBlockTimer(); } + } - public void NotifyArenaKill(int killCount, string killer, string victim) + public void NotifyArenaKill(int killCount, string killer, string victim) + { + var message = $"{victim} {_localizedStringFinder.GetString(EOResourceID.ARENA_WAS_ELIMINATED_BY)}{killer}"; + + if (killCount > 1) { - var message = $"{victim} {_localizedStringFinder.GetString(EOResourceID.ARENA_WAS_ELIMINATED_BY)}{killer}"; + var killed = _localizedStringFinder.GetString(EOResourceID.ARENA_KILLED); + var players = _localizedStringFinder.GetString(EOResourceID.ARENA_PLAYERS); + message = $"{message}, {killer} {killed}{killCount}{players}"; + } - if (killCount > 1) - { - var killed = _localizedStringFinder.GetString(EOResourceID.ARENA_KILLED); - var players = _localizedStringFinder.GetString(EOResourceID.ARENA_PLAYERS); - message = $"{message}, {killer} {killed}{killCount}{players}"; - } + var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.Skeleton, log: false, filter: false); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } - var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.Skeleton, log: false, filter: false); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } + public void NotifyArenaWin(string winner) + { + var message = _localizedStringFinder.GetString(EOResourceID.ARENA_WON_EVENT); + _serverMessageHandler.AddServerMessage($"{winner}{message}", SoundEffectID.ArenaWin, ChatIcon.Trophy); + } - public void NotifyArenaWin(string winner) + private static bool AdjacentToArenaTile(MapCoordinate coord, IReadOnlyMatrix tiles) + { + var check = new[] { - var message = _localizedStringFinder.GetString(EOResourceID.ARENA_WON_EVENT); - _serverMessageHandler.AddServerMessage($"{winner}{message}", SoundEffectID.ArenaWin, ChatIcon.Trophy); - } + coord, + new MapCoordinate(coord.X - 1, coord.Y), + new MapCoordinate(coord.X, coord.Y - 1), + new MapCoordinate(coord.X + 1, coord.Y), + new MapCoordinate(coord.X, coord.Y + 1), + }; - private static bool AdjacentToArenaTile(MapCoordinate coord, IReadOnlyMatrix tiles) + foreach (var checkCoord in check) { - var check = new[] + if (checkCoord.X >= 0 && checkCoord.X <= tiles.Cols && + checkCoord.Y >= 0 && checkCoord.Y <= tiles.Rows && + tiles[checkCoord.Y, checkCoord.X] == TileSpec.Arena) { - coord, - new MapCoordinate(coord.X - 1, coord.Y), - new MapCoordinate(coord.X, coord.Y - 1), - new MapCoordinate(coord.X + 1, coord.Y), - new MapCoordinate(coord.X, coord.Y + 1), - }; - - foreach (var checkCoord in check) - { - if (checkCoord.X >= 0 && checkCoord.X <= tiles.Cols && - checkCoord.Y >= 0 && checkCoord.Y <= tiles.Rows && - tiles[checkCoord.Y, checkCoord.X] == TileSpec.Arena) - { - return true; - } + return true; } - - return false; } + + return false; } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/JukeboxEventSubscriber.cs b/EndlessClient/Subscribers/JukeboxEventSubscriber.cs index 1fda5fe85..fa8b3d3c2 100644 --- a/EndlessClient/Subscribers/JukeboxEventSubscriber.cs +++ b/EndlessClient/Subscribers/JukeboxEventSubscriber.cs @@ -3,22 +3,21 @@ using EOLib.Domain.Notifiers; using EOLib.Localization; -namespace EndlessClient.Subscribers +namespace EndlessClient.Subscribers; + +[AutoMappedType] +public class JukeboxEventSubscriber : IJukeboxNotifier { - [AutoMappedType] - public class JukeboxEventSubscriber : IJukeboxNotifier - { - private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IEOMessageBoxFactory _messageBoxFactory; - public JukeboxEventSubscriber(IEOMessageBoxFactory messageBoxFactory) - { - _messageBoxFactory = messageBoxFactory; - } + public JukeboxEventSubscriber(IEOMessageBoxFactory messageBoxFactory) + { + _messageBoxFactory = messageBoxFactory; + } - public void JukeboxUnavailable() - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.JUKEBOX_REQUESTED_RECENTLY); - dlg.ShowDialog(); - } + public void JukeboxUnavailable() + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.JUKEBOX_REQUESTED_RECENTLY); + dlg.ShowDialog(); } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/LockerEventSubscriber.cs b/EndlessClient/Subscribers/LockerEventSubscriber.cs index dd2c27600..41623b15e 100644 --- a/EndlessClient/Subscribers/LockerEventSubscriber.cs +++ b/EndlessClient/Subscribers/LockerEventSubscriber.cs @@ -3,28 +3,27 @@ using EOLib.Domain.Notifiers; using EOLib.Localization; -namespace EndlessClient.Subscribers +namespace EndlessClient.Subscribers; + +[AutoMappedType] +public class LockerEventSubscriber : ILockerEventNotifier { - [AutoMappedType] - public class LockerEventSubscriber : ILockerEventNotifier - { - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ILocalizedStringFinder _localizedStringFinder; - public LockerEventSubscriber(IEOMessageBoxFactory messageBoxFactory, - ILocalizedStringFinder localizedStringFinder) - { - _messageBoxFactory = messageBoxFactory; - _localizedStringFinder = localizedStringFinder; - } + public LockerEventSubscriber(IEOMessageBoxFactory messageBoxFactory, + ILocalizedStringFinder localizedStringFinder) + { + _messageBoxFactory = messageBoxFactory; + _localizedStringFinder = localizedStringFinder; + } - public void NotifyLockerFull(int maxItems) - { - var message = _localizedStringFinder.GetString(DialogResourceID.LOCKER_FULL_DIFF_ITEMS_MAX + 1); - var caption = _localizedStringFinder.GetString(DialogResourceID.LOCKER_FULL_DIFF_ITEMS_MAX); + public void NotifyLockerFull(int maxItems) + { + var message = _localizedStringFinder.GetString(DialogResourceID.LOCKER_FULL_DIFF_ITEMS_MAX + 1); + var caption = _localizedStringFinder.GetString(DialogResourceID.LOCKER_FULL_DIFF_ITEMS_MAX); - var dlg = _messageBoxFactory.CreateMessageBox(message.Replace("25", $"{maxItems}"), caption); - dlg.ShowDialog(); - } + var dlg = _messageBoxFactory.CreateMessageBox(message.Replace("25", $"{maxItems}"), caption); + dlg.ShowDialog(); } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/MainCharacterEventSubscriber.cs b/EndlessClient/Subscribers/MainCharacterEventSubscriber.cs index f315a7336..25d17d935 100644 --- a/EndlessClient/Subscribers/MainCharacterEventSubscriber.cs +++ b/EndlessClient/Subscribers/MainCharacterEventSubscriber.cs @@ -6,81 +6,80 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Subscribers +namespace EndlessClient.Subscribers; + +[MappedType(BaseType = typeof(IMainCharacterEventNotifier))] +public class MainCharacterEventSubscriber : IMainCharacterEventNotifier { - [MappedType(BaseType = typeof(IMainCharacterEventNotifier))] - public class MainCharacterEventSubscriber : IMainCharacterEventNotifier + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IPubFileProvider _pubFileProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + + public MainCharacterEventSubscriber(IStatusLabelSetter statusLabelSetter, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + IPubFileProvider pubFileProvider, + ICharacterRendererProvider characterRendererProvider) + { + _statusLabelSetter = statusLabelSetter; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _pubFileProvider = pubFileProvider; + _characterRendererProvider = characterRendererProvider; + } + + public void NotifyGainedExp(int expDifference) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, + EOResourceID.STATUS_LABEL_YOU_GAINED_EXP, + $" {expDifference} EXP"); + + var youGained = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_YOU_GAINED_EXP); + var message = $"{youGained} {expDifference} EXP"; + + var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.Star); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } + + public void NotifyTakeDamage(int damageTaken, int playerPercentHealth, bool isHeal) + { + if (isHeal && damageTaken == 0) return; + + _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.ShowDamageCounter(damageTaken, playerPercentHealth, isHeal)); + } + + public void TakeItemFromMap(int id, int amountTaken) { - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IPubFileProvider _pubFileProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - - public MainCharacterEventSubscriber(IStatusLabelSetter statusLabelSetter, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - IPubFileProvider pubFileProvider, - ICharacterRendererProvider characterRendererProvider) - { - _statusLabelSetter = statusLabelSetter; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _pubFileProvider = pubFileProvider; - _characterRendererProvider = characterRendererProvider; - } - - public void NotifyGainedExp(int expDifference) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, - EOResourceID.STATUS_LABEL_YOU_GAINED_EXP, - $" {expDifference} EXP"); - - var youGained = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_YOU_GAINED_EXP); - var message = $"{youGained} {expDifference} EXP"; - - var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.Star); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } - - public void NotifyTakeDamage(int damageTaken, int playerPercentHealth, bool isHeal) - { - if (isHeal && damageTaken == 0) return; - - _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.ShowDamageCounter(damageTaken, playerPercentHealth, isHeal)); - } - - public void TakeItemFromMap(int id, int amountTaken) - { - var rec = _pubFileProvider.EIFFile[id]; - - var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_PICKUP_YOU_PICKED_UP)} {amountTaken} {rec.Name}"; - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.UpArrow)); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_YOU_PICKED_UP, - $" {amountTaken} {rec.Name}"); - } - - public void DropItem(int id, int amountDropped) - { - var rec = _pubFileProvider.EIFFile[id]; - - var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_DROP_YOU_DROPPED)} {amountDropped} {rec.Name}"; - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.DownArrow)); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_DROP_YOU_DROPPED, - $" {amountDropped} {rec.Name}"); - } - - public void JunkItem(int id, int amountRemoved) - { - var rec = _pubFileProvider.EIFFile[id]; - - var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_JUNK_YOU_JUNKED)} {amountRemoved} {rec.Name}"; - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.DownArrow)); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_JUNK_YOU_JUNKED, - $" {amountRemoved} {rec.Name}"); - } + var rec = _pubFileProvider.EIFFile[id]; + + var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_PICKUP_YOU_PICKED_UP)} {amountTaken} {rec.Name}"; + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.UpArrow)); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_YOU_PICKED_UP, + $" {amountTaken} {rec.Name}"); + } + + public void DropItem(int id, int amountDropped) + { + var rec = _pubFileProvider.EIFFile[id]; + + var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_DROP_YOU_DROPPED)} {amountDropped} {rec.Name}"; + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.DownArrow)); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_DROP_YOU_DROPPED, + $" {amountDropped} {rec.Name}"); + } + + public void JunkItem(int id, int amountRemoved) + { + var rec = _pubFileProvider.EIFFile[id]; + + var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_JUNK_YOU_JUNKED)} {amountRemoved} {rec.Name}"; + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.DownArrow)); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_JUNK_YOU_JUNKED, + $" {amountRemoved} {rec.Name}"); } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs b/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs index de1ebbe6f..42b40c081 100644 --- a/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs +++ b/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs @@ -9,70 +9,69 @@ using System; using System.Linq; -namespace EndlessClient.Subscribers +namespace EndlessClient.Subscribers; + +[MappedType(BaseType = typeof(IOtherCharacterEventNotifier))] +public class OtherCharacterEventSubscriber : IOtherCharacterEventNotifier { - [MappedType(BaseType = typeof(IOtherCharacterEventNotifier))] - public class OtherCharacterEventSubscriber : IOtherCharacterEventNotifier - { - private readonly IChatBubbleActions _chatBubbleActions; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly IConfigurationProvider _configurationProvider; - private readonly IChatProcessor _chatProcessor; + private readonly IChatBubbleActions _chatBubbleActions; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly IConfigurationProvider _configurationProvider; + private readonly IChatProcessor _chatProcessor; - public OtherCharacterEventSubscriber(IChatBubbleActions chatBubbleActions, - ICharacterRendererProvider characterRendererProvider, - IFriendIgnoreListService friendIgnoreListService, - IConfigurationProvider configurationProvider, - IChatProcessor chatProcessor) - { - _chatBubbleActions = chatBubbleActions; - _characterRendererProvider = characterRendererProvider; - _friendIgnoreListService = friendIgnoreListService; - _configurationProvider = configurationProvider; - _chatProcessor = chatProcessor; - } + public OtherCharacterEventSubscriber(IChatBubbleActions chatBubbleActions, + ICharacterRendererProvider characterRendererProvider, + IFriendIgnoreListService friendIgnoreListService, + IConfigurationProvider configurationProvider, + IChatProcessor chatProcessor) + { + _chatBubbleActions = chatBubbleActions; + _characterRendererProvider = characterRendererProvider; + _friendIgnoreListService = friendIgnoreListService; + _configurationProvider = configurationProvider; + _chatProcessor = chatProcessor; + } - public void OtherCharacterTakeDamage(int characterID, int playerPercentHealth, int damageTaken, bool isHeal) - { - if (!_characterRendererProvider.CharacterRenderers.ContainsKey(characterID) || - (isHeal && damageTaken == 0)) - return; + public void OtherCharacterTakeDamage(int characterID, int playerPercentHealth, int damageTaken, bool isHeal) + { + if (!_characterRendererProvider.CharacterRenderers.ContainsKey(characterID) || + (isHeal && damageTaken == 0)) + return; - _characterRendererProvider.CharacterRenderers[characterID].ShowDamageCounter(damageTaken, playerPercentHealth, isHeal); - } + _characterRendererProvider.CharacterRenderers[characterID].ShowDamageCounter(damageTaken, playerPercentHealth, isHeal); + } - public void OtherCharacterSaySomething(int characterID, string message) - { - SaySomethingShared(isGroupChat: false, characterID: characterID, message: message); - } + public void OtherCharacterSaySomething(int characterID, string message) + { + SaySomethingShared(isGroupChat: false, characterID: characterID, message: message); + } - public void OtherCharacterSaySomethingToGroup(int characterID, string message) - { - SaySomethingShared(isGroupChat: true, characterID: characterID, message: message); - } + public void OtherCharacterSaySomethingToGroup(int characterID, string message) + { + SaySomethingShared(isGroupChat: true, characterID: characterID, message: message); + } - public void AdminAnnounce(string message) - { - _chatBubbleActions.ShowChatBubbleForMainCharacter(message); - } + public void AdminAnnounce(string message) + { + _chatBubbleActions.ShowChatBubbleForMainCharacter(message); + } - private void SaySomethingShared(int characterID, string message, bool isGroupChat) + private void SaySomethingShared(int characterID, string message, bool isGroupChat) + { + if (_characterRendererProvider.CharacterRenderers.TryGetValue(characterID, out var characterRenderer) || + _characterRendererProvider.MainCharacterRenderer.HasValue) { - if (_characterRendererProvider.CharacterRenderers.TryGetValue(characterID, out var characterRenderer) || - _characterRendererProvider.MainCharacterRenderer.HasValue) - { - _characterRendererProvider.MainCharacterRenderer.MatchSome(x => characterRenderer = x); + _characterRendererProvider.MainCharacterRenderer.MatchSome(x => characterRenderer = x); - var name = characterRenderer.Character.Name; + var name = characterRenderer.Character.Name; - var ignoreList = _friendIgnoreListService.LoadList(Constants.IgnoreListFile); - if (ignoreList.Any(x => x.Equals(name, StringComparison.InvariantCultureIgnoreCase)) || - (_configurationProvider.StrictFilterEnabled && !_chatProcessor.FilterCurses(message).ShowChat)) - return; + var ignoreList = _friendIgnoreListService.LoadList(Constants.IgnoreListFile); + if (ignoreList.Any(x => x.Equals(name, StringComparison.InvariantCultureIgnoreCase)) || + (_configurationProvider.StrictFilterEnabled && !_chatProcessor.FilterCurses(message).ShowChat)) + return; - characterRenderer.ShowChatBubble(message, isGroupChat); - } + characterRenderer.ShowChatBubble(message, isGroupChat); } } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/ServerRebootEventSubscriber.cs b/EndlessClient/Subscribers/ServerRebootEventSubscriber.cs index 13d066d9c..a6e191217 100644 --- a/EndlessClient/Subscribers/ServerRebootEventSubscriber.cs +++ b/EndlessClient/Subscribers/ServerRebootEventSubscriber.cs @@ -5,30 +5,29 @@ using EOLib.Domain.Notifiers; using EOLib.Localization; -namespace EndlessClient.Subscribers +namespace EndlessClient.Subscribers; + +[AutoMappedType] +public class ServerRebootEventNotifier : IServerRebootNotifier { - [AutoMappedType] - public class ServerRebootEventNotifier : IServerRebootNotifier - { - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IServerMessageHandler _serverMessageHandler; - private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IServerMessageHandler _serverMessageHandler; + private readonly IStatusLabelSetter _statusLabelSetter; - public ServerRebootEventNotifier(ILocalizedStringFinder localizedStringFinder, - IServerMessageHandler serverMessageHandler, - IStatusLabelSetter statusLabelSetter, - ISfxPlayer sfxPlayer) - { - _localizedStringFinder = localizedStringFinder; - _serverMessageHandler = serverMessageHandler; - _statusLabelSetter = statusLabelSetter; - } + public ServerRebootEventNotifier(ILocalizedStringFinder localizedStringFinder, + IServerMessageHandler serverMessageHandler, + IStatusLabelSetter statusLabelSetter, + ISfxPlayer sfxPlayer) + { + _localizedStringFinder = localizedStringFinder; + _serverMessageHandler = serverMessageHandler; + _statusLabelSetter = statusLabelSetter; + } - public void NotifyServerReboot() - { - var message = _localizedStringFinder.GetString(EOResourceID.REBOOT_SEQUENCE_STARTED); - _serverMessageHandler.AddServerMessage(message, SoundEffectID.Reboot); - _statusLabelSetter.ShowWarning(message); - } + public void NotifyServerReboot() + { + var message = _localizedStringFinder.GetString(EOResourceID.REBOOT_SEQUENCE_STARTED); + _serverMessageHandler.AddServerMessage(message, SoundEffectID.Reboot); + _statusLabelSetter.ShowWarning(message); } } \ No newline at end of file diff --git a/EndlessClient/Test/CharacterStateTest.cs b/EndlessClient/Test/CharacterStateTest.cs index 8770a745e..f0025092e 100644 --- a/EndlessClient/Test/CharacterStateTest.cs +++ b/EndlessClient/Test/CharacterStateTest.cs @@ -15,292 +15,291 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Test +namespace EndlessClient.Test; + +public class CharacterStateTest : DrawableGameComponent { - public class CharacterStateTest : DrawableGameComponent + private enum DisplayState { - private enum DisplayState - { - Standing, - SitChair, - SitFloor, - Attack1, - Attack2, - Walk1, - Walk2, - Walk3, - SpellCast, - AttackingAnimation, - WalkingAnimation, - SpellCastAnimation - } + Standing, + SitChair, + SitFloor, + Attack1, + Attack2, + Walk1, + Walk2, + Walk3, + SpellCast, + AttackingAnimation, + WalkingAnimation, + SpellCastAnimation + } - private static readonly List _allDisplayStates; + private static readonly List _allDisplayStates; - static CharacterStateTest() - { - _allDisplayStates = ((DisplayState[])Enum.GetValues(typeof(DisplayState))).ToList(); - } + static CharacterStateTest() + { + _allDisplayStates = ((DisplayState[])Enum.GetValues(typeof(DisplayState))).ToList(); + } - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IMetadataProvider _weaponMetadataProvider; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IMetadataProvider _weaponMetadataProvider; - private CharacterRenderProperties _baseProperties; - private readonly Dictionary _itemIndices; - private readonly List _renderersForDifferentStates; + private CharacterRenderProperties _baseProperties; + private readonly Dictionary _itemIndices; + private readonly List _renderersForDifferentStates; - private KeyboardState _previousState, _currentState; + private KeyboardState _previousState, _currentState; - private bool _isBowEquipped; - private int _lastGraphic; + private bool _isBowEquipped; + private int _lastGraphic; - private DateTime _lastWalk, _lastAttack, _lastSpell; + private DateTime _lastWalk, _lastAttack, _lastSpell; - public CharacterStateTest(IEndlessGame baseGame, - ICharacterRendererFactory characterRendererFactory, - IEIFFileProvider eifFileProvider, - IMetadataProvider weaponMetadataProvider) - : base((Game)baseGame) - { - _characterRendererFactory = characterRendererFactory; - _eifFileProvider = eifFileProvider; - _weaponMetadataProvider = weaponMetadataProvider; + public CharacterStateTest(IEndlessGame baseGame, + ICharacterRendererFactory characterRendererFactory, + IEIFFileProvider eifFileProvider, + IMetadataProvider weaponMetadataProvider) + : base((Game)baseGame) + { + _characterRendererFactory = characterRendererFactory; + _eifFileProvider = eifFileProvider; + _weaponMetadataProvider = weaponMetadataProvider; - _itemIndices = ((ItemType[])Enum.GetValues(typeof(ItemType))).ToDictionary(k => k, v => 0); - _renderersForDifferentStates = new List(12); - } + _itemIndices = ((ItemType[])Enum.GetValues(typeof(ItemType))).ToDictionary(k => k, v => 0); + _renderersForDifferentStates = new List(12); + } - public override void Initialize() + public override void Initialize() + { + DrawOrder = 0; + + _baseProperties = new CharacterRenderProperties.Builder().ToImmutable(); + foreach (var displayState in _allDisplayStates) { - DrawOrder = 0; + var props = GetRenderPropertiesForState(displayState); + _renderersForDifferentStates.Add(_characterRendererFactory.CreateCharacterRenderer(Character.Default.WithRenderProperties(props), isUiControl: false)); + _renderersForDifferentStates.OfType().Last().DrawOrder = 10; + } - _baseProperties = new CharacterRenderProperties.Builder().ToImmutable(); - foreach (var displayState in _allDisplayStates) - { - var props = GetRenderPropertiesForState(displayState); - _renderersForDifferentStates.Add(_characterRendererFactory.CreateCharacterRenderer(Character.Default.WithRenderProperties(props), isUiControl: false)); - _renderersForDifferentStates.OfType().Last().DrawOrder = 10; - } + _renderersForDifferentStates.ForEach(Game.Components.Add); - _renderersForDifferentStates.ForEach(Game.Components.Add); + _currentState = _previousState = Keyboard.GetState(); + _lastWalk = _lastAttack = _lastSpell = DateTime.Now; - _currentState = _previousState = Keyboard.GetState(); - _lastWalk = _lastAttack = _lastSpell = DateTime.Now; + base.Initialize(); + } - base.Initialize(); - } + protected override void LoadContent() + { + RefreshDisplayedCharacters(); - protected override void LoadContent() + foreach (var displayState in _allDisplayStates) { - RefreshDisplayedCharacters(); - - foreach (var displayState in _allDisplayStates) - { - var characterRenderer = _renderersForDifferentStates[(int)displayState]; - characterRenderer.SetAbsoluteScreenPosition(50 + 640 / 4 * ((int)displayState % 4), - 30 + 480 / 3 * ((int)displayState / 4)); - } - - base.LoadContent(); + var characterRenderer = _renderersForDifferentStates[(int)displayState]; + characterRenderer.SetAbsoluteScreenPosition(50 + 640 / 4 * ((int)displayState % 4), + 30 + 480 / 3 * ((int)displayState / 4)); } - //standing = 0 - //sitting: chair floor - //attacking: 0 1 2 +animated (0-1-2-0) - //walking: 0 1 2 3 +animated (0-1-2-3-0) - //spellcast: 0 1 +animated (0-1-0) + base.LoadContent(); + } - public override void Update(GameTime gameTime) - { - _currentState = Keyboard.GetState(); + //standing = 0 + //sitting: chair floor + //attacking: 0 1 2 +animated (0-1-2-0) + //walking: 0 1 2 3 +animated (0-1-2-3-0) + //spellcast: 0 1 +animated (0-1-0) - var increment = ShiftPressed ? -1 : 1; + public override void Update(GameTime gameTime) + { + _currentState = Keyboard.GetState(); - var update = false; - if (KeyPressed(Keys.D1)) - { - _baseProperties = _baseProperties.WithGender((_baseProperties.Gender + increment) % 2); - update = true; - } - else if (KeyPressed(Keys.D2)) - { - if (CtrlPressed) - { - const int NUM_HAIR_COLORS = 10; - if (_baseProperties.HairColor + increment < 0) _baseProperties = _baseProperties.WithHairColor(NUM_HAIR_COLORS); - _baseProperties = _baseProperties.WithHairColor((_baseProperties.HairColor + increment) % NUM_HAIR_COLORS); - } - else - { - const int NUM_HAIR_STYLES = 21; - if (_baseProperties.HairStyle + increment < 0) _baseProperties = _baseProperties.WithHairColor(NUM_HAIR_STYLES); - _baseProperties = _baseProperties.WithHairStyle((_baseProperties.HairStyle + increment) % NUM_HAIR_STYLES); - } - update = true; - } - else if (KeyPressed(Keys.D3)) - { - _baseProperties = _baseProperties.WithHatGraphic(GetNextItemGraphicMatching(ItemType.Hat, _baseProperties.HatGraphic)); - update = true; - } - else if (KeyPressed(Keys.D4)) - { - _baseProperties = _baseProperties.WithArmorGraphic(GetNextItemGraphicMatching(ItemType.Armor, _baseProperties.ArmorGraphic)); - update = true; - } - else if (KeyPressed(Keys.D5)) - { - _baseProperties = _baseProperties.WithBootsGraphic(GetNextItemGraphicMatching(ItemType.Boots, _baseProperties.BootsGraphic)); - update = true; - } - else if (KeyPressed(Keys.D6) && !_isBowEquipped) + var increment = ShiftPressed ? -1 : 1; + + var update = false; + if (KeyPressed(Keys.D1)) + { + _baseProperties = _baseProperties.WithGender((_baseProperties.Gender + increment) % 2); + update = true; + } + else if (KeyPressed(Keys.D2)) + { + if (CtrlPressed) { - var nextGraphic = GetNextItemGraphicMatching(ItemType.Weapon, _baseProperties.WeaponGraphic); - _baseProperties = _baseProperties.WithWeaponGraphic(nextGraphic); - update = true; + const int NUM_HAIR_COLORS = 10; + if (_baseProperties.HairColor + increment < 0) _baseProperties = _baseProperties.WithHairColor(NUM_HAIR_COLORS); + _baseProperties = _baseProperties.WithHairColor((_baseProperties.HairColor + increment) % NUM_HAIR_COLORS); } - else if (KeyPressed(Keys.D7)) + else { - _baseProperties = _baseProperties.WithShieldGraphic(GetNextItemGraphicMatching(ItemType.Shield, _baseProperties.ShieldGraphic)); - update = true; + const int NUM_HAIR_STYLES = 21; + if (_baseProperties.HairStyle + increment < 0) _baseProperties = _baseProperties.WithHairColor(NUM_HAIR_STYLES); + _baseProperties = _baseProperties.WithHairStyle((_baseProperties.HairStyle + increment) % NUM_HAIR_STYLES); } - else if (KeyPressed(Keys.D8)) + update = true; + } + else if (KeyPressed(Keys.D3)) + { + _baseProperties = _baseProperties.WithHatGraphic(GetNextItemGraphicMatching(ItemType.Hat, _baseProperties.HatGraphic)); + update = true; + } + else if (KeyPressed(Keys.D4)) + { + _baseProperties = _baseProperties.WithArmorGraphic(GetNextItemGraphicMatching(ItemType.Armor, _baseProperties.ArmorGraphic)); + update = true; + } + else if (KeyPressed(Keys.D5)) + { + _baseProperties = _baseProperties.WithBootsGraphic(GetNextItemGraphicMatching(ItemType.Boots, _baseProperties.BootsGraphic)); + update = true; + } + else if (KeyPressed(Keys.D6) && !_isBowEquipped) + { + var nextGraphic = GetNextItemGraphicMatching(ItemType.Weapon, _baseProperties.WeaponGraphic); + _baseProperties = _baseProperties.WithWeaponGraphic(nextGraphic); + update = true; + } + else if (KeyPressed(Keys.D7)) + { + _baseProperties = _baseProperties.WithShieldGraphic(GetNextItemGraphicMatching(ItemType.Shield, _baseProperties.ShieldGraphic)); + update = true; + } + else if (KeyPressed(Keys.D8)) + { + if ((int)_baseProperties.Direction + increment < 0) _baseProperties = _baseProperties.WithDirection((EODirection)4); + _baseProperties = _baseProperties.WithDirection((EODirection)(((int)_baseProperties.Direction + increment) % 4)); + update = true; + } + else if (KeyPressed(Keys.Space)) + { + if (!_isBowEquipped) { - if ((int)_baseProperties.Direction + increment < 0) _baseProperties = _baseProperties.WithDirection((EODirection)4); - _baseProperties = _baseProperties.WithDirection((EODirection)(((int)_baseProperties.Direction + increment) % 4)); - update = true; + _lastGraphic = _baseProperties.WeaponGraphic; + var firstBowWeapon = EIFFile.First(x => x.Type == ItemType.Weapon && x.SubType == ItemSubType.Ranged); + _baseProperties = _baseProperties.WithWeaponGraphic(firstBowWeapon.DollGraphic); } - else if (KeyPressed(Keys.Space)) + else { - if (!_isBowEquipped) - { - _lastGraphic = _baseProperties.WeaponGraphic; - var firstBowWeapon = EIFFile.First(x => x.Type == ItemType.Weapon && x.SubType == ItemSubType.Ranged); - _baseProperties = _baseProperties.WithWeaponGraphic(firstBowWeapon.DollGraphic); - } - else - { - _baseProperties = _baseProperties.WithWeaponGraphic(_lastGraphic); - } - - _isBowEquipped = !_isBowEquipped; - update = true; + _baseProperties = _baseProperties.WithWeaponGraphic(_lastGraphic); } - if (update) - RefreshDisplayedCharacters(); - - _previousState = _currentState; - - var now = DateTime.Now; - if ((now - _lastWalk).TotalMilliseconds > 500) - { - var rend = _renderersForDifferentStates[(int)DisplayState.WalkingAnimation]; - rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextWalkFrame(false)); - _lastWalk = now; - } + _isBowEquipped = !_isBowEquipped; + update = true; + } - if ((now - _lastAttack).TotalMilliseconds > 500) - { - var rend = _renderersForDifferentStates[(int)DisplayState.AttackingAnimation]; - var isRanged = _weaponMetadataProvider.GetValueOrDefault(rend.Character.RenderProperties.WeaponGraphic).Ranged; - rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextAttackFrame(isRanged)); - _lastAttack = now; - } + if (update) + RefreshDisplayedCharacters(); - if ((now - _lastSpell).TotalMilliseconds > 500) - { - var rend = _renderersForDifferentStates[(int)DisplayState.SpellCastAnimation]; - rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextSpellCastFrame()); - _lastSpell = now; - } + _previousState = _currentState; - base.Update(gameTime); + var now = DateTime.Now; + if ((now - _lastWalk).TotalMilliseconds > 500) + { + var rend = _renderersForDifferentStates[(int)DisplayState.WalkingAnimation]; + rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextWalkFrame(false)); + _lastWalk = now; } - public override void Draw(GameTime gameTime) + if ((now - _lastAttack).TotalMilliseconds > 500) { - GraphicsDevice.Clear(Color.White); - - base.Draw(gameTime); + var rend = _renderersForDifferentStates[(int)DisplayState.AttackingAnimation]; + var isRanged = _weaponMetadataProvider.GetValueOrDefault(rend.Character.RenderProperties.WeaponGraphic).Ranged; + rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextAttackFrame(isRanged)); + _lastAttack = now; } - private CharacterRenderProperties GetRenderPropertiesForState(DisplayState displayState) + if ((now - _lastSpell).TotalMilliseconds > 500) { - var isRanged = _weaponMetadataProvider.GetValueOrDefault(_baseProperties.WeaponGraphic).Ranged; - switch (displayState) - { - case DisplayState.Standing: - return _baseProperties; - case DisplayState.SitChair: - return _baseProperties.WithSitState(SitState.Chair); - case DisplayState.SitFloor: - return _baseProperties.WithSitState(SitState.Floor); - case DisplayState.Attack1: - return _baseProperties.WithNextAttackFrame(isRanged); - case DisplayState.Attack2: - return _baseProperties.WithNextAttackFrame(isRanged).WithNextAttackFrame(isRanged); - case DisplayState.Walk1: - return _baseProperties.WithNextWalkFrame(); - case DisplayState.Walk2: - return _baseProperties.WithNextWalkFrame().WithNextWalkFrame(); - case DisplayState.Walk3: - return _baseProperties.WithNextWalkFrame().WithNextWalkFrame().WithNextWalkFrame(); - case DisplayState.SpellCast: - return _baseProperties.WithNextSpellCastFrame(); - //create a clone of the properties for animation - case DisplayState.WalkingAnimation: - case DisplayState.SpellCastAnimation: - case DisplayState.AttackingAnimation: - return _baseProperties.ToBuilder().ToImmutable(); - default: - throw new ArgumentOutOfRangeException(); - } + var rend = _renderersForDifferentStates[(int)DisplayState.SpellCastAnimation]; + rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextSpellCastFrame()); + _lastSpell = now; } - private void RefreshDisplayedCharacters() + base.Update(gameTime); + } + + public override void Draw(GameTime gameTime) + { + GraphicsDevice.Clear(Color.White); + + base.Draw(gameTime); + } + + private CharacterRenderProperties GetRenderPropertiesForState(DisplayState displayState) + { + var isRanged = _weaponMetadataProvider.GetValueOrDefault(_baseProperties.WeaponGraphic).Ranged; + switch (displayState) { - foreach (var displayState in _allDisplayStates) - { - var props = GetRenderPropertiesForState(displayState); - _renderersForDifferentStates[(int)displayState].Character = Character.Default.WithRenderProperties(props); - } + case DisplayState.Standing: + return _baseProperties; + case DisplayState.SitChair: + return _baseProperties.WithSitState(SitState.Chair); + case DisplayState.SitFloor: + return _baseProperties.WithSitState(SitState.Floor); + case DisplayState.Attack1: + return _baseProperties.WithNextAttackFrame(isRanged); + case DisplayState.Attack2: + return _baseProperties.WithNextAttackFrame(isRanged).WithNextAttackFrame(isRanged); + case DisplayState.Walk1: + return _baseProperties.WithNextWalkFrame(); + case DisplayState.Walk2: + return _baseProperties.WithNextWalkFrame().WithNextWalkFrame(); + case DisplayState.Walk3: + return _baseProperties.WithNextWalkFrame().WithNextWalkFrame().WithNextWalkFrame(); + case DisplayState.SpellCast: + return _baseProperties.WithNextSpellCastFrame(); + //create a clone of the properties for animation + case DisplayState.WalkingAnimation: + case DisplayState.SpellCastAnimation: + case DisplayState.AttackingAnimation: + return _baseProperties.ToBuilder().ToImmutable(); + default: + throw new ArgumentOutOfRangeException(); } + } - private bool KeyPressed(Keys key) + private void RefreshDisplayedCharacters() + { + foreach (var displayState in _allDisplayStates) { - return _previousState.IsKeyDown(key) && _currentState.IsKeyUp(key); + var props = GetRenderPropertiesForState(displayState); + _renderersForDifferentStates[(int)displayState].Character = Character.Default.WithRenderProperties(props); } + } - private bool ShiftPressed => _previousState.IsKeyDown(Keys.LeftShift) || _previousState.IsKeyDown(Keys.RightShift); + private bool KeyPressed(Keys key) + { + return _previousState.IsKeyDown(key) && _currentState.IsKeyUp(key); + } - private bool CtrlPressed => _previousState.IsKeyDown(Keys.LeftControl) || _previousState.IsKeyDown(Keys.RightControl); + private bool ShiftPressed => _previousState.IsKeyDown(Keys.LeftShift) || _previousState.IsKeyDown(Keys.RightShift); - private int GetNextItemGraphicMatching(ItemType type, int currentGraphic) - { - var increment = ShiftPressed ? -1 : 1; - var matchingItems = EIFFile.Where(x => x.Type == type).OrderBy(x => x.ID).ToList(); - _itemIndices[type] = (_itemIndices[type] + increment) % matchingItems.Count; + private bool CtrlPressed => _previousState.IsKeyDown(Keys.LeftControl) || _previousState.IsKeyDown(Keys.RightControl); - if (_itemIndices[type] + increment < 0) - { - _itemIndices[type] = 0; - return 0; - } + private int GetNextItemGraphicMatching(ItemType type, int currentGraphic) + { + var increment = ShiftPressed ? -1 : 1; + var matchingItems = EIFFile.Where(x => x.Type == type).OrderBy(x => x.ID).ToList(); + _itemIndices[type] = (_itemIndices[type] + increment) % matchingItems.Count; - return matchingItems[_itemIndices[type]].DollGraphic; + if (_itemIndices[type] + increment < 0) + { + _itemIndices[type] = 0; + return 0; } - private IPubFile EIFFile => _eifFileProvider.EIFFile; + return matchingItems[_itemIndices[type]].DollGraphic; + } + + private IPubFile EIFFile => _eifFileProvider.EIFFile; - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - _renderersForDifferentStates.ForEach(x => x.Dispose()); - } - base.Dispose(disposing); + _renderersForDifferentStates.ForEach(x => x.Dispose()); } + base.Dispose(disposing); } } \ No newline at end of file diff --git a/EndlessClient/Test/TestModeLauncher.cs b/EndlessClient/Test/TestModeLauncher.cs index b6d5e8f96..d0b7d55b9 100644 --- a/EndlessClient/Test/TestModeLauncher.cs +++ b/EndlessClient/Test/TestModeLauncher.cs @@ -5,48 +5,47 @@ using EndlessClient.Rendering.Metadata.Models; using EOLib.IO.Repositories; -namespace EndlessClient.Test +namespace EndlessClient.Test; + +[AutoMappedType] +public class TestModeLauncher : ITestModeLauncher { - [AutoMappedType] - public class TestModeLauncher : ITestModeLauncher - { - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IGameStateProvider _gameStateProvider; - private readonly IMetadataProvider _weaponMetadataProvider; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IGameStateProvider _gameStateProvider; + private readonly IMetadataProvider _weaponMetadataProvider; - public TestModeLauncher(IEndlessGameProvider endlessGameProvider, - ICharacterRendererFactory characterRendererFactory, - IEIFFileProvider eifFileProvider, - IGameStateProvider gameStateProvider, - IMetadataProvider weaponMetadataProvider) - { - _endlessGameProvider = endlessGameProvider; - _characterRendererFactory = characterRendererFactory; - _eifFileProvider = eifFileProvider; - _gameStateProvider = gameStateProvider; - _weaponMetadataProvider = weaponMetadataProvider; - } + public TestModeLauncher(IEndlessGameProvider endlessGameProvider, + ICharacterRendererFactory characterRendererFactory, + IEIFFileProvider eifFileProvider, + IGameStateProvider gameStateProvider, + IMetadataProvider weaponMetadataProvider) + { + _endlessGameProvider = endlessGameProvider; + _characterRendererFactory = characterRendererFactory; + _eifFileProvider = eifFileProvider; + _gameStateProvider = gameStateProvider; + _weaponMetadataProvider = weaponMetadataProvider; + } - public void LaunchTestMode() - { - if (_gameStateProvider.CurrentState != GameStates.None) - return; + public void LaunchTestMode() + { + if (_gameStateProvider.CurrentState != GameStates.None) + return; - var testMode = new CharacterStateTest( - _endlessGameProvider.Game, - _characterRendererFactory, - _eifFileProvider, - _weaponMetadataProvider); + var testMode = new CharacterStateTest( + _endlessGameProvider.Game, + _characterRendererFactory, + _eifFileProvider, + _weaponMetadataProvider); - _endlessGameProvider.Game.Components.Clear(); - _endlessGameProvider.Game.Components.Add(testMode); - } + _endlessGameProvider.Game.Components.Clear(); + _endlessGameProvider.Game.Components.Add(testMode); } +} - public interface ITestModeLauncher - { - void LaunchTestMode(); - } +public interface ITestModeLauncher +{ + void LaunchTestMode(); } \ No newline at end of file diff --git a/EndlessClient/UIControls/BlinkingLabel.cs b/EndlessClient/UIControls/BlinkingLabel.cs index 1b845f448..a875471e0 100644 --- a/EndlessClient/UIControls/BlinkingLabel.cs +++ b/EndlessClient/UIControls/BlinkingLabel.cs @@ -2,53 +2,52 @@ using System; using XNAControls; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +public class BlinkingLabel : XNALabel { - public class BlinkingLabel : XNALabel + /// + /// Get or Set the rate of blinking in milliseconds + /// + public int? BlinkRate { get; set; } + + private DateTime? _callbackStartTime; + private int _callbackDueTime; + private DateTime _lastToggleTime; + private Action _callback; + + public BlinkingLabel(string spriteFontContentName) + : base(spriteFontContentName) { - /// - /// Get or Set the rate of blinking in milliseconds - /// - public int? BlinkRate { get; set; } - - private DateTime? _callbackStartTime; - private int _callbackDueTime; - private DateTime _lastToggleTime; - private Action _callback; - - public BlinkingLabel(string spriteFontContentName) - : base(spriteFontContentName) - { - _lastToggleTime = DateTime.Now; - } + _lastToggleTime = DateTime.Now; + } - /// - /// Sets some action that is invoked after the specified amount of time - /// - /// Time to wait before invoking (in milliseconds) - /// Action to invoke - public void SetCallback(int dueTime, Action a) + /// + /// Sets some action that is invoked after the specified amount of time + /// + /// Time to wait before invoking (in milliseconds) + /// Action to invoke + public void SetCallback(int dueTime, Action a) + { + _callbackDueTime = dueTime; + _callbackStartTime = DateTime.Now; + _callback = a; + } + + public override void Update(GameTime gameTime) + { + if (_callbackStartTime.HasValue && (DateTime.Now - _callbackStartTime.Value).TotalMilliseconds > _callbackDueTime) { - _callbackDueTime = dueTime; - _callbackStartTime = DateTime.Now; - _callback = a; + _callback(); + _callbackStartTime = null; } - public override void Update(GameTime gameTime) + if (BlinkRate.HasValue && (DateTime.Now - _lastToggleTime).TotalMilliseconds > BlinkRate) { - if (_callbackStartTime.HasValue && (DateTime.Now - _callbackStartTime.Value).TotalMilliseconds > _callbackDueTime) - { - _callback(); - _callbackStartTime = null; - } - - if (BlinkRate.HasValue && (DateTime.Now - _lastToggleTime).TotalMilliseconds > BlinkRate) - { - _lastToggleTime = DateTime.Now; - Visible = !Visible; - } - - base.Update(gameTime); + _lastToggleTime = DateTime.Now; + Visible = !Visible; } + + base.Update(gameTime); } } \ No newline at end of file diff --git a/EndlessClient/UIControls/CharacterControl.cs b/EndlessClient/UIControls/CharacterControl.cs index fd68673cc..054ed5905 100644 --- a/EndlessClient/UIControls/CharacterControl.cs +++ b/EndlessClient/UIControls/CharacterControl.cs @@ -4,59 +4,58 @@ using Microsoft.Xna.Framework; using XNAControls; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +public class CharacterControl : XNAControl { - public class CharacterControl : XNAControl + public CharacterRenderProperties RenderProperties { - public CharacterRenderProperties RenderProperties - { - get { return _characterRenderer.Character.RenderProperties; } + get { return _characterRenderer.Character.RenderProperties; } - protected set - { - _characterRenderer.Character = _characterRenderer.Character.WithRenderProperties(value); - } + protected set + { + _characterRenderer.Character = _characterRenderer.Character.WithRenderProperties(value); } + } - protected readonly ICharacterRenderer _characterRenderer; + protected readonly ICharacterRenderer _characterRenderer; - public CharacterControl(Character character, - ICharacterRendererFactory characterRendererFactory) - { - _characterRenderer = characterRendererFactory.CreateCharacterRenderer(character, isUiControl: true); - } + public CharacterControl(Character character, + ICharacterRendererFactory characterRendererFactory) + { + _characterRenderer = characterRendererFactory.CreateCharacterRenderer(character, isUiControl: true); + } - public override void Initialize() - { - _characterRenderer.Initialize(); - _characterRenderer.SetAbsoluteScreenPosition(DrawAreaWithParentOffset.X, DrawAreaWithParentOffset.Y); + public override void Initialize() + { + _characterRenderer.Initialize(); + _characterRenderer.SetAbsoluteScreenPosition(DrawAreaWithParentOffset.X, DrawAreaWithParentOffset.Y); - base.Initialize(); - } + base.Initialize(); + } - protected override bool ShouldUpdate() - { - return Visible; - } + protected override bool ShouldUpdate() + { + return Visible; + } - protected override void OnUpdateControl(GameTime gameTime) - { - _characterRenderer.Update(gameTime); - base.OnUpdateControl(gameTime); - } + protected override void OnUpdateControl(GameTime gameTime) + { + _characterRenderer.Update(gameTime); + base.OnUpdateControl(gameTime); + } - protected override void OnDrawControl(GameTime gameTime) - { - _characterRenderer.Draw(gameTime); - base.OnDrawControl(gameTime); - } + protected override void OnDrawControl(GameTime gameTime) + { + _characterRenderer.Draw(gameTime); + base.OnDrawControl(gameTime); + } - protected override void Dispose(bool disposing) - { - if (disposing) - _characterRenderer.Dispose(); + protected override void Dispose(bool disposing) + { + if (disposing) + _characterRenderer.Dispose(); - base.Dispose(disposing); - } + base.Dispose(disposing); } } \ No newline at end of file diff --git a/EndlessClient/UIControls/CharacterInfoPanel.cs b/EndlessClient/UIControls/CharacterInfoPanel.cs index df74d5481..6ec22efb0 100644 --- a/EndlessClient/UIControls/CharacterInfoPanel.cs +++ b/EndlessClient/UIControls/CharacterInfoPanel.cs @@ -15,239 +15,238 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +public class CharacterInfoPanel : XNAControl { - public class CharacterInfoPanel : XNAControl - { - private readonly INativeGraphicsManager _gfxManager; - private readonly Character _character; - private readonly ILoginController _loginController; - private readonly ICharacterManagementController _characterManagementController; - private readonly IRendererRepositoryResetter _rendererRepositoryResetter; - private readonly CharacterControl _characterControl; - private readonly ISpriteSheet _adminGraphic; - private readonly IUserInputProvider _userInputProvider; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - private readonly Texture2D _backgroundImage; - - private readonly IXNAButton _loginButton, _deleteButton; - private readonly IXNALabel _nameLabel, _levelLabel; - - private readonly int _characterIndex; - - private Task _activeTask; - - //top left - 334, 36 + ndx*124 - protected CharacterInfoPanel(int characterIndex, - INativeGraphicsManager gfxManager, - IEODialogButtonService dialogButtonService) - { - _characterIndex = characterIndex; - _gfxManager = gfxManager; - DrawPosition = new Vector2(334, 36 + characterIndex * 124); - - _loginButton = new XNAButton(dialogButtonService.SmallButtonSheet, - new Vector2(161, 57), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Login), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Login)); - _loginButton.OnClick += (o, e) => AsyncButtonClick(() => _loginController.LoginToCharacter(_character)); - _loginButton.SetParentControl(this); - - _deleteButton = new XNAButton(dialogButtonService.SmallButtonSheet, - new Vector2(161, 85), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Delete), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Delete)); - _deleteButton.OnClick += (o, e) => AsyncButtonClick(() => _characterManagementController.DeleteCharacter(_character)); - _deleteButton.SetParentControl(this); - - _backgroundImage = _gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 11); - SetSize(_backgroundImage.Width, _backgroundImage.Height); - } + private readonly INativeGraphicsManager _gfxManager; + private readonly Character _character; + private readonly ILoginController _loginController; + private readonly ICharacterManagementController _characterManagementController; + private readonly IRendererRepositoryResetter _rendererRepositoryResetter; + private readonly CharacterControl _characterControl; + private readonly ISpriteSheet _adminGraphic; + private readonly IUserInputProvider _userInputProvider; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; + private readonly Texture2D _backgroundImage; + + private readonly IXNAButton _loginButton, _deleteButton; + private readonly IXNALabel _nameLabel, _levelLabel; + + private readonly int _characterIndex; + + private Task _activeTask; + + //top left - 334, 36 + ndx*124 + protected CharacterInfoPanel(int characterIndex, + INativeGraphicsManager gfxManager, + IEODialogButtonService dialogButtonService) + { + _characterIndex = characterIndex; + _gfxManager = gfxManager; + DrawPosition = new Vector2(334, 36 + characterIndex * 124); + + _loginButton = new XNAButton(dialogButtonService.SmallButtonSheet, + new Vector2(161, 57), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Login), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Login)); + _loginButton.OnClick += (o, e) => AsyncButtonClick(() => _loginController.LoginToCharacter(_character)); + _loginButton.SetParentControl(this); + + _deleteButton = new XNAButton(dialogButtonService.SmallButtonSheet, + new Vector2(161, 85), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Delete), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Delete)); + _deleteButton.OnClick += (o, e) => AsyncButtonClick(() => _characterManagementController.DeleteCharacter(_character)); + _deleteButton.SetParentControl(this); + + _backgroundImage = _gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 11); + SetSize(_backgroundImage.Width, _backgroundImage.Height); + } - public CharacterInfoPanel(int characterIndex, - Character character, - INativeGraphicsManager gfxManager, - IEODialogButtonService dialogButtonService, - ILoginController loginController, - ICharacterManagementController characterManagementController, - ICharacterRendererFactory rendererFactory, - IRendererRepositoryResetter rendererRepositoryResetter, - IUserInputProvider userInputProvider, - IXnaControlSoundMapper xnaControlSoundMapper) - : this(characterIndex, gfxManager, dialogButtonService) - { - _character = character; - _loginController = loginController; - _characterManagementController = characterManagementController; - _rendererRepositoryResetter = rendererRepositoryResetter; - _userInputProvider = userInputProvider; - _xnaControlSoundMapper = xnaControlSoundMapper; - - _characterControl = new CharacterControl(character, rendererFactory) - { - DrawPosition = new Vector2(68, 28) - }; - _characterControl.SetParentControl(this); - - _nameLabel = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = GetNameLabelLocation(), - ForeColor = ColorConstants.BeigeText, - Text = CapitalizeName(character.Name), - TextAlign = LabelAlignment.MiddleCenter, - AutoSize = false - }; - _nameLabel.SetParentControl(this); - - _levelLabel = new XNALabel(Constants.FontSize09) - { - DrawArea = GetLevelLabelLocation(), - ForeColor = ColorConstants.BeigeText, - Text = character.Stats.Stats[CharacterStat.Level].ToString() - }; - _levelLabel.SetParentControl(this); - - _adminGraphic = CreateAdminGraphic(character.AdminLevel); - } + public CharacterInfoPanel(int characterIndex, + Character character, + INativeGraphicsManager gfxManager, + IEODialogButtonService dialogButtonService, + ILoginController loginController, + ICharacterManagementController characterManagementController, + ICharacterRendererFactory rendererFactory, + IRendererRepositoryResetter rendererRepositoryResetter, + IUserInputProvider userInputProvider, + IXnaControlSoundMapper xnaControlSoundMapper) + : this(characterIndex, gfxManager, dialogButtonService) + { + _character = character; + _loginController = loginController; + _characterManagementController = characterManagementController; + _rendererRepositoryResetter = rendererRepositoryResetter; + _userInputProvider = userInputProvider; + _xnaControlSoundMapper = xnaControlSoundMapper; + + _characterControl = new CharacterControl(character, rendererFactory) + { + DrawPosition = new Vector2(68, 28) + }; + _characterControl.SetParentControl(this); + + _nameLabel = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = GetNameLabelLocation(), + ForeColor = ColorConstants.BeigeText, + Text = CapitalizeName(character.Name), + TextAlign = LabelAlignment.MiddleCenter, + AutoSize = false + }; + _nameLabel.SetParentControl(this); + + _levelLabel = new XNALabel(Constants.FontSize09) + { + DrawArea = GetLevelLabelLocation(), + ForeColor = ColorConstants.BeigeText, + Text = character.Stats.Stats[CharacterStat.Level].ToString() + }; + _levelLabel.SetParentControl(this); + + _adminGraphic = CreateAdminGraphic(character.AdminLevel); + } - public override void Initialize() - { - _characterControl.Initialize(); + public override void Initialize() + { + _characterControl.Initialize(); - _loginButton.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_loginButton); + _loginButton.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_loginButton); - _deleteButton.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_deleteButton); + _deleteButton.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_deleteButton); - _nameLabel.Initialize(); - _levelLabel.Initialize(); + _nameLabel.Initialize(); + _levelLabel.Initialize(); - base.Initialize(); - } + base.Initialize(); + } - protected override bool ShouldUpdate() - { - return Visible; - } + protected override bool ShouldUpdate() + { + return Visible; + } - protected override void OnUpdateControl(GameTime gameTime) - { - DoUpdateLogic(gameTime); - base.OnUpdateControl(gameTime); - } + protected override void OnUpdateControl(GameTime gameTime) + { + DoUpdateLogic(gameTime); + base.OnUpdateControl(gameTime); + } - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); - _spriteBatch.Draw(_backgroundImage, DrawPositionWithParentOffset, Color.White); - _spriteBatch.End(); + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); + _spriteBatch.Draw(_backgroundImage, DrawPositionWithParentOffset, Color.White); + _spriteBatch.End(); - DoDrawLogic(gameTime); + DoDrawLogic(gameTime); - base.OnDrawControl(gameTime); - } + base.OnDrawControl(gameTime); + } - protected virtual void AsyncButtonClick(Func clickHandler) + protected virtual void AsyncButtonClick(Func clickHandler) + { + if (_activeTask == null) { - if (_activeTask == null) - { - _activeTask = clickHandler(); - _activeTask.ContinueWith(_ => _activeTask = null); - } + _activeTask = clickHandler(); + _activeTask.ContinueWith(_ => _activeTask = null); } + } - protected virtual void DoUpdateLogic(GameTime gameTime) - { - _characterControl.Update(gameTime); - - var previousKeyState = _userInputProvider.PreviousKeyState; - var currentKeyState = _userInputProvider.CurrentKeyState; - if (currentKeyState.IsKeyPressedOnce(previousKeyState, Keys.D1 + _characterIndex)) - { - AsyncButtonClick(() => _loginController.LoginToCharacter(_character)); - } - } + protected virtual void DoUpdateLogic(GameTime gameTime) + { + _characterControl.Update(gameTime); - protected virtual void DoDrawLogic(GameTime gameTime) + var previousKeyState = _userInputProvider.PreviousKeyState; + var currentKeyState = _userInputProvider.CurrentKeyState; + if (currentKeyState.IsKeyPressedOnce(previousKeyState, Keys.D1 + _characterIndex)) { - _characterControl.Draw(gameTime); - - if (_adminGraphic.HasTexture && !_spriteBatch.IsDisposed) - { - _spriteBatch.Begin(); - _spriteBatch.Draw(_adminGraphic.SheetTexture, GetAdminGraphicLocation(), _adminGraphic.SourceRectangle, Color.White); - _spriteBatch.End(); - } + AsyncButtonClick(() => _loginController.LoginToCharacter(_character)); } + } - private static Rectangle GetNameLabelLocation() - { - return new Rectangle(165, 26, 89, 22); - } + protected virtual void DoDrawLogic(GameTime gameTime) + { + _characterControl.Draw(gameTime); - private static Rectangle GetLevelLabelLocation() + if (_adminGraphic.HasTexture && !_spriteBatch.IsDisposed) { - return new Rectangle(29, 99, 1, 1); + _spriteBatch.Begin(); + _spriteBatch.Draw(_adminGraphic.SheetTexture, GetAdminGraphicLocation(), _adminGraphic.SourceRectangle, Color.White); + _spriteBatch.End(); } + } - private Vector2 GetAdminGraphicLocation() - { - return new Vector2(DrawAreaWithParentOffset.X + 109, DrawAreaWithParentOffset.Y + 97); - } + private static Rectangle GetNameLabelLocation() + { + return new Rectangle(165, 26, 89, 22); + } - private static string CapitalizeName(string name) - { - return string.IsNullOrEmpty(name) ? string.Empty : (char)(name[0] - 32) + name.Substring(1); - } + private static Rectangle GetLevelLabelLocation() + { + return new Rectangle(29, 99, 1, 1); + } - private ISpriteSheet CreateAdminGraphic(AdminLevel adminLevel) - { - var adminGraphic = _gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 22); - - switch (adminLevel) - { - case AdminLevel.Player: - return new EmptySpriteSheet(); - case AdminLevel.Spy: - return new SpriteSheet(adminGraphic, new Rectangle(252, 39, 17, 17)); - case AdminLevel.LightGuide: - case AdminLevel.Guardian: - case AdminLevel.GameMaster: - case AdminLevel.HighGameMaster: - return new SpriteSheet(adminGraphic, new Rectangle(233, 39, 17, 17)); - default: - throw new ArgumentOutOfRangeException(nameof(adminLevel), adminLevel, null); - } - } + private Vector2 GetAdminGraphicLocation() + { + return new Vector2(DrawAreaWithParentOffset.X + 109, DrawAreaWithParentOffset.Y + 97); } - /// - /// This is a no-op class that represents an empty character slot. The buttons don't do anything, and nothing is drawn / updated - /// - public class EmptyCharacterInfoPanel : CharacterInfoPanel + private static string CapitalizeName(string name) { - public EmptyCharacterInfoPanel(int characterIndex, - INativeGraphicsManager gfxManager, - IEODialogButtonService dialogButtonService) - : base(characterIndex, gfxManager, dialogButtonService) - { - } + return string.IsNullOrEmpty(name) ? string.Empty : (char)(name[0] - 32) + name.Substring(1); + } - public override void Initialize() - { + private ISpriteSheet CreateAdminGraphic(AdminLevel adminLevel) + { + var adminGraphic = _gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 22); + + switch (adminLevel) + { + case AdminLevel.Player: + return new EmptySpriteSheet(); + case AdminLevel.Spy: + return new SpriteSheet(adminGraphic, new Rectangle(252, 39, 17, 17)); + case AdminLevel.LightGuide: + case AdminLevel.Guardian: + case AdminLevel.GameMaster: + case AdminLevel.HighGameMaster: + return new SpriteSheet(adminGraphic, new Rectangle(233, 39, 17, 17)); + default: + throw new ArgumentOutOfRangeException(nameof(adminLevel), adminLevel, null); } + } +} - protected override void DoUpdateLogic(GameTime gameTime) - { - } +/// +/// This is a no-op class that represents an empty character slot. The buttons don't do anything, and nothing is drawn / updated +/// +public class EmptyCharacterInfoPanel : CharacterInfoPanel +{ + public EmptyCharacterInfoPanel(int characterIndex, + INativeGraphicsManager gfxManager, + IEODialogButtonService dialogButtonService) + : base(characterIndex, gfxManager, dialogButtonService) + { + } - protected override void DoDrawLogic(GameTime gameTime) - { - } + public override void Initialize() + { + } - protected override void AsyncButtonClick(Func clickHandler) - { - } + protected override void DoUpdateLogic(GameTime gameTime) + { + } + + protected override void DoDrawLogic(GameTime gameTime) + { + } + + protected override void AsyncButtonClick(Func clickHandler) + { } } \ No newline at end of file diff --git a/EndlessClient/UIControls/CharacterInfoPanelFactory.cs b/EndlessClient/UIControls/CharacterInfoPanelFactory.cs index 5cd92c24b..268b19a75 100644 --- a/EndlessClient/UIControls/CharacterInfoPanelFactory.cs +++ b/EndlessClient/UIControls/CharacterInfoPanelFactory.cs @@ -9,67 +9,66 @@ using System; using System.Collections.Generic; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +[AutoMappedType(IsSingleton = true)] +public class CharacterInfoPanelFactory : ICharacterInfoPanelFactory { - [AutoMappedType(IsSingleton = true)] - public class CharacterInfoPanelFactory : ICharacterInfoPanelFactory + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly IRendererRepositoryResetter _rendererRepositoryResetter; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IUserInputProvider _userInputProvider; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; + private ILoginController _loginController; + private ICharacterManagementController _characterManagementController; + + public CharacterInfoPanelFactory(INativeGraphicsManager nativeGraphicsManager, + ICharacterRendererFactory characterRendererFactory, + IRendererRepositoryResetter rendererRepositoryResetter, + IEODialogButtonService eoDialogButtonService, + IUserInputProvider userInputProvider, + IXnaControlSoundMapper xnaControlSoundMapper) { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly IRendererRepositoryResetter _rendererRepositoryResetter; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IUserInputProvider _userInputProvider; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - private ILoginController _loginController; - private ICharacterManagementController _characterManagementController; + _nativeGraphicsManager = nativeGraphicsManager; + _characterRendererFactory = characterRendererFactory; + _rendererRepositoryResetter = rendererRepositoryResetter; + _eoDialogButtonService = eoDialogButtonService; + _userInputProvider = userInputProvider; + _xnaControlSoundMapper = xnaControlSoundMapper; + } - public CharacterInfoPanelFactory(INativeGraphicsManager nativeGraphicsManager, - ICharacterRendererFactory characterRendererFactory, - IRendererRepositoryResetter rendererRepositoryResetter, - IEODialogButtonService eoDialogButtonService, - IUserInputProvider userInputProvider, - IXnaControlSoundMapper xnaControlSoundMapper) - { - _nativeGraphicsManager = nativeGraphicsManager; - _characterRendererFactory = characterRendererFactory; - _rendererRepositoryResetter = rendererRepositoryResetter; - _eoDialogButtonService = eoDialogButtonService; - _userInputProvider = userInputProvider; - _xnaControlSoundMapper = xnaControlSoundMapper; - } + public void InjectLoginController(ILoginController loginController) + { + _loginController = loginController; + } - public void InjectLoginController(ILoginController loginController) - { - _loginController = loginController; - } + public void InjectCharacterManagementController(ICharacterManagementController characterManagementController) + { + _characterManagementController = characterManagementController; + } - public void InjectCharacterManagementController(ICharacterManagementController characterManagementController) - { - _characterManagementController = characterManagementController; - } + public IEnumerable CreatePanels(IEnumerable characters) + { + if (_loginController == null || _characterManagementController == null) + throw new InvalidOperationException("Missing controllers - the Unity container was initialized incorrectly"); - public IEnumerable CreatePanels(IEnumerable characters) + int i = 0; + foreach (var character in characters) { - if (_loginController == null || _characterManagementController == null) - throw new InvalidOperationException("Missing controllers - the Unity container was initialized incorrectly"); - - int i = 0; - foreach (var character in characters) - { - yield return new CharacterInfoPanel(i++, - character, - _nativeGraphicsManager, - _eoDialogButtonService, - _loginController, - _characterManagementController, - _characterRendererFactory, - _rendererRepositoryResetter, - _userInputProvider, - _xnaControlSoundMapper); - } - - for (; i < 3; ++i) - yield return new EmptyCharacterInfoPanel(i, _nativeGraphicsManager, _eoDialogButtonService); + yield return new CharacterInfoPanel(i++, + character, + _nativeGraphicsManager, + _eoDialogButtonService, + _loginController, + _characterManagementController, + _characterRendererFactory, + _rendererRepositoryResetter, + _userInputProvider, + _xnaControlSoundMapper); } + + for (; i < 3; ++i) + yield return new EmptyCharacterInfoPanel(i, _nativeGraphicsManager, _eoDialogButtonService); } } \ No newline at end of file diff --git a/EndlessClient/UIControls/ChatModePictureBox.cs b/EndlessClient/UIControls/ChatModePictureBox.cs index 4a88e318c..22c03ead4 100644 --- a/EndlessClient/UIControls/ChatModePictureBox.cs +++ b/EndlessClient/UIControls/ChatModePictureBox.cs @@ -8,96 +8,95 @@ using System; using XNAControls; -namespace EndlessClient.UIControls -{ - public class ChatModePictureBox : XNAPictureBox - { - private readonly IChatModeCalculator _chatModeCalculator; - private readonly IHudControlProvider _hudControlProvider; +namespace EndlessClient.UIControls; - public enum ChatMode - { - NoText, - Public, - Private, - Global, - Group, - Admin, - Muted, - Guild - } +public class ChatModePictureBox : XNAPictureBox +{ + private readonly IChatModeCalculator _chatModeCalculator; + private readonly IHudControlProvider _hudControlProvider; - private string _lastChat; - private Option _endMuteTime; + public enum ChatMode + { + NoText, + Public, + Private, + Global, + Group, + Admin, + Muted, + Guild + } - public ChatModePictureBox(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - IChatModeCalculator chatModeCalculator, - IHudControlProvider hudControlProvider) - { - _chatModeCalculator = chatModeCalculator; - _hudControlProvider = hudControlProvider; + private string _lastChat; + private Option _endMuteTime; - _lastChat = ""; - _endMuteTime = Option.None(); + public ChatModePictureBox(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + IChatModeCalculator chatModeCalculator, + IHudControlProvider hudControlProvider) + { + _chatModeCalculator = chatModeCalculator; + _hudControlProvider = hudControlProvider; - Texture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 31); + _lastChat = ""; + _endMuteTime = Option.None(); - DrawArea = new Rectangle(16, 309, Texture.Width, Texture.Height / 8 - 2); - SourceRectangle = new Rectangle(0, 0, Texture.Width, Texture.Height / 8 - 2); + Texture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 31); - if (clientWindowSizeProvider.Resizable) - { - DrawPosition = new Vector2(122, clientWindowSizeProvider.Height - 39); - clientWindowSizeProvider.GameWindowSizeChanged += (_, _) => DrawPosition = new Vector2(122, clientWindowSizeProvider.Height - 39); - } - } + DrawArea = new Rectangle(16, 309, Texture.Width, Texture.Height / 8 - 2); + SourceRectangle = new Rectangle(0, 0, Texture.Width, Texture.Height / 8 - 2); - public void SetMuted(DateTime endMuteTime) + if (clientWindowSizeProvider.Resizable) { - _lastChat = ""; - _endMuteTime = Option.Some(endMuteTime); - UpdateSourceRectangleForMode(ChatMode.Muted); + DrawPosition = new Vector2(122, clientWindowSizeProvider.Height - 39); + clientWindowSizeProvider.GameWindowSizeChanged += (_, _) => DrawPosition = new Vector2(122, clientWindowSizeProvider.Height - 39); } + } - protected override void OnUpdateControl(GameTime gameTime) - { - _endMuteTime.Match( - some: endTime => + public void SetMuted(DateTime endMuteTime) + { + _lastChat = ""; + _endMuteTime = Option.Some(endMuteTime); + UpdateSourceRectangleForMode(ChatMode.Muted); + } + + protected override void OnUpdateControl(GameTime gameTime) + { + _endMuteTime.Match( + some: endTime => + { + if (DateTime.Now >= endTime) { - if (DateTime.Now >= endTime) - { - _endMuteTime = Option.None(); - UpdateSourceRectangleForMode(ChatMode.NoText); - } - }, - none: () => + _endMuteTime = Option.None(); + UpdateSourceRectangleForMode(ChatMode.NoText); + } + }, + none: () => + { + if (AtLeastOneCharTypedOrDeleted()) { - if (AtLeastOneCharTypedOrDeleted()) - { - UpdateSourceRectangleForMode(_chatModeCalculator.CalculateMode(ChatTextBox.Text)); - _lastChat = ChatTextBox.Text; - } - }); - - base.OnUpdateControl(gameTime); - } + UpdateSourceRectangleForMode(_chatModeCalculator.CalculateMode(ChatTextBox.Text)); + _lastChat = ChatTextBox.Text; + } + }); - private bool AtLeastOneCharTypedOrDeleted() - { - return _hudControlProvider.IsInGame && - ((_lastChat.Length == 0 && ChatTextBox.Text.Length > 0) || - (_lastChat.Length > 0 && ChatTextBox.Text.Length == 0)); - } + base.OnUpdateControl(gameTime); + } - private void UpdateSourceRectangleForMode(ChatMode mode) - { - if (!SourceRectangle.HasValue) - throw new InvalidOperationException("SourceRectangle is expected to have a value."); + private bool AtLeastOneCharTypedOrDeleted() + { + return _hudControlProvider.IsInGame && + ((_lastChat.Length == 0 && ChatTextBox.Text.Length > 0) || + (_lastChat.Length > 0 && ChatTextBox.Text.Length == 0)); + } - SourceRectangle = new Rectangle(0, (int)((int)mode * (Texture.Height / 8f)), Texture.Width, Texture.Height / 8 - 2); - } + private void UpdateSourceRectangleForMode(ChatMode mode) + { + if (!SourceRectangle.HasValue) + throw new InvalidOperationException("SourceRectangle is expected to have a value."); - private ChatTextBox ChatTextBox => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); + SourceRectangle = new Rectangle(0, (int)((int)mode * (Texture.Height / 8f)), Texture.Width, Texture.Height / 8 - 2); } + + private ChatTextBox ChatTextBox => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); } \ No newline at end of file diff --git a/EndlessClient/UIControls/ChatTextBox.cs b/EndlessClient/UIControls/ChatTextBox.cs index 5bb41dc62..b1c23847b 100644 --- a/EndlessClient/UIControls/ChatTextBox.cs +++ b/EndlessClient/UIControls/ChatTextBox.cs @@ -10,129 +10,128 @@ using System; using XNAControls; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +/// +/// Special instance of an XNATextBox that should ignore input from the number pad (which is used for Emotes) +/// +public class ChatTextBox : XNATextBox { - /// - /// Special instance of an XNATextBox that should ignore input from the number pad (which is used for Emotes) - /// - public class ChatTextBox : XNATextBox - { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + + private bool _ignoreAllInput; + private Option _endMuteTime; - private bool _ignoreAllInput; - private Option _endMuteTime; + private readonly Rectangle? _leftSide, _background, _rightSide; - private readonly Rectangle? _leftSide, _background, _rightSide; + public ChatTextBox(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + IContentProvider contentManagerProvider) + : base(Rectangle.Empty, // (124, 308, 440, 19) + Constants.FontSize08, + caretTexture: contentManagerProvider.Textures[ContentProvider.Cursor]) + { + _nativeGraphicsManager = nativeGraphicsManager; + _clientWindowSizeProvider = clientWindowSizeProvider; - public ChatTextBox(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - IContentProvider contentManagerProvider) - : base(Rectangle.Empty, // (124, 308, 440, 19) - Constants.FontSize08, - caretTexture: contentManagerProvider.Textures[ContentProvider.Cursor]) + if (_clientWindowSizeProvider.Resizable) { - _nativeGraphicsManager = nativeGraphicsManager; - _clientWindowSizeProvider = clientWindowSizeProvider; + _leftSide = new Rectangle(10, 308, 12, 20); + _background = new Rectangle(22, 308, 560, 20); + _rightSide = new Rectangle(578, 308, 11, 20); - if (_clientWindowSizeProvider.Resizable) - { - _leftSide = new Rectangle(10, 308, 12, 20); - _background = new Rectangle(22, 308, 560, 20); - _rightSide = new Rectangle(578, 308, 11, 20); + DrawArea = new Rectangle(124, _clientWindowSizeProvider.Height - 40, _clientWindowSizeProvider.Width - 116, 20); - DrawArea = new Rectangle(124, _clientWindowSizeProvider.Height - 40, _clientWindowSizeProvider.Width - 116, 20); + // original X coordinate accounting for the width of chat mode picture + LeftPadding = 124; - // original X coordinate accounting for the width of chat mode picture - LeftPadding = 124; - - _clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => - { - // status icons: 124 width - // friend/ignore: 40 width - DrawArea = new Rectangle(124, _clientWindowSizeProvider.Height - 40, _clientWindowSizeProvider.Width - 116, 20); - MaxWidth = DrawArea.Width - 184; - }; - } - else + _clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => { - DrawArea = new Rectangle(124, 308, 440, 20); - } - - MaxChars = 140; - _endMuteTime = Option.None(); + // status icons: 124 width + // friend/ignore: 40 width + DrawArea = new Rectangle(124, _clientWindowSizeProvider.Height - 40, _clientWindowSizeProvider.Width - 116, 20); + MaxWidth = DrawArea.Width - 184; + }; } - - public override void Initialize() + else { - base.Initialize(); - - // This must be done after Initialize because MaxWidth uses the sprite font. - // SpriteFont is loaded in LoadContent which is called by Initialize. - MaxWidth = _clientWindowSizeProvider.Resizable ? DrawArea.Width - 184 : 440; + DrawArea = new Rectangle(124, 308, 440, 20); } - public void SetMuted(DateTime endMuteTime) - { - _ignoreAllInput = true; - _endMuteTime = Option.Some(endMuteTime); - } + MaxChars = 140; + _endMuteTime = Option.None(); + } - protected override void OnUpdateControl(GameTime gameTime) - { - _endMuteTime.MatchSome(endTime => - { - if (DateTime.Now > endTime) - { - _endMuteTime = Option.None(); - _ignoreAllInput = false; - } - }); - - base.OnUpdateControl(gameTime); - } + public override void Initialize() + { + base.Initialize(); + + // This must be done after Initialize because MaxWidth uses the sprite font. + // SpriteFont is loaded in LoadContent which is called by Initialize. + MaxWidth = _clientWindowSizeProvider.Resizable ? DrawArea.Width - 184 : 440; + } - protected override void OnDrawControl(GameTime gameTime) + public void SetMuted(DateTime endMuteTime) + { + _ignoreAllInput = true; + _endMuteTime = Option.Some(endMuteTime); + } + + protected override void OnUpdateControl(GameTime gameTime) + { + _endMuteTime.MatchSome(endTime => { - if (_clientWindowSizeProvider.Resizable && _background != null) + if (DateTime.Now > endTime) { - _spriteBatch.Begin(samplerState: SamplerState.LinearWrap); - _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, true), DrawArea, _background, Color.White); - _spriteBatch.End(); - - _spriteBatch.Begin(); - _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false), DrawPosition, _leftSide, Color.White); - _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false), new Vector2(DrawArea.X + DrawArea.Width - _rightSide.Value.Width, DrawPosition.Y), _rightSide, Color.White); - _spriteBatch.End(); + _endMuteTime = Option.None(); + _ignoreAllInput = false; } + }); - base.OnDrawControl(gameTime); - } + base.OnUpdateControl(gameTime); + } - protected override bool HandleTextInput(KeyboardEventArgs eventArgs) + protected override void OnDrawControl(GameTime gameTime) + { + if (_clientWindowSizeProvider.Resizable && _background != null) { - if (_ignoreAllInput) - return false; + _spriteBatch.Begin(samplerState: SamplerState.LinearWrap); + _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, true), DrawArea, _background, Color.White); + _spriteBatch.End(); + + _spriteBatch.Begin(); + _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false), DrawPosition, _leftSide, Color.White); + _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false), new Vector2(DrawArea.X + DrawArea.Width - _rightSide.Value.Width, DrawPosition.Y), _rightSide, Color.White); + _spriteBatch.End(); + } - if (IsSpecialInput(eventArgs.Key, eventArgs.Modifiers)) - HandleSpecialInput(eventArgs.Key); - else - base.HandleTextInput(eventArgs); + base.OnDrawControl(gameTime); + } - return true; - } + protected override bool HandleTextInput(KeyboardEventArgs eventArgs) + { + if (_ignoreAllInput) + return false; - private void HandleSpecialInput(Keys key) - { - if (key == Keys.Escape) - Text = ""; - } + if (IsSpecialInput(eventArgs.Key, eventArgs.Modifiers)) + HandleSpecialInput(eventArgs.Key); + else + base.HandleTextInput(eventArgs); - private bool IsSpecialInput(Keys k, KeyboardModifiers modifiers) - { - return k == Keys.Escape || k == Keys.Decimal || - (k >= Keys.NumPad0 && k <= Keys.NumPad9) || - modifiers == KeyboardModifiers.Alt; - } + return true; + } + + private void HandleSpecialInput(Keys key) + { + if (key == Keys.Escape) + Text = ""; + } + + private bool IsSpecialInput(Keys k, KeyboardModifiers modifiers) + { + return k == Keys.Escape || k == Keys.Decimal || + (k >= Keys.NumPad0 && k <= Keys.NumPad9) || + modifiers == KeyboardModifiers.Alt; } } \ No newline at end of file diff --git a/EndlessClient/UIControls/ClickableArea.cs b/EndlessClient/UIControls/ClickableArea.cs index 12103f835..5b1f59d78 100644 --- a/EndlessClient/UIControls/ClickableArea.cs +++ b/EndlessClient/UIControls/ClickableArea.cs @@ -3,39 +3,38 @@ using System; using XNAControls; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +public class ClickableArea : XNAControl, IXNAButton { - public class ClickableArea : XNAControl, IXNAButton + public Rectangle ClickArea { - public Rectangle ClickArea - { - get => DrawArea; - set => DrawArea = value; - } + get => DrawArea; + set => DrawArea = value; + } - public int? FlashSpeed - { - get => throw new InvalidOperationException("Unable to get flash speed on clickable area"); - set => throw new InvalidOperationException("Unable to get flash speed on clickable area"); - } + public int? FlashSpeed + { + get => throw new InvalidOperationException("Unable to get flash speed on clickable area"); + set => throw new InvalidOperationException("Unable to get flash speed on clickable area"); + } - public event EventHandler OnClick; + public event EventHandler OnClick; - public event EventHandler OnClickDrag - { - add => throw new InvalidOperationException("Unable to set ClickDrag event on clickable area"); - remove => throw new InvalidOperationException("Unable to set ClickDrag event on clickable area"); - } + public event EventHandler OnClickDrag + { + add => throw new InvalidOperationException("Unable to set ClickDrag event on clickable area"); + remove => throw new InvalidOperationException("Unable to set ClickDrag event on clickable area"); + } - public ClickableArea(Rectangle area) - { - ClickArea = area; - } + public ClickableArea(Rectangle area) + { + ClickArea = area; + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - OnClick?.Invoke(control, eventArgs); - return true; - } + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + OnClick?.Invoke(control, eventArgs); + return true; } } \ No newline at end of file diff --git a/EndlessClient/UIControls/CreateCharacterControl.cs b/EndlessClient/UIControls/CreateCharacterControl.cs index a945d61a0..60e79184e 100644 --- a/EndlessClient/UIControls/CreateCharacterControl.cs +++ b/EndlessClient/UIControls/CreateCharacterControl.cs @@ -6,77 +6,76 @@ using System; using XNAControls; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +public class CreateCharacterControl : CharacterControl { - public class CreateCharacterControl : CharacterControl - { - private Vector2 _lastPosition; + private Vector2 _lastPosition; - public event EventHandler Clicked; + public event EventHandler Clicked; - // default properties - public CreateCharacterControl(ICharacterRendererFactory characterRendererFactory) - : this(GetDefaultProperties(), characterRendererFactory) { } + // default properties + public CreateCharacterControl(ICharacterRendererFactory characterRendererFactory) + : this(GetDefaultProperties(), characterRendererFactory) { } - // custom render properties - public CreateCharacterControl(CharacterRenderProperties renderProperties, ICharacterRendererFactory characterRendererFactory) - : base(Character.Default.WithRenderProperties(renderProperties.WithDirection(EODirection.Down)), characterRendererFactory) - { - SetSize(99, 123); - _lastPosition = Vector2.Zero; - } + // custom render properties + public CreateCharacterControl(CharacterRenderProperties renderProperties, ICharacterRendererFactory characterRendererFactory) + : base(Character.Default.WithRenderProperties(renderProperties.WithDirection(EODirection.Down)), characterRendererFactory) + { + SetSize(99, 123); + _lastPosition = Vector2.Zero; + } - protected override void OnUpdateControl(GameTime gameTime) - { - if (!ShouldUpdate()) - return; + protected override void OnUpdateControl(GameTime gameTime) + { + if (!ShouldUpdate()) + return; - var actualDrawPosition = new Vector2(DrawPositionWithParentOffset.X + 40, - DrawPositionWithParentOffset.Y + 36); + var actualDrawPosition = new Vector2(DrawPositionWithParentOffset.X + 40, + DrawPositionWithParentOffset.Y + 36); - if (_lastPosition != actualDrawPosition) - _characterRenderer.SetAbsoluteScreenPosition((int)actualDrawPosition.X, (int)actualDrawPosition.Y); + if (_lastPosition != actualDrawPosition) + _characterRenderer.SetAbsoluteScreenPosition((int)actualDrawPosition.X, (int)actualDrawPosition.Y); - base.OnUpdateControl(gameTime); + base.OnUpdateControl(gameTime); - _lastPosition = actualDrawPosition; - } + _lastPosition = actualDrawPosition; + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - var nextDirectionInt = (int)RenderProperties.Direction + 1; - var nextDirection = (EODirection)(nextDirectionInt % 4); - RenderProperties = RenderProperties.WithDirection(nextDirection); + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + var nextDirectionInt = (int)RenderProperties.Direction + 1; + var nextDirection = (EODirection)(nextDirectionInt % 4); + RenderProperties = RenderProperties.WithDirection(nextDirection); - Clicked?.Invoke(this, EventArgs.Empty); + Clicked?.Invoke(this, EventArgs.Empty); - return true; - } + return true; + } - public void NextGender() - { - RenderProperties = RenderProperties.WithGender((RenderProperties.Gender + 1) % 2); - } + public void NextGender() + { + RenderProperties = RenderProperties.WithGender((RenderProperties.Gender + 1) % 2); + } - public void NextRace() - { - RenderProperties = RenderProperties.WithRace((RenderProperties.Race + 1) % 6); - } + public void NextRace() + { + RenderProperties = RenderProperties.WithRace((RenderProperties.Race + 1) % 6); + } - public void NextHairStyle() - { - RenderProperties = RenderProperties.WithHairStyle((RenderProperties.HairStyle + 1) % 21); - } + public void NextHairStyle() + { + RenderProperties = RenderProperties.WithHairStyle((RenderProperties.HairStyle + 1) % 21); + } - public void NextHairColor() - { - RenderProperties = RenderProperties.WithHairColor((RenderProperties.HairColor + 1) % 10); - } + public void NextHairColor() + { + RenderProperties = RenderProperties.WithHairColor((RenderProperties.HairColor + 1) % 10); + } - private static CharacterRenderProperties GetDefaultProperties() - { - return new CharacterRenderProperties.Builder { HairStyle = 1 }.ToImmutable(); - } + private static CharacterRenderProperties GetDefaultProperties() + { + return new CharacterRenderProperties.Builder { HairStyle = 1 }.ToImmutable(); } } \ No newline at end of file diff --git a/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs b/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs index a96eebfae..11789a3e1 100644 --- a/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs +++ b/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs @@ -2,12 +2,11 @@ using EOLib.Domain.Character; using System.Collections.Generic; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +public interface ICharacterInfoPanelFactory { - public interface ICharacterInfoPanelFactory - { - IEnumerable CreatePanels(IEnumerable characters); - void InjectLoginController(ILoginController loginController); - void InjectCharacterManagementController(ICharacterManagementController characterManagementController); - } + IEnumerable CreatePanels(IEnumerable characters); + void InjectLoginController(ILoginController loginController); + void InjectCharacterManagementController(ICharacterManagementController characterManagementController); } \ No newline at end of file diff --git a/EndlessClient/UIControls/ScrollBar.cs b/EndlessClient/UIControls/ScrollBar.cs index 82bc11581..aba6e0455 100644 --- a/EndlessClient/UIControls/ScrollBar.cs +++ b/EndlessClient/UIControls/ScrollBar.cs @@ -5,231 +5,230 @@ using System; using XNAControls; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +public enum ScrollBarColors { - public enum ScrollBarColors - { - LightOnDark, //bottom set of light - LightOnLight, //top set of light - LightOnMed, //middle set of light - DarkOnDark //very bottom set - } + LightOnDark, //bottom set of light + LightOnLight, //top set of light + LightOnMed, //middle set of light + DarkOnDark //very bottom set +} - public class ScrollBar : XNAControl, IScrollHandler - { - private Rectangle scrollArea; //area valid for scrolling: always 16 from top and 16 from bottom - public int ScrollOffset { get; private set; } - public int LinesToRender { get; set; } +public class ScrollBar : XNAControl, IScrollHandler +{ + private Rectangle scrollArea; //area valid for scrolling: always 16 from top and 16 from bottom + public int ScrollOffset { get; private set; } + public int LinesToRender { get; set; } - private readonly XNAButton _upButton, _downButton, _scrollButton; - private readonly Texture2D _backgroundTexture; - private readonly Rectangle? _backgroundTextureSource; + private readonly XNAButton _upButton, _downButton, _scrollButton; + private readonly Texture2D _backgroundTexture; + private readonly Rectangle? _backgroundTextureSource; - private int _totalHeight; + private int _totalHeight; - public override Rectangle DrawArea + public override Rectangle DrawArea + { + get => base.DrawArea; + set { - get => base.DrawArea; - set - { - base.DrawArea = value; + base.DrawArea = value; - scrollArea = new Rectangle(0, 15, 0, value.Height - 15); + scrollArea = new Rectangle(0, 15, 0, value.Height - 15); - if (_downButton != null) - _downButton.DrawPosition = new Vector2(0, value.Height - 15); - } + if (_downButton != null) + _downButton.DrawPosition = new Vector2(0, value.Height - 15); } + } - public ScrollBar(Vector2 locationRelativeToParent, - Vector2 size, - ScrollBarColors palette, - INativeGraphicsManager nativeGraphicsManager) + public ScrollBar(Vector2 locationRelativeToParent, + Vector2 size, + ScrollBarColors palette, + INativeGraphicsManager nativeGraphicsManager) + { + DrawPosition = locationRelativeToParent; + SetSize((int)size.X, (int)size.Y); + ScrollOffset = 0; + + var scrollSpriteSheet = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 29); + var upArrows = new Rectangle[2]; + var downArrows = new Rectangle[2]; + int vertOff; + switch (palette) { - DrawPosition = locationRelativeToParent; - SetSize((int)size.X, (int)size.Y); - ScrollOffset = 0; - - var scrollSpriteSheet = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 29); - var upArrows = new Rectangle[2]; - var downArrows = new Rectangle[2]; - int vertOff; - switch (palette) - { - case ScrollBarColors.LightOnLight: vertOff = 0; break; - case ScrollBarColors.LightOnMed: vertOff = 105; break; - case ScrollBarColors.LightOnDark: vertOff = 180; break; - case ScrollBarColors.DarkOnDark: vertOff = 255; break; - default: throw new ArgumentOutOfRangeException(nameof(palette)); - } - - //regions based on verticle offset (which is based on the chosen palette) - upArrows[0] = new Rectangle(0, vertOff + 15 * 3, 16, 15); - upArrows[1] = new Rectangle(0, vertOff + 15 * 4, 16, 15); - downArrows[0] = new Rectangle(0, vertOff + 15, 16, 15); - downArrows[1] = new Rectangle(0, vertOff + 15 * 2, 16, 15); - var scrollBox = new Rectangle(0, vertOff, 16, 15); - - _upButton = new XNAButton(scrollSpriteSheet, Vector2.Zero, upArrows[0], upArrows[1]); - _upButton.OnClick += arrowClicked; - _upButton.SetParentControl(this); - - _downButton = new XNAButton(scrollSpriteSheet, new Vector2(0, size.Y - 15), downArrows[0], downArrows[1]); - _downButton.OnClick += arrowClicked; - _downButton.SetParentControl(this); - - _scrollButton = new XNAButton(scrollSpriteSheet, new Vector2(0, 15), scrollBox, scrollBox); - _scrollButton.OnClickDrag += OnScrollButtonDragged; - _scrollButton.SetParentControl(this); - - _totalHeight = DrawAreaWithParentOffset.Height; + case ScrollBarColors.LightOnLight: vertOff = 0; break; + case ScrollBarColors.LightOnMed: vertOff = 105; break; + case ScrollBarColors.LightOnDark: vertOff = 180; break; + case ScrollBarColors.DarkOnDark: vertOff = 255; break; + default: throw new ArgumentOutOfRangeException(nameof(palette)); } - public ScrollBar(Vector2 locationRelativeToParent, Texture2D backgroundTexture, Rectangle? backgroundTextureSource, ScrollBarColors palette, INativeGraphicsManager nativeGraphicsManager) - : this(locationRelativeToParent, - (backgroundTextureSource.HasValue ? backgroundTextureSource.Value.Size : backgroundTexture.Bounds.Size).ToVector2(), - palette, - nativeGraphicsManager) - { - _backgroundTexture = backgroundTexture; - _backgroundTextureSource = backgroundTextureSource; + //regions based on verticle offset (which is based on the chosen palette) + upArrows[0] = new Rectangle(0, vertOff + 15 * 3, 16, 15); + upArrows[1] = new Rectangle(0, vertOff + 15 * 4, 16, 15); + downArrows[0] = new Rectangle(0, vertOff + 15, 16, 15); + downArrows[1] = new Rectangle(0, vertOff + 15 * 2, 16, 15); + var scrollBox = new Rectangle(0, vertOff, 16, 15); - // assume vertical scrollbar : center on background image - _upButton.DrawPosition = new Vector2((DrawArea.Width - _upButton.DrawArea.Width) / 2, _upButton.DrawPosition.Y + 1); - _downButton.DrawPosition = new Vector2((DrawArea.Width - _downButton.DrawArea.Width) / 2, _downButton.DrawPosition.Y); - _scrollButton.DrawPosition = new Vector2((DrawArea.Width - _scrollButton.DrawArea.Width) / 2, _scrollButton.DrawPosition.Y); - } + _upButton = new XNAButton(scrollSpriteSheet, Vector2.Zero, upArrows[0], upArrows[1]); + _upButton.OnClick += arrowClicked; + _upButton.SetParentControl(this); - public override void Initialize() - { - _upButton.Initialize(); - _downButton.Initialize(); - _scrollButton.Initialize(); + _downButton = new XNAButton(scrollSpriteSheet, new Vector2(0, size.Y - 15), downArrows[0], downArrows[1]); + _downButton.OnClick += arrowClicked; + _downButton.SetParentControl(this); - base.Initialize(); - } + _scrollButton = new XNAButton(scrollSpriteSheet, new Vector2(0, 15), scrollBox, scrollBox); + _scrollButton.OnClickDrag += OnScrollButtonDragged; + _scrollButton.SetParentControl(this); - public void UpdateDimensions(int numberOfLines) - { - _totalHeight = numberOfLines; - } + _totalHeight = DrawAreaWithParentOffset.Height; + } - public void ScrollToTop() - { - ScrollOffset = 0; - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawArea.X, _upButton.DrawArea.Height); - } + public ScrollBar(Vector2 locationRelativeToParent, Texture2D backgroundTexture, Rectangle? backgroundTextureSource, ScrollBarColors palette, INativeGraphicsManager nativeGraphicsManager) + : this(locationRelativeToParent, + (backgroundTextureSource.HasValue ? backgroundTextureSource.Value.Size : backgroundTexture.Bounds.Size).ToVector2(), + palette, + nativeGraphicsManager) + { + _backgroundTexture = backgroundTexture; + _backgroundTextureSource = backgroundTextureSource; - public void ScrollToEnd() - { - while (ScrollOffset < _totalHeight - LinesToRender) - arrowClicked(_downButton, new EventArgs()); - } + // assume vertical scrollbar : center on background image + _upButton.DrawPosition = new Vector2((DrawArea.Width - _upButton.DrawArea.Width) / 2, _upButton.DrawPosition.Y + 1); + _downButton.DrawPosition = new Vector2((DrawArea.Width - _downButton.DrawArea.Width) / 2, _downButton.DrawPosition.Y); + _scrollButton.DrawPosition = new Vector2((DrawArea.Width - _scrollButton.DrawArea.Width) / 2, _scrollButton.DrawPosition.Y); + } - public void SetScrollOffset(int offset) - { - ScrollOffset = offset; - } + public override void Initialize() + { + _upButton.Initialize(); + _downButton.Initialize(); + _scrollButton.Initialize(); - public void SetDownArrowFlashSpeed(int milliseconds) - { - _downButton.FlashSpeed = milliseconds; - } + base.Initialize(); + } + + public void UpdateDimensions(int numberOfLines) + { + _totalHeight = numberOfLines; + } + + public void ScrollToTop() + { + ScrollOffset = 0; + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawArea.X, _upButton.DrawArea.Height); + } + + public void ScrollToEnd() + { + while (ScrollOffset < _totalHeight - LinesToRender) + arrowClicked(_downButton, new EventArgs()); + } - protected override void OnDrawControl(GameTime gameTime) + public void SetScrollOffset(int offset) + { + ScrollOffset = offset; + } + + public void SetDownArrowFlashSpeed(int milliseconds) + { + _downButton.FlashSpeed = milliseconds; + } + + protected override void OnDrawControl(GameTime gameTime) + { + if (_backgroundTexture != null) { - if (_backgroundTexture != null) - { - _spriteBatch.Begin(); - _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _backgroundTextureSource, Color.White); - _spriteBatch.End(); - } - - base.OnDrawControl(gameTime); + _spriteBatch.Begin(); + _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _backgroundTextureSource, Color.White); + _spriteBatch.End(); } - //the point of arrowClicked and scrollDragged is to respond to input on the three buttons in such - // a way that ScrollOffset is updated and the Y coordinate for the scroll box is updated. - // ScrollOffset provides a value that is used within the EOScrollDialog.Draw method. - // The Y coordinate for the scroll box determines where it is drawn. - private void arrowClicked(object btn, EventArgs e) + base.OnDrawControl(gameTime); + } + + //the point of arrowClicked and scrollDragged is to respond to input on the three buttons in such + // a way that ScrollOffset is updated and the Y coordinate for the scroll box is updated. + // ScrollOffset provides a value that is used within the EOScrollDialog.Draw method. + // The Y coordinate for the scroll box determines where it is drawn. + private void arrowClicked(object btn, EventArgs e) + { + //_totalHeight contains the number of lines to render + //any less than LinesToRender shouldn't scroll + if (_totalHeight <= LinesToRender) + return; + + if (btn == _upButton) { - //_totalHeight contains the number of lines to render - //any less than LinesToRender shouldn't scroll - if (_totalHeight <= LinesToRender) + if (ScrollOffset > 0) + ScrollOffset--; + else return; + } + else if (btn == _downButton) + { + if (_downButton.FlashSpeed.HasValue) + _downButton.FlashSpeed = null; //as soon as it is clicked, stop flashing - if (btn == _upButton) - { - if (ScrollOffset > 0) - ScrollOffset--; - else - return; - } - else if (btn == _downButton) - { - if (_downButton.FlashSpeed.HasValue) - _downButton.FlashSpeed = null; //as soon as it is clicked, stop flashing - - if (ScrollOffset < _totalHeight - LinesToRender) - ScrollOffset++; - else - return; - } + if (ScrollOffset < _totalHeight - LinesToRender) + ScrollOffset++; else - { return; - } - - var pixelsPerLine = (float)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / (_totalHeight - LinesToRender); - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, _scrollButton.DrawArea.Height + pixelsPerLine * ScrollOffset); - if (_scrollButton.DrawPosition.Y > scrollArea.Height - _scrollButton.DrawArea.Height) - { - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, scrollArea.Height - _scrollButton.DrawArea.Height); - } + } + else + { + return; } - private void OnScrollButtonDragged(object btn, MouseEventArgs e) + var pixelsPerLine = (float)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / (_totalHeight - LinesToRender); + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, _scrollButton.DrawArea.Height + pixelsPerLine * ScrollOffset); + if (_scrollButton.DrawPosition.Y > scrollArea.Height - _scrollButton.DrawArea.Height) { - if (_downButton.FlashSpeed.HasValue) - _downButton.FlashSpeed = null; //as soon as we are dragged, stop flashing + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, scrollArea.Height - _scrollButton.DrawArea.Height); + } + } - var y = e.Position.Y - (DrawAreaWithParentOffset.Y + _scrollButton.DrawArea.Height / 2); + private void OnScrollButtonDragged(object btn, MouseEventArgs e) + { + if (_downButton.FlashSpeed.HasValue) + _downButton.FlashSpeed = null; //as soon as we are dragged, stop flashing - if (y < _upButton.DrawAreaWithParentOffset.Height) - y = _upButton.DrawAreaWithParentOffset.Height + 1; - else if (y > scrollArea.Height - _scrollButton.DrawArea.Height) - y = scrollArea.Height - _scrollButton.DrawArea.Height; + var y = e.Position.Y - (DrawAreaWithParentOffset.Y + _scrollButton.DrawArea.Height / 2); - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, y); + if (y < _upButton.DrawAreaWithParentOffset.Height) + y = _upButton.DrawAreaWithParentOffset.Height + 1; + else if (y > scrollArea.Height - _scrollButton.DrawArea.Height) + y = scrollArea.Height - _scrollButton.DrawArea.Height; - if (_totalHeight <= LinesToRender) - return; + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, y); - var pixelsPerLine = (double)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / (_totalHeight - LinesToRender); - ScrollOffset = (int)Math.Round((y - _scrollButton.DrawArea.Height) / pixelsPerLine); - } + if (_totalHeight <= LinesToRender) + return; - protected override bool HandleMouseWheelMoved(IXNAControl control, MouseEventArgs eventArgs) - { - if (_totalHeight <= LinesToRender) - return false; + var pixelsPerLine = (double)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / (_totalHeight - LinesToRender); + ScrollOffset = (int)Math.Round((y - _scrollButton.DrawArea.Height) / pixelsPerLine); + } - //value must be /-120, otherwise you get "Natural" (smooth) scroll. We'll have none of that. - var dif = eventArgs.ScrollWheelDelta / -120; - if ((dif < 0 && dif + ScrollOffset >= 0) || (dif > 0 && ScrollOffset + dif <= _totalHeight - LinesToRender)) - { - ScrollOffset += dif; + protected override bool HandleMouseWheelMoved(IXNAControl control, MouseEventArgs eventArgs) + { + if (_totalHeight <= LinesToRender) + return false; - var pixelsPerLine = (float)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / - (_totalHeight - LinesToRender); - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, _scrollButton.DrawArea.Height + pixelsPerLine * ScrollOffset); + //value must be /-120, otherwise you get "Natural" (smooth) scroll. We'll have none of that. + var dif = eventArgs.ScrollWheelDelta / -120; + if ((dif < 0 && dif + ScrollOffset >= 0) || (dif > 0 && ScrollOffset + dif <= _totalHeight - LinesToRender)) + { + ScrollOffset += dif; - if (_scrollButton.DrawPosition.Y > scrollArea.Height - _scrollButton.DrawArea.Height) - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, scrollArea.Height - _scrollButton.DrawArea.Height); - } + var pixelsPerLine = (float)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / + (_totalHeight - LinesToRender); + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, _scrollButton.DrawArea.Height + pixelsPerLine * ScrollOffset); - return true; + if (_scrollButton.DrawPosition.Y > scrollArea.Height - _scrollButton.DrawArea.Height) + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, scrollArea.Height - _scrollButton.DrawArea.Height); } + + return true; } } \ No newline at end of file diff --git a/EndlessClient/UIControls/StatusBarLabel.cs b/EndlessClient/UIControls/StatusBarLabel.cs index 4a4ef72ea..84205c57a 100644 --- a/EndlessClient/UIControls/StatusBarLabel.cs +++ b/EndlessClient/UIControls/StatusBarLabel.cs @@ -7,76 +7,75 @@ using System; using XNAControls; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +public class StatusBarLabel : XNALabel { - public class StatusBarLabel : XNALabel - { - private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000; + private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000; - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly IStatusLabelTextProvider _statusLabelTextProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly IStatusLabelTextProvider _statusLabelTextProvider; - private readonly Rectangle _leftSide = new Rectangle(58, 451, 12, 20); - private readonly Rectangle _background = new Rectangle(70, 451, 548, 20); - private readonly Rectangle _rightSide = new Rectangle(618, 451, 12, 20); + private readonly Rectangle _leftSide = new Rectangle(58, 451, 12, 20); + private readonly Rectangle _background = new Rectangle(70, 451, 548, 20); + private readonly Rectangle _rightSide = new Rectangle(618, 451, 12, 20); - private readonly Texture2D _hudBackground; + private readonly Texture2D _hudBackground; - public StatusBarLabel(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - IStatusLabelTextProvider statusLabelTextProvider) - : base(Constants.FontSize07) - { - _nativeGraphicsManager = nativeGraphicsManager; - _clientWindowSizeProvider = clientWindowSizeProvider; - _statusLabelTextProvider = statusLabelTextProvider; + public StatusBarLabel(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + IStatusLabelTextProvider statusLabelTextProvider) + : base(Constants.FontSize07) + { + _nativeGraphicsManager = nativeGraphicsManager; + _clientWindowSizeProvider = clientWindowSizeProvider; + _statusLabelTextProvider = statusLabelTextProvider; - if (_clientWindowSizeProvider.Resizable) - { - DrawArea = new Rectangle(40, _clientWindowSizeProvider.Height - 15, 1, 1); - _clientWindowSizeProvider.GameWindowSizeChanged += (_, _) => DrawArea = new Rectangle(40, _clientWindowSizeProvider.Height - 15, 1, 1); + if (_clientWindowSizeProvider.Resizable) + { + DrawArea = new Rectangle(40, _clientWindowSizeProvider.Height - 15, 1, 1); + _clientWindowSizeProvider.GameWindowSizeChanged += (_, _) => DrawArea = new Rectangle(40, _clientWindowSizeProvider.Height - 15, 1, 1); - _hudBackground = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false, true); - } - else - { - DrawArea = new Rectangle(97, _clientWindowSizeProvider.Height - 26, 1, 1); - } + _hudBackground = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false, true); } - - protected override void OnUnconditionalUpdateControl(GameTime gameTime) + else { - if (Text != _statusLabelTextProvider.StatusText) - { - Text = _statusLabelTextProvider.StatusText; - } - - if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS) - { - Text = string.Empty; - } + DrawArea = new Rectangle(97, _clientWindowSizeProvider.Height - 26, 1, 1); + } + } - base.OnUnconditionalUpdateControl(gameTime); + protected override void OnUnconditionalUpdateControl(GameTime gameTime) + { + if (Text != _statusLabelTextProvider.StatusText) + { + Text = _statusLabelTextProvider.StatusText; } - protected override void OnDrawControl(GameTime gameTime) + if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS) { - if (_clientWindowSizeProvider.Resizable) - { - var bgDrawArea = new Rectangle(0, _clientWindowSizeProvider.Height - 20, _clientWindowSizeProvider.Width, 20); + Text = string.Empty; + } + + base.OnUnconditionalUpdateControl(gameTime); + } - _spriteBatch.Begin(samplerState: SamplerState.LinearWrap); - _spriteBatch.Draw(_hudBackground, bgDrawArea, _background, Color.White); - _spriteBatch.End(); + protected override void OnDrawControl(GameTime gameTime) + { + if (_clientWindowSizeProvider.Resizable) + { + var bgDrawArea = new Rectangle(0, _clientWindowSizeProvider.Height - 20, _clientWindowSizeProvider.Width, 20); - _spriteBatch.Begin(); - _spriteBatch.Draw(_hudBackground, bgDrawArea.Location.ToVector2(), _leftSide, Color.White); - _spriteBatch.Draw(_hudBackground, new Vector2(_clientWindowSizeProvider.Width - _rightSide.Width, bgDrawArea.Y), _rightSide, Color.White); - _spriteBatch.End(); - } + _spriteBatch.Begin(samplerState: SamplerState.LinearWrap); + _spriteBatch.Draw(_hudBackground, bgDrawArea, _background, Color.White); + _spriteBatch.End(); - base.OnDrawControl(gameTime); + _spriteBatch.Begin(); + _spriteBatch.Draw(_hudBackground, bgDrawArea.Location.ToVector2(), _leftSide, Color.White); + _spriteBatch.Draw(_hudBackground, new Vector2(_clientWindowSizeProvider.Width - _rightSide.Width, bgDrawArea.Y), _rightSide, Color.White); + _spriteBatch.End(); } + + base.OnDrawControl(gameTime); } } \ No newline at end of file diff --git a/EndlessClient/UIControls/TimeLabel.cs b/EndlessClient/UIControls/TimeLabel.cs index 38c0b9e3a..98bf3837c 100644 --- a/EndlessClient/UIControls/TimeLabel.cs +++ b/EndlessClient/UIControls/TimeLabel.cs @@ -4,39 +4,38 @@ using System; using XNAControls; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +public class TimeLabel : XNALabel { - public class TimeLabel : XNALabel + private DateTime _lastUpdateTime; + + public TimeLabel(IClientWindowSizeProvider windowSizeProvider) + : base(Constants.FontSize07) { - private DateTime _lastUpdateTime; + _lastUpdateTime = DateTime.Now; + DrawArea = GetPositionBasedOnWindowSize(windowSizeProvider); + windowSizeProvider.GameWindowSizeChanged += (_, _) => DrawArea = GetPositionBasedOnWindowSize(windowSizeProvider); + } - public TimeLabel(IClientWindowSizeProvider windowSizeProvider) - : base(Constants.FontSize07) + protected override void OnUpdateControl(GameTime gameTime) + { + if (DateTime.Now.Second != _lastUpdateTime.Second) { + Text = $"{DateTime.Now.Hour,2:D2}:{DateTime.Now.Minute,2:D2}:{DateTime.Now.Second,2:D2}"; + _lastUpdateTime = DateTime.Now; - DrawArea = GetPositionBasedOnWindowSize(windowSizeProvider); - windowSizeProvider.GameWindowSizeChanged += (_, _) => DrawArea = GetPositionBasedOnWindowSize(windowSizeProvider); } - protected override void OnUpdateControl(GameTime gameTime) - { - if (DateTime.Now.Second != _lastUpdateTime.Second) - { - Text = $"{DateTime.Now.Hour,2:D2}:{DateTime.Now.Minute,2:D2}:{DateTime.Now.Second,2:D2}"; - - _lastUpdateTime = DateTime.Now; - } - - base.OnUpdateControl(gameTime); - } + base.OnUpdateControl(gameTime); + } - private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider windowSizeProvider) - { - //original location: 558, 456 - var xLoc = windowSizeProvider.Width - 82; - var yLoc = windowSizeProvider.Height - (windowSizeProvider.Resizable ? 15 : 26); + private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider windowSizeProvider) + { + //original location: 558, 456 + var xLoc = windowSizeProvider.Width - 82; + var yLoc = windowSizeProvider.Height - (windowSizeProvider.Resizable ? 15 : 26); - return new Rectangle(xLoc, yLoc, 1, 1); - } + return new Rectangle(xLoc, yLoc, 1, 1); } } \ No newline at end of file diff --git a/EndlessClient/UIControls/XnaControlSoundMapper.cs b/EndlessClient/UIControls/XnaControlSoundMapper.cs index 880c32796..e33f70a96 100644 --- a/EndlessClient/UIControls/XnaControlSoundMapper.cs +++ b/EndlessClient/UIControls/XnaControlSoundMapper.cs @@ -5,42 +5,41 @@ using Optional; using XNAControls; -namespace EndlessClient.UIControls +namespace EndlessClient.UIControls; + +[AutoMappedType] +public class XnaControlSoundMapper : IXnaControlSoundMapper { - [AutoMappedType] - public class XnaControlSoundMapper : IXnaControlSoundMapper - { - private readonly IConfigurationProvider _configurationProvider; - private readonly ISfxPlayer _sfxPlayer; + private readonly IConfigurationProvider _configurationProvider; + private readonly ISfxPlayer _sfxPlayer; - public XnaControlSoundMapper(IConfigurationProvider configurationProvider, - ISfxPlayer sfxPlayer) - { - _configurationProvider = configurationProvider; - _sfxPlayer = sfxPlayer; - } + public XnaControlSoundMapper(IConfigurationProvider configurationProvider, + ISfxPlayer sfxPlayer) + { + _configurationProvider = configurationProvider; + _sfxPlayer = sfxPlayer; + } - public void BindSoundToControl(IGameComponent component, Option soundEffectOverride = default) - { - soundEffectOverride.MatchSome(x => SetupSpecificSound((dynamic)component, x)); - soundEffectOverride.MatchNone(() => SetupSound((dynamic)component)); - } + public void BindSoundToControl(IGameComponent component, Option soundEffectOverride = default) + { + soundEffectOverride.MatchSome(x => SetupSpecificSound((dynamic)component, x)); + soundEffectOverride.MatchNone(() => SetupSound((dynamic)component)); + } - private void SetupSound(IXNAButton button) => SetupSpecificSound(button, SoundEffectID.ButtonClick); - private void SetupSpecificSound(IXNAButton button, SoundEffectID sound) => button.OnClick += (_, _) => _sfxPlayer.PlaySfx(sound); + private void SetupSound(IXNAButton button) => SetupSpecificSound(button, SoundEffectID.ButtonClick); + private void SetupSpecificSound(IXNAButton button, SoundEffectID sound) => button.OnClick += (_, _) => _sfxPlayer.PlaySfx(sound); - private void SetupSound(IXNATextBox textBox) => SetupSpecificSound(textBox, SoundEffectID.TextBoxFocus); - private void SetupSpecificSound(IXNATextBox textBox, SoundEffectID sound) => textBox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(sound); + private void SetupSound(IXNATextBox textBox) => SetupSpecificSound(textBox, SoundEffectID.TextBoxFocus); + private void SetupSpecificSound(IXNATextBox textBox, SoundEffectID sound) => textBox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(sound); - private void SetupSound(CreateCharacterControl characterControl) => SetupSpecificSound(characterControl, SoundEffectID.TextBoxFocus); - private void SetupSpecificSound(CreateCharacterControl characterControl, SoundEffectID sound) => characterControl.Clicked += (_, _) => _sfxPlayer.PlaySfx(sound); + private void SetupSound(CreateCharacterControl characterControl) => SetupSpecificSound(characterControl, SoundEffectID.TextBoxFocus); + private void SetupSpecificSound(CreateCharacterControl characterControl, SoundEffectID sound) => characterControl.Clicked += (_, _) => _sfxPlayer.PlaySfx(sound); - private void SetupSound(object unmatched) { } - private void SetupSpecificSound(object unmatched, SoundEffectID sound) { } - } + private void SetupSound(object unmatched) { } + private void SetupSpecificSound(object unmatched, SoundEffectID sound) { } +} - public interface IXnaControlSoundMapper - { - void BindSoundToControl(IGameComponent component, Option soundEffectOverride = default); - } +public interface IXnaControlSoundMapper +{ + void BindSoundToControl(IGameComponent component, Option soundEffectOverride = default); } \ No newline at end of file From b486c1582e9d11f07083a9b60a5d2e8a5ca99598 Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Wed, 31 Jul 2024 21:41:25 +0100 Subject: [PATCH 03/11] Block scoped using --- .editorconfig | 2 +- BatchMap/Program.cs | 473 ++++----- BatchPub/Program.cs | 25 +- BatchPub/frmMain.cs | 725 ++++++------- EOBot/ArgumentsParser.cs | 331 +++--- EOBot/BotBase.cs | 119 +-- EOBot/BotException.cs | 9 +- EOBot/BotFramework.cs | 211 ++-- EOBot/BotHelper.cs | 171 +-- EOBot/ConsoleHelper.cs | 127 +-- EOBot/DependencyMaster.cs | 9 +- EOBot/IBot.cs | 33 +- EOBot/IBotFactory.cs | 9 +- EOBot/Interpreter/BotInterpreter.cs | 127 +-- EOBot/Interpreter/BotScriptErrorException.cs | 15 +- EOBot/Interpreter/BotToken.cs | 31 +- EOBot/Interpreter/BotTokenParser.cs | 369 +++---- EOBot/Interpreter/BotTokenType.cs | 63 +- .../BuiltInIdentifierConfigurator.cs | 521 ++++----- .../Extensions/ProgramStateExtensions.cs | 35 +- .../Extensions/SymbolTableExtensions.cs | 67 +- EOBot/Interpreter/IdentifierBotToken.cs | 21 +- .../Interpreter/States/AssignmentEvaluator.cs | 141 +-- EOBot/Interpreter/States/BaseEvaluator.cs | 151 +-- EOBot/Interpreter/States/BlockEvaluator.cs | 157 +-- EOBot/Interpreter/States/EvalResult.cs | 31 +- .../Interpreter/States/ExpressionEvaluator.cs | 343 +++--- .../States/ExpressionTailEvaluator.cs | 31 +- EOBot/Interpreter/States/FunctionEvaluator.cs | 281 ++--- EOBot/Interpreter/States/GotoEvaluator.cs | 33 +- EOBot/Interpreter/States/IScriptEvaluator.cs | 9 +- EOBot/Interpreter/States/IfEvaluator.cs | 111 +- EOBot/Interpreter/States/KeywordEvaluator.cs | 29 +- EOBot/Interpreter/States/LabelEvaluator.cs | 17 +- EOBot/Interpreter/States/OperandEvaluator.cs | 29 +- EOBot/Interpreter/States/ProgramState.cs | 163 +-- EOBot/Interpreter/States/ScriptEvaluator.cs | 27 +- .../Interpreter/States/StatementEvaluator.cs | 41 +- .../States/StatementListEvaluator.cs | 25 +- EOBot/Interpreter/States/VariableEvaluator.cs | 89 +- EOBot/Interpreter/States/WhileEvaluator.cs | 57 +- EOBot/Interpreter/VariableBotToken.cs | 17 +- EOBot/Interpreter/Variables/ArrayVariable.cs | 33 +- EOBot/Interpreter/Variables/AsyncFunction.cs | 177 ++-- .../Variables/AsyncVoidFunction.cs | 177 ++-- EOBot/Interpreter/Variables/BoolVariable.cs | 23 +- EOBot/Interpreter/Variables/Function.cs | 177 ++-- EOBot/Interpreter/Variables/ICallable.cs | 37 +- EOBot/Interpreter/Variables/IIdentifiable.cs | 9 +- EOBot/Interpreter/Variables/IVariable.cs | 17 +- EOBot/Interpreter/Variables/IntVariable.cs | 23 +- EOBot/Interpreter/Variables/ObjectVariable.cs | 47 +- .../Variables/PredefinedIdentifiers.cs | 87 +- EOBot/Interpreter/Variables/StringVariable.cs | 23 +- .../Variables/UndefinedVariable.cs | 17 +- EOBot/Interpreter/Variables/VoidFunction.cs | 177 ++-- EOBot/NamesList.cs | 89 +- EOBot/Program.cs | 527 +++++----- EOBot/ScriptedBot.cs | 73 +- EOBot/ScriptedBotFactory.cs | 23 +- EOBot/TrainerBot.cs | 601 +++++------ EOBot/TrainerBotFactory.cs | 23 +- .../ConfigFileLoadActionsTest.cs | 189 ++-- EOLib.Config.Test/IniReaderTest.cs | 477 ++++----- .../GraphicsDeviceTestHelper.cs | 53 +- .../NativeGraphicsLoaderTest.cs | 99 +- .../NativeGraphicsManagerTest.cs | 353 +++---- EOLib.Graphics.Test/PEFileCollectionTest.cs | 105 +- EOLib.Graphics.Test/RectangleExtensionTest.cs | 57 +- EOLib.Graphics/ColorConstants.cs | 21 +- EOLib.Graphics/GFXTypes.cs | 207 ++-- EOLib.Graphics/IGraphicsDeviceRepository.cs | 35 +- EOLib.Graphics/INativeGraphicsLoader.cs | 9 +- EOLib.Graphics/INativeGraphicsManager.cs | 29 +- EOLib.Graphics/LibraryLoadException.cs | 23 +- EOLib.Graphics/NativeGraphicsLoader.cs | 47 +- EOLib.Graphics/NativeGraphicsManager.cs | 183 ++-- EOLib.Graphics/PEFileCollection.cs | 45 +- EOLib.Graphics/RectangleExtension.cs | 45 +- EOLib.IO.Test/EIFRecordExtensionsTest.cs | 75 +- EOLib.IO.Test/Map/MapFilePropertiesTest.cs | 221 ++-- EOLib.IO.Test/Map/MapFileTest.cs | 259 ++--- .../Map/MapStringEncoderServiceTest.cs | 127 +-- EOLib.IO.Test/Pub/BasePubFileTest.cs | 323 +++--- EOLib.IO.Test/Pub/ECFFileTest.cs | 15 +- EOLib.IO.Test/Pub/ECFRecordTest.cs | 39 +- EOLib.IO.Test/Pub/EIFFileTest.cs | 15 +- EOLib.IO.Test/Pub/EIFRecordTest.cs | 39 +- EOLib.IO.Test/Pub/ENFFileTest.cs | 15 +- EOLib.IO.Test/Pub/ENFRecordTest.cs | 39 +- EOLib.IO.Test/Pub/ESFFileTest.cs | 15 +- EOLib.IO.Test/Pub/ESFRecordTest.cs | 39 +- .../Serializers/PubFileSerializerTest.cs | 231 ++-- .../Serializers/PubRecordSerializerTest.cs | 81 +- .../DataFileLoadActionsTest.cs | 117 ++- .../EDFLoaderServiceTest.cs | 303 +++--- .../LocalizedStringServiceTest.cs | 245 ++--- .../FileTransfer/FileRequestServiceTest.cs | 429 ++++---- .../TestHelpers/PacketSendServiceHelpers.cs | 31 +- EndlessClient/Audio/AudioActions.cs | 107 +- EndlessClient/Audio/MfxPlayer.cs | 197 ++-- EndlessClient/Audio/SfxPlayer.cs | 155 +-- EndlessClient/Audio/SoundEffectID.cs | 203 ++-- EndlessClient/Audio/WAVFileValidator.cs | 41 +- EndlessClient/Content/ContentProvider.cs | 249 ++--- .../ControlSets/BackButtonControlSet.cs | 89 +- EndlessClient/ControlSets/BaseControlSet.cs | 175 ++-- .../ControlSets/ControlSetFactory.cs | 171 +-- .../ControlSets/CreateAccountControlSet.cs | 331 +++--- EndlessClient/ControlSets/EmptyControlSet.cs | 43 +- .../ControlSets/GameControlIdentifier.cs | 65 +- EndlessClient/ControlSets/IControlSet.cs | 65 +- .../ControlSets/IControlSetFactory.cs | 17 +- .../ControlSets/IControlSetRepository.cs | 35 +- .../ControlSets/IHudControlProvider.cs | 93 +- EndlessClient/ControlSets/InGameControlSet.cs | 93 +- .../ControlSets/InitialControlSet.cs | 263 ++--- .../ControlSets/IntermediateControlSet.cs | 113 +- .../ControlSets/LoggedInControlSet.cs | 149 +-- .../ControlSets/LoginPromptControlSet.cs | 241 ++--- .../ControlSets/ViewCreditsControlSet.cs | 57 +- .../Controllers/AccountController.cs | 183 ++-- .../Controllers/ArrowKeyController.cs | 217 ++-- EndlessClient/Controllers/BardController.cs | 57 +- .../CharacterManagementController.cs | 227 ++-- EndlessClient/Controllers/ChatController.cs | 159 +-- .../Controllers/ControlKeyController.cs | 143 +-- .../Controllers/FunctionKeyController.cs | 175 ++-- .../Controllers/InventoryController.cs | 651 ++++++------ EndlessClient/Controllers/LoginController.cs | 481 ++++----- .../Controllers/MainButtonController.cs | 259 ++--- .../Controllers/MapInteractionController.cs | 487 ++++----- .../Controllers/NPCInteractionController.cs | 125 +-- EndlessClient/Controllers/NumPadController.cs | 51 +- .../Controllers/TrainingController.cs | 79 +- .../Actions/AccountDialogDisplayActions.cs | 135 +-- .../Dialogs/Actions/CharacterDialogActions.cs | 117 ++- .../Actions/ErrorDialogDisplayAction.cs | 263 ++--- .../Dialogs/Actions/FirstTimePlayerActions.cs | 43 +- EndlessClient/Dialogs/Actions/HelpActions.cs | 155 +-- .../Actions/IAccountDialogDisplayActions.cs | 19 +- .../Actions/ICharacterDialogActions.cs | 17 +- .../Actions/IErrorDialogDisplayAction.cs | 19 +- .../Dialogs/Actions/InGameDialogActions.cs | 791 +++++++------- .../Dialogs/Actions/NpcInteractionActions.cs | 347 +++--- .../Dialogs/Actions/PartyDialogActions.cs | 121 +-- .../Dialogs/Actions/TradeDialogActions.cs | 127 +-- .../Dialogs/ActiveDialogRepository.cs | 269 ++--- EndlessClient/Dialogs/BankAccountDialog.cs | 389 +++---- EndlessClient/Dialogs/BarberDialog.cs | 309 +++--- EndlessClient/Dialogs/BardDialog.cs | 149 +-- EndlessClient/Dialogs/BaseEODialog.cs | 61 +- EndlessClient/Dialogs/BoardDialog.cs | 477 ++++----- EndlessClient/Dialogs/BookDialog.cs | 171 +-- EndlessClient/Dialogs/ChangePasswordDialog.cs | 211 ++-- EndlessClient/Dialogs/ChestDialog.cs | 167 +-- .../Dialogs/CreateCharacterDialog.cs | 301 +++--- EndlessClient/Dialogs/EODialogButton.cs | 13 +- EndlessClient/Dialogs/EOMessageBox.cs | 201 ++-- .../Extensions/EquipLocationExtensions.cs | 43 +- .../Factories/BankAccountDialogFactory.cs | 119 +-- .../Dialogs/Factories/BarberDialogFactory.cs | 111 +- .../Dialogs/Factories/BardDialogFactory.cs | 47 +- .../Dialogs/Factories/BoardDialogFactory.cs | 103 +- .../Dialogs/Factories/BookDialogFactory.cs | 59 +- .../Factories/ChangePasswordDialogFactory.cs | 73 +- .../Dialogs/Factories/ChestDialogFactory.cs | 111 +- .../CreateAccountProgressDialogFactory.cs | 69 +- .../CreateAccountWarningDialogFactory.cs | 67 +- .../Factories/CreateCharacterDialogFactory.cs | 79 +- .../Dialogs/Factories/EOMessageBoxFactory.cs | 161 +-- .../FriendIgnoreListDialogFactory.cs | 207 ++-- .../Factories/GameLoadingDialogFactory.cs | 55 +- .../Dialogs/Factories/HelpDialogFactory.cs | 115 +- .../Factories/IChangePasswordDialogFactory.cs | 9 +- .../Dialogs/Factories/IEOMessageBoxFactory.cs | 45 +- .../Factories/InnkeeperDialogFactory.cs | 103 +- .../Factories/ItemTransferDialogFactory.cs | 91 +- .../Dialogs/Factories/JukeboxDialogFactory.cs | 103 +- .../Dialogs/Factories/LawDialogFactory.cs | 95 +- .../Dialogs/Factories/LockerDialogFactory.cs | 111 +- .../Factories/PaperdollDialogFactory.cs | 115 +- .../Dialogs/Factories/QuestDialogFactory.cs | 71 +- .../Factories/QuestStatusDialogFactory.cs | 63 +- .../Factories/ScrollingListDialogFactory.cs | 37 +- .../Factories/SessionExpDialogFactory.cs | 71 +- .../Dialogs/Factories/ShopDialogFactory.cs | 119 +-- .../Factories/SkillmasterDialogFactory.cs | 127 +-- .../Factories/TextInputDialogFactory.cs | 69 +- .../Factories/TextInputMultiDialogFactory.cs | 79 +- .../Dialogs/Factories/TradeDialogFactory.cs | 119 +-- .../Dialogs/FriendIgnoreListDialog.cs | 43 +- EndlessClient/Dialogs/GameLoadingDialog.cs | 209 ++-- EndlessClient/Dialogs/InnkeeperDialog.cs | 401 +++---- EndlessClient/Dialogs/ItemTransferDialog.cs | 325 +++--- EndlessClient/Dialogs/JukeboxDialog.cs | 269 ++--- EndlessClient/Dialogs/LawDialog.cs | 323 +++--- EndlessClient/Dialogs/ListDialogItem.cs | 431 ++++---- EndlessClient/Dialogs/LockerDialog.cs | 173 +-- EndlessClient/Dialogs/PaperdollDialog.cs | 229 ++-- EndlessClient/Dialogs/PaperdollDialogItem.cs | 167 +-- EndlessClient/Dialogs/PlayerInfoDialog.cs | 249 ++--- EndlessClient/Dialogs/ProgressDialog.cs | 193 ++-- EndlessClient/Dialogs/QuestDialog.cs | 285 ++--- EndlessClient/Dialogs/QuestStatusDialog.cs | 201 ++-- .../Dialogs/QuestStatusListDialogItem.cs | 197 ++-- EndlessClient/Dialogs/ScrollingListDialog.cs | 945 ++++++++--------- .../Dialogs/ScrollingMessageDialog.cs | 155 +-- .../Dialogs/Services/EODialogButtonService.cs | 83 +- .../Dialogs/Services/EODialogIconService.cs | 87 +- EndlessClient/Dialogs/SessionExpDialog.cs | 189 ++-- EndlessClient/Dialogs/ShopDialog.cs | 641 ++++++------ EndlessClient/Dialogs/SkillmasterDialog.cs | 657 ++++++------ EndlessClient/Dialogs/TextInputDialog.cs | 107 +- EndlessClient/Dialogs/TextMultiInputDialog.cs | 243 ++--- EndlessClient/Dialogs/TradeDialog.cs | 637 +++++------ .../GameExecution/DebugGameRunner.cs | 17 +- EndlessClient/GameExecution/EndlessGame.cs | 425 ++++---- EndlessClient/GameExecution/GameRunnerBase.cs | 201 ++-- .../GameExecution/GameStateActions.cs | 243 ++--- EndlessClient/GameExecution/GameStates.cs | 75 +- EndlessClient/GameExecution/IEndlessGame.cs | 21 +- .../GameExecution/IEndlessGameProvider.cs | 29 +- EndlessClient/GameExecution/IGameRunner.cs | 11 +- .../GameExecution/IGameStateActions.cs | 13 +- .../GameExecution/IGameStateRepository.cs | 29 +- .../GameExecution/ReleaseGameRunner.cs | 171 +-- EndlessClient/HUD/AStarPathFinder.cs | 153 +-- EndlessClient/HUD/Chat/ChatBubbleActions.cs | 65 +- EndlessClient/HUD/Chat/ChatModeCalculator.cs | 55 +- .../HUD/Chat/ChatNotificationActions.cs | 155 +-- EndlessClient/HUD/Chat/ChatPanelTab.cs | 351 +++---- EndlessClient/HUD/Chat/ChatTextBoxActions.cs | 43 +- EndlessClient/HUD/Chat/IChatModeCalculator.cs | 9 +- EndlessClient/HUD/Chat/IChatTextBoxActions.cs | 11 +- .../HUD/Chat/PrivateMessageActions.cs | 109 +- .../HUD/Chat/ServerMessageHandler.cs | 63 +- .../HUD/Controls/DragCompletedEventArgs.cs | 25 +- .../HUD/Controls/DraggablePanelItem.cs | 193 ++-- .../HUD/Controls/HudBackgroundFrame.cs | 97 +- .../HUD/Controls/HudControlIdentifier.cs | 109 +- .../HUD/Controls/HudControlsFactory.cs | 987 +++++++++--------- .../HUD/Controls/IDraggableItemContainer.cs | 9 +- .../HUD/Controls/IHudControlsFactory.cs | 11 +- .../Controls/PeriodicStatUpdaterComponent.cs | 101 +- EndlessClient/HUD/HudButtonController.cs | 227 ++-- EndlessClient/HUD/HudStateActions.cs | 117 ++- EndlessClient/HUD/IHudButtonController.cs | 37 +- EndlessClient/HUD/IHudStateActions.cs | 11 +- EndlessClient/HUD/IStatusLabelSetter.cs | 15 +- .../HUD/IStatusLabelTextRepository.cs | 43 +- EndlessClient/HUD/InGameStates.cs | 31 +- .../HUD/Inventory/InventoryPanelItem.cs | 347 +++--- .../HUD/Inventory/InventoryService.cs | 149 +-- .../HUD/Inventory/InventorySlotRepository.cs | 53 +- .../HUD/Inventory/InventorySpaceValidator.cs | 121 +-- EndlessClient/HUD/ItemNameColorService.cs | 43 +- EndlessClient/HUD/Panels/ActiveSpellsPanel.cs | 933 ++++++++--------- EndlessClient/HUD/Panels/ChatPanel.cs | 201 ++-- EndlessClient/HUD/Panels/DraggableHudPanel.cs | 89 +- EndlessClient/HUD/Panels/HelpPanel.cs | 23 +- EndlessClient/HUD/Panels/HudPanelFactory.cs | 425 ++++---- EndlessClient/HUD/Panels/IHudPanel.cs | 21 +- EndlessClient/HUD/Panels/IHudPanelFactory.cs | 27 +- EndlessClient/HUD/Panels/InventoryPanel.cs | 827 +++++++-------- EndlessClient/HUD/Panels/NewsPanel.cs | 187 ++-- EndlessClient/HUD/Panels/OnlineListPanel.cs | 363 +++---- EndlessClient/HUD/Panels/PartyPanel.cs | 237 ++--- .../HUD/Panels/PassiveSpellsPanel.cs | 23 +- EndlessClient/HUD/Panels/SettingsPanel.cs | 407 ++++---- EndlessClient/HUD/Panels/StatsPanel.cs | 381 +++---- EndlessClient/HUD/Party/PartyPanelMember.cs | 201 ++-- EndlessClient/HUD/Spells/SpellPanelItem.cs | 271 ++--- .../HUD/Spells/SpellSelectActions.cs | 87 +- .../HUD/Spells/SpellSlotDataRepository.cs | 87 +- EndlessClient/HUD/StatusBars/HPStatusBar.cs | 51 +- EndlessClient/HUD/StatusBars/SPStatusBar.cs | 53 +- EndlessClient/HUD/StatusBars/StatusBarBase.cs | 169 +-- EndlessClient/HUD/StatusBars/TNLStatusBar.cs | 83 +- EndlessClient/HUD/StatusBars/TPStatusBar.cs | 53 +- EndlessClient/HUD/StatusLabelSetter.cs | 129 +-- EndlessClient/HUD/UserInterfaceActions.cs | 155 +-- .../Initialization/ConfigInitializer.cs | 25 +- .../EndlessClientInitializer.cs | 145 +-- .../Initialization/GraphicsInitializer.cs | 55 +- .../Initialization/IGameInitializer.cs | 9 +- .../Initialization/LocalizationInitializer.cs | 25 +- EndlessClient/Input/ArrowKeyHandler.cs | 53 +- EndlessClient/Input/ControlKeyHandler.cs | 41 +- .../Input/CurrentUserInputTracker.cs | 35 +- EndlessClient/Input/FunctionKeyHandler.cs | 53 +- EndlessClient/Input/IUserInputRepository.cs | 47 +- .../Input/IUserInputTimeRepository.cs | 33 +- EndlessClient/Input/InputHandlerBase.cs | 145 +-- .../Input/KeyboardStateExtensions.cs | 47 +- EndlessClient/Input/NumPadHandler.cs | 57 +- EndlessClient/Input/PanelShortcutHandler.cs | 81 +- .../Input/PreviousUserInputTracker.cs | 35 +- EndlessClient/Input/UnwalkableTileActions.cs | 285 ++--- .../Input/UnwalkableTileActionsHandler.cs | 91 +- EndlessClient/Input/UserInputHandler.cs | 113 +- .../Input/UserInputHandlerFactory.cs | 111 +- .../Network/PacketHandlerGameComponent.cs | 65 +- .../Network/UnknownEntitiesRequester.cs | 161 +-- EndlessClient/Program.cs | 45 +- .../Character/CharacterAnimationActions.cs | 633 +++++------ .../Rendering/Character/CharacterAnimator.cs | 915 ++++++++-------- .../Rendering/Character/CharacterRenderer.cs | 811 +++++++------- .../Character/CharacterRendererUpdater.cs | 283 ++--- .../Character/CharacterStateCache.cs | 133 +-- .../Rendering/Character/CharacterTextures.cs | 81 +- .../Rendering/Character/ICharacterRenderer.cs | 23 +- .../Character/ICharacterRendererRepository.cs | 65 +- .../Character/ICharacterStateCache.cs | 29 +- .../Rendering/Character/ICharacterTextures.cs | 31 +- .../Rendering/Character/ISpellCaster.cs | 13 +- .../Character/PeriodicEmoteHandler.cs | 389 +++---- .../CharacterProperties/ArmorRenderer.cs | 97 +- .../BaseCharacterPropertyRenderer.cs | 37 +- .../CharacterProperties/BootsRenderer.cs | 123 +-- .../CharacterPropertyRendererBuilder.cs | 137 +-- .../CharacterProperties/EmoteRenderer.cs | 49 +- .../CharacterProperties/FaceRenderer.cs | 73 +- .../HairRenderLocationCalculator.cs | 87 +- .../CharacterProperties/HairRenderer.cs | 35 +- .../CharacterProperties/HatRenderer.cs | 57 +- .../ICharacterPropertyRenderer.cs | 13 +- .../ICharacterPropertyRendererBuilder.cs | 11 +- .../CharacterProperties/ShieldRenderer.cs | 155 +-- .../SkinRenderLocationCalculator.cs | 109 +- .../CharacterProperties/SkinRenderer.cs | 35 +- .../CharacterProperties/WeaponRenderer.cs | 95 +- .../WeaponSlashRenderer.cs | 57 +- EndlessClient/Rendering/Chat/ChatBubble.cs | 307 +++--- .../Rendering/Chat/ChatBubbleFactory.cs | 51 +- .../Rendering/Chat/ChatBubbleTexture.cs | 27 +- .../Chat/ChatBubbleTextureProvider.cs | 61 +- .../Rendering/Chat/ChatColorExtensions.cs | 25 +- .../Rendering/Chat/ChatRenderable.cs | 157 +-- .../Rendering/Chat/ChatRenderableGenerator.cs | 195 ++-- .../Rendering/Chat/IChatRenderable.cs | 13 +- .../Chat/IChatRenderableGenerator.cs | 11 +- .../Rendering/ClientWindowSizeRepository.cs | 157 +-- .../Rendering/ContextMenuRenderer.cs | 525 +++++----- .../Rendering/ContextMenuRepository.cs | 33 +- .../Rendering/DispatcherGameComponent.cs | 51 +- .../Rendering/Effects/EffectAnimationType.cs | 15 +- .../Rendering/Effects/EffectLayer.cs | 13 +- .../Rendering/Effects/EffectRenderer.cs | 307 +++--- .../Effects/EffectRendererFactory.cs | 55 +- .../Rendering/Effects/EffectSpriteInfo.cs | 167 +-- .../Rendering/Effects/EffectSpriteManager.cs | 91 +- .../Rendering/Effects/HardCodedEffect.cs | 27 +- .../Rendering/Effects/IEffectSpriteInfo.cs | 17 +- .../Effects/PositionOffsetEffectMetadata.cs | 17 +- .../Effects/RandomFlickeringEffectMetadata.cs | 17 +- .../Effects/VerticalSlidingEffectMetadata.cs | 13 +- .../Factories/CharacterRendererFactory.cs | 143 +-- .../Factories/ContextMenuRendererFactory.cs | 145 +-- .../Factories/HealthBarRendererFactory.cs | 31 +- .../Factories/ICharacterRendererFactory.cs | 9 +- .../Factories/IMapRendererFactory.cs | 9 +- .../Factories/IRenderTargetFactory.cs | 11 +- .../Rendering/Factories/MapRendererFactory.cs | 153 +-- .../Factories/MouseCursorRendererFactory.cs | 101 +- .../Factories/RenderTargetFactory.cs | 51 +- .../Rendering/GridDrawCoordinateCalculator.cs | 281 ++--- EndlessClient/Rendering/HealthBarRenderer.cs | 245 ++--- .../Rendering/IGameWindowRepository.cs | 27 +- EndlessClient/Rendering/IMapActor.cs | 25 +- .../Rendering/Map/ClickDispatcher.cs | 387 +++---- .../Rendering/Map/ClickDispatcherFactory.cs | 135 +-- .../Rendering/Map/DynamicMapObjectUpdater.cs | 219 ++-- .../Rendering/Map/IMapItemGraphicProvider.cs | 9 +- .../Map/IMapRenderDistanceCalculator.cs | 9 +- EndlessClient/Rendering/Map/IMapRenderer.cs | 23 +- .../Rendering/Map/MapChangedActions.cs | 389 +++---- .../Map/MapEntityRendererProvider.cs | 205 ++-- .../Rendering/Map/MapItemGraphicProvider.cs | 45 +- .../Map/MapObjectBoundsCalculator.cs | 59 +- .../Rendering/Map/MapRenderBounds.cs | 29 +- .../Map/MapRenderDistanceCalculator.cs | 39 +- EndlessClient/Rendering/Map/MapRenderLayer.cs | 35 +- EndlessClient/Rendering/Map/MapRenderer.cs | 841 +++++++-------- .../Rendering/Map/MiniMapRenderer.cs | 435 ++++---- .../Rendering/Map/MiniMapRendererFactory.cs | 87 +- .../BaseMapEntityRenderer.cs | 115 +- .../MapEntityRenderers/GroundLayerRenderer.cs | 151 +-- .../MapEntityRenderers/IMapEntityRenderer.cs | 15 +- .../IMapEntityRendererProvider.cs | 13 +- .../MainCharacterEntityRenderer.cs | 69 +- .../MapItemLayerRenderer.cs | 67 +- .../MapObjectLayerRenderer.cs | 113 +- .../MapEntityRenderers/NPCEntityRenderer.cs | 75 +- .../MapEntityRenderers/OnTopLayerRenderer.cs | 69 +- .../OtherCharacterEntityRenderer.cs | 61 +- .../Overlay2LayerRenderer.cs | 61 +- .../OverlayLayerRenderer.cs | 61 +- .../MapEntityRenderers/RoofLayerRenderer.cs | 69 +- .../MapEntityRenderers/ShadowLayerRenderer.cs | 89 +- .../MapEntityRenderers/WallLayerRenderer.cs | 177 ++-- .../Metadata/EffectMetadataProvider.cs | 107 +- .../Rendering/Metadata/GFXMetadataLoader.cs | 93 +- .../Rendering/Metadata/HatMetadataProvider.cs | 103 +- .../Rendering/Metadata/IMetadataProvider.cs | 13 +- .../Metadata/Models/EffectMetadata.cs | 59 +- .../Rendering/Metadata/Models/HatMetadata.cs | 21 +- .../Rendering/Metadata/Models/IGFXMetadata.cs | 7 +- .../Rendering/Metadata/Models/NPCMetadata.cs | 35 +- .../Metadata/Models/ShieldMetadata.cs | 9 +- .../Metadata/Models/WeaponMetadata.cs | 9 +- .../Rendering/Metadata/NPCMetadataProvider.cs | 379 +++---- .../Metadata/ShieldMetadataProvider.cs | 49 +- .../Metadata/WeaponMetadataProvider.cs | 185 ++-- .../Rendering/MouseCursorRenderer.cs | 503 ++++----- EndlessClient/Rendering/NPC/INPCRenderer.cs | 17 +- EndlessClient/Rendering/NPC/NPCActions.cs | 253 ++--- EndlessClient/Rendering/NPC/NPCAnimator.cs | 201 ++-- EndlessClient/Rendering/NPC/NPCCache.cs | 83 +- EndlessClient/Rendering/NPC/NPCRenderer.cs | 513 ++++----- .../Rendering/NPC/NPCRendererFactory.cs | 113 +- .../Rendering/NPC/NPCRendererRepository.cs | 59 +- .../Rendering/NPC/NPCRendererUpdater.cs | 197 ++-- .../Rendering/PlayerStatusIconRenderer.cs | 145 +-- EndlessClient/Rendering/PointComparer.cs | 19 +- .../Rendering/RenderFrameActionTime.cs | 55 +- .../Rendering/RenderOffsetCalculator.cs | 155 +-- .../Rendering/RendererRepositoryResetter.cs | 57 +- .../Sprites/ArmorShieldSpriteType.cs | 35 +- .../Rendering/Sprites/BootsSpriteType.cs | 23 +- .../Sprites/CharacterSpriteCalculator.cs | 833 +++++++-------- .../Rendering/Sprites/EmoteSpriteType.cs | 37 +- .../Rendering/Sprites/EmptySpriteSheet.cs | 39 +- .../Sprites/ICharacterSpriteCalculator.cs | 27 +- .../Rendering/Sprites/ISpriteSheet.cs | 17 +- .../Rendering/Sprites/NPCSpriteDataCache.cs | 157 +-- .../Rendering/Sprites/NPCSpriteSheet.cs | 107 +- .../Rendering/Sprites/SpriteSheet.cs | 69 +- .../Rendering/Sprites/WeaponSpriteType.cs | 29 +- .../Services/FriendIgnoreListService.cs | 129 +-- .../Subscribers/ArenaEventSubscriber.cs | 143 +-- .../Subscribers/JukeboxEventSubscriber.cs | 27 +- .../Subscribers/LockerEventSubscriber.cs | 37 +- .../MainCharacterEventSubscriber.cs | 147 +-- .../OtherCharacterEventSubscriber.cs | 103 +- .../ServerRebootEventSubscriber.cs | 43 +- EndlessClient/Test/CharacterStateTest.cs | 455 ++++---- EndlessClient/Test/TestModeLauncher.cs | 73 +- EndlessClient/UIControls/BlinkingLabel.cs | 79 +- EndlessClient/UIControls/CharacterControl.cs | 81 +- .../UIControls/CharacterInfoPanel.cs | 399 +++---- .../UIControls/CharacterInfoPanelFactory.cs | 107 +- .../UIControls/ChatModePictureBox.cs | 147 +-- EndlessClient/UIControls/ChatTextBox.cs | 197 ++-- EndlessClient/UIControls/ClickableArea.cs | 53 +- .../UIControls/CreateCharacterControl.cs | 107 +- .../UIControls/ICharacterInfoPanelFactory.cs | 13 +- EndlessClient/UIControls/ScrollBar.cs | 363 +++---- EndlessClient/UIControls/StatusBarLabel.cs | 107 +- EndlessClient/UIControls/TimeLabel.cs | 49 +- .../UIControls/XnaControlSoundMapper.cs | 59 +- 461 files changed, 33194 insertions(+), 32734 deletions(-) diff --git a/.editorconfig b/.editorconfig index b9eae88d8..d2f90518b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -111,7 +111,7 @@ csharp_style_prefer_readonly_struct_member = true:suggestion # Code-block preferences csharp_prefer_braces = true:silent csharp_prefer_simple_using_statement = true:suggestion -csharp_style_namespace_declarations = file_scoped:warning +csharp_style_namespace_declarations = block_scoped:warning csharp_style_prefer_method_group_conversion = true:silent csharp_style_prefer_primary_constructors = true:suggestion csharp_style_prefer_top_level_statements = true:silent diff --git a/BatchMap/Program.cs b/BatchMap/Program.cs index 700ce1067..c88ed8e56 100644 --- a/BatchMap/Program.cs +++ b/BatchMap/Program.cs @@ -8,308 +8,309 @@ using System.IO; using System.Linq; -namespace BatchMap; - -public static class Program +namespace BatchMap { - private static ITypeRegistry _typeRegistry; - private static IPubFileProvider _pubProvider; - private static IMapFileProvider _mapFileProvider; - - private static void Main(string[] args) + public static class Program { - if (args.Length != 3) - { - Console.WriteLine("Usage: BatchMap.exe "); - return; - } + private static ITypeRegistry _typeRegistry; + private static IPubFileProvider _pubProvider; + private static IMapFileProvider _mapFileProvider; - var srcFilePath = args[0]; - var dstFilePath = args[1]; - var pubFilePath = args[2]; - var singleFileProcess = false; - - if (srcFilePath.ToLower().EndsWith(".emf") && !dstFilePath.ToLower().EndsWith(".emf")) + private static void Main(string[] args) { - Console.WriteLine("Invalid: single map cannot be processed into output directory. Specify destination emf file."); - return; - } + if (args.Length != 3) + { + Console.WriteLine("Usage: BatchMap.exe "); + return; + } - if (dstFilePath.ToLower().EndsWith(".emf") && !srcFilePath.ToLower().EndsWith(".emf")) - { - Console.WriteLine("Invalid: map directory cannot be processed into single output map. Specify destination output directory."); - return; - } + var srcFilePath = args[0]; + var dstFilePath = args[1]; + var pubFilePath = args[2]; + var singleFileProcess = false; - if (srcFilePath.ToLower().EndsWith(".emf") && dstFilePath.ToLower().EndsWith(".emf")) - { - singleFileProcess = true; - if (!File.Exists(srcFilePath)) + if (srcFilePath.ToLower().EndsWith(".emf") && !dstFilePath.ToLower().EndsWith(".emf")) { - Console.WriteLine("Invalid input: input file does not exist!"); + Console.WriteLine("Invalid: single map cannot be processed into output directory. Specify destination emf file."); return; } - if (File.Exists(dstFilePath)) + if (dstFilePath.ToLower().EndsWith(".emf") && !srcFilePath.ToLower().EndsWith(".emf")) { - char inp; - do - { - Console.Write("Destination file exists. Overwrite? [y/n] "); - string input = Console.ReadLine() ?? ""; - inp = input.Length > 0 ? input[0] : ' '; - } while (inp != 'y' && inp != 'n' && inp != 'Y' && inp != 'N'); + Console.WriteLine("Invalid: map directory cannot be processed into single output map. Specify destination output directory."); + return; + } - if (inp == 'n' || inp == 'N') + if (srcFilePath.ToLower().EndsWith(".emf") && dstFilePath.ToLower().EndsWith(".emf")) + { + singleFileProcess = true; + if (!File.Exists(srcFilePath)) { - Console.WriteLine("Will not overwrite existing file. Exiting."); + Console.WriteLine("Invalid input: input file does not exist!"); return; } + + if (File.Exists(dstFilePath)) + { + char inp; + do + { + Console.Write("Destination file exists. Overwrite? [y/n] "); + string input = Console.ReadLine() ?? ""; + inp = input.Length > 0 ? input[0] : ' '; + } while (inp != 'y' && inp != 'n' && inp != 'Y' && inp != 'N'); + + if (inp == 'n' || inp == 'N') + { + Console.WriteLine("Will not overwrite existing file. Exiting."); + return; + } + } } - } - else - { - if (!Directory.Exists(srcFilePath) || Directory.GetFiles(srcFilePath, "*.emf").Length == 0) + else { - Console.WriteLine("Invalid input: source directory does not exist or is missing maps!"); - return; - } + if (!Directory.Exists(srcFilePath) || Directory.GetFiles(srcFilePath, "*.emf").Length == 0) + { + Console.WriteLine("Invalid input: source directory does not exist or is missing maps!"); + return; + } - if (Directory.Exists(dstFilePath) && Directory.GetFiles(dstFilePath, "*.emf").Length > 0) - { - char inp; - do + if (Directory.Exists(dstFilePath) && Directory.GetFiles(dstFilePath, "*.emf").Length > 0) { - Console.WriteLine("Destination directory contains emf files. Overwrite? [y/n] "); - string input = Console.ReadLine() ?? ""; - inp = input.Length > 0 ? input[0] : ' '; - } while (inp != 'y' && inp != 'n' && inp != 'Y' && inp != 'N'); + char inp; + do + { + Console.WriteLine("Destination directory contains emf files. Overwrite? [y/n] "); + string input = Console.ReadLine() ?? ""; + inp = input.Length > 0 ? input[0] : ' '; + } while (inp != 'y' && inp != 'n' && inp != 'Y' && inp != 'N'); - if (inp == 'n' || inp == 'N') + if (inp == 'n' || inp == 'N') + { + Console.WriteLine("Will not overwrite existing files. Exiting."); + return; + } + } + else if (!Directory.Exists(dstFilePath)) { - Console.WriteLine("Will not overwrite existing files. Exiting."); - return; + Directory.CreateDirectory(dstFilePath); } } - else if (!Directory.Exists(dstFilePath)) + + SetupDependencies(); + + try + { + var actions = _typeRegistry.Resolve(); + + actions.LoadItemFileByName(Path.Combine(pubFilePath, "dat001.eif")); + actions.LoadNPCFileByName(Path.Combine(pubFilePath, "dtn001.enf")); + } + catch { - Directory.CreateDirectory(dstFilePath); + Console.WriteLine("Error loading pub files!"); + _typeRegistry.Dispose(); + return; } - } - SetupDependencies(); + try + { + ProcessFiles(srcFilePath, dstFilePath, singleFileProcess); + } + catch (Exception ex) + { + Console.WriteLine(); - try - { - var actions = _typeRegistry.Resolve(); + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("Exception was thrown: "); + Console.ForegroundColor = ConsoleColor.Gray; + Console.WriteLine(ex.Message); + + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("\nCall stack: \n"); + Console.ForegroundColor = ConsoleColor.Gray; + Console.WriteLine(ex.StackTrace); + } - actions.LoadItemFileByName(Path.Combine(pubFilePath, "dat001.eif")); - actions.LoadNPCFileByName(Path.Combine(pubFilePath, "dtn001.enf")); - } - catch - { - Console.WriteLine("Error loading pub files!"); _typeRegistry.Dispose(); - return; } - try + private static void SetupDependencies() { - ProcessFiles(srcFilePath, dstFilePath, singleFileProcess); - } - catch (Exception ex) - { - Console.WriteLine(); - - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("Exception was thrown: "); - Console.ForegroundColor = ConsoleColor.Gray; - Console.WriteLine(ex.Message); + _typeRegistry = new UnityRegistry("EOLib.IO"); + _typeRegistry.RegisterDiscoveredTypes(); - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("\nCall stack: \n"); - Console.ForegroundColor = ConsoleColor.Gray; - Console.WriteLine(ex.StackTrace); + _pubProvider = _typeRegistry.Resolve(); + _mapFileProvider = _typeRegistry.Resolve(); } - _typeRegistry.Dispose(); - } - - private static void SetupDependencies() - { - _typeRegistry = new UnityRegistry("EOLib.IO"); - _typeRegistry.RegisterDiscoveredTypes(); - - _pubProvider = _typeRegistry.Resolve(); - _mapFileProvider = _typeRegistry.Resolve(); - } - - private static void ProcessFiles(string src, string dst, bool singleFile) - { - var mapFileLoadActions = _typeRegistry.Resolve(); - var mapFileSaveService = _typeRegistry.Resolve(); + private static void ProcessFiles(string src, string dst, bool singleFile) + { + var mapFileLoadActions = _typeRegistry.Resolve(); + var mapFileSaveService = _typeRegistry.Resolve(); - var inFiles = singleFile ? new[] { src } : Directory.GetFiles(src, "*.emf"); + var inFiles = singleFile ? new[] { src } : Directory.GetFiles(src, "*.emf"); - for (int mapIndex = 0; mapIndex < inFiles.Length; ++mapIndex) - { - var mapID = new MapPathToIDConverter().ConvertFromPathToID(inFiles[mapIndex]); - - mapFileLoadActions.LoadMapFileByName(inFiles[mapIndex]); - var mapFile = _mapFileProvider.MapFiles[mapID]; - - var changesMade = false; - - //todo: find way to store actual input data, since invalid tiles/warps will be auto-removed - //for (int i = mapFile.TileRows.Count - 1; i >= 0; --i) - //{ - // var tr = mapFile.TileRows[i]; - // for (int j = tr.EntityItems.Count - 1; j >= 0; --j) - // { - // var tt = tr.EntityItems[j]; - // if (tt.X > mapFile.Properties.Width || tr.Y > mapFile.Properties.Height) - // { - // Console.WriteLine("[MAP {0}] Tile {1}x{2} ({3}) is out of map bounds. Removing.", - // mapID, tt.X, tr.Y, Enum.GetName(typeof(TileSpec), tt.Value)); - // mapFile.RemoveTileAt(tr.Y, tt.X); - // changesMade = true; - // } - // } - //} - - //for (int i = mapFile.WarpRows.Count - 1; i >= 0; --i) - //{ - // var tr = mapFile.WarpRows[i]; - // for (int j = tr.EntityItems.Count - 1; j >= 0; --j) - // { - // var tt = tr.EntityItems[j]; - // if (tt.X > mapFile.Properties.Width || tr.Y > mapFile.Properties.Height) - // { - // Console.WriteLine("[MAP {0}] Warp {1}x{2} is out of map bounds. Removing.", mapID, tt.X, tr.Y); - // mapFile.RemoveWarpAt(tr.Y, tt.X); - // changesMade = true; - // } - // } - //} - - for (int ndx = mapFile.NPCSpawns.Count - 1; ndx >= 0; --ndx) + for (int mapIndex = 0; mapIndex < inFiles.Length; ++mapIndex) { - var npcSpawn = mapFile.NPCSpawns[ndx]; - var npcRec = _pubProvider.ENFFile[npcSpawn.ID]; - if (npcSpawn.ID > _pubProvider.ENFFile.Length || npcRec == null) + var mapID = new MapPathToIDConverter().ConvertFromPathToID(inFiles[mapIndex]); + + mapFileLoadActions.LoadMapFileByName(inFiles[mapIndex]); + var mapFile = _mapFileProvider.MapFiles[mapID]; + + var changesMade = false; + + //todo: find way to store actual input data, since invalid tiles/warps will be auto-removed + //for (int i = mapFile.TileRows.Count - 1; i >= 0; --i) + //{ + // var tr = mapFile.TileRows[i]; + // for (int j = tr.EntityItems.Count - 1; j >= 0; --j) + // { + // var tt = tr.EntityItems[j]; + // if (tt.X > mapFile.Properties.Width || tr.Y > mapFile.Properties.Height) + // { + // Console.WriteLine("[MAP {0}] Tile {1}x{2} ({3}) is out of map bounds. Removing.", + // mapID, tt.X, tr.Y, Enum.GetName(typeof(TileSpec), tt.Value)); + // mapFile.RemoveTileAt(tr.Y, tt.X); + // changesMade = true; + // } + // } + //} + + //for (int i = mapFile.WarpRows.Count - 1; i >= 0; --i) + //{ + // var tr = mapFile.WarpRows[i]; + // for (int j = tr.EntityItems.Count - 1; j >= 0; --j) + // { + // var tt = tr.EntityItems[j]; + // if (tt.X > mapFile.Properties.Width || tr.Y > mapFile.Properties.Height) + // { + // Console.WriteLine("[MAP {0}] Warp {1}x{2} is out of map bounds. Removing.", mapID, tt.X, tr.Y); + // mapFile.RemoveWarpAt(tr.Y, tt.X); + // changesMade = true; + // } + // } + //} + + for (int ndx = mapFile.NPCSpawns.Count - 1; ndx >= 0; --ndx) { - Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} uses non-existent NPC #{3}. Removing.", mapID, npcSpawn.X, npcSpawn.Y, npcSpawn.ID); - mapFile = mapFile.RemoveNPCSpawn(npcSpawn); - changesMade = true; - continue; - } + var npcSpawn = mapFile.NPCSpawns[ndx]; + var npcRec = _pubProvider.ENFFile[npcSpawn.ID]; + if (npcSpawn.ID > _pubProvider.ENFFile.Length || npcRec == null) + { + Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} uses non-existent NPC #{3}. Removing.", mapID, npcSpawn.X, npcSpawn.Y, npcSpawn.ID); + mapFile = mapFile.RemoveNPCSpawn(npcSpawn); + changesMade = true; + continue; + } - if (npcSpawn.X > mapFile.Properties.Width || npcSpawn.Y > mapFile.Properties.Height) - { - Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} ({3}) is out of map bounds. Removing.", mapID, npcSpawn.X, npcSpawn.Y, npcRec.Name); - mapFile = mapFile.RemoveNPCSpawn(npcSpawn); - changesMade = true; - continue; - } + if (npcSpawn.X > mapFile.Properties.Width || npcSpawn.Y > mapFile.Properties.Height) + { + Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} ({3}) is out of map bounds. Removing.", mapID, npcSpawn.X, npcSpawn.Y, npcRec.Name); + mapFile = mapFile.RemoveNPCSpawn(npcSpawn); + changesMade = true; + continue; + } - if (!TileIsValidNPCSpawnPoint(mapFile, npcSpawn.X, npcSpawn.Y)) - { - Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} ({3}) is invalid...", mapID, npcSpawn.X, npcSpawn.Y, npcRec.Name); - var found = false; - for (int row = npcSpawn.Y - 2; row < npcSpawn.Y + 2; ++row) + if (!TileIsValidNPCSpawnPoint(mapFile, npcSpawn.X, npcSpawn.Y)) { - if (found) break; - for (int col = npcSpawn.X - 2; col < npcSpawn.X + 2; ++col) + Console.WriteLine("[MAP {0}] NPC Spawn {1}x{2} ({3}) is invalid...", mapID, npcSpawn.X, npcSpawn.Y, npcRec.Name); + var found = false; + for (int row = npcSpawn.Y - 2; row < npcSpawn.Y + 2; ++row) { if (found) break; - if (TileIsValidNPCSpawnPoint(mapFile, col, row)) + for (int col = npcSpawn.X - 2; col < npcSpawn.X + 2; ++col) { - Console.WriteLine("[MAP {0}] Found valid spawn point. Continuing.", mapID); - found = true; + if (found) break; + if (TileIsValidNPCSpawnPoint(mapFile, col, row)) + { + Console.WriteLine("[MAP {0}] Found valid spawn point. Continuing.", mapID); + found = true; + } } } + + if (!found) + { + Console.WriteLine("[MAP {0}] NPC couldn't spawn anywhere valid! Removing.", mapID); + mapFile = mapFile.RemoveNPCSpawn(npcSpawn); + changesMade = true; + } } + } - if (!found) + for (int ndx = mapFile.Chests.Count - 1; ndx >= 0; --ndx) + { + var chestSpawn = mapFile.Chests[ndx]; + var rec = _pubProvider.EIFFile[chestSpawn.ItemID]; + if (chestSpawn.ItemID > _pubProvider.EIFFile.Length || rec == null) { - Console.WriteLine("[MAP {0}] NPC couldn't spawn anywhere valid! Removing.", mapID); - mapFile = mapFile.RemoveNPCSpawn(npcSpawn); + Console.WriteLine("[MAP {0}] Chest Spawn {1}x{2} uses non-existent Item #{3}. Removing.", mapID, chestSpawn.X, chestSpawn.Y, chestSpawn.ItemID); + mapFile = mapFile.RemoveChestSpawn(chestSpawn); + changesMade = true; + continue; + } + + if (chestSpawn.X > mapFile.Properties.Width || + chestSpawn.Y > mapFile.Properties.Height || + mapFile.Tiles[chestSpawn.Y, chestSpawn.X] != TileSpec.Chest) + { + Console.WriteLine("[MAP {0}] Chest Spawn {1}x{2} points to a non-chest. Removing.", mapID, chestSpawn.X, chestSpawn.Y); + mapFile = mapFile.RemoveChestSpawn(chestSpawn); changesMade = true; } } - } - for (int ndx = mapFile.Chests.Count - 1; ndx >= 0; --ndx) - { - var chestSpawn = mapFile.Chests[ndx]; - var rec = _pubProvider.EIFFile[chestSpawn.ItemID]; - if (chestSpawn.ItemID > _pubProvider.EIFFile.Length || rec == null) + if (!changesMade) { - Console.WriteLine("[MAP {0}] Chest Spawn {1}x{2} uses non-existent Item #{3}. Removing.", mapID, chestSpawn.X, chestSpawn.Y, chestSpawn.ItemID); - mapFile = mapFile.RemoveChestSpawn(chestSpawn); - changesMade = true; + Console.WriteLine("Map {0} processed without any errors. No changes made.", mapID); continue; } - if (chestSpawn.X > mapFile.Properties.Width || - chestSpawn.Y > mapFile.Properties.Height || - mapFile.Tiles[chestSpawn.Y, chestSpawn.X] != TileSpec.Chest) + if (mapIndex == 0 && singleFile && inFiles.Length == 1) { - Console.WriteLine("[MAP {0}] Chest Spawn {1}x{2} points to a non-chest. Removing.", mapID, chestSpawn.X, chestSpawn.Y); - mapFile = mapFile.RemoveChestSpawn(chestSpawn); - changesMade = true; + mapFileSaveService.SaveFile(dst, mapFile); + break; } - } - if (!changesMade) - { - Console.WriteLine("Map {0} processed without any errors. No changes made.", mapID); - continue; + mapFileSaveService.SaveFile( + Path.Combine(dst, $"{mapID,5:D5}.emf"), + mapFile); } - - if (mapIndex == 0 && singleFile && inFiles.Length == 1) - { - mapFileSaveService.SaveFile(dst, mapFile); - break; - } - - mapFileSaveService.SaveFile( - Path.Combine(dst, $"{mapID,5:D5}.emf"), - mapFile); } - } - - private static bool TileIsValidNPCSpawnPoint(IMapFile EMF, int x, int y) - { - if (EMF.Warps[y, x] != null) - return false; - switch (EMF.Tiles[y, x]) + private static bool TileIsValidNPCSpawnPoint(IMapFile EMF, int x, int y) { - case TileSpec.Wall: - case TileSpec.ChairDown: - case TileSpec.ChairLeft: - case TileSpec.ChairRight: - case TileSpec.ChairUp: - case TileSpec.ChairDownRight: - case TileSpec.ChairUpLeft: - case TileSpec.ChairAll: - case TileSpec.Chest: - case TileSpec.BankVault: - case TileSpec.NPCBoundary: - case TileSpec.MapEdge: - case TileSpec.Board1: - case TileSpec.Board2: - case TileSpec.Board3: - case TileSpec.Board4: - case TileSpec.Board5: - case TileSpec.Board6: - case TileSpec.Board7: - case TileSpec.Board8: - case TileSpec.Jukebox: + if (EMF.Warps[y, x] != null) return false; - } - return true; + switch (EMF.Tiles[y, x]) + { + case TileSpec.Wall: + case TileSpec.ChairDown: + case TileSpec.ChairLeft: + case TileSpec.ChairRight: + case TileSpec.ChairUp: + case TileSpec.ChairDownRight: + case TileSpec.ChairUpLeft: + case TileSpec.ChairAll: + case TileSpec.Chest: + case TileSpec.BankVault: + case TileSpec.NPCBoundary: + case TileSpec.MapEdge: + case TileSpec.Board1: + case TileSpec.Board2: + case TileSpec.Board3: + case TileSpec.Board4: + case TileSpec.Board5: + case TileSpec.Board6: + case TileSpec.Board7: + case TileSpec.Board8: + case TileSpec.Jukebox: + return false; + } + + return true; + } } } \ No newline at end of file diff --git a/BatchPub/Program.cs b/BatchPub/Program.cs index 13ad94191..78957a790 100644 --- a/BatchPub/Program.cs +++ b/BatchPub/Program.cs @@ -1,19 +1,20 @@ using System; using System.Windows.Forms; -namespace BatchPub; - -static class Program +namespace BatchPub { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() + static class Program { - Application.EnableVisualStyles(); - Application.SetHighDpiMode(HighDpiMode.SystemAware); - Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new frmMain()); + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new frmMain()); + } } } \ No newline at end of file diff --git a/BatchPub/frmMain.cs b/BatchPub/frmMain.cs index 4f47ddec2..da545cc36 100644 --- a/BatchPub/frmMain.cs +++ b/BatchPub/frmMain.cs @@ -9,446 +9,447 @@ using System.Text.RegularExpressions; using System.Windows.Forms; -namespace BatchPub; - -public partial class frmMain : Form +namespace BatchPub { - private IPubFile eif; - private string _fname; - private bool changes; - - private enum CompareOperator - { - EQ, - GT, - LT, - GTE, - LTE, - NE, - REGEX - } - - public frmMain() + public partial class frmMain : Form { - InitializeComponent(); - InitializeMore(); - } + private IPubFile eif; + private string _fname; + private bool changes; - private void btnReset_Click(object sender, EventArgs e) - { - SuspendLayout(); - Controls.Clear(); - ResumeLayout(); - InitializeComponent(); - InitializeMore(); - eif = null; - } - - private void InitializeMore() - { - cmbStepTwoField.Items.Clear(); - cmbStepThreeField.Items.Clear(); + private enum CompareOperator + { + EQ, + GT, + LT, + GTE, + LTE, + NE, + REGEX + } - var eifType = typeof(EIFRecord); - foreach (System.Reflection.PropertyInfo prop in eifType.GetProperties()) + public frmMain() { - cmbStepTwoField.Items.Add(new PropInfo(prop)); - cmbStepThreeField.Items.Add(new PropInfo(prop)); + InitializeComponent(); + InitializeMore(); } - } - private void btnProcess_Click(object sender, EventArgs e) - { - //process everything - System.Reflection.PropertyInfo pi = (cmbStepTwoField.SelectedItem as PropInfo).PropertyInfo; - object newValue; - switch ((cmbStepTwoField.SelectedItem as PropInfo).PropertyInfo.Name) + private void btnReset_Click(object sender, EventArgs e) { - case "Type": - case "SubType": - case "Special": - case "Size": - newValue = cmbStepTwoValue.SelectedIndex; - break; - case "Name": - newValue = txtStepTwoValue.Text; - break; - default: - int dummy; - newValue = txtStepTwoValue.Text.ToString(); - if (!int.TryParse(newValue.ToString(), out dummy)) - { - MessageBox.Show("Only integer values are supported for the value field in step two."); - return; - } - newValue = dummy; - break; + SuspendLayout(); + Controls.Clear(); + ResumeLayout(); + InitializeComponent(); + InitializeMore(); + eif = null; } - if (!chkFilterOn.Checked) - { //process the change for EVERY item record. save changes immediately. - if (MessageBox.Show( - "This change will be processed for every item immediately. The change is irreversible. Are you sure you want to continue? You may specify a filter by checking the filter option.", "No filter selected", - MessageBoxButtons.YesNo, - MessageBoxIcon.Exclamation) == DialogResult.No - ) - { - return; - } + private void InitializeMore() + { + cmbStepTwoField.Items.Clear(); + cmbStepThreeField.Items.Clear(); - rtfOutput.Text += "Processing change: set " + pi.Name + "(" + pi.PropertyType.ToString() + ")=" + newValue.ToString() + " for all items..."; - foreach (var rec in eif) + var eifType = typeof(EIFRecord); + foreach (System.Reflection.PropertyInfo prop in eifType.GetProperties()) { - System.Reflection.PropertyInfo prop = rec.GetType().GetProperty(pi.Name); - prop.SetValue(rec, Convert.ChangeType(newValue, pi.PropertyType)); + cmbStepTwoField.Items.Add(new PropInfo(prop)); + cmbStepThreeField.Items.Add(new PropInfo(prop)); } - - rtfOutput.Text += "done.\n\n"; } - else + + private void btnProcess_Click(object sender, EventArgs e) { - object compareValue; - CompareOperator op; - try + //process everything + System.Reflection.PropertyInfo pi = (cmbStepTwoField.SelectedItem as PropInfo).PropertyInfo; + object newValue; + switch ((cmbStepTwoField.SelectedItem as PropInfo).PropertyInfo.Name) { - op = (CompareOperator)cmbCompareType.SelectedIndex; - if (op == CompareOperator.REGEX && cmbCompareValue.Enabled) + case "Type": + case "SubType": + case "Special": + case "Size": + newValue = cmbStepTwoValue.SelectedIndex; + break; + case "Name": + newValue = txtStepTwoValue.Text; + break; + default: + int dummy; + newValue = txtStepTwoValue.Text.ToString(); + if (!int.TryParse(newValue.ToString(), out dummy)) + { + MessageBox.Show("Only integer values are supported for the value field in step two."); + return; + } + newValue = dummy; + break; + } + + if (!chkFilterOn.Checked) + { //process the change for EVERY item record. save changes immediately. + if (MessageBox.Show( + "This change will be processed for every item immediately. The change is irreversible. Are you sure you want to continue? You may specify a filter by checking the filter option.", "No filter selected", + MessageBoxButtons.YesNo, + MessageBoxIcon.Exclamation) == DialogResult.No + ) { - MessageBox.Show("You can't use a regex to parse enumerated types"); return; } - } - catch - { - MessageBox.Show("Invalid comparison operator specified."); - return; - } - Regex comparer = null; - if (op == CompareOperator.REGEX) + rtfOutput.Text += "Processing change: set " + pi.Name + "(" + pi.PropertyType.ToString() + ")=" + newValue.ToString() + " for all items..."; + foreach (var rec in eif) + { + System.Reflection.PropertyInfo prop = rec.GetType().GetProperty(pi.Name); + prop.SetValue(rec, Convert.ChangeType(newValue, pi.PropertyType)); + } + + rtfOutput.Text += "done.\n\n"; + } + else { + object compareValue; + CompareOperator op; try { - compareValue = txtCompareValue.Text; - comparer = new Regex(compareValue.ToString()); + op = (CompareOperator)cmbCompareType.SelectedIndex; + if (op == CompareOperator.REGEX && cmbCompareValue.Enabled) + { + MessageBox.Show("You can't use a regex to parse enumerated types"); + return; + } } - catch (Exception ex) + catch { - MessageBox.Show("Unable to parse regular expression:\n " + ex.Message, "Error!"); + MessageBox.Show("Invalid comparison operator specified."); return; } - } - else - { - switch ((cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo.Name) + + Regex comparer = null; + if (op == CompareOperator.REGEX) { - case "Type": - compareValue = (ItemType)cmbCompareValue.SelectedIndex; - break; - case "SubType": - compareValue = (ItemSubType)cmbCompareValue.SelectedIndex; - break; - case "Special": - compareValue = (ItemSpecial)cmbCompareValue.SelectedIndex; - break; - case "Size": - compareValue = (ItemSize)cmbCompareValue.SelectedIndex; - break; - case "Name": - compareValue = txtCompareValue.Text; - break; - default: + try + { compareValue = txtCompareValue.Text; - int dummy; - if (!int.TryParse(compareValue.ToString(), out dummy)) - { - MessageBox.Show("Only integer values are allowed for this comparison type.", "Error parsing"); - return; - } - compareValue = dummy; - break; + comparer = new Regex(compareValue.ToString()); + } + catch (Exception ex) + { + MessageBox.Show("Unable to parse regular expression:\n " + ex.Message, "Error!"); + return; + } } - } - - List filtered = eif.Where(record => + else { - EIFRecord rec = (EIFRecord)record; - if (rec == null || rec.ID == 0) return false; - - System.Reflection.PropertyInfo comparePropertyInfo = (cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo; - System.Reflection.PropertyInfo currentInfo = rec.GetType().GetProperty(comparePropertyInfo.Name); - switch (op) + switch ((cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo.Name) { - case CompareOperator.EQ: - return compareValue.ToString() == currentInfo.GetValue(rec).ToString(); - case CompareOperator.GT: - return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) > 0; - case CompareOperator.GTE: - return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) >= 0; - case CompareOperator.LT: - return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) < 0; - case CompareOperator.LTE: - return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) <= 0; - case CompareOperator.NE: - return compareValue.ToString() != currentInfo.GetValue(rec).ToString(); - case CompareOperator.REGEX: - object curValAsString = currentInfo.GetValue(rec); - if (curValAsString == null) - return false; - - return comparer.IsMatch(curValAsString.ToString()); + case "Type": + compareValue = (ItemType)cmbCompareValue.SelectedIndex; + break; + case "SubType": + compareValue = (ItemSubType)cmbCompareValue.SelectedIndex; + break; + case "Special": + compareValue = (ItemSpecial)cmbCompareValue.SelectedIndex; + break; + case "Size": + compareValue = (ItemSize)cmbCompareValue.SelectedIndex; + break; + case "Name": + compareValue = txtCompareValue.Text; + break; default: - return false; + compareValue = txtCompareValue.Text; + int dummy; + if (!int.TryParse(compareValue.ToString(), out dummy)) + { + MessageBox.Show("Only integer values are allowed for this comparison type.", "Error parsing"); + return; + } + compareValue = dummy; + break; } - }).ToList(); + } - filtered.ForEach(rec => - { - if (!changes) - changes = true; - - int index = rec.ID - 1; - - rtfOutput.Text += "Found matching item " + rec.Name + " (" + rec.ID + ")\n"; - rtfOutput.Text += " replacing " + pi.Name + " (currently " + pi.GetValue(rec).ToString() + ") with new value " + newValue.ToString() + "\n"; - rtfOutput.SelectionStart = rtfOutput.TextLength; - rtfOutput.ScrollToCaret(); - - object setter; - //enums are special: convert them to object - if (pi.PropertyType == typeof(ItemType) || - pi.PropertyType == typeof(ItemSubType) || - pi.PropertyType == typeof(ItemSpecial) || - pi.PropertyType == typeof(ItemSize)) - setter = Convert.ChangeType(Enum.ToObject(pi.PropertyType, newValue), pi.PropertyType); - else - setter = Convert.ChangeType(newValue, pi.PropertyType); + List filtered = eif.Where(record => + { + EIFRecord rec = (EIFRecord)record; + if (rec == null || rec.ID == 0) return false; - pi.SetValue(rec, setter); + System.Reflection.PropertyInfo comparePropertyInfo = (cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo; + System.Reflection.PropertyInfo currentInfo = rec.GetType().GetProperty(comparePropertyInfo.Name); + switch (op) + { + case CompareOperator.EQ: + return compareValue.ToString() == currentInfo.GetValue(rec).ToString(); + case CompareOperator.GT: + return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) > 0; + case CompareOperator.GTE: + return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) >= 0; + case CompareOperator.LT: + return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) < 0; + case CompareOperator.LTE: + return compareValue.ToString().CompareTo(currentInfo.GetValue(rec).ToString()) <= 0; + case CompareOperator.NE: + return compareValue.ToString() != currentInfo.GetValue(rec).ToString(); + case CompareOperator.REGEX: + object curValAsString = currentInfo.GetValue(rec); + if (curValAsString == null) + return false; + + return comparer.IsMatch(curValAsString.ToString()); + default: + return false; + } + }).ToList(); - //eif.ReplaceRecordAt(index, rec); //todo: way to modify pub files - }); + filtered.ForEach(rec => + { + if (!changes) + changes = true; + + int index = rec.ID - 1; + + rtfOutput.Text += "Found matching item " + rec.Name + " (" + rec.ID + ")\n"; + rtfOutput.Text += " replacing " + pi.Name + " (currently " + pi.GetValue(rec).ToString() + ") with new value " + newValue.ToString() + "\n"; + rtfOutput.SelectionStart = rtfOutput.TextLength; + rtfOutput.ScrollToCaret(); + + object setter; + //enums are special: convert them to object + if (pi.PropertyType == typeof(ItemType) || + pi.PropertyType == typeof(ItemSubType) || + pi.PropertyType == typeof(ItemSpecial) || + pi.PropertyType == typeof(ItemSize)) + setter = Convert.ChangeType(Enum.ToObject(pi.PropertyType, newValue), pi.PropertyType); + else + setter = Convert.ChangeType(newValue, pi.PropertyType); + + pi.SetValue(rec, setter); + + //eif.ReplaceRecordAt(index, rec); //todo: way to modify pub files + }); + } } - } - - private void btnExit_Click(object sender, EventArgs e) - { - this.Close(); - } - private void btnBrowse_Click(object sender, EventArgs e) - { - using (OpenFileDialog ofd = new OpenFileDialog()) + private void btnExit_Click(object sender, EventArgs e) { - ofd.CheckFileExists = true; - ofd.CheckPathExists = true; - ofd.AddExtension = true; - ofd.Filter = "Endless Online Item Data File|*.eif"; - ofd.Multiselect = false; - ofd.InitialDirectory = Application.ExecutablePath; - - if (ofd.ShowDialog() == DialogResult.Cancel) - return; - - txtFileName.Text = ofd.FileName; + this.Close(); } - } - private void btnLoad_Click(object sender, EventArgs e) - { - var deserializer = new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); - _fname = ""; - try + private void btnBrowse_Click(object sender, EventArgs e) { - var fileBytes = File.ReadAllBytes(_fname = string.IsNullOrEmpty(txtFileName.Text) ? string.Format(PubFileNameConstants.EIFFormat, 1) : txtFileName.Text); - eif = deserializer.DeserializeFromByteArray(1, fileBytes, () => new EIFFile()); - lblFileName.Text = "Loaded file: " + _fname; - grpStepTwo.Enabled = true; - btnReset.Enabled = true; + using (OpenFileDialog ofd = new OpenFileDialog()) + { + ofd.CheckFileExists = true; + ofd.CheckPathExists = true; + ofd.AddExtension = true; + ofd.Filter = "Endless Online Item Data File|*.eif"; + ofd.Multiselect = false; + ofd.InitialDirectory = Application.ExecutablePath; + + if (ofd.ShowDialog() == DialogResult.Cancel) + return; + + txtFileName.Text = ofd.FileName; + } } - catch (Exception ex) + + private void btnLoad_Click(object sender, EventArgs e) { - eif = null; - MessageBox.Show("Error loading " + _fname + ":\n" + ex.Message, "Error!"); + var deserializer = new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); + _fname = ""; + try + { + var fileBytes = File.ReadAllBytes(_fname = string.IsNullOrEmpty(txtFileName.Text) ? string.Format(PubFileNameConstants.EIFFormat, 1) : txtFileName.Text); + eif = deserializer.DeserializeFromByteArray(1, fileBytes, () => new EIFFile()); + lblFileName.Text = "Loaded file: " + _fname; + grpStepTwo.Enabled = true; + btnReset.Enabled = true; + } + catch (Exception ex) + { + eif = null; + MessageBox.Show("Error loading " + _fname + ":\n" + ex.Message, "Error!"); + } } - } - private void cmbStepTwoField_SelectedIndexChanged(object sender, EventArgs e) - { - cmbStepTwoValue.Items.Clear(); - txtStepTwoValue.Enabled = false; - cmbStepTwoValue.Enabled = true; - switch ((cmbStepTwoField.SelectedItem as PropInfo).DisplayName) + private void cmbStepTwoField_SelectedIndexChanged(object sender, EventArgs e) { - case "Type": - foreach (string val in Enum.GetNames(typeof(ItemType))) - cmbStepTwoValue.Items.Add(val); - break; - case "SubType": - foreach (string val in Enum.GetNames(typeof(ItemSubType))) - cmbStepTwoValue.Items.Add(val); - break; - case "Special": - foreach (string val in Enum.GetNames(typeof(ItemSpecial))) - cmbStepTwoValue.Items.Add(val); - break; - case "Size": - foreach (string val in Enum.GetNames(typeof(ItemSize))) - cmbStepTwoValue.Items.Add(val); - break; - default: - txtStepTwoValue.Enabled = true; - cmbStepTwoValue.Enabled = false; - break; + cmbStepTwoValue.Items.Clear(); + txtStepTwoValue.Enabled = false; + cmbStepTwoValue.Enabled = true; + switch ((cmbStepTwoField.SelectedItem as PropInfo).DisplayName) + { + case "Type": + foreach (string val in Enum.GetNames(typeof(ItemType))) + cmbStepTwoValue.Items.Add(val); + break; + case "SubType": + foreach (string val in Enum.GetNames(typeof(ItemSubType))) + cmbStepTwoValue.Items.Add(val); + break; + case "Special": + foreach (string val in Enum.GetNames(typeof(ItemSpecial))) + cmbStepTwoValue.Items.Add(val); + break; + case "Size": + foreach (string val in Enum.GetNames(typeof(ItemSize))) + cmbStepTwoValue.Items.Add(val); + break; + default: + txtStepTwoValue.Enabled = true; + cmbStepTwoValue.Enabled = false; + break; + } } - } - private void LeaveStepTwo(object sender, EventArgs e) - { - if (cmbStepTwoField.SelectedIndex >= 0 && - ((txtStepTwoValue.Enabled && txtStepTwoValue.TextLength > 0) || (cmbStepTwoValue.Enabled && cmbStepTwoValue.SelectedIndex >= 0)) - ) + private void LeaveStepTwo(object sender, EventArgs e) { - grpStepThree.Enabled = true; - btnProcess.Enabled = true; + if (cmbStepTwoField.SelectedIndex >= 0 && + ((txtStepTwoValue.Enabled && txtStepTwoValue.TextLength > 0) || (cmbStepTwoValue.Enabled && cmbStepTwoValue.SelectedIndex >= 0)) + ) + { + grpStepThree.Enabled = true; + btnProcess.Enabled = true; + } + else + { + grpStepThree.Enabled = false; + btnProcess.Enabled = false; + } } - else + + private void chkFilterOn_CheckedChanged(object sender, EventArgs e) { - grpStepThree.Enabled = false; - btnProcess.Enabled = false; + if (chkFilterOn.Checked) + { + cmbStepThreeField.Enabled = true; + txtCompareValue.Enabled = true; + cmbCompareType.Enabled = true; + cmbCompareType.SelectedIndex = 0; + cmbStepThreeField.SelectedIndex = 0; + } + else + { + cmbStepThreeField.Enabled = false; + txtCompareValue.Enabled = false; + cmbCompareType.Enabled = false; + cmbCompareType.SelectedIndex = -1; + cmbStepThreeField.SelectedIndex = -1; + } } - } - private void chkFilterOn_CheckedChanged(object sender, EventArgs e) - { - if (chkFilterOn.Checked) + private void frmMain_Load(object sender, EventArgs e) { - cmbStepThreeField.Enabled = true; - txtCompareValue.Enabled = true; - cmbCompareType.Enabled = true; - cmbCompareType.SelectedIndex = 0; - cmbStepThreeField.SelectedIndex = 0; + MessageBox.Show("It is highly recommended that you back up your pub files before using this utility. Changes are irreversable.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } - else + + private void cmbStepThreeField_SelectedIndexChanged(object sender, EventArgs e) { - cmbStepThreeField.Enabled = false; + SuspendLayout(); + cmbCompareValue.Items.Clear(); + cmbCompareValue.Enabled = true; + cmbCompareValue.Visible = true; txtCompareValue.Enabled = false; - cmbCompareType.Enabled = false; - cmbCompareType.SelectedIndex = -1; - cmbStepThreeField.SelectedIndex = -1; - } - } + txtCompareValue.Visible = false; - private void frmMain_Load(object sender, EventArgs e) - { - MessageBox.Show("It is highly recommended that you back up your pub files before using this utility. Changes are irreversable.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning); - } + if (cmbStepThreeField.SelectedItem == null) + { + ResumeLayout(); + return; + } - private void cmbStepThreeField_SelectedIndexChanged(object sender, EventArgs e) - { - SuspendLayout(); - cmbCompareValue.Items.Clear(); - cmbCompareValue.Enabled = true; - cmbCompareValue.Visible = true; - txtCompareValue.Enabled = false; - txtCompareValue.Visible = false; - - if (cmbStepThreeField.SelectedItem == null) - { + switch ((cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo.Name) + { + case "Type": + foreach (string val in Enum.GetNames(typeof(ItemType))) + cmbCompareValue.Items.Add(val); + break; + case "SubType": + foreach (string val in Enum.GetNames(typeof(ItemSubType))) + cmbCompareValue.Items.Add(val); + break; + case "Special": + foreach (string val in Enum.GetNames(typeof(ItemSpecial))) + cmbCompareValue.Items.Add(val); + break; + case "Size": + foreach (string val in Enum.GetNames(typeof(ItemSize))) + cmbCompareValue.Items.Add(val); + break; + default: + cmbCompareValue.Enabled = false; + cmbCompareValue.Visible = false; + txtCompareValue.Enabled = true; + txtCompareValue.Visible = true; + break; + } ResumeLayout(); - return; } - switch ((cmbStepThreeField.SelectedItem as PropInfo).PropertyInfo.Name) + private void rtfOutput_TextChanged(object sender, EventArgs e) { - case "Type": - foreach (string val in Enum.GetNames(typeof(ItemType))) - cmbCompareValue.Items.Add(val); - break; - case "SubType": - foreach (string val in Enum.GetNames(typeof(ItemSubType))) - cmbCompareValue.Items.Add(val); - break; - case "Special": - foreach (string val in Enum.GetNames(typeof(ItemSpecial))) - cmbCompareValue.Items.Add(val); - break; - case "Size": - foreach (string val in Enum.GetNames(typeof(ItemSize))) - cmbCompareValue.Items.Add(val); - break; - default: - cmbCompareValue.Enabled = false; - cmbCompareValue.Visible = false; - txtCompareValue.Enabled = true; - txtCompareValue.Visible = true; - break; + if (rtfOutput.TextLength > 0) + btnClear.Enabled = true; + else + btnClear.Enabled = false; } - ResumeLayout(); - } - - private void rtfOutput_TextChanged(object sender, EventArgs e) - { - if (rtfOutput.TextLength > 0) - btnClear.Enabled = true; - else - btnClear.Enabled = false; - } - private void btnClear_Click(object sender, EventArgs e) - { - rtfOutput.Text = ""; - } + private void btnClear_Click(object sender, EventArgs e) + { + rtfOutput.Text = ""; + } - private void btnSave_Click(object sender, EventArgs e) - { - if (changes) + private void btnSave_Click(object sender, EventArgs e) { - DialogResult dr = MessageBox.Show("WARNING: This will update the pub file you currently have open with any batch changes that have been made. Confirm that this behavior is desired.", "Confirm changes?", MessageBoxButtons.YesNo); - if (dr == DialogResult.No) - return; + if (changes) + { + DialogResult dr = MessageBox.Show("WARNING: This will update the pub file you currently have open with any batch changes that have been made. Confirm that this behavior is desired.", "Confirm changes?", MessageBoxButtons.YesNo); + if (dr == DialogResult.No) + return; - //var version = eif.Version; - //if (eif.Version == 0) - //{ - // version = 1; - // MessageBox.Show("Saving using this tool will update the version of the EIF file."); - //} + //var version = eif.Version; + //if (eif.Version == 0) + //{ + // version = 1; + // MessageBox.Show("Saving using this tool will update the version of the EIF file."); + //} - try - { - var serializer = new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); - var bytes = serializer.SerializeToByteArray(eif); + try + { + var serializer = new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); + var bytes = serializer.SerializeToByteArray(eif); + } + catch (Exception ex) + { + MessageBox.Show("Error saving changes to the file:\n" + ex.Message); + return; + } + + MessageBox.Show("Changes saved."); } - catch (Exception ex) + else { - MessageBox.Show("Error saving changes to the file:\n" + ex.Message); - return; + MessageBox.Show("Changes to the pub file were not detected. No changes have been processed."); } - - MessageBox.Show("Changes saved."); - } - else - { - MessageBox.Show("Changes to the pub file were not detected. No changes have been processed."); } } -} - -public class PropInfo -{ - public System.Reflection.PropertyInfo PropertyInfo { get; set; } - public string DisplayName => PropertyInfo.Name; - public PropInfo(System.Reflection.PropertyInfo info) + public class PropInfo { - if (info == null) - throw new ArgumentNullException("Info parameter may not be null."); - PropertyInfo = info; - } + public System.Reflection.PropertyInfo PropertyInfo { get; set; } + public string DisplayName => PropertyInfo.Name; - public override string ToString() - { - return DisplayName; + public PropInfo(System.Reflection.PropertyInfo info) + { + if (info == null) + throw new ArgumentNullException("Info parameter may not be null."); + PropertyInfo = info; + } + + public override string ToString() + { + return DisplayName; + } } } \ No newline at end of file diff --git a/EOBot/ArgumentsParser.cs b/EOBot/ArgumentsParser.cs index aebb17faf..a0a0c7a6a 100644 --- a/EOBot/ArgumentsParser.cs +++ b/EOBot/ArgumentsParser.cs @@ -3,213 +3,214 @@ using System.IO; using System.Linq; -namespace EOBot; - -public enum ArgsError -{ - NoError, - BadFormat, - WrongNumberOfArgs, - InvalidPort, - InvalidNumberOfBots, - TooManyBots, - NotEnoughBots, - InvalidSimultaneousNumberOfBots, - InvalidWaitFlag, - InvalidInitDelay, - InvalidPath, - InvalidScriptArgs, - AutoConnectRequired -} - -public class ArgumentsParser +namespace EOBot { - public ArgsError Error { get; private set; } + public enum ArgsError + { + NoError, + BadFormat, + WrongNumberOfArgs, + InvalidPort, + InvalidNumberOfBots, + TooManyBots, + NotEnoughBots, + InvalidSimultaneousNumberOfBots, + InvalidWaitFlag, + InvalidInitDelay, + InvalidPath, + InvalidScriptArgs, + AutoConnectRequired + } - public string ScriptFile { get; private set; } + public class ArgumentsParser + { + public ArgsError Error { get; private set; } - public string Host { get; private set; } - public ushort Port { get; private set; } + public string ScriptFile { get; private set; } - public int NumBots { get; private set; } - public int SimultaneousBots { get; private set; } + public string Host { get; private set; } + public ushort Port { get; private set; } - public int InitDelay { get; private set; } + public int NumBots { get; private set; } + public int SimultaneousBots { get; private set; } - public string Account { get; private set; } - public string Password { get; private set; } - public string Character { get; private set; } + public int InitDelay { get; private set; } - public bool AutoConnect { get; private set; } = true; + public string Account { get; private set; } + public string Password { get; private set; } + public string Character { get; private set; } - public List UserArgs { get; internal set; } + public bool AutoConnect { get; private set; } = true; - public bool ExtendedHelp { get; private set; } + public List UserArgs { get; internal set; } + public bool ExtendedHelp { get; private set; } - public ArgumentsParser(string[] args) - { - InitDelay = 1100; - Error = ArgsError.NoError; - - if ((!args.Contains("--") && args.Select(x => x.ToLower()).Contains("help")) || - (args.Contains("--") && args.TakeWhile(x => x != "--").Select(x => x.ToLower()).Contains("help"))) - { - ExtendedHelp = true; - } - else + public ArgumentsParser(string[] args) { - for (int i = 0; i < args.Length; i++) - { - var arg = args[i]; - - if (arg == "--") - { - UserArgs = new List(); - for (i = i + 1; i < args.Length; i++) - { - UserArgs.Add(args[i]); - } - break; - } + InitDelay = 1100; - var pair = arg.Split('='); + Error = ArgsError.NoError; - if (pair.Length != 2) + if ((!args.Contains("--") && args.Select(x => x.ToLower()).Contains("help")) || + (args.Contains("--") && args.TakeWhile(x => x != "--").Select(x => x.ToLower()).Contains("help"))) + { + ExtendedHelp = true; + } + else + { + for (int i = 0; i < args.Length; i++) { - Error = ArgsError.BadFormat; - return; - } + var arg = args[i]; - switch (pair[0].ToLower()) - { - case "script": - if (!File.Exists(pair[1])) + if (arg == "--") + { + UserArgs = new List(); + for (i = i + 1; i < args.Length; i++) { - Error = ArgsError.InvalidPath; - return; + UserArgs.Add(args[i]); } - ScriptFile = pair[1]; break; - case "autoconnect": - AutoConnect = bool.Parse(pair[1]); - break; - case "host": - ParseHost(pair[1]); - break; - case "port": - if (!ParsePort(pair[1])) - return; - break; - case "bots": - if (!ParseNumBots(pair)) - return; - break; - case "initdelay": - if (!ParseInitDelay(pair[1])) - return; - break; - case "account": - Account = pair[1]; - break; - case "password": - Password = pair[1]; - break; - case "character": - Character = pair[1]; - break; - default: + } + + var pair = arg.Split('='); + + if (pair.Length != 2) + { Error = ArgsError.BadFormat; return; + } + + switch (pair[0].ToLower()) + { + case "script": + if (!File.Exists(pair[1])) + { + Error = ArgsError.InvalidPath; + return; + } + ScriptFile = pair[1]; + break; + case "autoconnect": + AutoConnect = bool.Parse(pair[1]); + break; + case "host": + ParseHost(pair[1]); + break; + case "port": + if (!ParsePort(pair[1])) + return; + break; + case "bots": + if (!ParseNumBots(pair)) + return; + break; + case "initdelay": + if (!ParseInitDelay(pair[1])) + return; + break; + case "account": + Account = pair[1]; + break; + case "password": + Password = pair[1]; + break; + case "character": + Character = pair[1]; + break; + default: + Error = ArgsError.BadFormat; + return; + } } - } - if (ScriptFile == null) - { - if (Host == null || Port == 0 || NumBots == 0 || Account == null || Password == null || Character == null) + if (ScriptFile == null) { - Error = ArgsError.WrongNumberOfArgs; + if (Host == null || Port == 0 || NumBots == 0 || Account == null || Password == null || Character == null) + { + Error = ArgsError.WrongNumberOfArgs; + } + else if (UserArgs != null || !AutoConnect) + { + Error = ArgsError.InvalidScriptArgs; + } } - else if (UserArgs != null || !AutoConnect) + else if (NumBots > 1 && ScriptFile != null && !AutoConnect) { - Error = ArgsError.InvalidScriptArgs; + Error = ArgsError.AutoConnectRequired; } } - else if (NumBots > 1 && ScriptFile != null && !AutoConnect) - { - Error = ArgsError.AutoConnectRequired; - } } - } - private void ParseHost(string hostStr) - { - Host = hostStr; - } - - private bool ParsePort(string portStr) - { - ushort port; - if (!ushort.TryParse(portStr, out port)) + private void ParseHost(string hostStr) { - Error = ArgsError.InvalidPort; - return false; + Host = hostStr; } - Port = port; - return true; - } - - private bool ParseNumBots(string[] pair) - { - var both = pair[1].Split(','); - if (both.Length < 1 || both.Length > 2) + private bool ParsePort(string portStr) { - Error = ArgsError.BadFormat; - return false; + ushort port; + if (!ushort.TryParse(portStr, out port)) + { + Error = ArgsError.InvalidPort; + return false; + } + Port = port; + return true; } - bool needSimul = both.Length == 2; - - int numBots, simul = -1; - if (!int.TryParse(both[0], out numBots)) - { - Error = ArgsError.InvalidNumberOfBots; - return false; - } - if (needSimul && !int.TryParse(both[1], out simul)) - { - Error = ArgsError.InvalidSimultaneousNumberOfBots; - return false; - } - if (numBots > BotFramework.NUM_BOTS_MAX || (needSimul && (simul > BotFramework.NUM_BOTS_MAX || simul > numBots))) - { - Error = ArgsError.TooManyBots; - return false; - } - if (numBots < 1 || (needSimul && simul < 1)) + private bool ParseNumBots(string[] pair) { - Error = ArgsError.NotEnoughBots; - return false; - } + var both = pair[1].Split(','); - NumBots = numBots; - SimultaneousBots = needSimul ? simul : numBots; - return true; - } + if (both.Length < 1 || both.Length > 2) + { + Error = ArgsError.BadFormat; + return false; + } - private bool ParseInitDelay(string initDelay) - { - int delay; - if (!int.TryParse(initDelay, out delay) || delay < 1100) - { - Error = ArgsError.InvalidInitDelay; - return false; + bool needSimul = both.Length == 2; + + int numBots, simul = -1; + if (!int.TryParse(both[0], out numBots)) + { + Error = ArgsError.InvalidNumberOfBots; + return false; + } + if (needSimul && !int.TryParse(both[1], out simul)) + { + Error = ArgsError.InvalidSimultaneousNumberOfBots; + return false; + } + if (numBots > BotFramework.NUM_BOTS_MAX || (needSimul && (simul > BotFramework.NUM_BOTS_MAX || simul > numBots))) + { + Error = ArgsError.TooManyBots; + return false; + } + if (numBots < 1 || (needSimul && simul < 1)) + { + Error = ArgsError.NotEnoughBots; + return false; + } + + NumBots = numBots; + SimultaneousBots = needSimul ? simul : numBots; + return true; } - InitDelay = delay; + private bool ParseInitDelay(string initDelay) + { + int delay; + if (!int.TryParse(initDelay, out delay) || delay < 1100) + { + Error = ArgsError.InvalidInitDelay; + return false; + } - return true; + InitDelay = delay; + + return true; + } } } \ No newline at end of file diff --git a/EOBot/BotBase.cs b/EOBot/BotBase.cs index 1ee4790f6..731bcded0 100644 --- a/EOBot/BotBase.cs +++ b/EOBot/BotBase.cs @@ -10,82 +10,83 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot; - -public abstract class BotBase : IBot +namespace EOBot { - protected bool _initialized; + public abstract class BotBase : IBot + { + protected bool _initialized; - protected readonly int _index; + protected readonly int _index; - public event Action WorkCompleted; + public event Action WorkCompleted; - protected Random _random; + protected Random _random; - protected BotBase(int botIndex) - { - _index = botIndex; - _random = new Random(); - } - - //all bots are going to want to do the init handshake with the server - public virtual async Task InitializeAsync(string host, int port) - { - var c = DependencyMaster.TypeRegistry[_index]; + protected BotBase(int botIndex) + { + _index = botIndex; + _random = new Random(); + } - var networkClientRepository = c.Resolve(); - var networkClientFactory = c.Resolve(); - networkClientRepository.NetworkClient = networkClientFactory.CreateNetworkClient(); + //all bots are going to want to do the init handshake with the server + public virtual async Task InitializeAsync(string host, int port) + { + var c = DependencyMaster.TypeRegistry[_index]; - var configRepo = c.Resolve(); - configRepo.Host = host; - configRepo.Port = port; + var networkClientRepository = c.Resolve(); + var networkClientFactory = c.Resolve(); + networkClientRepository.NetworkClient = networkClientFactory.CreateNetworkClient(); - configRepo.VersionMajor = 0; - configRepo.VersionMinor = 0; - configRepo.VersionBuild = 29; + var configRepo = c.Resolve(); + configRepo.Host = host; + configRepo.Port = port; - var connectionActions = c.Resolve(); - var connectResult = await connectionActions.ConnectToServer(); - if (connectResult != ConnectResult.Success) - throw new ArgumentException($"Bot {_index}: Unable to connect to server! Host={host} Port={port}"); + configRepo.VersionMajor = 0; + configRepo.VersionMinor = 0; + configRepo.VersionBuild = 29; - var backgroundReceiveActions = c.Resolve(); - backgroundReceiveActions.RunBackgroundReceiveLoop(); - WorkCompleted += () => - { - backgroundReceiveActions.CancelBackgroundReceiveLoop(); - connectionActions.DisconnectFromServer(); - }; + var connectionActions = c.Resolve(); + var connectResult = await connectionActions.ConnectToServer(); + if (connectResult != ConnectResult.Success) + throw new ArgumentException($"Bot {_index}: Unable to connect to server! Host={host} Port={port}"); - var handshakeResult = await connectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)); + var backgroundReceiveActions = c.Resolve(); + backgroundReceiveActions.RunBackgroundReceiveLoop(); + WorkCompleted += () => + { + backgroundReceiveActions.CancelBackgroundReceiveLoop(); + connectionActions.DisconnectFromServer(); + }; - if (handshakeResult.ReplyCode != InitReply.Ok) - throw new InvalidOperationException(string.Format("Bot {0}: Invalid response from server or connection failed! Must receive an OK reply.", _index)); + var handshakeResult = await connectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)); - var handshakeData = (InitInitServerPacket.ReplyCodeDataOk)handshakeResult.ReplyCodeData; + if (handshakeResult.ReplyCode != InitReply.Ok) + throw new InvalidOperationException(string.Format("Bot {0}: Invalid response from server or connection failed! Must receive an OK reply.", _index)); - var packetProcessActions = c.Resolve(); - packetProcessActions.SetSequenceStart(InitSequenceStart.FromInitValues(handshakeData.Seq1, handshakeData.Seq2)); - packetProcessActions.SetEncodeMultiples(handshakeData.ServerEncryptionMultiple, handshakeData.ClientEncryptionMultiple); + var handshakeData = (InitInitServerPacket.ReplyCodeDataOk)handshakeResult.ReplyCodeData; - connectionActions.CompleteHandshake(handshakeResult); + var packetProcessActions = c.Resolve(); + packetProcessActions.SetSequenceStart(InitSequenceStart.FromInitValues(handshakeData.Seq1, handshakeData.Seq2)); + packetProcessActions.SetEncodeMultiples(handshakeData.ServerEncryptionMultiple, handshakeData.ClientEncryptionMultiple); - _initialized = true; - } + connectionActions.CompleteHandshake(handshakeResult); - public async Task RunAsync(CancellationToken ct) - { - if (!_initialized) - throw new InvalidOperationException("Initialize must be called before calling RunAsync"); + _initialized = true; + } - await DoWorkAsync(ct); - WorkCompleted?.Invoke(); + public async Task RunAsync(CancellationToken ct) + { + if (!_initialized) + throw new InvalidOperationException("Initialize must be called before calling RunAsync"); + + await DoWorkAsync(ct); + WorkCompleted?.Invoke(); + } + + /// + /// Abstract worker method. Override with custom work logic for the bot to execute + /// + /// A cancellation token that will be signalled when Terminate() is called + protected abstract Task DoWorkAsync(CancellationToken ct); } - - /// - /// Abstract worker method. Override with custom work logic for the bot to execute - /// - /// A cancellation token that will be signalled when Terminate() is called - protected abstract Task DoWorkAsync(CancellationToken ct); } \ No newline at end of file diff --git a/EOBot/BotException.cs b/EOBot/BotException.cs index 83f306d0f..558420ab9 100644 --- a/EOBot/BotException.cs +++ b/EOBot/BotException.cs @@ -1,8 +1,9 @@ using System; -namespace EOBot; - -public class BotException : Exception +namespace EOBot { - public BotException(string message) : base(message) { } + public class BotException : Exception + { + public BotException(string message) : base(message) { } + } } \ No newline at end of file diff --git a/EOBot/BotFramework.cs b/EOBot/BotFramework.cs index e766626f3..732455115 100644 --- a/EOBot/BotFramework.cs +++ b/EOBot/BotFramework.cs @@ -5,147 +5,148 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot; - -sealed class BotFramework : IDisposable +namespace EOBot { - public const int NUM_BOTS_MAX = 25; - - private readonly CancellationTokenSource _cancellationTokenSource; - private readonly List _botsList; - private readonly string _host; - private readonly ushort _port; + sealed class BotFramework : IDisposable + { + public const int NUM_BOTS_MAX = 25; - private Semaphore _doneSignal; - private bool _initialized; - private int _numBots; - private bool _terminating; + private readonly CancellationTokenSource _cancellationTokenSource; + private readonly List _botsList; + private readonly string _host; + private readonly ushort _port; - public BotFramework(ArgumentsParser parsedArgs) - { - if (parsedArgs == null) - throw new ArgumentNullException(nameof(parsedArgs)); + private Semaphore _doneSignal; + private bool _initialized; + private int _numBots; + private bool _terminating; - _cancellationTokenSource = new CancellationTokenSource(); + public BotFramework(ArgumentsParser parsedArgs) + { + if (parsedArgs == null) + throw new ArgumentNullException(nameof(parsedArgs)); - var numberOfBots = parsedArgs.NumBots; - var simultaneousBots = parsedArgs.SimultaneousBots; - var host = parsedArgs.Host; - var port = parsedArgs.Port; + _cancellationTokenSource = new CancellationTokenSource(); - if (numberOfBots > NUM_BOTS_MAX || simultaneousBots > NUM_BOTS_MAX || simultaneousBots > numberOfBots) - throw new ArgumentException("Too many bots requested"); + var numberOfBots = parsedArgs.NumBots; + var simultaneousBots = parsedArgs.SimultaneousBots; + var host = parsedArgs.Host; + var port = parsedArgs.Port; - if (numberOfBots <= 0 || simultaneousBots <= 0) - throw new ArgumentException("Not enough bots requested"); + if (numberOfBots > NUM_BOTS_MAX || simultaneousBots > NUM_BOTS_MAX || simultaneousBots > numberOfBots) + throw new ArgumentException("Too many bots requested"); - _numBots = numberOfBots; - _host = host; - _port = port; + if (numberOfBots <= 0 || simultaneousBots <= 0) + throw new ArgumentException("Not enough bots requested"); - _botsList = new List(numberOfBots); + _numBots = numberOfBots; + _host = host; + _port = port; - _doneSignal = new Semaphore(simultaneousBots, simultaneousBots); - } + _botsList = new List(numberOfBots); - public async Task InitializeAsync(IBotFactory botFactory, int delayBetweenInitsMS = 1100) - { - if (_initialized) - throw new InvalidOperationException("Unable to initialize bot framework a second time."); + _doneSignal = new Semaphore(simultaneousBots, simultaneousBots); + } - int numFailed = 0; - for (int i = 0; i < _numBots; ++i) + public async Task InitializeAsync(IBotFactory botFactory, int delayBetweenInitsMS = 1100) { - if (_terminating) - throw new BotException("Received termination signal; initialization has been cancelled"); + if (_initialized) + throw new InvalidOperationException("Unable to initialize bot framework a second time."); - try + int numFailed = 0; + for (int i = 0; i < _numBots; ++i) { - var bot = botFactory.CreateBot(i); - bot.WorkCompleted += () => _doneSignal.Release(); - await bot.InitializeAsync(_host, _port); - _botsList.Add(bot); + if (_terminating) + throw new BotException("Received termination signal; initialization has been cancelled"); + + try + { + var bot = botFactory.CreateBot(i); + bot.WorkCompleted += () => _doneSignal.Release(); + await bot.InitializeAsync(_host, _port); + _botsList.Add(bot); + } + catch (Exception ex) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, ex.Message, ConsoleColor.DarkRed); + numFailed++; + continue; + } + + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Bot {i} initialized."); + await Task.Delay(delayBetweenInitsMS); //minimum for this is 1sec server-side } - catch (Exception ex) + + if (numFailed > 0) { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, ex.Message, ConsoleColor.DarkRed); - numFailed++; - continue; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, "Some bot instances failed to initialize. These bot instances will not be run.", ConsoleColor.DarkYellow); + _numBots -= numFailed; + } + else if (numFailed == _numBots) + { + throw new BotException("All bots failed to initialize. No bots will run."); } - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Bot {i} initialized."); - await Task.Delay(delayBetweenInitsMS); //minimum for this is 1sec server-side + _initialized = true; } - if (numFailed > 0) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, "Some bot instances failed to initialize. These bot instances will not be run.", ConsoleColor.DarkYellow); - _numBots -= numFailed; - } - else if (numFailed == _numBots) + public async Task RunAsync() { - throw new BotException("All bots failed to initialize. No bots will run."); - } + if (!_initialized) + throw new InvalidOperationException("Must call Initialize() before running!"); - _initialized = true; - } + var botTasks = new List(); - public async Task RunAsync() - { - if (!_initialized) - throw new InvalidOperationException("Must call Initialize() before running!"); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "Bot framework run has started.\n"); + for (int i = 0; i < _numBots; ++i) + { + _doneSignal.WaitOne(); + //acquire mutex for bot + //semaphore limits number of concurrently running bots based on cmd-line param + botTasks.Add(_botsList[i].RunAsync(_cancellationTokenSource.Token)); + } - var botTasks = new List(); + // this is done to force handling of exceptions as an Aggregate exception so errors from multiple bots are shown properly + // otherwise, only the first exception from the first faulting task will be thrown + var continuation = Task.WhenAll(botTasks); + try + { + await continuation; + } + catch { } - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "Bot framework run has started.\n"); - for (int i = 0; i < _numBots; ++i) - { - _doneSignal.WaitOne(); - //acquire mutex for bot - //semaphore limits number of concurrently running bots based on cmd-line param - botTasks.Add(_botsList[i].RunAsync(_cancellationTokenSource.Token)); + if (continuation.Status != TaskStatus.RanToCompletion && continuation.Exception != null) + { + throw continuation.Exception; + } } - // this is done to force handling of exceptions as an Aggregate exception so errors from multiple bots are shown properly - // otherwise, only the first exception from the first faulting task will be thrown - var continuation = Task.WhenAll(botTasks); - try + public void TerminateBots() { - await continuation; + _terminating = true; + if (!_initialized) return; + + _cancellationTokenSource.Cancel(); } - catch { } - if (continuation.Status != TaskStatus.RanToCompletion && continuation.Exception != null) + ~BotFramework() { - throw continuation.Exception; + Dispose(false); + GC.SuppressFinalize(this); } - } - - public void TerminateBots() - { - _terminating = true; - if (!_initialized) return; - - _cancellationTokenSource.Cancel(); - } - ~BotFramework() - { - Dispose(false); - GC.SuppressFinalize(this); - } - - public void Dispose() - { - Dispose(true); - } + public void Dispose() + { + Dispose(true); + } - private void Dispose(bool disposing) - { - if (disposing) + private void Dispose(bool disposing) { - _doneSignal?.Dispose(); - _cancellationTokenSource?.Dispose(); + if (disposing) + { + _doneSignal?.Dispose(); + _cancellationTokenSource?.Dispose(); + } } } } \ No newline at end of file diff --git a/EOBot/BotHelper.cs b/EOBot/BotHelper.cs index 06c02151b..373f4addd 100644 --- a/EOBot/BotHelper.cs +++ b/EOBot/BotHelper.cs @@ -12,114 +12,115 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot; - -delegate void DisplayMessageFunc(string message = ""); - -public class BotHelper +namespace EOBot { - private readonly int _botIndex; - - public BotHelper(int botIndex) - { - _botIndex = botIndex; - } + delegate void DisplayMessageFunc(string message = ""); - public async Task CreateAccountAsync(string name, string password) + public class BotHelper { - var accountActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var accParams = new CreateAccountParameters(name, password, password, name, name, name + "@eobot.net"); - var nameResult = await accountActions.CheckAccountNameWithServer(name); - return nameResult >= (AccountReply)10 - ? await accountActions.CreateAccount(accParams, (int)nameResult) - : nameResult; - } + private readonly int _botIndex; - public async Task LoginToAccountAsync(string name, string password) - { - var loginActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var loginParameters = new LoginParameters(name, password); - return await loginActions.LoginToServer(loginParameters); - } - - public async Task CreateCharacterAsync(string name) - { - var characterActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var createId = await characterActions.RequestCharacterCreation(); - var charParams = new CharacterCreateParameters(name, 0, 1, 0, 0); - return await characterActions.CreateCharacter(charParams, createId); - } - - public async Task LoginToCharacterAsync(string name) - { - var loginActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var characters = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var mapStateProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - - if (characters.Characters == null || !characters.Characters.Any()) - await CreateCharacterAsync(name); + public BotHelper(int botIndex) + { + _botIndex = botIndex; + } - var character = characters.Characters.Single(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)); - var sessionID = await loginActions.RequestCharacterLogin(character); + public async Task CreateAccountAsync(string name, string password) + { + var accountActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var accParams = new CreateAccountParameters(name, password, password, name, name, name + "@eobot.net"); + var nameResult = await accountActions.CheckAccountNameWithServer(name); + return nameResult >= (AccountReply)10 + ? await accountActions.CreateAccount(accParams, (int)nameResult) + : nameResult; + } - var unableToLoadMap = false; - try + public async Task LoginToAccountAsync(string name, string password) { - var mapLoadActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - mapLoadActions.LoadMapFileByID(mapStateProvider.CurrentMapID); + var loginActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var loginParameters = new LoginParameters(name, password); + return await loginActions.LoginToServer(loginParameters); } - catch (IOException) + + public async Task CreateCharacterAsync(string name) { - unableToLoadMap = true; + var characterActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var createId = await characterActions.RequestCharacterCreation(); + var charParams = new CharacterCreateParameters(name, 0, 1, 0, 0); + return await characterActions.CreateCharacter(charParams, createId); } - var fileRequestActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - if (unableToLoadMap || fileRequestActions.NeedsFileForLogin(FileType.Emf, mapStateProvider.CurrentMapID)) - await fileRequestActions.GetMapFromServer(mapStateProvider.CurrentMapID, sessionID); + public async Task LoginToCharacterAsync(string name) + { + var loginActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var characters = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var mapStateProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - if (fileRequestActions.NeedsFileForLogin(FileType.Eif)) - await fileRequestActions.GetItemFileFromServer(sessionID); + if (characters.Characters == null || !characters.Characters.Any()) + await CreateCharacterAsync(name); - if (fileRequestActions.NeedsFileForLogin(FileType.Enf)) - await fileRequestActions.GetNPCFileFromServer(sessionID); + var character = characters.Characters.Single(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)); + var sessionID = await loginActions.RequestCharacterLogin(character); - if (fileRequestActions.NeedsFileForLogin(FileType.Esf)) - await fileRequestActions.GetSpellFileFromServer(sessionID); + var unableToLoadMap = false; + try + { + var mapLoadActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + mapLoadActions.LoadMapFileByID(mapStateProvider.CurrentMapID); + } + catch (IOException) + { + unableToLoadMap = true; + } - if (fileRequestActions.NeedsFileForLogin(FileType.Ecf)) - await fileRequestActions.GetClassFileFromServer(sessionID); + var fileRequestActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + if (unableToLoadMap || fileRequestActions.NeedsFileForLogin(FileType.Emf, mapStateProvider.CurrentMapID)) + await fileRequestActions.GetMapFromServer(mapStateProvider.CurrentMapID, sessionID); - await loginActions.CompleteCharacterLogin(sessionID); - } + if (fileRequestActions.NeedsFileForLogin(FileType.Eif)) + await fileRequestActions.GetItemFileFromServer(sessionID); - public async Task ChangePasswordAsync(string name, string oldPass, string newPass) - { - var accountActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var accParams = new ChangePasswordParameters(name, oldPass, newPass); - return await accountActions.ChangePassword(accParams); - } + if (fileRequestActions.NeedsFileForLogin(FileType.Enf)) + await fileRequestActions.GetNPCFileFromServer(sessionID); - public async Task DeleteCharacterAsync(string name, bool force) - { - var characterSelectorRepository = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - characterSelectorRepository.CharacterForDelete = characterSelectorRepository.Characters.SingleOrNone(x => x.Name == name); + if (fileRequestActions.NeedsFileForLogin(FileType.Esf)) + await fileRequestActions.GetSpellFileFromServer(sessionID); - if (!characterSelectorRepository.CharacterForDelete.HasValue) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Character {name} could not be deleted / does not exist"); - return (CharacterReply)255; - } + if (fileRequestActions.NeedsFileForLogin(FileType.Ecf)) + await fileRequestActions.GetClassFileFromServer(sessionID); - var characterActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var deleteId = await characterActions.RequestCharacterDelete(); + await loginActions.CompleteCharacterLogin(sessionID); + } - if (!force) + public async Task ChangePasswordAsync(string name, string oldPass, string newPass) { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, "DELETING CHARACTER - ARE YOU SURE [Y/N]?", ConsoleColor.Yellow); - if (Console.ReadLine().ToLower() != "y") - return CharacterReply.NotApproved; + var accountActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var accParams = new ChangePasswordParameters(name, oldPass, newPass); + return await accountActions.ChangePassword(accParams); } - return await characterActions.DeleteCharacter(deleteId); + public async Task DeleteCharacterAsync(string name, bool force) + { + var characterSelectorRepository = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + characterSelectorRepository.CharacterForDelete = characterSelectorRepository.Characters.SingleOrNone(x => x.Name == name); + + if (!characterSelectorRepository.CharacterForDelete.HasValue) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Character {name} could not be deleted / does not exist"); + return (CharacterReply)255; + } + + var characterActions = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var deleteId = await characterActions.RequestCharacterDelete(); + + if (!force) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, "DELETING CHARACTER - ARE YOU SURE [Y/N]?", ConsoleColor.Yellow); + if (Console.ReadLine().ToLower() != "y") + return CharacterReply.NotApproved; + } + + return await characterActions.DeleteCharacter(deleteId); + } } } \ No newline at end of file diff --git a/EOBot/ConsoleHelper.cs b/EOBot/ConsoleHelper.cs index 6d1386fce..16053186f 100644 --- a/EOBot/ConsoleHelper.cs +++ b/EOBot/ConsoleHelper.cs @@ -2,78 +2,79 @@ using System.Linq; using System.Reflection; -namespace EOBot; - -internal sealed class StringValue : Attribute -{ - public string Value { get; set; } - - public StringValue(string value) => Value = value; -} - -internal static class EnumExtensions +namespace EOBot { - public static string String(this Enum item) + internal sealed class StringValue : Attribute { - var enumType = item.GetType(); - var memberInfos = enumType.GetMember(item.ToString()); - var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == enumType); - var valueAttributes = enumValueMemberInfo.GetCustomAttributes(false); - return valueAttributes.Single().Value; + public string Value { get; set; } + + public StringValue(string value) => Value = value; } -} -public static class ConsoleHelper -{ - public enum Type + internal static class EnumExtensions { - [StringValue(" ")] - None, - [StringValue("WRN ")] - Warning, - [StringValue("ERR ")] - Error, - [StringValue("ATK ")] - Attack, - [StringValue("MOVE")] - Move, - [StringValue("WALK")] - Walk, - [StringValue("FACE")] - Face, - [StringValue("TAKE")] - TakeItem, - [StringValue("JUNK")] - JunkItem, - [StringValue("USE ")] - UseItem, - [StringValue("CAST")] - Cast, - [StringValue("SIT ")] - Sit, - [StringValue("HIT ")] - Hit, - [StringValue("EXP ")] - Experience, - [StringValue("HEAL")] - Heal, - [StringValue("DMG ")] - Damage, - [StringValue("DEAD")] - Dead, - [StringValue("ITEM")] - Item, - [StringValue("CHAT")] - Chat + public static string String(this Enum item) + { + var enumType = item.GetType(); + var memberInfos = enumType.GetMember(item.ToString()); + var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == enumType); + var valueAttributes = enumValueMemberInfo.GetCustomAttributes(false); + return valueAttributes.Single().Value; + } } - public static void WriteMessage(Type messageType, string message, ConsoleColor color = ConsoleColor.Gray) + public static class ConsoleHelper { - var oldColor = Console.ForegroundColor; - Console.ForegroundColor = color; + public enum Type + { + [StringValue(" ")] + None, + [StringValue("WRN ")] + Warning, + [StringValue("ERR ")] + Error, + [StringValue("ATK ")] + Attack, + [StringValue("MOVE")] + Move, + [StringValue("WALK")] + Walk, + [StringValue("FACE")] + Face, + [StringValue("TAKE")] + TakeItem, + [StringValue("JUNK")] + JunkItem, + [StringValue("USE ")] + UseItem, + [StringValue("CAST")] + Cast, + [StringValue("SIT ")] + Sit, + [StringValue("HIT ")] + Hit, + [StringValue("EXP ")] + Experience, + [StringValue("HEAL")] + Heal, + [StringValue("DMG ")] + Damage, + [StringValue("DEAD")] + Dead, + [StringValue("ITEM")] + Item, + [StringValue("CHAT")] + Chat + } + + public static void WriteMessage(Type messageType, string message, ConsoleColor color = ConsoleColor.Gray) + { + var oldColor = Console.ForegroundColor; + Console.ForegroundColor = color; - Console.WriteLine($"[{messageType.String()}] {message}"); + Console.WriteLine($"[{messageType.String()}] {message}"); - Console.ForegroundColor = oldColor; + Console.ForegroundColor = oldColor; + } } } \ No newline at end of file diff --git a/EOBot/DependencyMaster.cs b/EOBot/DependencyMaster.cs index 41647d49d..72ffebcb6 100644 --- a/EOBot/DependencyMaster.cs +++ b/EOBot/DependencyMaster.cs @@ -1,8 +1,9 @@ using AutomaticTypeMapper; -namespace EOBot; - -public static class DependencyMaster +namespace EOBot { - public static ITypeRegistry[] TypeRegistry { get; set; } + public static class DependencyMaster + { + public static ITypeRegistry[] TypeRegistry { get; set; } + } } \ No newline at end of file diff --git a/EOBot/IBot.cs b/EOBot/IBot.cs index fb76b7865..48eca1739 100644 --- a/EOBot/IBot.cs +++ b/EOBot/IBot.cs @@ -2,23 +2,24 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot; - -public interface IBot +namespace EOBot { - /// - /// Event that is called when work for the Bot has been completed - /// - event Action WorkCompleted; + public interface IBot + { + /// + /// Event that is called when work for the Bot has been completed + /// + event Action WorkCompleted; - /// - /// Initialization logic for the bot instance. Called automatically by the framework. - /// - Task InitializeAsync(string host, int port); + /// + /// Initialization logic for the bot instance. Called automatically by the framework. + /// + Task InitializeAsync(string host, int port); - /// - /// Run logic for the bot instance. Called automatically by the framework. - /// - /// True to wait until a call to Terminate() is made, false otherwise - Task RunAsync(CancellationToken cancellationToken); + /// + /// Run logic for the bot instance. Called automatically by the framework. + /// + /// True to wait until a call to Terminate() is made, false otherwise + Task RunAsync(CancellationToken cancellationToken); + } } \ No newline at end of file diff --git a/EOBot/IBotFactory.cs b/EOBot/IBotFactory.cs index 1d4bbfcae..ee573ea0c 100644 --- a/EOBot/IBotFactory.cs +++ b/EOBot/IBotFactory.cs @@ -1,6 +1,7 @@ -namespace EOBot; - -interface IBotFactory +namespace EOBot { - IBot CreateBot(int index); + interface IBotFactory + { + IBot CreateBot(int index); + } } \ No newline at end of file diff --git a/EOBot/Interpreter/BotInterpreter.cs b/EOBot/Interpreter/BotInterpreter.cs index e85f0a27f..4be01ea55 100644 --- a/EOBot/Interpreter/BotInterpreter.cs +++ b/EOBot/Interpreter/BotInterpreter.cs @@ -4,87 +4,88 @@ using System.IO; using System.Threading.Tasks; -namespace EOBot.Interpreter; - -public class BotInterpreter +namespace EOBot.Interpreter { - private readonly BotTokenParser _parser; - - public BotInterpreter(string filePath) - : this(File.OpenText(filePath)) + public class BotInterpreter { - } + private readonly BotTokenParser _parser; - public BotInterpreter(StreamReader inputStream) - { - _parser = new BotTokenParser(inputStream); - } - - public IReadOnlyList Parse() - { - _parser.Reset(); + public BotInterpreter(string filePath) + : this(File.OpenText(filePath)) + { + } - var retList = new List(); + public BotInterpreter(StreamReader inputStream) + { + _parser = new BotTokenParser(inputStream); + } - BotToken nextToken; - do + public IReadOnlyList Parse() { - nextToken = _parser.GetNextToken(); - if (nextToken.TokenType == BotTokenType.Error) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error at line {_parser.LineNumber} column {_parser.Column}: token value {nextToken.TokenValue}", ConsoleColor.Red); - throw new InvalidOperationException("Unable to parse input"); - } + _parser.Reset(); - retList.Add(nextToken); - } while (nextToken.TokenType != BotTokenType.EOF); + var retList = new List(); - return retList; - } - - internal ProgramState Prepare(int botIndex, ArgumentsParser parsedArgs, IReadOnlyList tokens) - { - ProgramState input = new ProgramState(tokens); + BotToken nextToken; + do + { + nextToken = _parser.GetNextToken(); + if (nextToken.TokenType == BotTokenType.Error) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error at line {_parser.LineNumber} column {_parser.Column}: token value {nextToken.TokenValue}", ConsoleColor.Red); + throw new InvalidOperationException("Unable to parse input"); + } - var setup = new BuiltInIdentifierConfigurator(input, botIndex, parsedArgs); - setup.SetupBuiltInFunctions(); - setup.SetupBuiltInVariables(); + retList.Add(nextToken); + } while (nextToken.TokenType != BotTokenType.EOF); - return input; - } + return retList; + } - public async Task Run(ProgramState programState) - { - var evaluators = new List(); - evaluators.Add(new StatementListEvaluator(evaluators)); - evaluators.Add(new StatementEvaluator(evaluators)); - evaluators.Add(new AssignmentEvaluator(evaluators)); - evaluators.Add(new KeywordEvaluator(evaluators)); - evaluators.Add(new LabelEvaluator()); - evaluators.Add(new FunctionEvaluator(evaluators)); - evaluators.Add(new VariableEvaluator(evaluators)); - evaluators.Add(new ExpressionEvaluator(evaluators)); - evaluators.Add(new ExpressionTailEvaluator(evaluators)); - evaluators.Add(new OperandEvaluator(evaluators)); - evaluators.Add(new IfEvaluator(evaluators)); - evaluators.Add(new WhileEvaluator(evaluators)); - evaluators.Add(new GotoEvaluator()); + internal ProgramState Prepare(int botIndex, ArgumentsParser parsedArgs, IReadOnlyList tokens) + { + ProgramState input = new ProgramState(tokens); - IScriptEvaluator scriptEvaluator = new ScriptEvaluator(evaluators); + var setup = new BuiltInIdentifierConfigurator(input, botIndex, parsedArgs); + setup.SetupBuiltInFunctions(); + setup.SetupBuiltInVariables(); - var result = await scriptEvaluator.EvaluateAsync(programState); - if (result.Result == EvalResult.Failed) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error during execution at line {result.Token.LineNumber} column {result.Token.Column}", ConsoleColor.DarkRed); - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, result.Reason, ConsoleColor.DarkRed); + return input; } - else if (result.Result == EvalResult.NotMatch) + + public async Task Run(ProgramState programState) { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error at line {result.Token.LineNumber} column {result.Token.Column}: {result.Token.TokenType} {result.Token.TokenValue} was unexpected", ConsoleColor.DarkRed); - if (!string.IsNullOrWhiteSpace(result.Reason)) + var evaluators = new List(); + evaluators.Add(new StatementListEvaluator(evaluators)); + evaluators.Add(new StatementEvaluator(evaluators)); + evaluators.Add(new AssignmentEvaluator(evaluators)); + evaluators.Add(new KeywordEvaluator(evaluators)); + evaluators.Add(new LabelEvaluator()); + evaluators.Add(new FunctionEvaluator(evaluators)); + evaluators.Add(new VariableEvaluator(evaluators)); + evaluators.Add(new ExpressionEvaluator(evaluators)); + evaluators.Add(new ExpressionTailEvaluator(evaluators)); + evaluators.Add(new OperandEvaluator(evaluators)); + evaluators.Add(new IfEvaluator(evaluators)); + evaluators.Add(new WhileEvaluator(evaluators)); + evaluators.Add(new GotoEvaluator()); + + IScriptEvaluator scriptEvaluator = new ScriptEvaluator(evaluators); + + var result = await scriptEvaluator.EvaluateAsync(programState); + if (result.Result == EvalResult.Failed) { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error during execution at line {result.Token.LineNumber} column {result.Token.Column}", ConsoleColor.DarkRed); ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, result.Reason, ConsoleColor.DarkRed); } + else if (result.Result == EvalResult.NotMatch) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Error at line {result.Token.LineNumber} column {result.Token.Column}: {result.Token.TokenType} {result.Token.TokenValue} was unexpected", ConsoleColor.DarkRed); + if (!string.IsNullOrWhiteSpace(result.Reason)) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, result.Reason, ConsoleColor.DarkRed); + } + } } } } \ No newline at end of file diff --git a/EOBot/Interpreter/BotScriptErrorException.cs b/EOBot/Interpreter/BotScriptErrorException.cs index 0f7e8f740..121d3cb0d 100644 --- a/EOBot/Interpreter/BotScriptErrorException.cs +++ b/EOBot/Interpreter/BotScriptErrorException.cs @@ -1,12 +1,13 @@ using System; -namespace EOBot.Interpreter; - -public class BotScriptErrorException : Exception +namespace EOBot.Interpreter { - public BotScriptErrorException(string message) - : base(message) { } + public class BotScriptErrorException : Exception + { + public BotScriptErrorException(string message) + : base(message) { } - public BotScriptErrorException(string message, BotToken token) - : base($"Error at line {token.LineNumber} column {token.Column}: {message}") { } + public BotScriptErrorException(string message, BotToken token) + : base($"Error at line {token.LineNumber} column {token.Column}: {message}") { } + } } \ No newline at end of file diff --git a/EOBot/Interpreter/BotToken.cs b/EOBot/Interpreter/BotToken.cs index ba4beb9a6..460ddba07 100644 --- a/EOBot/Interpreter/BotToken.cs +++ b/EOBot/Interpreter/BotToken.cs @@ -1,22 +1,23 @@ -namespace EOBot.Interpreter; - -public class BotToken +namespace EOBot.Interpreter { - public BotTokenType TokenType { get; } + public class BotToken + { + public BotTokenType TokenType { get; } - public string TokenValue { get; } + public string TokenValue { get; } - public int LineNumber { get; } + public int LineNumber { get; } - public int Column { get; } + public int Column { get; } - public BotToken(BotTokenType tokenType, string tokenValue, int line, int col) - { - TokenType = tokenType; - TokenValue = tokenValue; - LineNumber = line; - Column = col; - } + public BotToken(BotTokenType tokenType, string tokenValue, int line, int col) + { + TokenType = tokenType; + TokenValue = tokenValue; + LineNumber = line; + Column = col; + } - public override string ToString() => $"{TokenType}: {TokenValue}"; + public override string ToString() => $"{TokenType}: {TokenValue}"; + } } \ No newline at end of file diff --git a/EOBot/Interpreter/BotTokenParser.cs b/EOBot/Interpreter/BotTokenParser.cs index a385cac43..69a89ff16 100644 --- a/EOBot/Interpreter/BotTokenParser.cs +++ b/EOBot/Interpreter/BotTokenParser.cs @@ -2,232 +2,233 @@ using System.Collections.Generic; using System.IO; -namespace EOBot.Interpreter; - -public sealed class BotTokenParser : IDisposable +namespace EOBot.Interpreter { - private static readonly HashSet Keywords = new HashSet + public sealed class BotTokenParser : IDisposable { - "if", - "while", - "goto", - "else", - }; + private static readonly HashSet Keywords = new HashSet + { + "if", + "while", + "goto", + "else", + }; - private static readonly HashSet Literals = new HashSet - { - "true", - "false" - }; + private static readonly HashSet Literals = new HashSet + { + "true", + "false" + }; - private readonly StreamReader _inputStream; - private readonly bool _streamNeedsDispose; + private readonly StreamReader _inputStream; + private readonly bool _streamNeedsDispose; - public int LineNumber { get; private set; } + public int LineNumber { get; private set; } - public int Column { get; private set; } + public int Column { get; private set; } - public BotTokenParser(string filePath) - : this(File.OpenText(filePath)) - { - _streamNeedsDispose = true; - } - - public BotTokenParser(StreamReader inputStream) - { - _inputStream = inputStream; - LineNumber = 1; - Column = 1; - } + public BotTokenParser(string filePath) + : this(File.OpenText(filePath)) + { + _streamNeedsDispose = true; + } - public void Reset() - { - _inputStream.BaseStream.Seek(0, SeekOrigin.Begin); - LineNumber = 1; - Column = 1; - } + public BotTokenParser(StreamReader inputStream) + { + _inputStream = inputStream; + LineNumber = 1; + Column = 1; + } - public BotToken GetNextToken() - { - if (_inputStream.EndOfStream) - return Token(BotTokenType.EOF, string.Empty); + public void Reset() + { + _inputStream.BaseStream.Seek(0, SeekOrigin.Begin); + LineNumber = 1; + Column = 1; + } - char inputChar; - do + public BotToken GetNextToken() { - inputChar = Read(); + if (_inputStream.EndOfStream) + return Token(BotTokenType.EOF, string.Empty); - if (inputChar == '\n') + char inputChar; + do { - LineNumber++; - Column = 1; - return Token(BotTokenType.NewLine, inputChar.ToString()); - } + inputChar = Read(); - if (inputChar == '/' && !_inputStream.EndOfStream && Peek() == '*') - { - // skip the comment: block format - do + if (inputChar == '\n') { - inputChar = Read(); - } while (!(inputChar == '*' && !_inputStream.EndOfStream && Peek() == '/')); + LineNumber++; + Column = 1; + return Token(BotTokenType.NewLine, inputChar.ToString()); + } - // skip the slash ending the comment and set input char to the character after the comment - Read(); - inputChar = Read(); - } - else if (inputChar == '/' && !_inputStream.EndOfStream && Peek() == '/') - { - // skip the comment: line format - do + if (inputChar == '/' && !_inputStream.EndOfStream && Peek() == '*') { + // skip the comment: block format + do + { + inputChar = Read(); + } while (!(inputChar == '*' && !_inputStream.EndOfStream && Peek() == '/')); + + // skip the slash ending the comment and set input char to the character after the comment + Read(); inputChar = Read(); - } while (inputChar != '\n' && !_inputStream.EndOfStream); + } + else if (inputChar == '/' && !_inputStream.EndOfStream && Peek() == '/') + { + // skip the comment: line format + do + { + inputChar = Read(); + } while (inputChar != '\n' && !_inputStream.EndOfStream); - LineNumber++; - Column = 1; - return Token(BotTokenType.NewLine, inputChar.ToString()); - } - } while (!_inputStream.EndOfStream && char.IsWhiteSpace(inputChar)); + LineNumber++; + Column = 1; + return Token(BotTokenType.NewLine, inputChar.ToString()); + } + } while (!_inputStream.EndOfStream && char.IsWhiteSpace(inputChar)); - if (char.IsLetter(inputChar)) - { - var identifier = inputChar.ToString(); - while ((char.IsLetterOrDigit(Peek()) || Peek() == '_') && !_inputStream.EndOfStream) - identifier += Read(); + if (char.IsLetter(inputChar)) + { + var identifier = inputChar.ToString(); + while ((char.IsLetterOrDigit(Peek()) || Peek() == '_') && !_inputStream.EndOfStream) + identifier += Read(); - var type = Keywords.Contains(identifier) - ? BotTokenType.Keyword - : Literals.Contains(identifier) - ? BotTokenType.Literal - : BotTokenType.Identifier; + var type = Keywords.Contains(identifier) + ? BotTokenType.Keyword + : Literals.Contains(identifier) + ? BotTokenType.Literal + : BotTokenType.Identifier; - return Token(type, identifier); - } - else if (char.IsDigit(inputChar)) - { - var number = inputChar.ToString(); - while (char.IsDigit(Peek()) && !_inputStream.EndOfStream) - number += Read(); - return Token(BotTokenType.Literal, number); - } - else - { - switch (inputChar) + return Token(type, identifier); + } + else if (char.IsDigit(inputChar)) { - case '(': return Token(BotTokenType.LParen, inputChar.ToString()); - case ')': return Token(BotTokenType.RParen, inputChar.ToString()); - case '{': return Token(BotTokenType.LBrace, inputChar.ToString()); - case '}': return Token(BotTokenType.RBrace, inputChar.ToString()); - case '[': return Token(BotTokenType.LBracket, inputChar.ToString()); - case ']': return Token(BotTokenType.RBracket, inputChar.ToString()); - case ':': return Token(BotTokenType.Colon, inputChar.ToString()); - case ',': return Token(BotTokenType.Comma, inputChar.ToString()); - case '"': - { - var stringLiteral = string.Empty; - while (Peek() != '"' && !_inputStream.EndOfStream) - stringLiteral += Read(); + var number = inputChar.ToString(); + while (char.IsDigit(Peek()) && !_inputStream.EndOfStream) + number += Read(); + return Token(BotTokenType.Literal, number); + } + else + { + switch (inputChar) + { + case '(': return Token(BotTokenType.LParen, inputChar.ToString()); + case ')': return Token(BotTokenType.RParen, inputChar.ToString()); + case '{': return Token(BotTokenType.LBrace, inputChar.ToString()); + case '}': return Token(BotTokenType.RBrace, inputChar.ToString()); + case '[': return Token(BotTokenType.LBracket, inputChar.ToString()); + case ']': return Token(BotTokenType.RBracket, inputChar.ToString()); + case ':': return Token(BotTokenType.Colon, inputChar.ToString()); + case ',': return Token(BotTokenType.Comma, inputChar.ToString()); + case '"': + { + var stringLiteral = string.Empty; + while (Peek() != '"' && !_inputStream.EndOfStream) + stringLiteral += Read(); - if (_inputStream.EndOfStream) - return Token(BotTokenType.Error, string.Empty); + if (_inputStream.EndOfStream) + return Token(BotTokenType.Error, string.Empty); - Read(); - return Token(BotTokenType.Literal, stringLiteral); - } - case '=': - { - switch (Peek()) + Read(); + return Token(BotTokenType.Literal, stringLiteral); + } + case '=': { - case '=': - var nextChar = Read(); - return Token(BotTokenType.EqualOperator, inputChar.ToString() + nextChar); - default: - return Token(BotTokenType.AssignOperator, inputChar.ToString()); + switch (Peek()) + { + case '=': + var nextChar = Read(); + return Token(BotTokenType.EqualOperator, inputChar.ToString() + nextChar); + default: + return Token(BotTokenType.AssignOperator, inputChar.ToString()); + } } - } - case '!': - { - switch (Peek()) + case '!': { - case '=': - var nextChar = Read(); - return Token(BotTokenType.NotEqualOperator, inputChar.ToString() + nextChar); - default: - return Token(BotTokenType.NotOperator, inputChar.ToString()); + switch (Peek()) + { + case '=': + var nextChar = Read(); + return Token(BotTokenType.NotEqualOperator, inputChar.ToString() + nextChar); + default: + return Token(BotTokenType.NotOperator, inputChar.ToString()); + } } - } - case '>': - { - switch (Peek()) + case '>': { - case '=': - var nextChar = Read(); - return Token(BotTokenType.GreaterThanEqOperator, inputChar.ToString() + nextChar); - default: - return Token(BotTokenType.GreaterThanOperator, inputChar.ToString()); + switch (Peek()) + { + case '=': + var nextChar = Read(); + return Token(BotTokenType.GreaterThanEqOperator, inputChar.ToString() + nextChar); + default: + return Token(BotTokenType.GreaterThanOperator, inputChar.ToString()); + } } - } - case '<': - { - switch (Peek()) + case '<': { - case '=': - var nextChar = Read(); - return Token(BotTokenType.LessThanEqOperator, inputChar.ToString() + nextChar); - default: - return Token(BotTokenType.LessThanOperator, inputChar.ToString()); + switch (Peek()) + { + case '=': + var nextChar = Read(); + return Token(BotTokenType.LessThanEqOperator, inputChar.ToString() + nextChar); + default: + return Token(BotTokenType.LessThanOperator, inputChar.ToString()); + } } - } - case '$': - { - if (_inputStream.EndOfStream) - return Token(BotTokenType.Error, inputChar.ToString()); + case '$': + { + if (_inputStream.EndOfStream) + return Token(BotTokenType.Error, inputChar.ToString()); - // ensure variable starts with letter or underscore before getting variable name - inputChar = Peek(); - if (!char.IsLetter(inputChar) && inputChar != '_') - return Token(BotTokenType.Error, inputChar.ToString()); + // ensure variable starts with letter or underscore before getting variable name + inputChar = Peek(); + if (!char.IsLetter(inputChar) && inputChar != '_') + return Token(BotTokenType.Error, inputChar.ToString()); - var variable = string.Empty; - for (inputChar = Peek(); !_inputStream.EndOfStream && (char.IsLetterOrDigit(inputChar) || inputChar == '_'); inputChar = Peek()) - { - variable += Read(); - } + var variable = string.Empty; + for (inputChar = Peek(); !_inputStream.EndOfStream && (char.IsLetterOrDigit(inputChar) || inputChar == '_'); inputChar = Peek()) + { + variable += Read(); + } - return Token(BotTokenType.Variable, variable); - } - case '+': return Token(BotTokenType.PlusOperator, inputChar.ToString()); - case '-': return Token(BotTokenType.MinusOperator, inputChar.ToString()); - case '*': return Token(BotTokenType.MultiplyOperator, inputChar.ToString()); - case '/': return Token(BotTokenType.DivideOperator, inputChar.ToString()); - case '.': return Token(BotTokenType.Dot, inputChar.ToString()); - default: return Token(BotTokenType.Error, inputChar.ToString()); + return Token(BotTokenType.Variable, variable); + } + case '+': return Token(BotTokenType.PlusOperator, inputChar.ToString()); + case '-': return Token(BotTokenType.MinusOperator, inputChar.ToString()); + case '*': return Token(BotTokenType.MultiplyOperator, inputChar.ToString()); + case '/': return Token(BotTokenType.DivideOperator, inputChar.ToString()); + case '.': return Token(BotTokenType.Dot, inputChar.ToString()); + default: return Token(BotTokenType.Error, inputChar.ToString()); + } } } - } - private BotToken Token(BotTokenType tokenType, string tokenValue) - { - return new BotToken(tokenType, tokenValue, LineNumber, Column); - } + private BotToken Token(BotTokenType tokenType, string tokenValue) + { + return new BotToken(tokenType, tokenValue, LineNumber, Column); + } - public void Dispose() - { - if (_streamNeedsDispose) - _inputStream.Dispose(); + public void Dispose() + { + if (_streamNeedsDispose) + _inputStream.Dispose(); - GC.SuppressFinalize(this); - } + GC.SuppressFinalize(this); + } - private char Peek() - { - return (char)_inputStream.Peek(); - } + private char Peek() + { + return (char)_inputStream.Peek(); + } - private char Read() - { - Column++; - return (char)_inputStream.Read(); + private char Read() + { + Column++; + return (char)_inputStream.Read(); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/BotTokenType.cs b/EOBot/Interpreter/BotTokenType.cs index b2145907d..e93ed43cd 100644 --- a/EOBot/Interpreter/BotTokenType.cs +++ b/EOBot/Interpreter/BotTokenType.cs @@ -1,33 +1,34 @@ -namespace EOBot.Interpreter; - -public enum BotTokenType +namespace EOBot.Interpreter { - EOF, - LParen, - RParen, - LBrace, - RBrace, - LBracket, - RBracket, - Colon, - Comma, - Keyword, - Variable, - Identifier, - Literal, - AssignOperator, - EqualOperator, - LessThanOperator, - LessThanEqOperator, - GreaterThanOperator, - GreaterThanEqOperator, - NotEqualOperator, - PlusOperator, - MinusOperator, - MultiplyOperator, - DivideOperator, - NotOperator, - Dot, - NewLine, - Error, + public enum BotTokenType + { + EOF, + LParen, + RParen, + LBrace, + RBrace, + LBracket, + RBracket, + Colon, + Comma, + Keyword, + Variable, + Identifier, + Literal, + AssignOperator, + EqualOperator, + LessThanOperator, + LessThanEqOperator, + GreaterThanOperator, + GreaterThanEqOperator, + NotEqualOperator, + PlusOperator, + MinusOperator, + MultiplyOperator, + DivideOperator, + NotOperator, + Dot, + NewLine, + Error, + } } \ No newline at end of file diff --git a/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs b/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs index 7e5522044..7069b8c51 100644 --- a/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs +++ b/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs @@ -21,306 +21,307 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot.Interpreter; - -public class BuiltInIdentifierConfigurator +namespace EOBot.Interpreter { - private readonly ProgramState _state; - private readonly int _botIndex; - private readonly ArgumentsParser _parsedArgs; - private readonly BotHelper _botHelper; - private readonly Random _random; - - public BuiltInIdentifierConfigurator(ProgramState state, int botIndex, ArgumentsParser parsedArgs) + public class BuiltInIdentifierConfigurator { - _state = state; - _botIndex = botIndex; - _parsedArgs = parsedArgs; - _botHelper = new BotHelper(_botIndex); - _random = new Random(); - } + private readonly ProgramState _state; + private readonly int _botIndex; + private readonly ArgumentsParser _parsedArgs; + private readonly BotHelper _botHelper; + private readonly Random _random; - public void SetupBuiltInFunctions() - { - _state.SymbolTable[PredefinedIdentifiers.PRINT_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.PRINT_FUNC, param1 => ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, param1.ToString()))); - _state.SymbolTable[PredefinedIdentifiers.LEN_FUNC] = Readonly(new Function(PredefinedIdentifiers.LEN_FUNC, param1 => param1.Value.Count)); - _state.SymbolTable[PredefinedIdentifiers.ARRAY_FUNC] = Readonly(new Function>(PredefinedIdentifiers.ARRAY_FUNC, param1 => Enumerable.Repeat(UndefinedVariable.Instance, param1).Cast().ToList())); - _state.SymbolTable[PredefinedIdentifiers.SLEEP_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.SLEEP_FUNC, param1 => Thread.Sleep(param1))); - _state.SymbolTable[PredefinedIdentifiers.TIME_FUNC] = Readonly(new Function(PredefinedIdentifiers.TIME_FUNC, () => DateTime.Now.ToLongTimeString())); - _state.SymbolTable[PredefinedIdentifiers.OBJECT_FUNC] = Readonly(new Function(PredefinedIdentifiers.OBJECT_FUNC, () => new ObjectVariable())); - _state.SymbolTable[PredefinedIdentifiers.SETENV_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.SETENV_FUNC, (varName, varValue) => Environment.SetEnvironmentVariable(varName, varValue, EnvironmentVariableTarget.User))); - _state.SymbolTable[PredefinedIdentifiers.GETENV_FUNC] = Readonly(new Function(PredefinedIdentifiers.GETENV_FUNC, varName => Environment.GetEnvironmentVariable(varName, EnvironmentVariableTarget.User))); - _state.SymbolTable[PredefinedIdentifiers.ERROR_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.ERROR_FUNC, message => throw new BotScriptErrorException(message))); - _state.SymbolTable[PredefinedIdentifiers.LOWER_FUNC] = Readonly(new Function(PredefinedIdentifiers.LOWER_FUNC, s => s.ToLower())); - _state.SymbolTable[PredefinedIdentifiers.UPPER_FUNC] = Readonly(new Function(PredefinedIdentifiers.UPPER_FUNC, s => s.ToUpper())); - - BotDependencySetup(); - // pre-game flow - _state.SymbolTable[PredefinedIdentifiers.CONNECT_FUNC] = Readonly(new AsyncVoidFunction(PredefinedIdentifiers.CONNECT_FUNC, ConnectAsync)); - _state.SymbolTable[PredefinedIdentifiers.DISCONNECT_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.DISCONNECT_FUNC, Disconnect)); - _state.SymbolTable[PredefinedIdentifiers.CREATE_ACCOUNT_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_ACCOUNT_FUNC, CreateAccountAsync)); - _state.SymbolTable[PredefinedIdentifiers.LOGIN_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.LOGIN_FUNC, LoginAsync)); - _state.SymbolTable[PredefinedIdentifiers.CREATE_AND_LOGIN_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_AND_LOGIN_FUNC, CreateAndLoginAsync)); - _state.SymbolTable[PredefinedIdentifiers.CHANGE_PASS_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CHANGE_PASS_FUNC, ChangePasswordAsync)); - _state.SymbolTable[PredefinedIdentifiers.CREATE_CHARACTER_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_CHARACTER_FUNC, CreateCharacterAsync)); - _state.SymbolTable[PredefinedIdentifiers.DELETE_CHARACTER_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.DELETE_CHARACTER_FUNC, DeleteCharacterAsync)); - _state.SymbolTable[PredefinedIdentifiers.LOGIN_CHARACTER_FUNC] = Readonly(new AsyncVoidFunction(PredefinedIdentifiers.LOGIN_CHARACTER_FUNC, LoginToCharacterAsync)); - - // in-game stuff - _state.SymbolTable[PredefinedIdentifiers.JOIN_PARTY] = Readonly(new VoidFunction(PredefinedIdentifiers.JOIN_PARTY, JoinParty)); - _state.SymbolTable[PredefinedIdentifiers.CHAT] = Readonly(new VoidFunction(PredefinedIdentifiers.CHAT, Chat)); - } + public BuiltInIdentifierConfigurator(ProgramState state, int botIndex, ArgumentsParser parsedArgs) + { + _state = state; + _botIndex = botIndex; + _parsedArgs = parsedArgs; + _botHelper = new BotHelper(_botIndex); + _random = new Random(); + } - public void SetupBuiltInVariables() - { - _state.SymbolTable[PredefinedIdentifiers.HOST] = Readonly(new StringVariable(_parsedArgs.Host)); - _state.SymbolTable[PredefinedIdentifiers.PORT] = Readonly(new IntVariable(_parsedArgs.Port)); - _state.SymbolTable[PredefinedIdentifiers.USER] = Readonly(new StringVariable(_parsedArgs.Account)); - _state.SymbolTable[PredefinedIdentifiers.PASS] = Readonly(new StringVariable(_parsedArgs.Password)); - _state.SymbolTable[PredefinedIdentifiers.BOTINDEX] = Readonly(new IntVariable(_botIndex)); - _state.SymbolTable[PredefinedIdentifiers.ARGS] = Readonly(new ArrayVariable( - (_parsedArgs.UserArgs ?? new List()).Select(x => new StringVariable(x)).Cast().ToList())); - - // default to version 0.0.28 - _state.SymbolTable[PredefinedIdentifiers.VERSION] = (false, new IntVariable(28)); - - _state.SymbolTable[PredefinedIdentifiers.RESULT] = (false, UndefinedVariable.Instance); - _state.SymbolTable[PredefinedIdentifiers.ACCOUNT] = SetupAccountObject(); - _state.SymbolTable[PredefinedIdentifiers.CHARACTER] = SetupCharacterObject(); - _state.SymbolTable[PredefinedIdentifiers.MAPSTATE] = SetupMapStateObject(); - } + public void SetupBuiltInFunctions() + { + _state.SymbolTable[PredefinedIdentifiers.PRINT_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.PRINT_FUNC, param1 => ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, param1.ToString()))); + _state.SymbolTable[PredefinedIdentifiers.LEN_FUNC] = Readonly(new Function(PredefinedIdentifiers.LEN_FUNC, param1 => param1.Value.Count)); + _state.SymbolTable[PredefinedIdentifiers.ARRAY_FUNC] = Readonly(new Function>(PredefinedIdentifiers.ARRAY_FUNC, param1 => Enumerable.Repeat(UndefinedVariable.Instance, param1).Cast().ToList())); + _state.SymbolTable[PredefinedIdentifiers.SLEEP_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.SLEEP_FUNC, param1 => Thread.Sleep(param1))); + _state.SymbolTable[PredefinedIdentifiers.TIME_FUNC] = Readonly(new Function(PredefinedIdentifiers.TIME_FUNC, () => DateTime.Now.ToLongTimeString())); + _state.SymbolTable[PredefinedIdentifiers.OBJECT_FUNC] = Readonly(new Function(PredefinedIdentifiers.OBJECT_FUNC, () => new ObjectVariable())); + _state.SymbolTable[PredefinedIdentifiers.SETENV_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.SETENV_FUNC, (varName, varValue) => Environment.SetEnvironmentVariable(varName, varValue, EnvironmentVariableTarget.User))); + _state.SymbolTable[PredefinedIdentifiers.GETENV_FUNC] = Readonly(new Function(PredefinedIdentifiers.GETENV_FUNC, varName => Environment.GetEnvironmentVariable(varName, EnvironmentVariableTarget.User))); + _state.SymbolTable[PredefinedIdentifiers.ERROR_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.ERROR_FUNC, message => throw new BotScriptErrorException(message))); + _state.SymbolTable[PredefinedIdentifiers.LOWER_FUNC] = Readonly(new Function(PredefinedIdentifiers.LOWER_FUNC, s => s.ToLower())); + _state.SymbolTable[PredefinedIdentifiers.UPPER_FUNC] = Readonly(new Function(PredefinedIdentifiers.UPPER_FUNC, s => s.ToUpper())); + + BotDependencySetup(); + // pre-game flow + _state.SymbolTable[PredefinedIdentifiers.CONNECT_FUNC] = Readonly(new AsyncVoidFunction(PredefinedIdentifiers.CONNECT_FUNC, ConnectAsync)); + _state.SymbolTable[PredefinedIdentifiers.DISCONNECT_FUNC] = Readonly(new VoidFunction(PredefinedIdentifiers.DISCONNECT_FUNC, Disconnect)); + _state.SymbolTable[PredefinedIdentifiers.CREATE_ACCOUNT_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_ACCOUNT_FUNC, CreateAccountAsync)); + _state.SymbolTable[PredefinedIdentifiers.LOGIN_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.LOGIN_FUNC, LoginAsync)); + _state.SymbolTable[PredefinedIdentifiers.CREATE_AND_LOGIN_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_AND_LOGIN_FUNC, CreateAndLoginAsync)); + _state.SymbolTable[PredefinedIdentifiers.CHANGE_PASS_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CHANGE_PASS_FUNC, ChangePasswordAsync)); + _state.SymbolTable[PredefinedIdentifiers.CREATE_CHARACTER_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.CREATE_CHARACTER_FUNC, CreateCharacterAsync)); + _state.SymbolTable[PredefinedIdentifiers.DELETE_CHARACTER_FUNC] = Readonly(new AsyncFunction(PredefinedIdentifiers.DELETE_CHARACTER_FUNC, DeleteCharacterAsync)); + _state.SymbolTable[PredefinedIdentifiers.LOGIN_CHARACTER_FUNC] = Readonly(new AsyncVoidFunction(PredefinedIdentifiers.LOGIN_CHARACTER_FUNC, LoginToCharacterAsync)); + + // in-game stuff + _state.SymbolTable[PredefinedIdentifiers.JOIN_PARTY] = Readonly(new VoidFunction(PredefinedIdentifiers.JOIN_PARTY, JoinParty)); + _state.SymbolTable[PredefinedIdentifiers.CHAT] = Readonly(new VoidFunction(PredefinedIdentifiers.CHAT, Chat)); + } - private static (bool, IIdentifiable) Readonly(IIdentifiable identifiable) - { - return (true, identifiable); - } + public void SetupBuiltInVariables() + { + _state.SymbolTable[PredefinedIdentifiers.HOST] = Readonly(new StringVariable(_parsedArgs.Host)); + _state.SymbolTable[PredefinedIdentifiers.PORT] = Readonly(new IntVariable(_parsedArgs.Port)); + _state.SymbolTable[PredefinedIdentifiers.USER] = Readonly(new StringVariable(_parsedArgs.Account)); + _state.SymbolTable[PredefinedIdentifiers.PASS] = Readonly(new StringVariable(_parsedArgs.Password)); + _state.SymbolTable[PredefinedIdentifiers.BOTINDEX] = Readonly(new IntVariable(_botIndex)); + _state.SymbolTable[PredefinedIdentifiers.ARGS] = Readonly(new ArrayVariable( + (_parsedArgs.UserArgs ?? new List()).Select(x => new StringVariable(x)).Cast().ToList())); + + // default to version 0.0.28 + _state.SymbolTable[PredefinedIdentifiers.VERSION] = (false, new IntVariable(28)); + + _state.SymbolTable[PredefinedIdentifiers.RESULT] = (false, UndefinedVariable.Instance); + _state.SymbolTable[PredefinedIdentifiers.ACCOUNT] = SetupAccountObject(); + _state.SymbolTable[PredefinedIdentifiers.CHARACTER] = SetupCharacterObject(); + _state.SymbolTable[PredefinedIdentifiers.MAPSTATE] = SetupMapStateObject(); + } - private void BotDependencySetup() - { - var c = DependencyMaster.TypeRegistry[_botIndex]; - var networkClientRepository = c.Resolve(); - var networkClientFactory = c.Resolve(); + private static (bool, IIdentifiable) Readonly(IIdentifiable identifiable) + { + return (true, identifiable); + } - const int LongReceiveTimeout = 15000; - networkClientRepository.NetworkClient = networkClientFactory.CreateNetworkClient(LongReceiveTimeout); - } + private void BotDependencySetup() + { + var c = DependencyMaster.TypeRegistry[_botIndex]; + var networkClientRepository = c.Resolve(); + var networkClientFactory = c.Resolve(); - private async Task ConnectAsync(string host, int port) - { - var c = DependencyMaster.TypeRegistry[_botIndex]; + const int LongReceiveTimeout = 15000; + networkClientRepository.NetworkClient = networkClientFactory.CreateNetworkClient(LongReceiveTimeout); + } - var configRepo = c.Resolve(); - configRepo.Host = host; - configRepo.Port = port; + private async Task ConnectAsync(string host, int port) + { + var c = DependencyMaster.TypeRegistry[_botIndex]; - configRepo.VersionBuild = ((IntVariable)_state.SymbolTable[PredefinedIdentifiers.VERSION].Identifiable).Value; + var configRepo = c.Resolve(); + configRepo.Host = host; + configRepo.Port = port; - var connectionActions = c.Resolve(); - var connectResult = await connectionActions.ConnectToServer(); - if (connectResult != ConnectResult.Success) - throw new ArgumentException($"Bot {_botIndex}: Unable to connect to server! Host={host} Port={port}"); + configRepo.VersionBuild = ((IntVariable)_state.SymbolTable[PredefinedIdentifiers.VERSION].Identifiable).Value; - var backgroundReceiveActions = c.Resolve(); - backgroundReceiveActions.RunBackgroundReceiveLoop(); + var connectionActions = c.Resolve(); + var connectResult = await connectionActions.ConnectToServer(); + if (connectResult != ConnectResult.Success) + throw new ArgumentException($"Bot {_botIndex}: Unable to connect to server! Host={host} Port={port}"); - var handshakeResult = await connectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)); + var backgroundReceiveActions = c.Resolve(); + backgroundReceiveActions.RunBackgroundReceiveLoop(); - if (handshakeResult.ReplyCode != InitReply.Ok) - throw new InvalidOperationException($"Bot {_botIndex}: Invalid response from server or connection failed! Must receive an OK reply."); + var handshakeResult = await connectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)); - var handshakeData = (InitInitServerPacket.ReplyCodeDataOk)handshakeResult.ReplyCodeData; + if (handshakeResult.ReplyCode != InitReply.Ok) + throw new InvalidOperationException($"Bot {_botIndex}: Invalid response from server or connection failed! Must receive an OK reply."); - var packetProcessActions = c.Resolve(); - packetProcessActions.SetSequenceStart(InitSequenceStart.FromInitValues(handshakeData.Seq1, handshakeData.Seq2)); - packetProcessActions.SetEncodeMultiples(handshakeData.ServerEncryptionMultiple, handshakeData.ClientEncryptionMultiple); + var handshakeData = (InitInitServerPacket.ReplyCodeDataOk)handshakeResult.ReplyCodeData; - connectionActions.CompleteHandshake(handshakeResult); - } + var packetProcessActions = c.Resolve(); + packetProcessActions.SetSequenceStart(InitSequenceStart.FromInitValues(handshakeData.Seq1, handshakeData.Seq2)); + packetProcessActions.SetEncodeMultiples(handshakeData.ServerEncryptionMultiple, handshakeData.ClientEncryptionMultiple); - private void Disconnect() - { - var c = DependencyMaster.TypeRegistry[_botIndex]; - var backgroundReceiveActions = c.Resolve(); - var connectionActions = c.Resolve(); + connectionActions.CompleteHandshake(handshakeResult); + } - backgroundReceiveActions.CancelBackgroundReceiveLoop(); - connectionActions.DisconnectFromServer(); - } + private void Disconnect() + { + var c = DependencyMaster.TypeRegistry[_botIndex]; + var backgroundReceiveActions = c.Resolve(); + var connectionActions = c.Resolve(); - private async Task CreateAccountAsync(string user, string pass) - { - return (int)await _botHelper.CreateAccountAsync(user, pass); - } + backgroundReceiveActions.CancelBackgroundReceiveLoop(); + connectionActions.DisconnectFromServer(); + } - private async Task LoginAsync(string user, string pass) - { - return (int)await _botHelper.LoginToAccountAsync(user, pass); - } + private async Task CreateAccountAsync(string user, string pass) + { + return (int)await _botHelper.CreateAccountAsync(user, pass); + } - private async Task CreateAndLoginAsync(string user, string pass) - { - var accountReply = (AccountReply)await CreateAccountAsync(user, pass); - if (accountReply == AccountReply.Created || accountReply == AccountReply.Exists) + private async Task LoginAsync(string user, string pass) { - return await LoginAsync(user, pass); + return (int)await _botHelper.LoginToAccountAsync(user, pass); } - return (int)LoginReply.WrongUser; - } + private async Task CreateAndLoginAsync(string user, string pass) + { + var accountReply = (AccountReply)await CreateAccountAsync(user, pass); + if (accountReply == AccountReply.Created || accountReply == AccountReply.Exists) + { + return await LoginAsync(user, pass); + } - private async Task ChangePasswordAsync(string user, string oldPass, string newPass) - { - return (int)await _botHelper.ChangePasswordAsync(user, oldPass, newPass); - } + return (int)LoginReply.WrongUser; + } - private async Task CreateCharacterAsync(string charName) - { - return (int)await _botHelper.CreateCharacterAsync(charName); - } + private async Task ChangePasswordAsync(string user, string oldPass, string newPass) + { + return (int)await _botHelper.ChangePasswordAsync(user, oldPass, newPass); + } - private async Task DeleteCharacterAsync(string charName, bool force) - { - return (int)await _botHelper.DeleteCharacterAsync(charName, force); - } + private async Task CreateCharacterAsync(string charName) + { + return (int)await _botHelper.CreateCharacterAsync(charName); + } - private Task LoginToCharacterAsync(string charName) - { - return _botHelper.LoginToCharacterAsync(charName); - } + private async Task DeleteCharacterAsync(string charName, bool force) + { + return (int)await _botHelper.DeleteCharacterAsync(charName, force); + } - private void JoinParty(int characterId) - { - var c = DependencyMaster.TypeRegistry[_botIndex]; - c.Resolve().RequestParty(PartyRequestType.Join, characterId); - } + private Task LoginToCharacterAsync(string charName) + { + return _botHelper.LoginToCharacterAsync(charName); + } - private void Chat(string chatText) - { - var c = DependencyMaster.TypeRegistry[_botIndex]; - c.Resolve().SendChatToServer(chatText, string.Empty, ChatType.Local); - } + private void JoinParty(int characterId) + { + var c = DependencyMaster.TypeRegistry[_botIndex]; + c.Resolve().RequestParty(PartyRequestType.Join, characterId); + } - private (bool, IIdentifiable) SetupAccountObject() - { - var playerInfoProv = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var charSelectProv = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - - var accountObj = new RuntimeEvaluatedMemberObjectVariable(); - accountObj.SymbolTable[PredefinedIdentifiers.NAME] = (true, () => new StringVariable(playerInfoProv.LoggedInAccountName)); - accountObj.SymbolTable[PredefinedIdentifiers.CHARACTERS] = (true, - () => new ArrayVariable( - charSelectProv.Characters.Select(x => - { - var retObj = new ObjectVariable(); - retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(x.Name)); - return (IVariable)retObj; - }).ToList())); + private void Chat(string chatText) + { + var c = DependencyMaster.TypeRegistry[_botIndex]; + c.Resolve().SendChatToServer(chatText, string.Empty, ChatType.Local); + } - return Readonly(accountObj); - } + private (bool, IIdentifiable) SetupAccountObject() + { + var playerInfoProv = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var charSelectProv = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + + var accountObj = new RuntimeEvaluatedMemberObjectVariable(); + accountObj.SymbolTable[PredefinedIdentifiers.NAME] = (true, () => new StringVariable(playerInfoProv.LoggedInAccountName)); + accountObj.SymbolTable[PredefinedIdentifiers.CHARACTERS] = (true, + () => new ArrayVariable( + charSelectProv.Characters.Select(x => + { + var retObj = new ObjectVariable(); + retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(x.Name)); + return (IVariable)retObj; + }).ToList())); + + return Readonly(accountObj); + } - private (bool, IIdentifiable) SetupCharacterObject() - { - var cp = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var inventoryProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var pubProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - - var charObj = new RuntimeEvaluatedMemberObjectVariable(); - charObj.SymbolTable["id"] = (true, () => new IntVariable(cp.MainCharacter.ID)); - charObj.SymbolTable[PredefinedIdentifiers.NAME] = (true, () => new StringVariable(cp.MainCharacter.Name)); - charObj.SymbolTable["map"] = (true, () => new IntVariable(cp.MainCharacter.MapID)); - charObj.SymbolTable["x"] = (true, () => new IntVariable(cp.MainCharacter.RenderProperties.MapX)); - charObj.SymbolTable["y"] = (true, () => new IntVariable(cp.MainCharacter.RenderProperties.MapY)); - charObj.SymbolTable["direction"] = (true, () => new IntVariable((int)cp.MainCharacter.RenderProperties.Direction)); - charObj.SymbolTable["admin"] = (true, () => new IntVariable((int)cp.MainCharacter.AdminLevel)); - charObj.SymbolTable["inventory"] = (true, - () => new ArrayVariable( - inventoryProvider.ItemInventory.Select(x => - { - var itemName = pubProvider.EIFFile.Single(d => d.ID == x.ItemID).Name; - - var retObj = new ObjectVariable(); - retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(itemName)); - retObj.SymbolTable["id"] = Readonly(new IntVariable(x.ItemID)); - retObj.SymbolTable["amount"] = Readonly(new IntVariable(x.Amount)); - return (IVariable)retObj; - }).ToList())); - charObj.SymbolTable["spells"] = (true, - () => new ArrayVariable( - inventoryProvider.SpellInventory.Select(x => + private (bool, IIdentifiable) SetupCharacterObject() + { + var cp = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var inventoryProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + var pubProvider = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + + var charObj = new RuntimeEvaluatedMemberObjectVariable(); + charObj.SymbolTable["id"] = (true, () => new IntVariable(cp.MainCharacter.ID)); + charObj.SymbolTable[PredefinedIdentifiers.NAME] = (true, () => new StringVariable(cp.MainCharacter.Name)); + charObj.SymbolTable["map"] = (true, () => new IntVariable(cp.MainCharacter.MapID)); + charObj.SymbolTable["x"] = (true, () => new IntVariable(cp.MainCharacter.RenderProperties.MapX)); + charObj.SymbolTable["y"] = (true, () => new IntVariable(cp.MainCharacter.RenderProperties.MapY)); + charObj.SymbolTable["direction"] = (true, () => new IntVariable((int)cp.MainCharacter.RenderProperties.Direction)); + charObj.SymbolTable["admin"] = (true, () => new IntVariable((int)cp.MainCharacter.AdminLevel)); + charObj.SymbolTable["inventory"] = (true, + () => new ArrayVariable( + inventoryProvider.ItemInventory.Select(x => + { + var itemName = pubProvider.EIFFile.Single(d => d.ID == x.ItemID).Name; + + var retObj = new ObjectVariable(); + retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(itemName)); + retObj.SymbolTable["id"] = Readonly(new IntVariable(x.ItemID)); + retObj.SymbolTable["amount"] = Readonly(new IntVariable(x.Amount)); + return (IVariable)retObj; + }).ToList())); + charObj.SymbolTable["spells"] = (true, + () => new ArrayVariable( + inventoryProvider.SpellInventory.Select(x => + { + var spellName = pubProvider.ESFFile.Single(d => d.ID == x.ID).Name; + + var retObj = new ObjectVariable(); + retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(spellName)); + retObj.SymbolTable["id"] = Readonly(new IntVariable(x.ID)); + retObj.SymbolTable["amount"] = Readonly(new IntVariable(x.Level)); + return (IVariable)retObj; + }).ToList())); + charObj.SymbolTable["stats"] = (true, + () => { - var spellName = pubProvider.ESFFile.Single(d => d.ID == x.ID).Name; - - var retObj = new ObjectVariable(); - retObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(spellName)); - retObj.SymbolTable["id"] = Readonly(new IntVariable(x.ID)); - retObj.SymbolTable["amount"] = Readonly(new IntVariable(x.Level)); - return (IVariable)retObj; - }).ToList())); - charObj.SymbolTable["stats"] = (true, - () => - { - var statsObj = new ObjectVariable(); - statsObj.SymbolTable["hp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.HP])); - statsObj.SymbolTable["maxhp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxHP])); - statsObj.SymbolTable["weight"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.Weight])); - statsObj.SymbolTable["maxweight"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxWeight])); - statsObj.SymbolTable["tp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.TP])); - statsObj.SymbolTable["maxtp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxTP])); - return statsObj; - } - ); - - return Readonly(charObj); - } + var statsObj = new ObjectVariable(); + statsObj.SymbolTable["hp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.HP])); + statsObj.SymbolTable["maxhp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxHP])); + statsObj.SymbolTable["weight"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.Weight])); + statsObj.SymbolTable["maxweight"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxWeight])); + statsObj.SymbolTable["tp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.TP])); + statsObj.SymbolTable["maxtp"] = Readonly(new IntVariable(cp.MainCharacter.Stats[CharacterStat.MaxTP])); + return statsObj; + } + ); + + return Readonly(charObj); + } - private (bool, IIdentifiable) SetupMapStateObject() - { - var ms = DependencyMaster.TypeRegistry[_botIndex].Resolve(); + private (bool, IIdentifiable) SetupMapStateObject() + { + var ms = DependencyMaster.TypeRegistry[_botIndex].Resolve(); - var mapStateObj = new RuntimeEvaluatedMemberObjectVariable(); - mapStateObj.SymbolTable["characters"] = (true, () => new ArrayVariable(ms.Characters.Select(GetMapStateCharacter).ToList())); - mapStateObj.SymbolTable["npcs"] = (true, () => new ArrayVariable(ms.NPCs.Select(GetMapStateNPC).ToList())); - mapStateObj.SymbolTable["items"] = (true, () => new ArrayVariable(ms.MapItems.Select(GetMapStateItem).ToList())); + var mapStateObj = new RuntimeEvaluatedMemberObjectVariable(); + mapStateObj.SymbolTable["characters"] = (true, () => new ArrayVariable(ms.Characters.Select(GetMapStateCharacter).ToList())); + mapStateObj.SymbolTable["npcs"] = (true, () => new ArrayVariable(ms.NPCs.Select(GetMapStateNPC).ToList())); + mapStateObj.SymbolTable["items"] = (true, () => new ArrayVariable(ms.MapItems.Select(GetMapStateItem).ToList())); - return Readonly(mapStateObj); - } + return Readonly(mapStateObj); + } - private IVariable GetMapStateCharacter(Character c) - { - var charObj = new ObjectVariable(); - charObj.SymbolTable["id"] = Readonly(new IntVariable(c.ID)); - charObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(c.Name)); - charObj.SymbolTable["map"] = Readonly(new IntVariable(c.MapID)); - charObj.SymbolTable["x"] = Readonly(new IntVariable(c.RenderProperties.MapX)); - charObj.SymbolTable["y"] = Readonly(new IntVariable(c.RenderProperties.MapY)); - charObj.SymbolTable["direction"] = Readonly(new IntVariable((int)c.RenderProperties.Direction)); - return charObj; - } + private IVariable GetMapStateCharacter(Character c) + { + var charObj = new ObjectVariable(); + charObj.SymbolTable["id"] = Readonly(new IntVariable(c.ID)); + charObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(c.Name)); + charObj.SymbolTable["map"] = Readonly(new IntVariable(c.MapID)); + charObj.SymbolTable["x"] = Readonly(new IntVariable(c.RenderProperties.MapX)); + charObj.SymbolTable["y"] = Readonly(new IntVariable(c.RenderProperties.MapY)); + charObj.SymbolTable["direction"] = Readonly(new IntVariable((int)c.RenderProperties.Direction)); + return charObj; + } - private IVariable GetMapStateNPC(NPC npc) - { - var npcFile = DependencyMaster.TypeRegistry[_botIndex].Resolve().ENFFile; - - var npcObj = new ObjectVariable(); - npcObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(npcFile.Single(x => x.ID == npc.ID).Name)); - npcObj.SymbolTable["x"] = Readonly(new IntVariable(npc.X)); - npcObj.SymbolTable["y"] = Readonly(new IntVariable(npc.Y)); - npcObj.SymbolTable["id"] = Readonly(new IntVariable(npc.ID)); - npcObj.SymbolTable["direction"] = Readonly(new IntVariable((int)npc.Direction)); - return npcObj; - } + private IVariable GetMapStateNPC(NPC npc) + { + var npcFile = DependencyMaster.TypeRegistry[_botIndex].Resolve().ENFFile; + + var npcObj = new ObjectVariable(); + npcObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(npcFile.Single(x => x.ID == npc.ID).Name)); + npcObj.SymbolTable["x"] = Readonly(new IntVariable(npc.X)); + npcObj.SymbolTable["y"] = Readonly(new IntVariable(npc.Y)); + npcObj.SymbolTable["id"] = Readonly(new IntVariable(npc.ID)); + npcObj.SymbolTable["direction"] = Readonly(new IntVariable((int)npc.Direction)); + return npcObj; + } - private IVariable GetMapStateItem(MapItem item) - { - var itemFile = DependencyMaster.TypeRegistry[_botIndex].Resolve().EIFFile; - - var itemObj = new ObjectVariable(); - itemObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(itemFile.Single(x => x.ID == item.ItemID).Name)); - itemObj.SymbolTable["x"] = Readonly(new IntVariable(item.X)); - itemObj.SymbolTable["y"] = Readonly(new IntVariable(item.Y)); - itemObj.SymbolTable["id"] = Readonly(new IntVariable(item.ItemID)); - itemObj.SymbolTable["amount"] = Readonly(new IntVariable(item.Amount)); - return itemObj; + private IVariable GetMapStateItem(MapItem item) + { + var itemFile = DependencyMaster.TypeRegistry[_botIndex].Resolve().EIFFile; + + var itemObj = new ObjectVariable(); + itemObj.SymbolTable[PredefinedIdentifiers.NAME] = Readonly(new StringVariable(itemFile.Single(x => x.ID == item.ItemID).Name)); + itemObj.SymbolTable["x"] = Readonly(new IntVariable(item.X)); + itemObj.SymbolTable["y"] = Readonly(new IntVariable(item.Y)); + itemObj.SymbolTable["id"] = Readonly(new IntVariable(item.ItemID)); + itemObj.SymbolTable["amount"] = Readonly(new IntVariable(item.Amount)); + return itemObj; + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs b/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs index 19f1d6f72..4a7ec0625 100644 --- a/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs +++ b/EOBot/Interpreter/Extensions/ProgramStateExtensions.cs @@ -1,27 +1,28 @@ using EOBot.Interpreter.States; -namespace EOBot.Interpreter.Extensions; - -public static class ProgramStateExtensions +namespace EOBot.Interpreter.Extensions { - public static bool MatchOneOf(this ProgramState input, params BotTokenType[] tokenTypes) + public static class ProgramStateExtensions { - // todo: there's probably LINQ for this but I'm tired and my brain isn't quite working - // needs to stop trying to match after first match, can't use FirstOrDefault unless default(BotTokenType) can be used as an "empty" value - foreach (var type in tokenTypes) + public static bool MatchOneOf(this ProgramState input, params BotTokenType[] tokenTypes) { - if (input.Match(type)) - return true; - } + // todo: there's probably LINQ for this but I'm tired and my brain isn't quite working + // needs to stop trying to match after first match, can't use FirstOrDefault unless default(BotTokenType) can be used as an "empty" value + foreach (var type in tokenTypes) + { + if (input.Match(type)) + return true; + } - return false; - } + return false; + } - public static BotToken Current(this ProgramState input) - { - if (input.ExecutionIndex >= input.Program.Count) - return input.Program[input.Program.Count - 1]; + public static BotToken Current(this ProgramState input) + { + if (input.ExecutionIndex >= input.Program.Count) + return input.Program[input.Program.Count - 1]; - return input.Program[input.ExecutionIndex]; + return input.Program[input.ExecutionIndex]; + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs b/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs index aefdbdf21..974525d41 100644 --- a/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs +++ b/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs @@ -2,54 +2,55 @@ using EOBot.Interpreter.Variables; using System.Collections.Generic; -namespace EOBot.Interpreter.Extensions; - -public static class SymbolTableExtensions +namespace EOBot.Interpreter.Extensions { - - public static (EvalResult Result, string Reason, IVariable Variable) GetVariable(this Dictionary symbols, string identifier, int? arrayIndex = null) + public static class SymbolTableExtensions { - if (!symbols.ContainsKey(identifier)) - symbols[identifier] = (false, UndefinedVariable.Instance); - var variableValue = symbols[identifier].Identifiable as IVariable; - if (variableValue == null) + public static (EvalResult Result, string Reason, IVariable Variable) GetVariable(this Dictionary symbols, string identifier, int? arrayIndex = null) { - return (EvalResult.Failed, $"Identifier {identifier} is not a variable", null); - } + if (!symbols.ContainsKey(identifier)) + symbols[identifier] = (false, UndefinedVariable.Instance); - if (arrayIndex != null) - { - var arrayVariable = variableValue as ArrayVariable; - - if (arrayVariable == null) + var variableValue = symbols[identifier].Identifiable as IVariable; + if (variableValue == null) { - return (EvalResult.Failed, $"Identifier {identifier} is not an array", null); + return (EvalResult.Failed, $"Identifier {identifier} is not a variable", null); } - if (arrayVariable.Value.Count <= arrayIndex.Value) + if (arrayIndex != null) { - return (EvalResult.Failed, $"Index {arrayIndex.Value} is out of range of the array {identifier} (size {arrayVariable.Value.Count})", null); + var arrayVariable = variableValue as ArrayVariable; + + if (arrayVariable == null) + { + return (EvalResult.Failed, $"Identifier {identifier} is not an array", null); + } + + if (arrayVariable.Value.Count <= arrayIndex.Value) + { + return (EvalResult.Failed, $"Index {arrayIndex.Value} is out of range of the array {identifier} (size {arrayVariable.Value.Count})", null); + } + + variableValue = arrayVariable.Value[arrayIndex.Value]; } - variableValue = arrayVariable.Value[arrayIndex.Value]; + return (EvalResult.Ok, string.Empty, variableValue); } - return (EvalResult.Ok, string.Empty, variableValue); - } - - public static (EvalResult Result, string Reason, T Variable) GetVariable(this Dictionary symbols, string identifier, int? arrayIndex = null) - where T : class, IVariable - { - var getResult = GetVariable(symbols, identifier, arrayIndex); + public static (EvalResult Result, string Reason, T Variable) GetVariable(this Dictionary symbols, string identifier, int? arrayIndex = null) + where T : class, IVariable + { + var getResult = GetVariable(symbols, identifier, arrayIndex); - if (getResult.Result != EvalResult.Ok) - return (getResult.Result, getResult.Reason, null); + if (getResult.Result != EvalResult.Ok) + return (getResult.Result, getResult.Reason, null); - var variable = getResult.Variable as T; - if (variable == null) - return (EvalResult.Failed, $"Identifier {identifier} is not a {typeof(T).Name}", null); + var variable = getResult.Variable as T; + if (variable == null) + return (EvalResult.Failed, $"Identifier {identifier} is not a {typeof(T).Name}", null); - return (EvalResult.Ok, string.Empty, variable); + return (EvalResult.Ok, string.Empty, variable); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/IdentifierBotToken.cs b/EOBot/Interpreter/IdentifierBotToken.cs index 50ec2250d..5b59a915e 100644 --- a/EOBot/Interpreter/IdentifierBotToken.cs +++ b/EOBot/Interpreter/IdentifierBotToken.cs @@ -1,15 +1,16 @@ -namespace EOBot.Interpreter; - -public class IdentifierBotToken : BotToken +namespace EOBot.Interpreter { - public int? ArrayIndex { get; } + public class IdentifierBotToken : BotToken + { + public int? ArrayIndex { get; } - public IdentifierBotToken Member { get; } + public IdentifierBotToken Member { get; } - public IdentifierBotToken(BotToken identifier, int? arrayIndex = null, IdentifierBotToken member = null) - : base(identifier.TokenType, identifier.TokenValue, identifier.LineNumber, identifier.Column) - { - ArrayIndex = arrayIndex; - Member = member; + public IdentifierBotToken(BotToken identifier, int? arrayIndex = null, IdentifierBotToken member = null) + : base(identifier.TokenType, identifier.TokenValue, identifier.LineNumber, identifier.Column) + { + ArrayIndex = arrayIndex; + Member = member; + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/AssignmentEvaluator.cs b/EOBot/Interpreter/States/AssignmentEvaluator.cs index ad0d3c600..4cd58275e 100644 --- a/EOBot/Interpreter/States/AssignmentEvaluator.cs +++ b/EOBot/Interpreter/States/AssignmentEvaluator.cs @@ -4,95 +4,96 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class AssignmentEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public AssignmentEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class AssignmentEvaluator : BaseEvaluator { - var eval = await Evaluator().EvaluateAsync(input); - if (eval.Result != EvalResult.Ok) - return eval; + public AssignmentEvaluator(IEnumerable evaluators) + : base(evaluators) { } - if (!input.Match(BotTokenType.AssignOperator)) - return Error(input.Current(), BotTokenType.AssignOperator); + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + var eval = await Evaluator().EvaluateAsync(input); + if (eval.Result != EvalResult.Ok) + return eval; - eval = await Evaluator().EvaluateAsync(input); - if (eval.Result != EvalResult.Ok) - return eval; + if (!input.Match(BotTokenType.AssignOperator)) + return Error(input.Current(), BotTokenType.AssignOperator); - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var expressionResult = (VariableBotToken)input.OperationStack.Pop(); + eval = await Evaluator().EvaluateAsync(input); + if (eval.Result != EvalResult.Ok) + return eval; - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var assignOp = input.OperationStack.Pop(); - if (assignOp.TokenType != BotTokenType.AssignOperator) - return StackTokenError(BotTokenType.AssignOperator, assignOp); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var expressionResult = (VariableBotToken)input.OperationStack.Pop(); - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var assignmentTarget = (IdentifierBotToken)input.OperationStack.Pop(); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var assignOp = input.OperationStack.Pop(); + if (assignOp.TokenType != BotTokenType.AssignOperator) + return StackTokenError(BotTokenType.AssignOperator, assignOp); - return Assign(input.SymbolTable, assignmentTarget, expressionResult); - } + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var assignmentTarget = (IdentifierBotToken)input.OperationStack.Pop(); - private (EvalResult, string, BotToken) Assign(Dictionary symbols, IdentifierBotToken assignmentTarget, VariableBotToken expressionResult) - { - if (assignmentTarget.Member != null) - { - if (!symbols.ContainsKey(assignmentTarget.TokenValue)) - return IdentifierNotFoundError(assignmentTarget); + return Assign(input.SymbolTable, assignmentTarget, expressionResult); + } - var getVariableRes = symbols.GetVariable(assignmentTarget.TokenValue, assignmentTarget.ArrayIndex); - if (getVariableRes.Result != EvalResult.Ok) + private (EvalResult, string, BotToken) Assign(Dictionary symbols, IdentifierBotToken assignmentTarget, VariableBotToken expressionResult) + { + if (assignmentTarget.Member != null) { - var getRuntimeEvaluatedVariableRes = symbols.GetVariable(assignmentTarget.TokenValue, assignmentTarget.ArrayIndex); - if (getRuntimeEvaluatedVariableRes.Result != EvalResult.Ok) - return (EvalResult.Failed, $"Identifier '{assignmentTarget.TokenValue}' is not an object", assignmentTarget); - - getVariableRes.Result = getRuntimeEvaluatedVariableRes.Result; - getVariableRes.Reason = getRuntimeEvaluatedVariableRes.Reason; - getVariableRes.Variable = new ObjectVariable( - getRuntimeEvaluatedVariableRes.Variable.SymbolTable - .Select(x => (x.Key, (x.Value.ReadOnly, x.Value.Variable()))) - .ToDictionary(x => x.Key, x => x.Item2)); + if (!symbols.ContainsKey(assignmentTarget.TokenValue)) + return IdentifierNotFoundError(assignmentTarget); + + var getVariableRes = symbols.GetVariable(assignmentTarget.TokenValue, assignmentTarget.ArrayIndex); + if (getVariableRes.Result != EvalResult.Ok) + { + var getRuntimeEvaluatedVariableRes = symbols.GetVariable(assignmentTarget.TokenValue, assignmentTarget.ArrayIndex); + if (getRuntimeEvaluatedVariableRes.Result != EvalResult.Ok) + return (EvalResult.Failed, $"Identifier '{assignmentTarget.TokenValue}' is not an object", assignmentTarget); + + getVariableRes.Result = getRuntimeEvaluatedVariableRes.Result; + getVariableRes.Reason = getRuntimeEvaluatedVariableRes.Reason; + getVariableRes.Variable = new ObjectVariable( + getRuntimeEvaluatedVariableRes.Variable.SymbolTable + .Select(x => (x.Key, (x.Value.ReadOnly, x.Value.Variable()))) + .ToDictionary(x => x.Key, x => x.Item2)); + } + + var targetObject = getVariableRes.Variable; + return Assign(targetObject.SymbolTable, assignmentTarget.Member, expressionResult); } - var targetObject = getVariableRes.Variable; - return Assign(targetObject.SymbolTable, assignmentTarget.Member, expressionResult); - } + if (assignmentTarget.ArrayIndex != null) + { + if (!symbols.ContainsKey(assignmentTarget.TokenValue)) + return IdentifierNotFoundError(assignmentTarget); - if (assignmentTarget.ArrayIndex != null) - { - if (!symbols.ContainsKey(assignmentTarget.TokenValue)) - return IdentifierNotFoundError(assignmentTarget); + var getVariableResult = symbols.GetVariable(assignmentTarget.TokenValue); + if (getVariableResult.Result != EvalResult.Ok) + return (getVariableResult.Result, getVariableResult.Reason, assignmentTarget); - var getVariableResult = symbols.GetVariable(assignmentTarget.TokenValue); - if (getVariableResult.Result != EvalResult.Ok) - return (getVariableResult.Result, getVariableResult.Reason, assignmentTarget); + var targetArray = getVariableResult.Variable; + targetArray.Value[assignmentTarget.ArrayIndex.Value] = expressionResult.VariableValue; + } + else + { + if (symbols.ContainsKey(assignmentTarget.TokenValue) && symbols[assignmentTarget.TokenValue].ReadOnly) + return ReadOnlyVariableError(assignmentTarget); - var targetArray = getVariableResult.Variable; - targetArray.Value[assignmentTarget.ArrayIndex.Value] = expressionResult.VariableValue; - } - else - { - if (symbols.ContainsKey(assignmentTarget.TokenValue) && symbols[assignmentTarget.TokenValue].ReadOnly) - return ReadOnlyVariableError(assignmentTarget); + if (symbols.ContainsKey(assignmentTarget.TokenValue) && symbols[assignmentTarget.TokenValue].Identifiable.GetType() != expressionResult.VariableValue.GetType()) + { + // todo: surface warnings to caller and let caller decide what to do with it instead of making the interpreter write to console directly + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Changing type of variable {assignmentTarget.TokenValue} from {symbols[assignmentTarget.TokenValue].Identifiable.GetType()} to {expressionResult.VariableValue.GetType()}", System.ConsoleColor.DarkYellow); + } - if (symbols.ContainsKey(assignmentTarget.TokenValue) && symbols[assignmentTarget.TokenValue].Identifiable.GetType() != expressionResult.VariableValue.GetType()) - { - // todo: surface warnings to caller and let caller decide what to do with it instead of making the interpreter write to console directly - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Changing type of variable {assignmentTarget.TokenValue} from {symbols[assignmentTarget.TokenValue].Identifiable.GetType()} to {expressionResult.VariableValue.GetType()}", System.ConsoleColor.DarkYellow); + symbols[assignmentTarget.TokenValue] = (false, expressionResult.VariableValue); } - symbols[assignmentTarget.TokenValue] = (false, expressionResult.VariableValue); + return Success(); } - - return Success(); } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/BaseEvaluator.cs b/EOBot/Interpreter/States/BaseEvaluator.cs index 08df15cbe..39449f0f4 100644 --- a/EOBot/Interpreter/States/BaseEvaluator.cs +++ b/EOBot/Interpreter/States/BaseEvaluator.cs @@ -2,82 +2,83 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public abstract class BaseEvaluator : IScriptEvaluator +namespace EOBot.Interpreter.States { - private readonly IEnumerable _evaluators; - - protected BaseEvaluator() { } - - protected BaseEvaluator(IEnumerable evaluators) - { - _evaluators = evaluators; - } - - public abstract Task<(EvalResult Result, string Reason, BotToken Token)> EvaluateAsync(ProgramState input); - - protected IScriptEvaluator Evaluator() where T : IScriptEvaluator - { - return _evaluators.OfType().Single(); - } - - protected (EvalResult, string, BotToken) Success(BotToken token = null) - { - return (EvalResult.Ok, string.Empty, token); - } - - protected (EvalResult, string, BotToken) Error(BotToken current, params BotTokenType[] expectedTypes) - { - var extra = string.IsNullOrWhiteSpace(current.TokenValue) - ? string.Empty - : $" ({current.TokenValue})"; - - if (expectedTypes.Length == 0) - return (EvalResult.Failed, string.Empty, current); - else if (expectedTypes.Length == 1) - return (EvalResult.Failed, $"Expected {expectedTypes[0]}, got {current.TokenType}{extra}", current); - else - return (EvalResult.Failed, $"Expected one of [{string.Join(", ", expectedTypes)}], got {current.TokenType}{extra}", current); - } - - protected (EvalResult, string, BotToken) UnexpectedTokenError(BotToken current, params BotTokenType[] unexpectedTypes) - { - if (unexpectedTypes.Length == 0) - return (EvalResult.Failed, string.Empty, current); - else if (unexpectedTypes.Length == 1) - return (EvalResult.Failed, $"{unexpectedTypes[0]} was unexpected", current); - else - return (EvalResult.Failed, $"One of {string.Join(",", unexpectedTypes)} was unexpected", current); - } - - protected (EvalResult, string, BotToken) StackEmptyError(BotToken current) - { - return (EvalResult.Failed, $"Expected operation stack to have operands, but it was empty", current); - } - - protected (EvalResult, string, BotToken) UnsupportedOperatorError(BotToken actualToken) - { - return (EvalResult.Failed, $"Unsupported operator evaluating expression: {actualToken.TokenType}", actualToken); - } - - protected (EvalResult, string, BotToken) StackTokenError(BotTokenType expectedTokenType, BotToken actualToken) - { - return (EvalResult.Failed, $"Expected operation stack to have {expectedTokenType} token, got {actualToken.TokenType}", actualToken); - } - - protected (EvalResult, string, BotToken) ReadOnlyVariableError(IdentifierBotToken token) - { - return (EvalResult.Failed, $"Attempted to assign value to read-only variable {token.TokenValue}", token); - } - - protected (EvalResult, string, BotToken) IdentifierNotFoundError(IdentifierBotToken token) - { - return (EvalResult.Failed, $"Identifier {token.TokenValue} is not defined", token); - } - - protected (EvalResult, string, BotToken) GotoError(BotToken token) + public abstract class BaseEvaluator : IScriptEvaluator { - return (EvalResult.Failed, $"Failed to goto label {token.TokenValue}", token); + private readonly IEnumerable _evaluators; + + protected BaseEvaluator() { } + + protected BaseEvaluator(IEnumerable evaluators) + { + _evaluators = evaluators; + } + + public abstract Task<(EvalResult Result, string Reason, BotToken Token)> EvaluateAsync(ProgramState input); + + protected IScriptEvaluator Evaluator() where T : IScriptEvaluator + { + return _evaluators.OfType().Single(); + } + + protected (EvalResult, string, BotToken) Success(BotToken token = null) + { + return (EvalResult.Ok, string.Empty, token); + } + + protected (EvalResult, string, BotToken) Error(BotToken current, params BotTokenType[] expectedTypes) + { + var extra = string.IsNullOrWhiteSpace(current.TokenValue) + ? string.Empty + : $" ({current.TokenValue})"; + + if (expectedTypes.Length == 0) + return (EvalResult.Failed, string.Empty, current); + else if (expectedTypes.Length == 1) + return (EvalResult.Failed, $"Expected {expectedTypes[0]}, got {current.TokenType}{extra}", current); + else + return (EvalResult.Failed, $"Expected one of [{string.Join(", ", expectedTypes)}], got {current.TokenType}{extra}", current); + } + + protected (EvalResult, string, BotToken) UnexpectedTokenError(BotToken current, params BotTokenType[] unexpectedTypes) + { + if (unexpectedTypes.Length == 0) + return (EvalResult.Failed, string.Empty, current); + else if (unexpectedTypes.Length == 1) + return (EvalResult.Failed, $"{unexpectedTypes[0]} was unexpected", current); + else + return (EvalResult.Failed, $"One of {string.Join(",", unexpectedTypes)} was unexpected", current); + } + + protected (EvalResult, string, BotToken) StackEmptyError(BotToken current) + { + return (EvalResult.Failed, $"Expected operation stack to have operands, but it was empty", current); + } + + protected (EvalResult, string, BotToken) UnsupportedOperatorError(BotToken actualToken) + { + return (EvalResult.Failed, $"Unsupported operator evaluating expression: {actualToken.TokenType}", actualToken); + } + + protected (EvalResult, string, BotToken) StackTokenError(BotTokenType expectedTokenType, BotToken actualToken) + { + return (EvalResult.Failed, $"Expected operation stack to have {expectedTokenType} token, got {actualToken.TokenType}", actualToken); + } + + protected (EvalResult, string, BotToken) ReadOnlyVariableError(IdentifierBotToken token) + { + return (EvalResult.Failed, $"Attempted to assign value to read-only variable {token.TokenValue}", token); + } + + protected (EvalResult, string, BotToken) IdentifierNotFoundError(IdentifierBotToken token) + { + return (EvalResult.Failed, $"Identifier {token.TokenValue} is not defined", token); + } + + protected (EvalResult, string, BotToken) GotoError(BotToken token) + { + return (EvalResult.Failed, $"Failed to goto label {token.TokenValue}", token); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/BlockEvaluator.cs b/EOBot/Interpreter/States/BlockEvaluator.cs index 21e83deb2..eca9cec26 100644 --- a/EOBot/Interpreter/States/BlockEvaluator.cs +++ b/EOBot/Interpreter/States/BlockEvaluator.cs @@ -2,106 +2,107 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public abstract class BlockEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - protected BlockEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - protected async Task<(EvalResult, string, BotToken)> EvaluateConditionAsync(int blockStartIndex, ProgramState input) + public abstract class BlockEvaluator : BaseEvaluator { - input.Goto(blockStartIndex); - - if (!input.ExpectPair(BotTokenType.Keyword, BotTokenType.LParen)) - return (EvalResult.Failed, "Missing keyword and lparen to start condition evaluation", input.Current()); + protected BlockEvaluator(IEnumerable evaluators) + : base(evaluators) { } - var evalResult = await Evaluator().EvaluateAsync(input); - if (evalResult.Result != EvalResult.Ok) - return evalResult; - - if (!input.Expect(BotTokenType.RParen)) - return Error(input.Current(), BotTokenType.RParen); + protected async Task<(EvalResult, string, BotToken)> EvaluateConditionAsync(int blockStartIndex, ProgramState input) + { + input.Goto(blockStartIndex); - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); + if (!input.ExpectPair(BotTokenType.Keyword, BotTokenType.LParen)) + return (EvalResult.Failed, "Missing keyword and lparen to start condition evaluation", input.Current()); - return Success(input.OperationStack.Pop()); - } + var evalResult = await Evaluator().EvaluateAsync(input); + if (evalResult.Result != EvalResult.Ok) + return evalResult; - protected async Task<(EvalResult, string, BotToken)> EvaluateBlockAsync(ProgramState input) - { - input.Expect(BotTokenType.NewLine); + if (!input.Expect(BotTokenType.RParen)) + return Error(input.Current(), BotTokenType.RParen); - (EvalResult Result, string, BotToken) evalResult; + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); - // either: multi-line statement / evaluate statement list (consumes RBrace as end condition) - // or: single statement - // evaluated in separate blocks because we want to check statement list OR statement, not both - if (input.Expect(BotTokenType.LBrace)) - { - evalResult = await Evaluator().EvaluateAsync(input); - if (evalResult.Result != EvalResult.Ok) - return evalResult; + return Success(input.OperationStack.Pop()); } - else + + protected async Task<(EvalResult, string, BotToken)> EvaluateBlockAsync(ProgramState input) { - evalResult = await Evaluator().EvaluateAsync(input); - if (evalResult.Result != EvalResult.Ok) - return evalResult; - } + input.Expect(BotTokenType.NewLine); + (EvalResult Result, string, BotToken) evalResult; - RestoreLastNewline(input); - return evalResult; - } + // either: multi-line statement / evaluate statement list (consumes RBrace as end condition) + // or: single statement + // evaluated in separate blocks because we want to check statement list OR statement, not both + if (input.Expect(BotTokenType.LBrace)) + { + evalResult = await Evaluator().EvaluateAsync(input); + if (evalResult.Result != EvalResult.Ok) + return evalResult; + } + else + { + evalResult = await Evaluator().EvaluateAsync(input); + if (evalResult.Result != EvalResult.Ok) + return evalResult; + } - protected void SkipBlock(ProgramState input) - { - // ensure that for 'else if' the if condition is skipped as well - var current = input.Current(); - if (current.TokenType == BotTokenType.Keyword && current.TokenValue == "if") - { - input.Expect(BotTokenType.Keyword); - input.Expect(BotTokenType.LParen); - while (!input.Expect(BotTokenType.RParen)) - input.SkipToken(); - } - // potential newline character - skip so we can advance execution beyond the block - input.Expect(BotTokenType.NewLine); + RestoreLastNewline(input); + return evalResult; + } - // skip the rest of the block - if (input.Expect(BotTokenType.LBrace)) + protected void SkipBlock(ProgramState input) { - int rBraceCount = 1; - while (rBraceCount > 0 && input.Current().TokenType != BotTokenType.EOF) + // ensure that for 'else if' the if condition is skipped as well + var current = input.Current(); + if (current.TokenType == BotTokenType.Keyword && current.TokenValue == "if") { - if (input.Current().TokenType == BotTokenType.LBrace) - rBraceCount++; - else if (input.Current().TokenType == BotTokenType.RBrace) - rBraceCount--; - - input.SkipToken(); + input.Expect(BotTokenType.Keyword); + input.Expect(BotTokenType.LParen); + while (!input.Expect(BotTokenType.RParen)) + input.SkipToken(); } - } - else - { - // optional newline before statement + + // potential newline character - skip so we can advance execution beyond the block input.Expect(BotTokenType.NewLine); - while (input.Current().TokenType != BotTokenType.NewLine && input.Current().TokenType != BotTokenType.EOF) - input.SkipToken(); + // skip the rest of the block + if (input.Expect(BotTokenType.LBrace)) + { + int rBraceCount = 1; + while (rBraceCount > 0 && input.Current().TokenType != BotTokenType.EOF) + { + if (input.Current().TokenType == BotTokenType.LBrace) + rBraceCount++; + else if (input.Current().TokenType == BotTokenType.RBrace) + rBraceCount--; + + input.SkipToken(); + } + } + else + { + // optional newline before statement + input.Expect(BotTokenType.NewLine); - // optional newline after statement - input.Expect(BotTokenType.NewLine); + while (input.Current().TokenType != BotTokenType.NewLine && input.Current().TokenType != BotTokenType.EOF) + input.SkipToken(); + + // optional newline after statement + input.Expect(BotTokenType.NewLine); + } } - } - protected static void RestoreLastNewline(ProgramState input) - { - // hack: put the \n token back since StatementList/Statement will have consumed it - if (input.Program[input.ExecutionIndex - 1].TokenType == BotTokenType.NewLine) - input.Goto(input.ExecutionIndex - 1); + protected static void RestoreLastNewline(ProgramState input) + { + // hack: put the \n token back since StatementList/Statement will have consumed it + if (input.Program[input.ExecutionIndex - 1].TokenType == BotTokenType.NewLine) + input.Goto(input.ExecutionIndex - 1); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/EvalResult.cs b/EOBot/Interpreter/States/EvalResult.cs index dae1cbc98..714f138db 100644 --- a/EOBot/Interpreter/States/EvalResult.cs +++ b/EOBot/Interpreter/States/EvalResult.cs @@ -1,17 +1,18 @@ -namespace EOBot.Interpreter.States; - -public enum EvalResult +namespace EOBot.Interpreter.States { - /// - /// The result of the evaluation succeeded - /// - Ok, - /// - /// The result of the evaluation failed - /// - Failed, - /// - /// The evaluator was not a match for the program's current execution point - /// - NotMatch + public enum EvalResult + { + /// + /// The result of the evaluation succeeded + /// + Ok, + /// + /// The result of the evaluation failed + /// + Failed, + /// + /// The evaluator was not a match for the program's current execution point + /// + NotMatch + } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/ExpressionEvaluator.cs b/EOBot/Interpreter/States/ExpressionEvaluator.cs index 0bde0fb61..1df7948e7 100644 --- a/EOBot/Interpreter/States/ExpressionEvaluator.cs +++ b/EOBot/Interpreter/States/ExpressionEvaluator.cs @@ -4,225 +4,226 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class ExpressionEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public ExpressionEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - // todo: this code is a mess and could use cleaning up (lots of copy/paste...) - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class ExpressionEvaluator : BaseEvaluator { - input.Match(BotTokenType.NotOperator); + public ExpressionEvaluator(IEnumerable evaluators) + : base(evaluators) { } - if (input.Expect(BotTokenType.LParen)) - { - var evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result != EvalResult.Ok) - return evalRes; - - // if we get an RParen, the nested expression has been evaluated - if (input.Expect(BotTokenType.RParen)) - return NegateIfNeeded(input); - - // expression_tail is optional - evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result == EvalResult.NotMatch) - return EvaluateSingleOperand(input); - else if (evalRes.Result == EvalResult.Failed) - return evalRes; - - if (!input.Expect(BotTokenType.RParen)) - return Error(input.Current(), BotTokenType.RParen); - } - else + // todo: this code is a mess and could use cleaning up (lots of copy/paste...) + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - // an expression can be a function call - var evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result == EvalResult.Ok) - { - // there may or may not be an expression tail after a function call - // if there is an expression tail, evaluate the operands below, otherwise return early - evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result == EvalResult.NotMatch) - { - // function call as single operand expression - negate the result if needed - return NegateIfNeeded(input); - } - else if (evalRes.Result == EvalResult.Failed) - return evalRes; - } - else if (evalRes.Result == EvalResult.NotMatch) + input.Match(BotTokenType.NotOperator); + + if (input.Expect(BotTokenType.LParen)) { - // if not a function, evaluate operand and expression tail (basic expression) - evalRes = await Evaluator().EvaluateAsync(input); + var evalRes = await Evaluator().EvaluateAsync(input); if (evalRes.Result != EvalResult.Ok) return evalRes; - // expression_tail is optional, if not set no need to evaluate operation stack below / return early + // if we get an RParen, the nested expression has been evaluated + if (input.Expect(BotTokenType.RParen)) + return NegateIfNeeded(input); + + // expression_tail is optional evalRes = await Evaluator().EvaluateAsync(input); if (evalRes.Result == EvalResult.NotMatch) return EvaluateSingleOperand(input); else if (evalRes.Result == EvalResult.Failed) return evalRes; + + if (!input.Expect(BotTokenType.RParen)) + return Error(input.Current(), BotTokenType.RParen); } else { - return evalRes; + // an expression can be a function call + var evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result == EvalResult.Ok) + { + // there may or may not be an expression tail after a function call + // if there is an expression tail, evaluate the operands below, otherwise return early + evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result == EvalResult.NotMatch) + { + // function call as single operand expression - negate the result if needed + return NegateIfNeeded(input); + } + else if (evalRes.Result == EvalResult.Failed) + return evalRes; + } + else if (evalRes.Result == EvalResult.NotMatch) + { + // if not a function, evaluate operand and expression tail (basic expression) + evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result != EvalResult.Ok) + return evalRes; + + // expression_tail is optional, if not set no need to evaluate operation stack below / return early + evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result == EvalResult.NotMatch) + return EvaluateSingleOperand(input); + else if (evalRes.Result == EvalResult.Failed) + return evalRes; + } + else + { + return evalRes; + } } - } - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); - var (result, reason, op2) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); - if (result == EvalResult.Failed) - return (result, reason, op2); - var operand2 = op2 as VariableBotToken; + var (result, reason, op2) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); + if (result == EvalResult.Failed) + return (result, reason, op2); + var operand2 = op2 as VariableBotToken; - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var @operator = input.OperationStack.Pop(); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var @operator = input.OperationStack.Pop(); - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); - BotToken op1; - (result, reason, op1) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); - if (result == EvalResult.Failed) - return (result, reason, op1); - var operand1 = op1 as VariableBotToken; + BotToken op1; + (result, reason, op1) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); + if (result == EvalResult.Failed) + return (result, reason, op1); + var operand1 = op1 as VariableBotToken; - (IVariable Result, string Reason) res; - res.Reason = string.Empty; - switch (@operator.TokenType) - { - case BotTokenType.EqualOperator: res.Result = new BoolVariable(operand1.VariableValue.Equals(operand2.VariableValue)); break; - case BotTokenType.NotEqualOperator: res.Result = new BoolVariable(!operand1.VariableValue.Equals(operand2.VariableValue)); break; - case BotTokenType.LessThanOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) < 0); break; - case BotTokenType.GreaterThanOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) > 0); break; - case BotTokenType.LessThanEqOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) <= 0); break; - case BotTokenType.GreaterThanEqOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) >= 0); break; - case BotTokenType.PlusOperator: res = Add((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; - case BotTokenType.MinusOperator: res = Subtract((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; - case BotTokenType.MultiplyOperator: res = Multiply((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; - case BotTokenType.DivideOperator: res = Divide((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; - default: return UnsupportedOperatorError(@operator); - } - - if (res.Result == null) - return (EvalResult.Failed, $"Error evaluating expression: {res.Reason}", input.Current()); + (IVariable Result, string Reason) res; + res.Reason = string.Empty; + switch (@operator.TokenType) + { + case BotTokenType.EqualOperator: res.Result = new BoolVariable(operand1.VariableValue.Equals(operand2.VariableValue)); break; + case BotTokenType.NotEqualOperator: res.Result = new BoolVariable(!operand1.VariableValue.Equals(operand2.VariableValue)); break; + case BotTokenType.LessThanOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) < 0); break; + case BotTokenType.GreaterThanOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) > 0); break; + case BotTokenType.LessThanEqOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) <= 0); break; + case BotTokenType.GreaterThanEqOperator: res.Result = new BoolVariable(operand1.VariableValue.CompareTo(operand2.VariableValue) >= 0); break; + case BotTokenType.PlusOperator: res = Add((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; + case BotTokenType.MinusOperator: res = Subtract((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; + case BotTokenType.MultiplyOperator: res = Multiply((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; + case BotTokenType.DivideOperator: res = Divide((dynamic)operand1.VariableValue, (dynamic)operand2.VariableValue); break; + default: return UnsupportedOperatorError(@operator); + } - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, res.Result.StringValue, res.Result)); - return NegateIfNeeded(input); - } + if (res.Result == null) + return (EvalResult.Failed, $"Error evaluating expression: {res.Reason}", input.Current()); - private (EvalResult, string, BotToken) EvaluateSingleOperand(ProgramState input) - { - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, res.Result.StringValue, res.Result)); + return NegateIfNeeded(input); + } - // convert to variable token (resolve identifier) so consumer of expression result can use it - var (localResult, localReason, singleOperand) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); - if (localResult != EvalResult.Ok) - return (localResult, localReason, singleOperand); + private (EvalResult, string, BotToken) EvaluateSingleOperand(ProgramState input) + { + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); - input.OperationStack.Push(singleOperand); - return NegateIfNeeded(input); - } + // convert to variable token (resolve identifier) so consumer of expression result can use it + var (localResult, localReason, singleOperand) = GetOperand(input.SymbolTable, input.OperationStack.Pop()); + if (localResult != EvalResult.Ok) + return (localResult, localReason, singleOperand); - // todo: a lot of this code is the same as what's in AssignmentEvaluator::Assign, see if it can be split out/shared - private (EvalResult, string, BotToken) GetOperand(Dictionary symbols, BotToken nextToken) - { - if (nextToken.TokenType == BotTokenType.Literal) - { - if (int.TryParse(nextToken.TokenValue, out var intValue)) - return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new IntVariable(intValue))); - else if (bool.TryParse(nextToken.TokenValue, out var boolValue)) - return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new BoolVariable(boolValue))); - else - return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new StringVariable(nextToken.TokenValue))); + input.OperationStack.Push(singleOperand); + return NegateIfNeeded(input); } - var operand = nextToken as VariableBotToken; - if (operand == null) + // todo: a lot of this code is the same as what's in AssignmentEvaluator::Assign, see if it can be split out/shared + private (EvalResult, string, BotToken) GetOperand(Dictionary symbols, BotToken nextToken) { - var identifier = nextToken as IdentifierBotToken; - if (identifier == null) - return (EvalResult.Failed, $"Expected operand of type Variable or Identifier but got {nextToken.TokenType}", nextToken); - - if (identifier.Member == null) + if (nextToken.TokenType == BotTokenType.Literal) { - var getVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); - if (getVariableRes.Result != EvalResult.Ok) - return (getVariableRes.Result, getVariableRes.Reason, identifier); - - operand = new VariableBotToken(BotTokenType.Literal, getVariableRes.Variable.ToString(), getVariableRes.Variable); + if (int.TryParse(nextToken.TokenValue, out var intValue)) + return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new IntVariable(intValue))); + else if (bool.TryParse(nextToken.TokenValue, out var boolValue)) + return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new BoolVariable(boolValue))); + else + return Success(new VariableBotToken(BotTokenType.Literal, nextToken.TokenValue, new StringVariable(nextToken.TokenValue))); } - else + + var operand = nextToken as VariableBotToken; + if (operand == null) { - var getVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); - if (getVariableRes.Result != EvalResult.Ok) + var identifier = nextToken as IdentifierBotToken; + if (identifier == null) + return (EvalResult.Failed, $"Expected operand of type Variable or Identifier but got {nextToken.TokenType}", nextToken); + + if (identifier.Member == null) { - var getRuntimeEvaluatedVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); - if (getRuntimeEvaluatedVariableRes.Result != EvalResult.Ok) - return (EvalResult.Failed, $"Identifier '{identifier.TokenValue}' is not an object", identifier); - - getVariableRes.Result = getRuntimeEvaluatedVariableRes.Result; - getVariableRes.Reason = getRuntimeEvaluatedVariableRes.Reason; - getVariableRes.Variable = new ObjectVariable( - getRuntimeEvaluatedVariableRes.Variable.SymbolTable - .Select(x => (x.Key, (x.Value.ReadOnly, x.Value.Variable()))) - .ToDictionary(x => x.Key, x => x.Item2)); - } + var getVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); + if (getVariableRes.Result != EvalResult.Ok) + return (getVariableRes.Result, getVariableRes.Reason, identifier); - return GetOperand(getVariableRes.Variable.SymbolTable, identifier.Member); + operand = new VariableBotToken(BotTokenType.Literal, getVariableRes.Variable.ToString(), getVariableRes.Variable); + } + else + { + var getVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); + if (getVariableRes.Result != EvalResult.Ok) + { + var getRuntimeEvaluatedVariableRes = symbols.GetVariable(identifier.TokenValue, identifier.ArrayIndex); + if (getRuntimeEvaluatedVariableRes.Result != EvalResult.Ok) + return (EvalResult.Failed, $"Identifier '{identifier.TokenValue}' is not an object", identifier); + + getVariableRes.Result = getRuntimeEvaluatedVariableRes.Result; + getVariableRes.Reason = getRuntimeEvaluatedVariableRes.Reason; + getVariableRes.Variable = new ObjectVariable( + getRuntimeEvaluatedVariableRes.Variable.SymbolTable + .Select(x => (x.Key, (x.Value.ReadOnly, x.Value.Variable()))) + .ToDictionary(x => x.Key, x => x.Item2)); + } + + return GetOperand(getVariableRes.Variable.SymbolTable, identifier.Member); + } } + + return Success(operand); } - return Success(operand); - } + // negate the VariableBotToken on top of the stack if there as a 'not' operator immediately below it + private (EvalResult, string, BotToken) NegateIfNeeded(ProgramState input) + { + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); - // negate the VariableBotToken on top of the stack if there as a 'not' operator immediately below it - private (EvalResult, string, BotToken) NegateIfNeeded(ProgramState input) - { - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); + var operand = input.OperationStack.Pop(); - var operand = input.OperationStack.Pop(); + var varToken = operand as VariableBotToken; + if (varToken == null) + return StackTokenError(BotTokenType.Literal, operand); - var varToken = operand as VariableBotToken; - if (varToken == null) - return StackTokenError(BotTokenType.Literal, operand); + while (input.OperationStack.Count > 0 && input.OperationStack.Peek().TokenType == BotTokenType.NotOperator) + { + var notOperator = input.OperationStack.Pop(); - while (input.OperationStack.Count > 0 && input.OperationStack.Peek().TokenType == BotTokenType.NotOperator) - { - var notOperator = input.OperationStack.Pop(); + var boolOperand = varToken.VariableValue as BoolVariable; + if (boolOperand == null) + return UnsupportedOperatorError(notOperator); - var boolOperand = varToken.VariableValue as BoolVariable; - if (boolOperand == null) - return UnsupportedOperatorError(notOperator); + varToken = new VariableBotToken(varToken.TokenType, (!boolOperand.Value).ToString(), new BoolVariable(!boolOperand.Value)); + } - varToken = new VariableBotToken(varToken.TokenType, (!boolOperand.Value).ToString(), new BoolVariable(!boolOperand.Value)); + input.OperationStack.Push(varToken); + return Success(); } - input.OperationStack.Push(varToken); - return Success(); - } - - private (IVariable, string) Add(IntVariable a, IntVariable b) => (new IntVariable(a.Value + b.Value), string.Empty); - private (IVariable, string) Add(IntVariable a, StringVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); - private (IVariable, string) Add(StringVariable a, IntVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); - private (IVariable, string) Add(StringVariable a, StringVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); - private (IVariable, string) Add(object a, object b) => (null, $"Objects {a} and {b} could not be added (currently the operands must be int or string)"); + private (IVariable, string) Add(IntVariable a, IntVariable b) => (new IntVariable(a.Value + b.Value), string.Empty); + private (IVariable, string) Add(IntVariable a, StringVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); + private (IVariable, string) Add(StringVariable a, IntVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); + private (IVariable, string) Add(StringVariable a, StringVariable b) => (new StringVariable(a.Value + b.Value), string.Empty); + private (IVariable, string) Add(object a, object b) => (null, $"Objects {a} and {b} could not be added (currently the operands must be int or string)"); - private (IVariable, string) Subtract(IntVariable a, IntVariable b) => (new IntVariable(a.Value - b.Value), string.Empty); - private (IVariable, string) Subtract(object a, object b) => (null, $"Objects {a} and {b} could not be subtracted (currently the operands must be int)"); + private (IVariable, string) Subtract(IntVariable a, IntVariable b) => (new IntVariable(a.Value - b.Value), string.Empty); + private (IVariable, string) Subtract(object a, object b) => (null, $"Objects {a} and {b} could not be subtracted (currently the operands must be int)"); - private (IVariable, string) Multiply(IntVariable a, IntVariable b) => (new IntVariable(a.Value * b.Value), string.Empty); - private (IVariable, string) Multiply(object a, object b) => (null, $"Objects {a} and {b} could not be multiplied (currently the operands must be int)"); + private (IVariable, string) Multiply(IntVariable a, IntVariable b) => (new IntVariable(a.Value * b.Value), string.Empty); + private (IVariable, string) Multiply(object a, object b) => (null, $"Objects {a} and {b} could not be multiplied (currently the operands must be int)"); - private (IVariable, string) Divide(IntVariable a, IntVariable b) => (new IntVariable(a.Value / b.Value), string.Empty); - private (IVariable, string) Divide(object a, object b) => (null, $"Objects {a} and {b} could not be divided (currently the operands must be int)"); + private (IVariable, string) Divide(IntVariable a, IntVariable b) => (new IntVariable(a.Value / b.Value), string.Empty); + private (IVariable, string) Divide(object a, object b) => (null, $"Objects {a} and {b} could not be divided (currently the operands must be int)"); + } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/ExpressionTailEvaluator.cs b/EOBot/Interpreter/States/ExpressionTailEvaluator.cs index 2e2f7b354..c24d311dd 100644 --- a/EOBot/Interpreter/States/ExpressionTailEvaluator.cs +++ b/EOBot/Interpreter/States/ExpressionTailEvaluator.cs @@ -2,25 +2,26 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class ExpressionTailEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public ExpressionTailEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class ExpressionTailEvaluator : BaseEvaluator { - var expectedTokens = new[] + public ExpressionTailEvaluator(IEnumerable evaluators) + : base(evaluators) { } + + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - BotTokenType.EqualOperator, BotTokenType.NotEqualOperator, BotTokenType.GreaterThanOperator, - BotTokenType.LessThanOperator, BotTokenType.GreaterThanEqOperator, BotTokenType.LessThanEqOperator, - BotTokenType.PlusOperator, BotTokenType.MinusOperator, BotTokenType.MultiplyOperator, BotTokenType.DivideOperator - }; + var expectedTokens = new[] + { + BotTokenType.EqualOperator, BotTokenType.NotEqualOperator, BotTokenType.GreaterThanOperator, + BotTokenType.LessThanOperator, BotTokenType.GreaterThanEqOperator, BotTokenType.LessThanEqOperator, + BotTokenType.PlusOperator, BotTokenType.MinusOperator, BotTokenType.MultiplyOperator, BotTokenType.DivideOperator + }; - if (!input.MatchOneOf(expectedTokens)) - return (EvalResult.NotMatch, string.Empty, input.Current()); + if (!input.MatchOneOf(expectedTokens)) + return (EvalResult.NotMatch, string.Empty, input.Current()); - return await Evaluator().EvaluateAsync(input); + return await Evaluator().EvaluateAsync(input); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/FunctionEvaluator.cs b/EOBot/Interpreter/States/FunctionEvaluator.cs index b7698bbac..8888e0837 100644 --- a/EOBot/Interpreter/States/FunctionEvaluator.cs +++ b/EOBot/Interpreter/States/FunctionEvaluator.cs @@ -5,168 +5,169 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class FunctionEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public FunctionEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class FunctionEvaluator : BaseEvaluator { - if (!input.MatchPair(BotTokenType.Identifier, BotTokenType.LParen)) - return (EvalResult.NotMatch, string.Empty, input.Current()); + public FunctionEvaluator(IEnumerable evaluators) + : base(evaluators) { } - var firstParam = true; - while (!input.Match(BotTokenType.RParen)) + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - if (input.Expect(BotTokenType.NewLine) || input.Expect(BotTokenType.EOF)) - return UnexpectedTokenError(input.Current(), BotTokenType.NewLine, BotTokenType.EOF); - - if (!firstParam && !input.Expect(BotTokenType.Comma)) - return Error(input.Current(), BotTokenType.Comma); - - var parameterExpression = await Evaluator().EvaluateAsync(input); - if (parameterExpression.Result != EvalResult.Ok) - return parameterExpression; - - firstParam = false; + if (!input.MatchPair(BotTokenType.Identifier, BotTokenType.LParen)) + return (EvalResult.NotMatch, string.Empty, input.Current()); + + var firstParam = true; + while (!input.Match(BotTokenType.RParen)) + { + if (input.Expect(BotTokenType.NewLine) || input.Expect(BotTokenType.EOF)) + return UnexpectedTokenError(input.Current(), BotTokenType.NewLine, BotTokenType.EOF); + + if (!firstParam && !input.Expect(BotTokenType.Comma)) + return Error(input.Current(), BotTokenType.Comma); + + var parameterExpression = await Evaluator().EvaluateAsync(input); + if (parameterExpression.Result != EvalResult.Ok) + return parameterExpression; + + firstParam = false; + } + + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var rParen = input.OperationStack.Pop(); + if (rParen.TokenType != BotTokenType.RParen) + return StackTokenError(BotTokenType.RParen, rParen); + + var parameters = new List(); + while (input.OperationStack.Count > 0 && input.OperationStack.Peek().TokenType != BotTokenType.LParen) + { + var parameter = (VariableBotToken)input.OperationStack.Pop(); + parameters.Insert(0, parameter); + } + + var lParen = input.OperationStack.Pop(); + if (lParen.TokenType != BotTokenType.LParen) + return StackTokenError(BotTokenType.LParen, lParen); + + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var functionToken = input.OperationStack.Pop(); + + if (!input.SymbolTable.ContainsKey(functionToken.TokenValue)) + return IdentifierNotFoundError(new IdentifierBotToken(functionToken)); + + var function = input.SymbolTable[functionToken.TokenValue].Identifiable; + + try + { + if (function is IAsyncFunction) + await CallAsync(input, (dynamic)function, parameters.Select(x => x.VariableValue).ToArray()); + else if (function is IFunction) + Call(input, (dynamic)function, parameters.Select(x => x.VariableValue).ToArray()); + else + return (EvalResult.Failed, $"Expected identifier {functionToken.TokenValue} to be a function, but it was {function.GetType().Name}", functionToken); + } + catch (BotScriptErrorException bse) + { + // stack information isn't really important since this is only used to signal to the framework that a bot failed + // recreate the exception so it prints line number/column info with the error + throw new BotScriptErrorException(bse.Message, functionToken); + } + catch (ArgumentException ae) + { + return (EvalResult.Failed, ae.Message, functionToken); + } + + return Success(); } - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var rParen = input.OperationStack.Pop(); - if (rParen.TokenType != BotTokenType.RParen) - return StackTokenError(BotTokenType.RParen, rParen); - - var parameters = new List(); - while (input.OperationStack.Count > 0 && input.OperationStack.Peek().TokenType != BotTokenType.LParen) + private void Call(ProgramState input, ICallable function, params IVariable[] variables) { - var parameter = (VariableBotToken)input.OperationStack.Pop(); - parameters.Insert(0, parameter); + function.Call(variables); } - var lParen = input.OperationStack.Pop(); - if (lParen.TokenType != BotTokenType.LParen) - return StackTokenError(BotTokenType.LParen, lParen); - - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var functionToken = input.OperationStack.Pop(); - - if (!input.SymbolTable.ContainsKey(functionToken.TokenValue)) - return IdentifierNotFoundError(new IdentifierBotToken(functionToken)); - - var function = input.SymbolTable[functionToken.TokenValue].Identifiable; - - try + private void Call(ProgramState input, ICallable function, params IVariable[] variables) { - if (function is IAsyncFunction) - await CallAsync(input, (dynamic)function, parameters.Select(x => x.VariableValue).ToArray()); - else if (function is IFunction) - Call(input, (dynamic)function, parameters.Select(x => x.VariableValue).ToArray()); - else - return (EvalResult.Failed, $"Expected identifier {functionToken.TokenValue} to be a function, but it was {function.GetType().Name}", functionToken); + var result = function.Call(variables); + var varResult = new IntVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); } - catch (BotScriptErrorException bse) + + private void Call(ProgramState input, ICallable function, params IVariable[] variables) { - // stack information isn't really important since this is only used to signal to the framework that a bot failed - // recreate the exception so it prints line number/column info with the error - throw new BotScriptErrorException(bse.Message, functionToken); + var result = function.Call(variables); + var varResult = new StringVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); } - catch (ArgumentException ae) + + private void Call(ProgramState input, ICallable> function, params IVariable[] variables) { - return (EvalResult.Failed, ae.Message, functionToken); + var result = function.Call(variables); + var varResult = new ArrayVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); } - return Success(); - } - - private void Call(ProgramState input, ICallable function, params IVariable[] variables) - { - function.Call(variables); - } - - private void Call(ProgramState input, ICallable function, params IVariable[] variables) - { - var result = function.Call(variables); - var varResult = new IntVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } - - private void Call(ProgramState input, ICallable function, params IVariable[] variables) - { - var result = function.Call(variables); - var varResult = new StringVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } - - private void Call(ProgramState input, ICallable> function, params IVariable[] variables) - { - var result = function.Call(variables); - var varResult = new ArrayVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } - - private void Call(ProgramState input, ICallable function, params IVariable[] variables) - { - var result = function.Call(variables); - var varResult = new BoolVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + private void Call(ProgramState input, ICallable function, params IVariable[] variables) + { + var result = function.Call(variables); + var varResult = new BoolVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } - private void Call(ProgramState input, ICallable function, params IVariable[] variables) - { - var varResult = function.Call(variables); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + private void Call(ProgramState input, ICallable function, params IVariable[] variables) + { + var varResult = function.Call(variables); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } - private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) - { - await function.CallAsync(variables); - } + private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + { + await function.CallAsync(variables); + } - private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) - { - var result = await function.CallAsync(variables); - var varResult = new IntVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + { + var result = await function.CallAsync(variables); + var varResult = new IntVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } - private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) - { - var result = await function.CallAsync(variables); - var varResult = new StringVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + { + var result = await function.CallAsync(variables); + var varResult = new StringVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } - private async Task CallAsync(ProgramState input, IAsyncCallable> function, params IVariable[] variables) - { - var result = await function.CallAsync(variables); - var varResult = new ArrayVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + private async Task CallAsync(ProgramState input, IAsyncCallable> function, params IVariable[] variables) + { + var result = await function.CallAsync(variables); + var varResult = new ArrayVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } - private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) - { - var result = await function.CallAsync(variables); - var varResult = new BoolVariable(result); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); - } + private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + { + var result = await function.CallAsync(variables); + var varResult = new BoolVariable(result); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } - private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) - { - var varResult = await function.CallAsync(variables); - input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); - input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + private async Task CallAsync(ProgramState input, IAsyncCallable function, params IVariable[] variables) + { + var varResult = await function.CallAsync(variables); + input.SymbolTable[PredefinedIdentifiers.RESULT] = (true, varResult); + input.OperationStack.Push(new VariableBotToken(BotTokenType.Literal, varResult.StringValue, varResult)); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/GotoEvaluator.cs b/EOBot/Interpreter/States/GotoEvaluator.cs index 20337d6dd..71c2d5292 100644 --- a/EOBot/Interpreter/States/GotoEvaluator.cs +++ b/EOBot/Interpreter/States/GotoEvaluator.cs @@ -1,27 +1,28 @@ using EOBot.Interpreter.Extensions; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class GotoEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public override Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class GotoEvaluator : BaseEvaluator { - // ensure we have the right keyword before advancing the program - var current = input.Current(); - if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "goto") - return Task.FromResult((EvalResult.NotMatch, string.Empty, input.Current())); + public override Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + // ensure we have the right keyword before advancing the program + var current = input.Current(); + if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "goto") + return Task.FromResult((EvalResult.NotMatch, string.Empty, input.Current())); - input.Expect(BotTokenType.Keyword); + input.Expect(BotTokenType.Keyword); - if (!input.Match(BotTokenType.Identifier)) - return Task.FromResult(Error(input.Current(), BotTokenType.Identifier)); + if (!input.Match(BotTokenType.Identifier)) + return Task.FromResult(Error(input.Current(), BotTokenType.Identifier)); - var label = input.OperationStack.Pop(); - if (!input.Labels.ContainsKey(label.TokenValue)) - return Task.FromResult(IdentifierNotFoundError(new IdentifierBotToken(label))); + var label = input.OperationStack.Pop(); + if (!input.Labels.ContainsKey(label.TokenValue)) + return Task.FromResult(IdentifierNotFoundError(new IdentifierBotToken(label))); - var result = input.Goto(input.Labels[label.TokenValue]); - return Task.FromResult(result ? Success() : GotoError(label)); + var result = input.Goto(input.Labels[label.TokenValue]); + return Task.FromResult(result ? Success() : GotoError(label)); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/IScriptEvaluator.cs b/EOBot/Interpreter/States/IScriptEvaluator.cs index 0266ba280..db12d2a4a 100644 --- a/EOBot/Interpreter/States/IScriptEvaluator.cs +++ b/EOBot/Interpreter/States/IScriptEvaluator.cs @@ -1,8 +1,9 @@ using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public interface IScriptEvaluator +namespace EOBot.Interpreter.States { - Task<(EvalResult Result, string Reason, BotToken Token)> EvaluateAsync(ProgramState input); + public interface IScriptEvaluator + { + Task<(EvalResult Result, string Reason, BotToken Token)> EvaluateAsync(ProgramState input); + } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/IfEvaluator.cs b/EOBot/Interpreter/States/IfEvaluator.cs index c53a1642c..1285e7df0 100644 --- a/EOBot/Interpreter/States/IfEvaluator.cs +++ b/EOBot/Interpreter/States/IfEvaluator.cs @@ -2,78 +2,79 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class IfEvaluator : BlockEvaluator +namespace EOBot.Interpreter.States { - public IfEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class IfEvaluator : BlockEvaluator { - // ensure we have the right keyword before advancing the program - var current = input.Current(); - if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "if") - return (EvalResult.NotMatch, string.Empty, input.Current()); + public IfEvaluator(IEnumerable evaluators) + : base(evaluators) { } - var ifStartIndex = input.ExecutionIndex; - - var (result, reason, token) = await EvaluateConditionAsync(ifStartIndex, input); - if (result == EvalResult.Ok) + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - if (bool.TryParse(token.TokenValue, out var conditionValue) && conditionValue) - { - var ifRes = await EvaluateBlockAsync(input); - if (ifRes.Item1 == EvalResult.Ok) - SkipElseBlocks(input); + // ensure we have the right keyword before advancing the program + var current = input.Current(); + if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "if") + return (EvalResult.NotMatch, string.Empty, input.Current()); - return ifRes; - } + var ifStartIndex = input.ExecutionIndex; + + var (result, reason, token) = await EvaluateConditionAsync(ifStartIndex, input); + if (result == EvalResult.Ok) + { + if (bool.TryParse(token.TokenValue, out var conditionValue) && conditionValue) + { + var ifRes = await EvaluateBlockAsync(input); + if (ifRes.Item1 == EvalResult.Ok) + SkipElseBlocks(input); - SkipBlock(input); + return ifRes; + } - while (input.Expect(BotTokenType.NewLine)) ; + SkipBlock(input); - if (IsElse(input)) - { - input.Expect(BotTokenType.Keyword); + while (input.Expect(BotTokenType.NewLine)) ; - var elseIfRes = await Evaluator().EvaluateAsync(input); - if (elseIfRes.Result == EvalResult.Failed) - return elseIfRes; - else if (elseIfRes.Result == EvalResult.Ok) + if (IsElse(input)) { - SkipElseBlocks(input); - return elseIfRes; + input.Expect(BotTokenType.Keyword); + + var elseIfRes = await Evaluator().EvaluateAsync(input); + if (elseIfRes.Result == EvalResult.Failed) + return elseIfRes; + else if (elseIfRes.Result == EvalResult.Ok) + { + SkipElseBlocks(input); + return elseIfRes; + } + + // if not a match for else if, it is an else block + return await EvaluateBlockAsync(input); } - - // if not a match for else if, it is an else block - return await EvaluateBlockAsync(input); } - } - RestoreLastNewline(input); - return (result, reason, token); - } - - private bool IsElse(ProgramState input) - { - var current = input.Current(); - return current.TokenType == BotTokenType.Keyword && current.TokenValue == "else"; - } + RestoreLastNewline(input); + return (result, reason, token); + } - private void SkipElseBlocks(ProgramState input) - { - while (input.Expect(BotTokenType.NewLine)) ; + private bool IsElse(ProgramState input) + { + var current = input.Current(); + return current.TokenType == BotTokenType.Keyword && current.TokenValue == "else"; + } - // skip the rest of the following blocks if evaluated - while (IsElse(input)) + private void SkipElseBlocks(ProgramState input) { - input.Expect(BotTokenType.Keyword); - SkipBlock(input); while (input.Expect(BotTokenType.NewLine)) ; - } - RestoreLastNewline(input); + // skip the rest of the following blocks if evaluated + while (IsElse(input)) + { + input.Expect(BotTokenType.Keyword); + SkipBlock(input); + while (input.Expect(BotTokenType.NewLine)) ; + } + + RestoreLastNewline(input); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/KeywordEvaluator.cs b/EOBot/Interpreter/States/KeywordEvaluator.cs index 73a32dc9c..e55c4278c 100644 --- a/EOBot/Interpreter/States/KeywordEvaluator.cs +++ b/EOBot/Interpreter/States/KeywordEvaluator.cs @@ -1,26 +1,27 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class KeywordEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public KeywordEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class KeywordEvaluator : BaseEvaluator { - var res = await Evaluator().EvaluateAsync(input); - if (res.Result == EvalResult.NotMatch) - { - res = await Evaluator().EvaluateAsync(input); + public KeywordEvaluator(IEnumerable evaluators) + : base(evaluators) { } + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + var res = await Evaluator().EvaluateAsync(input); if (res.Result == EvalResult.NotMatch) { - res = await Evaluator().EvaluateAsync(input); + res = await Evaluator().EvaluateAsync(input); + + if (res.Result == EvalResult.NotMatch) + { + res = await Evaluator().EvaluateAsync(input); + } } - } - return res; + return res; + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/LabelEvaluator.cs b/EOBot/Interpreter/States/LabelEvaluator.cs index d41d00006..def562c1c 100644 --- a/EOBot/Interpreter/States/LabelEvaluator.cs +++ b/EOBot/Interpreter/States/LabelEvaluator.cs @@ -1,15 +1,16 @@ using EOBot.Interpreter.Extensions; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class LabelEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public override Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class LabelEvaluator : BaseEvaluator { - var result = input.ExpectPair(BotTokenType.Identifier, BotTokenType.Colon) - ? EvalResult.Ok - : EvalResult.NotMatch; - return Task.FromResult((result, string.Empty, input.Current())); + public override Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + var result = input.ExpectPair(BotTokenType.Identifier, BotTokenType.Colon) + ? EvalResult.Ok + : EvalResult.NotMatch; + return Task.FromResult((result, string.Empty, input.Current())); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/OperandEvaluator.cs b/EOBot/Interpreter/States/OperandEvaluator.cs index 89594f517..058dbb9a3 100644 --- a/EOBot/Interpreter/States/OperandEvaluator.cs +++ b/EOBot/Interpreter/States/OperandEvaluator.cs @@ -2,25 +2,26 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class OperandEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public OperandEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class OperandEvaluator : BaseEvaluator { - if (input.Match(BotTokenType.NotOperator)) + public OperandEvaluator(IEnumerable evaluators) + : base(evaluators) { } + + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { + if (input.Match(BotTokenType.NotOperator)) + { - } + } - var evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result == EvalResult.Ok) - return evalRes; + var evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result == EvalResult.Ok) + return evalRes; - var matchRes = input.Match(BotTokenType.Literal); - return matchRes ? Success() : (EvalResult.NotMatch, string.Empty, input.Current()); + var matchRes = input.Match(BotTokenType.Literal); + return matchRes ? Success() : (EvalResult.NotMatch, string.Empty, input.Current()); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/ProgramState.cs b/EOBot/Interpreter/States/ProgramState.cs index 1b2290fbb..5ce7906d7 100644 --- a/EOBot/Interpreter/States/ProgramState.cs +++ b/EOBot/Interpreter/States/ProgramState.cs @@ -3,114 +3,115 @@ using System.Collections.Generic; using System.Linq; -namespace EOBot.Interpreter.States; - -public class ProgramState +namespace EOBot.Interpreter.States { - public Stack OperationStack { get; } - - public IReadOnlyList Program { get; } - - public Dictionary SymbolTable { get; } - - public Dictionary Labels { get; } - - public int ExecutionIndex { get; private set; } - - public ProgramState(IReadOnlyList program) + public class ProgramState { - OperationStack = new Stack(); - Program = program; - SymbolTable = new Dictionary(); - Labels = Program - .Select((token, ndx) => (token, ndx)) - .Where(x => x.token.TokenType == BotTokenType.Identifier && Program[x.ndx + 1].TokenType == BotTokenType.Colon) - .ToDictionary(x => x.token.TokenValue, y => y.ndx + 2); - ExecutionIndex = 0; - } + public Stack OperationStack { get; } - public void SkipToken() - { - ExecutionIndex++; - } + public IReadOnlyList Program { get; } - public bool Goto(int executionIndex) - { - if (executionIndex >= Program.Count) - return false; + public Dictionary SymbolTable { get; } - ExecutionIndex = executionIndex; - return true; - } + public Dictionary Labels { get; } - /// - /// Check for a token at the program's execution index. If it is the expected type, increment execution index. - /// - public bool Expect(BotTokenType tokenType) - { - if (ExecutionIndex >= Program.Count) - return tokenType == BotTokenType.EOF; + public int ExecutionIndex { get; private set; } + + public ProgramState(IReadOnlyList program) + { + OperationStack = new Stack(); + Program = program; + SymbolTable = new Dictionary(); + Labels = Program + .Select((token, ndx) => (token, ndx)) + .Where(x => x.token.TokenType == BotTokenType.Identifier && Program[x.ndx + 1].TokenType == BotTokenType.Colon) + .ToDictionary(x => x.token.TokenValue, y => y.ndx + 2); + ExecutionIndex = 0; + } - if (Program[ExecutionIndex].TokenType == tokenType) + public void SkipToken() { ExecutionIndex++; + } + + public bool Goto(int executionIndex) + { + if (executionIndex >= Program.Count) + return false; + + ExecutionIndex = executionIndex; return true; } - return false; - } + /// + /// Check for a token at the program's execution index. If it is the expected type, increment execution index. + /// + public bool Expect(BotTokenType tokenType) + { + if (ExecutionIndex >= Program.Count) + return tokenType == BotTokenType.EOF; + + if (Program[ExecutionIndex].TokenType == tokenType) + { + ExecutionIndex++; + return true; + } - /// - /// Check for a token at the program's execution index. If it is the expected type, push it onto the operation stack and increment execution index. - /// - public bool Match(BotTokenType tokenType) - { - if (ExecutionIndex >= Program.Count) return false; + } - if (Program[ExecutionIndex].TokenType == tokenType) + /// + /// Check for a token at the program's execution index. If it is the expected type, push it onto the operation stack and increment execution index. + /// + public bool Match(BotTokenType tokenType) { - OperationStack.Push(Program[ExecutionIndex]); - ExecutionIndex++; - return true; - } + if (ExecutionIndex >= Program.Count) + return false; - return false; - } + if (Program[ExecutionIndex].TokenType == tokenType) + { + OperationStack.Push(Program[ExecutionIndex]); + ExecutionIndex++; + return true; + } - public bool ExpectPair(BotTokenType first, BotTokenType second) - { - if (ExecutionIndex >= Program.Count - 1) return false; + } - if (Program[ExecutionIndex].TokenType == first && - Program[ExecutionIndex + 1].TokenType == second) + public bool ExpectPair(BotTokenType first, BotTokenType second) { - ExecutionIndex += 2; - return true; - } + if (ExecutionIndex >= Program.Count - 1) + return false; - return false; - } + if (Program[ExecutionIndex].TokenType == first && + Program[ExecutionIndex + 1].TokenType == second) + { + ExecutionIndex += 2; + return true; + } - /// - /// Matches a pair of tokens in order at the program's execution index. - /// - public bool MatchPair(BotTokenType first, BotTokenType second) - { - if (ExecutionIndex >= Program.Count - 1) return false; + } - if (Program[ExecutionIndex].TokenType == first && - Program[ExecutionIndex + 1].TokenType == second) + /// + /// Matches a pair of tokens in order at the program's execution index. + /// + public bool MatchPair(BotTokenType first, BotTokenType second) { - OperationStack.Push(Program[ExecutionIndex]); - OperationStack.Push(Program[ExecutionIndex + 1]); - ExecutionIndex += 2; + if (ExecutionIndex >= Program.Count - 1) + return false; - return true; - } + if (Program[ExecutionIndex].TokenType == first && + Program[ExecutionIndex + 1].TokenType == second) + { + OperationStack.Push(Program[ExecutionIndex]); + OperationStack.Push(Program[ExecutionIndex + 1]); + ExecutionIndex += 2; + + return true; + } - return false; + return false; + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/ScriptEvaluator.cs b/EOBot/Interpreter/States/ScriptEvaluator.cs index 6854347b3..93cf583c1 100644 --- a/EOBot/Interpreter/States/ScriptEvaluator.cs +++ b/EOBot/Interpreter/States/ScriptEvaluator.cs @@ -2,22 +2,23 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class ScriptEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public ScriptEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class ScriptEvaluator : BaseEvaluator { - var evalResult = await Evaluator().EvaluateAsync(input); - if (evalResult.Result != EvalResult.Ok) - return evalResult; + public ScriptEvaluator(IEnumerable evaluators) + : base(evaluators) { } + + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + { + var evalResult = await Evaluator().EvaluateAsync(input); + if (evalResult.Result != EvalResult.Ok) + return evalResult; - if (!input.Expect(BotTokenType.EOF)) - return Error(input.Current(), BotTokenType.EOF); + if (!input.Expect(BotTokenType.EOF)) + return Error(input.Current(), BotTokenType.EOF); - return Success(); + return Success(); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/StatementEvaluator.cs b/EOBot/Interpreter/States/StatementEvaluator.cs index 3da758305..cda9f1fb4 100644 --- a/EOBot/Interpreter/States/StatementEvaluator.cs +++ b/EOBot/Interpreter/States/StatementEvaluator.cs @@ -2,38 +2,39 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class StatementEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public StatementEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class StatementEvaluator : BaseEvaluator { - while (input.Current().TokenType == BotTokenType.NewLine) - input.Expect(BotTokenType.NewLine); + public StatementEvaluator(IEnumerable evaluators) + : base(evaluators) { } - var (result, reason, token) = await Evaluator().EvaluateAsync(input); - if (result == EvalResult.NotMatch) + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - (result, reason, token) = await Evaluator().EvaluateAsync(input); + while (input.Current().TokenType == BotTokenType.NewLine) + input.Expect(BotTokenType.NewLine); + + var (result, reason, token) = await Evaluator().EvaluateAsync(input); if (result == EvalResult.NotMatch) { - (result, reason, token) = await Evaluator().EvaluateAsync(input); + (result, reason, token) = await Evaluator().EvaluateAsync(input); if (result == EvalResult.NotMatch) { - (result, reason, token) = await Evaluator().EvaluateAsync(input); + (result, reason, token) = await Evaluator().EvaluateAsync(input); + if (result == EvalResult.NotMatch) + { + (result, reason, token) = await Evaluator().EvaluateAsync(input); + } } } - } - if (result != EvalResult.Ok) - return (result, reason, token); + if (result != EvalResult.Ok) + return (result, reason, token); - if (!input.Expect(BotTokenType.NewLine) && !input.Expect(BotTokenType.EOF)) - return Error(input.Current(), BotTokenType.NewLine, BotTokenType.EOF); + if (!input.Expect(BotTokenType.NewLine) && !input.Expect(BotTokenType.EOF)) + return Error(input.Current(), BotTokenType.NewLine, BotTokenType.EOF); - return (result, reason, token); + return (result, reason, token); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/StatementListEvaluator.cs b/EOBot/Interpreter/States/StatementListEvaluator.cs index c65e11b8c..31da34c1a 100644 --- a/EOBot/Interpreter/States/StatementListEvaluator.cs +++ b/EOBot/Interpreter/States/StatementListEvaluator.cs @@ -1,22 +1,23 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class StatementListEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public StatementListEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class StatementListEvaluator : BaseEvaluator { - (EvalResult Result, string, BotToken) result; + public StatementListEvaluator(IEnumerable evaluators) + : base(evaluators) { } - do + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - result = await Evaluator().EvaluateAsync(input); - } while (result.Result == EvalResult.Ok && !input.Expect(BotTokenType.EOF) && !input.Expect(BotTokenType.RBrace)); + (EvalResult Result, string, BotToken) result; + + do + { + result = await Evaluator().EvaluateAsync(input); + } while (result.Result == EvalResult.Ok && !input.Expect(BotTokenType.EOF) && !input.Expect(BotTokenType.RBrace)); - return result; + return result; + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/VariableEvaluator.cs b/EOBot/Interpreter/States/VariableEvaluator.cs index c23d7e6b4..44f2ff5d7 100644 --- a/EOBot/Interpreter/States/VariableEvaluator.cs +++ b/EOBot/Interpreter/States/VariableEvaluator.cs @@ -3,64 +3,65 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class VariableEvaluator : BaseEvaluator +namespace EOBot.Interpreter.States { - public VariableEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class VariableEvaluator : BaseEvaluator { - if (!input.Match(BotTokenType.Variable)) - return (EvalResult.NotMatch, string.Empty, input.Current()); + public VariableEvaluator(IEnumerable evaluators) + : base(evaluators) { } - int? arrayIndex = null; - if (input.Expect(BotTokenType.LBracket)) + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - var expressionEval = await Evaluator().EvaluateAsync(input); - if (expressionEval.Result != EvalResult.Ok) - return expressionEval; + if (!input.Match(BotTokenType.Variable)) + return (EvalResult.NotMatch, string.Empty, input.Current()); - if (!input.Expect(BotTokenType.RBracket)) - return Error(input.Current(), BotTokenType.RBracket); + int? arrayIndex = null; + if (input.Expect(BotTokenType.LBracket)) + { + var expressionEval = await Evaluator().EvaluateAsync(input); + if (expressionEval.Result != EvalResult.Ok) + return expressionEval; - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var expressionResult = (VariableBotToken)input.OperationStack.Pop(); + if (!input.Expect(BotTokenType.RBracket)) + return Error(input.Current(), BotTokenType.RBracket); - if (!(expressionResult.VariableValue is IntVariable)) - return (EvalResult.Failed, $"Expected index to be int, but it was {expressionResult.VariableValue.GetType().Name}", expressionResult); + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var expressionResult = (VariableBotToken)input.OperationStack.Pop(); - arrayIndex = ((IntVariable)expressionResult.VariableValue).Value; - } + if (!(expressionResult.VariableValue is IntVariable)) + return (EvalResult.Failed, $"Expected index to be int, but it was {expressionResult.VariableValue.GetType().Name}", expressionResult); - IdentifierBotToken nestedIdentifier = null; - if (input.Match(BotTokenType.Dot)) - { - var evalRes = await Evaluator().EvaluateAsync(input); - if (evalRes.Result != EvalResult.Ok) - return evalRes; + arrayIndex = ((IntVariable)expressionResult.VariableValue).Value; + } - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - nestedIdentifier = (IdentifierBotToken)input.OperationStack.Pop(); - if (nestedIdentifier.TokenType != BotTokenType.Variable) - return StackTokenError(BotTokenType.Variable, nestedIdentifier); + IdentifierBotToken nestedIdentifier = null; + if (input.Match(BotTokenType.Dot)) + { + var evalRes = await Evaluator().EvaluateAsync(input); + if (evalRes.Result != EvalResult.Ok) + return evalRes; + + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + nestedIdentifier = (IdentifierBotToken)input.OperationStack.Pop(); + if (nestedIdentifier.TokenType != BotTokenType.Variable) + return StackTokenError(BotTokenType.Variable, nestedIdentifier); + + if (input.OperationStack.Count == 0) + return StackEmptyError(input.Current()); + var expectedDot = input.OperationStack.Pop(); + if (expectedDot.TokenType != BotTokenType.Dot) + return StackTokenError(BotTokenType.Dot, expectedDot); + } if (input.OperationStack.Count == 0) return StackEmptyError(input.Current()); - var expectedDot = input.OperationStack.Pop(); - if (expectedDot.TokenType != BotTokenType.Dot) - return StackTokenError(BotTokenType.Dot, expectedDot); - } - - if (input.OperationStack.Count == 0) - return StackEmptyError(input.Current()); - var identifier = input.OperationStack.Pop(); + var identifier = input.OperationStack.Pop(); - input.OperationStack.Push(new IdentifierBotToken(identifier, arrayIndex, nestedIdentifier)); + input.OperationStack.Push(new IdentifierBotToken(identifier, arrayIndex, nestedIdentifier)); - return Success(); + return Success(); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/States/WhileEvaluator.cs b/EOBot/Interpreter/States/WhileEvaluator.cs index 688ac7dc4..b8b576296 100644 --- a/EOBot/Interpreter/States/WhileEvaluator.cs +++ b/EOBot/Interpreter/States/WhileEvaluator.cs @@ -2,39 +2,40 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace EOBot.Interpreter.States; - -public class WhileEvaluator : BlockEvaluator +namespace EOBot.Interpreter.States { - public WhileEvaluator(IEnumerable evaluators) - : base(evaluators) { } - - public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) + public class WhileEvaluator : BlockEvaluator { - // ensure we have the right keyword before advancing the program - var current = input.Current(); - if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "while") - return (EvalResult.NotMatch, string.Empty, input.Current()); - - var whileLoopStartIndex = input.ExecutionIndex; + public WhileEvaluator(IEnumerable evaluators) + : base(evaluators) { } - EvalResult result; - string reason; - BotToken token; - for ((result, reason, token) = await EvaluateConditionAsync(whileLoopStartIndex, input); - result == EvalResult.Ok && bool.TryParse(token.TokenValue, out var conditionValue) && conditionValue; - (result, reason, token) = await EvaluateConditionAsync(whileLoopStartIndex, input)) + public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(ProgramState input) { - var blockEval = await EvaluateBlockAsync(input); - if (blockEval.Item1 != EvalResult.Ok) - return blockEval; - } + // ensure we have the right keyword before advancing the program + var current = input.Current(); + if (current.TokenType != BotTokenType.Keyword || current.TokenValue != "while") + return (EvalResult.NotMatch, string.Empty, input.Current()); - if (result == EvalResult.Ok) - { - SkipBlock(input); - } + var whileLoopStartIndex = input.ExecutionIndex; + + EvalResult result; + string reason; + BotToken token; + for ((result, reason, token) = await EvaluateConditionAsync(whileLoopStartIndex, input); + result == EvalResult.Ok && bool.TryParse(token.TokenValue, out var conditionValue) && conditionValue; + (result, reason, token) = await EvaluateConditionAsync(whileLoopStartIndex, input)) + { + var blockEval = await EvaluateBlockAsync(input); + if (blockEval.Item1 != EvalResult.Ok) + return blockEval; + } - return (result, reason, token); + if (result == EvalResult.Ok) + { + SkipBlock(input); + } + + return (result, reason, token); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/VariableBotToken.cs b/EOBot/Interpreter/VariableBotToken.cs index 31f9dfb2f..953de3f5b 100644 --- a/EOBot/Interpreter/VariableBotToken.cs +++ b/EOBot/Interpreter/VariableBotToken.cs @@ -1,14 +1,15 @@ using EOBot.Interpreter.Variables; -namespace EOBot.Interpreter; - -public class VariableBotToken : BotToken +namespace EOBot.Interpreter { - public IVariable VariableValue { get; } - - public VariableBotToken(BotTokenType tokenType, string tokenValue, IVariable variableValue) - : base(tokenType, tokenValue, 0, 0) + public class VariableBotToken : BotToken { - VariableValue = variableValue; + public IVariable VariableValue { get; } + + public VariableBotToken(BotTokenType tokenType, string tokenValue, IVariable variableValue) + : base(tokenType, tokenValue, 0, 0) + { + VariableValue = variableValue; + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/ArrayVariable.cs b/EOBot/Interpreter/Variables/ArrayVariable.cs index 8c3807bd4..25e01a1a4 100644 --- a/EOBot/Interpreter/Variables/ArrayVariable.cs +++ b/EOBot/Interpreter/Variables/ArrayVariable.cs @@ -2,26 +2,27 @@ using System.Collections.Generic; using System.Linq; -namespace EOBot.Interpreter.Variables; - -public class ArrayVariable : IVariable> +namespace EOBot.Interpreter.Variables { - public List Value { get; } + public class ArrayVariable : IVariable> + { + public List Value { get; } - public string StringValue => "[" + string.Join(", ", Value.Select(x => x.StringValue)) + "]"; + public string StringValue => "[" + string.Join(", ", Value.Select(x => x.StringValue)) + "]"; - public ArrayVariable(List value) - { - Value = value; - } + public ArrayVariable(List value) + { + Value = value; + } - // todo: should arrays be comparable? - public int CompareTo(object obj) => -1; + // todo: should arrays be comparable? + public int CompareTo(object obj) => -1; - public IVariable> WithNewValue(List value) - { - return new ArrayVariable(value); - } + public IVariable> WithNewValue(List value) + { + return new ArrayVariable(value); + } - public override string ToString() => StringValue; + public override string ToString() => StringValue; + } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/AsyncFunction.cs b/EOBot/Interpreter/Variables/AsyncFunction.cs index 9e9fe701d..85a2136c4 100644 --- a/EOBot/Interpreter/Variables/AsyncFunction.cs +++ b/EOBot/Interpreter/Variables/AsyncFunction.cs @@ -1,131 +1,132 @@ using System; using System.Threading.Tasks; -namespace EOBot.Interpreter.Variables; - -public class AsyncFunction : IAsyncCallable +namespace EOBot.Interpreter.Variables { - private readonly Func> _referenceFunc; - - public string StringValue { get; } - - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } - - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncFunction : IAsyncCallable { - if (parameters.Length != 0) - throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); + private readonly Func> _referenceFunc; - return _referenceFunc(); - } -} + public string StringValue { get; } -public class AsyncFunction : IAsyncCallable -{ - private readonly Func> _referenceFunc; + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 0) + throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc(); + } } - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncFunction : IAsyncCallable { - if (parameters.Length != 1) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func> _referenceFunc; - // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface - return _referenceFunc((TParam1)(dynamic)parameters[0]); - } -} + public string StringValue { get; } -public class AsyncFunction : IAsyncCallable -{ - private readonly Func> _referenceFunc; + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 1) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface + return _referenceFunc((TParam1)(dynamic)parameters[0]); + } } - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncFunction : IAsyncCallable { - if (parameters.Length != 2) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func> _referenceFunc; - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); - } -} + public string StringValue { get; } -public class AsyncFunction : IAsyncCallable -{ - private readonly Func> _referenceFunc; + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 2) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); + } } - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncFunction : IAsyncCallable { - if (parameters.Length != 3) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func> _referenceFunc; - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); - } -} + public string StringValue { get; } -public class AsyncFunction : IAsyncCallable -{ - private readonly Func> _referenceFunc; + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 3) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); + } } - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncFunction : IAsyncCallable { - if (parameters.Length != 4) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func> _referenceFunc; - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); - } -} + public string StringValue { get; } -public class AsyncFunction : IAsyncCallable -{ - private readonly Func> _referenceFunc; + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 4) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public AsyncFunction(string functionName, Func> referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); + } } - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncFunction : IAsyncCallable { - if (parameters.Length != 5) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func> _referenceFunc; + + public string StringValue { get; } + + public AsyncFunction(string functionName, Func> referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } + + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 5) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/AsyncVoidFunction.cs b/EOBot/Interpreter/Variables/AsyncVoidFunction.cs index 66254844f..f4beb6c09 100644 --- a/EOBot/Interpreter/Variables/AsyncVoidFunction.cs +++ b/EOBot/Interpreter/Variables/AsyncVoidFunction.cs @@ -1,131 +1,132 @@ using System; using System.Threading.Tasks; -namespace EOBot.Interpreter.Variables; - -public class AsyncVoidFunction : IAsyncCallable +namespace EOBot.Interpreter.Variables { - private readonly Func _referenceFunc; - - public string StringValue { get; } - - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } - - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncVoidFunction : IAsyncCallable { - if (parameters.Length != 0) - throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); + private readonly Func _referenceFunc; - return _referenceFunc(); - } -} + public string StringValue { get; } -public class AsyncVoidFunction : IAsyncCallable -{ - private readonly Func _referenceFunc; + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 0) + throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc(); + } } - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncVoidFunction : IAsyncCallable { - if (parameters.Length != 1) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func _referenceFunc; - // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface - return _referenceFunc((TParam1)(dynamic)parameters[0]); - } -} + public string StringValue { get; } -public class AsyncVoidFunction : IAsyncCallable -{ - private readonly Func _referenceFunc; + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 1) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface + return _referenceFunc((TParam1)(dynamic)parameters[0]); + } } - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncVoidFunction : IAsyncCallable { - if (parameters.Length != 2) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func _referenceFunc; - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); - } -} + public string StringValue { get; } -public class AsyncVoidFunction : IAsyncCallable -{ - private readonly Func _referenceFunc; + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 2) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); + } } - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncVoidFunction : IAsyncCallable { - if (parameters.Length != 3) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func _referenceFunc; - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); - } -} + public string StringValue { get; } -public class AsyncVoidFunction : IAsyncCallable -{ - private readonly Func _referenceFunc; + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 3) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); + } } - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncVoidFunction : IAsyncCallable { - if (parameters.Length != 4) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func _referenceFunc; - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); - } -} + public string StringValue { get; } -public class AsyncVoidFunction : IAsyncCallable -{ - private readonly Func _referenceFunc; + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 4) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public AsyncVoidFunction(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); + } } - public Task CallAsync(params IIdentifiable[] parameters) + public class AsyncVoidFunction : IAsyncCallable { - if (parameters.Length != 5) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func _referenceFunc; + + public string StringValue { get; } + + public AsyncVoidFunction(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } + + public Task CallAsync(params IIdentifiable[] parameters) + { + if (parameters.Length != 5) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/BoolVariable.cs b/EOBot/Interpreter/Variables/BoolVariable.cs index 533ee1371..369537c19 100644 --- a/EOBot/Interpreter/Variables/BoolVariable.cs +++ b/EOBot/Interpreter/Variables/BoolVariable.cs @@ -1,20 +1,21 @@ -namespace EOBot.Interpreter.Variables; - -public class BoolVariable : IVariable +namespace EOBot.Interpreter.Variables { - public bool Value { get; } + public class BoolVariable : IVariable + { + public bool Value { get; } - public BoolVariable(bool value) => Value = value; + public BoolVariable(bool value) => Value = value; - public string StringValue => Value.ToString(); + public string StringValue => Value.ToString(); - public override bool Equals(object obj) => CompareTo(obj) == 0; + public override bool Equals(object obj) => CompareTo(obj) == 0; - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value.GetHashCode(); - public int CompareTo(object obj) => obj is BoolVariable ? Value.CompareTo(((BoolVariable)obj).Value) : -1; + public int CompareTo(object obj) => obj is BoolVariable ? Value.CompareTo(((BoolVariable)obj).Value) : -1; - public static explicit operator bool(BoolVariable input) => input.Value; + public static explicit operator bool(BoolVariable input) => input.Value; - public override string ToString() => StringValue; + public override string ToString() => StringValue; + } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/Function.cs b/EOBot/Interpreter/Variables/Function.cs index d41a8340c..4615850b7 100644 --- a/EOBot/Interpreter/Variables/Function.cs +++ b/EOBot/Interpreter/Variables/Function.cs @@ -1,130 +1,131 @@ using System; -namespace EOBot.Interpreter.Variables; - -public class Function : ICallable +namespace EOBot.Interpreter.Variables { - private readonly Func _referenceFunc; - - public string StringValue { get; } - - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } - - public T Call(params IIdentifiable[] parameters) + public class Function : ICallable { - if (parameters.Length != 0) - throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); + private readonly Func _referenceFunc; - return _referenceFunc(); - } -} + public string StringValue { get; } -public class Function : ICallable -{ - private readonly Func _referenceFunc; + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public T Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 0) + throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc(); + } } - public T Call(params IIdentifiable[] parameters) + public class Function : ICallable { - if (parameters.Length != 1) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func _referenceFunc; - // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface - return _referenceFunc((TParam1)(dynamic)parameters[0]); - } -} + public string StringValue { get; } -public class Function : ICallable -{ - private readonly Func _referenceFunc; + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public T Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 1) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface + return _referenceFunc((TParam1)(dynamic)parameters[0]); + } } - public T Call(params IIdentifiable[] parameters) + public class Function : ICallable { - if (parameters.Length != 2) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func _referenceFunc; - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); - } -} + public string StringValue { get; } -public class Function : ICallable -{ - private readonly Func _referenceFunc; + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public T Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 2) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); + } } - public T Call(params IIdentifiable[] parameters) + public class Function : ICallable { - if (parameters.Length != 3) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func _referenceFunc; - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); - } -} + public string StringValue { get; } -public class Function : ICallable -{ - private readonly Func _referenceFunc; + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public T Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 3) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); + } } - public T Call(params IIdentifiable[] parameters) + public class Function : ICallable { - if (parameters.Length != 4) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func _referenceFunc; - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); - } -} + public string StringValue { get; } -public class Function : ICallable -{ - private readonly Func _referenceFunc; + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public T Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 4) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public Function(string functionName, Func referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); + } } - public T Call(params IIdentifiable[] parameters) + public class Function : ICallable { - if (parameters.Length != 5) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Func _referenceFunc; + + public string StringValue { get; } + + public Function(string functionName, Func referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } + + public T Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 5) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); + return _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); + } } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/ICallable.cs b/EOBot/Interpreter/Variables/ICallable.cs index 9ded8ff1a..b82f237fd 100644 --- a/EOBot/Interpreter/Variables/ICallable.cs +++ b/EOBot/Interpreter/Variables/ICallable.cs @@ -1,26 +1,27 @@ using System.Threading.Tasks; -namespace EOBot.Interpreter.Variables; - -public interface IFunction : IIdentifiable { } -public interface ICallable : IFunction +namespace EOBot.Interpreter.Variables { - void Call(params IIdentifiable[] parameters); -} + public interface IFunction : IIdentifiable { } + public interface ICallable : IFunction + { + void Call(params IIdentifiable[] parameters); + } -public interface ICallable : IFunction -{ - T Call(params IIdentifiable[] parameters); -} + public interface ICallable : IFunction + { + T Call(params IIdentifiable[] parameters); + } -public interface IAsyncFunction : IIdentifiable { } + public interface IAsyncFunction : IIdentifiable { } -public interface IAsyncCallable : IAsyncFunction -{ - Task CallAsync(params IIdentifiable[] parameters); -} + public interface IAsyncCallable : IAsyncFunction + { + Task CallAsync(params IIdentifiable[] parameters); + } -public interface IAsyncCallable : IAsyncFunction -{ - Task CallAsync(params IIdentifiable[] parameters); + public interface IAsyncCallable : IAsyncFunction + { + Task CallAsync(params IIdentifiable[] parameters); + } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/IIdentifiable.cs b/EOBot/Interpreter/Variables/IIdentifiable.cs index 6b5081f74..f1c87c708 100644 --- a/EOBot/Interpreter/Variables/IIdentifiable.cs +++ b/EOBot/Interpreter/Variables/IIdentifiable.cs @@ -1,6 +1,7 @@ -namespace EOBot.Interpreter.Variables; - -public interface IIdentifiable +namespace EOBot.Interpreter.Variables { - string StringValue { get; } + public interface IIdentifiable + { + string StringValue { get; } + } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/IVariable.cs b/EOBot/Interpreter/Variables/IVariable.cs index ee054be41..42badf86c 100644 --- a/EOBot/Interpreter/Variables/IVariable.cs +++ b/EOBot/Interpreter/Variables/IVariable.cs @@ -1,13 +1,14 @@ using System; -namespace EOBot.Interpreter.Variables; - -// marker interface so we don't have to implement CompareTo for a million different function/action interfaces -public interface IVariable : IIdentifiable, IComparable +namespace EOBot.Interpreter.Variables { -} + // marker interface so we don't have to implement CompareTo for a million different function/action interfaces + public interface IVariable : IIdentifiable, IComparable + { + } -public interface IVariable : IVariable -{ - T Value { get; } + public interface IVariable : IVariable + { + T Value { get; } + } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/IntVariable.cs b/EOBot/Interpreter/Variables/IntVariable.cs index f584f43d9..397d519aa 100644 --- a/EOBot/Interpreter/Variables/IntVariable.cs +++ b/EOBot/Interpreter/Variables/IntVariable.cs @@ -1,20 +1,21 @@ -namespace EOBot.Interpreter.Variables; - -public class IntVariable : IVariable +namespace EOBot.Interpreter.Variables { - public int Value { get; } + public class IntVariable : IVariable + { + public int Value { get; } - public IntVariable(int value) => Value = value; + public IntVariable(int value) => Value = value; - public string StringValue => Value.ToString(); + public string StringValue => Value.ToString(); - public override bool Equals(object obj) => CompareTo(obj) == 0; + public override bool Equals(object obj) => CompareTo(obj) == 0; - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value.GetHashCode(); - public int CompareTo(object obj) => obj is IntVariable ? Value.CompareTo(((IntVariable)obj).Value) : -1; + public int CompareTo(object obj) => obj is IntVariable ? Value.CompareTo(((IntVariable)obj).Value) : -1; - public static explicit operator int(IntVariable input) => input.Value; + public static explicit operator int(IntVariable input) => input.Value; - public override string ToString() => StringValue; + public override string ToString() => StringValue; + } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/ObjectVariable.cs b/EOBot/Interpreter/Variables/ObjectVariable.cs index 74c217819..099c9a8ca 100644 --- a/EOBot/Interpreter/Variables/ObjectVariable.cs +++ b/EOBot/Interpreter/Variables/ObjectVariable.cs @@ -2,44 +2,45 @@ using System.Collections.Generic; using System.Linq; -namespace EOBot.Interpreter.Variables; - -public class ObjectVariable : IVariable +namespace EOBot.Interpreter.Variables { - public object Value => SymbolTable; + public class ObjectVariable : IVariable + { + public object Value => SymbolTable; - public Dictionary SymbolTable { get; } + public Dictionary SymbolTable { get; } - public ObjectVariable() => SymbolTable = new Dictionary(); + public ObjectVariable() => SymbolTable = new Dictionary(); - public ObjectVariable(Dictionary symbolTable) => SymbolTable = symbolTable; + public ObjectVariable(Dictionary symbolTable) => SymbolTable = symbolTable; - public string StringValue => $"Object: [{string.Join(", ", SymbolTable.Select(x => $"({x.Key}, {x.Value.Variable})"))}]"; + public string StringValue => $"Object: [{string.Join(", ", SymbolTable.Select(x => $"({x.Key}, {x.Value.Variable})"))}]"; - public override bool Equals(object obj) => CompareTo(obj) == 0; + public override bool Equals(object obj) => CompareTo(obj) == 0; - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value.GetHashCode(); - public int CompareTo(object obj) => obj is ObjectVariable ? SymbolTable.Equals(((ObjectVariable)obj).SymbolTable) ? 0 : -1 : -1; + public int CompareTo(object obj) => obj is ObjectVariable ? SymbolTable.Equals(((ObjectVariable)obj).SymbolTable) ? 0 : -1 : -1; - public override string ToString() => StringValue; -} + public override string ToString() => StringValue; + } -public class RuntimeEvaluatedMemberObjectVariable : IVariable -{ - public object Value => SymbolTable; + public class RuntimeEvaluatedMemberObjectVariable : IVariable + { + public object Value => SymbolTable; - public Dictionary Variable)> SymbolTable { get; } + public Dictionary Variable)> SymbolTable { get; } - public RuntimeEvaluatedMemberObjectVariable() => SymbolTable = new Dictionary)>(); + public RuntimeEvaluatedMemberObjectVariable() => SymbolTable = new Dictionary)>(); - public string StringValue => $"Object: [{string.Join(", ", SymbolTable.Select(x => $"({x.Key}, {x.Value.Variable()})"))}]"; + public string StringValue => $"Object: [{string.Join(", ", SymbolTable.Select(x => $"({x.Key}, {x.Value.Variable()})"))}]"; - public override bool Equals(object obj) => CompareTo(obj) == 0; + public override bool Equals(object obj) => CompareTo(obj) == 0; - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value.GetHashCode(); - public int CompareTo(object obj) => obj is ObjectVariable ? SymbolTable.Equals(((ObjectVariable)obj).SymbolTable) ? 0 : -1 : -1; + public int CompareTo(object obj) => obj is ObjectVariable ? SymbolTable.Equals(((ObjectVariable)obj).SymbolTable) ? 0 : -1 : -1; - public override string ToString() => StringValue; + public override string ToString() => StringValue; + } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs b/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs index 23cabf21e..977d4dcd1 100644 --- a/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs +++ b/EOBot/Interpreter/Variables/PredefinedIdentifiers.cs @@ -1,50 +1,51 @@ -namespace EOBot.Interpreter.Variables; - -public static class PredefinedIdentifiers +namespace EOBot.Interpreter.Variables { - // variables - public const string RESULT = "result"; - public const string HOST = "host"; - public const string PORT = "port"; - public const string USER = "user"; - public const string PASS = "pass"; - public const string VERSION = "version"; - public const string ARGS = "args"; - public const string BOTINDEX = "botindex"; - public const string RETCODE = "retcode"; + public static class PredefinedIdentifiers + { + // variables + public const string RESULT = "result"; + public const string HOST = "host"; + public const string PORT = "port"; + public const string USER = "user"; + public const string PASS = "pass"; + public const string VERSION = "version"; + public const string ARGS = "args"; + public const string BOTINDEX = "botindex"; + public const string RETCODE = "retcode"; - // state variables - public const string ACCOUNT = "account"; - public const string CHARACTER = "character"; - public const string MAPSTATE = "mapstate"; + // state variables + public const string ACCOUNT = "account"; + public const string CHARACTER = "character"; + public const string MAPSTATE = "mapstate"; - public const string NAME = "name"; - public const string CHARACTERS = "characters"; + public const string NAME = "name"; + public const string CHARACTERS = "characters"; - // interpreter functions - public const string PRINT_FUNC = "print"; - public const string LEN_FUNC = "len"; - public const string ARRAY_FUNC = "array"; - public const string OBJECT_FUNC = "object"; - public const string SLEEP_FUNC = "sleep"; - public const string TIME_FUNC = "time"; - public const string SETENV_FUNC = "setenv"; - public const string GETENV_FUNC = "getenv"; - public const string ERROR_FUNC = "error"; - public const string LOWER_FUNC = "lower"; - public const string UPPER_FUNC = "upper"; + // interpreter functions + public const string PRINT_FUNC = "print"; + public const string LEN_FUNC = "len"; + public const string ARRAY_FUNC = "array"; + public const string OBJECT_FUNC = "object"; + public const string SLEEP_FUNC = "sleep"; + public const string TIME_FUNC = "time"; + public const string SETENV_FUNC = "setenv"; + public const string GETENV_FUNC = "getenv"; + public const string ERROR_FUNC = "error"; + public const string LOWER_FUNC = "lower"; + public const string UPPER_FUNC = "upper"; - // game functions - public const string CONNECT_FUNC = "Connect"; - public const string DISCONNECT_FUNC = "Disconnect"; - public const string CREATE_ACCOUNT_FUNC = "CreateAccount"; - public const string LOGIN_FUNC = "Login"; - public const string CREATE_AND_LOGIN_FUNC = "CreateAndLogin"; - public const string CHANGE_PASS_FUNC = "ChangePassword"; - public const string CREATE_CHARACTER_FUNC = "CreateCharacter"; - public const string LOGIN_CHARACTER_FUNC = "LoginCharacter"; - public const string DELETE_CHARACTER_FUNC = "DeleteCharacter"; + // game functions + public const string CONNECT_FUNC = "Connect"; + public const string DISCONNECT_FUNC = "Disconnect"; + public const string CREATE_ACCOUNT_FUNC = "CreateAccount"; + public const string LOGIN_FUNC = "Login"; + public const string CREATE_AND_LOGIN_FUNC = "CreateAndLogin"; + public const string CHANGE_PASS_FUNC = "ChangePassword"; + public const string CREATE_CHARACTER_FUNC = "CreateCharacter"; + public const string LOGIN_CHARACTER_FUNC = "LoginCharacter"; + public const string DELETE_CHARACTER_FUNC = "DeleteCharacter"; - public const string JOIN_PARTY = "JoinParty"; - public const string CHAT = "Chat"; + public const string JOIN_PARTY = "JoinParty"; + public const string CHAT = "Chat"; + } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/StringVariable.cs b/EOBot/Interpreter/Variables/StringVariable.cs index 82ca102ca..7884fd76b 100644 --- a/EOBot/Interpreter/Variables/StringVariable.cs +++ b/EOBot/Interpreter/Variables/StringVariable.cs @@ -1,20 +1,21 @@ -namespace EOBot.Interpreter.Variables; - -public class StringVariable : IVariable +namespace EOBot.Interpreter.Variables { - public string Value { get; } + public class StringVariable : IVariable + { + public string Value { get; } - public StringVariable(string value) => Value = value; + public StringVariable(string value) => Value = value; - public string StringValue => Value; + public string StringValue => Value; - public override bool Equals(object obj) => CompareTo(obj) == 0; + public override bool Equals(object obj) => CompareTo(obj) == 0; - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value.GetHashCode(); - public int CompareTo(object obj) => obj is StringVariable ? Value.CompareTo(((StringVariable)obj).Value) : -1; + public int CompareTo(object obj) => obj is StringVariable ? Value.CompareTo(((StringVariable)obj).Value) : -1; - public static explicit operator string(StringVariable variable) => variable.Value; + public static explicit operator string(StringVariable variable) => variable.Value; - public override string ToString() => StringValue; + public override string ToString() => StringValue; + } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/UndefinedVariable.cs b/EOBot/Interpreter/Variables/UndefinedVariable.cs index 2ab86a224..95582b946 100644 --- a/EOBot/Interpreter/Variables/UndefinedVariable.cs +++ b/EOBot/Interpreter/Variables/UndefinedVariable.cs @@ -1,14 +1,15 @@ -namespace EOBot.Interpreter.Variables; - -public class UndefinedVariable : IVariable +namespace EOBot.Interpreter.Variables { - public static UndefinedVariable Instance { get; } = new UndefinedVariable(); + public class UndefinedVariable : IVariable + { + public static UndefinedVariable Instance { get; } = new UndefinedVariable(); - public string StringValue => "Undefined"; + public string StringValue => "Undefined"; - private UndefinedVariable() { } + private UndefinedVariable() { } - public int CompareTo(object obj) => obj is UndefinedVariable ? 0 : -1; + public int CompareTo(object obj) => obj is UndefinedVariable ? 0 : -1; - public override string ToString() => StringValue; + public override string ToString() => StringValue; + } } \ No newline at end of file diff --git a/EOBot/Interpreter/Variables/VoidFunction.cs b/EOBot/Interpreter/Variables/VoidFunction.cs index 9b61d82a0..1429b34ef 100644 --- a/EOBot/Interpreter/Variables/VoidFunction.cs +++ b/EOBot/Interpreter/Variables/VoidFunction.cs @@ -1,130 +1,131 @@ using System; -namespace EOBot.Interpreter.Variables; - -public class VoidFunction : ICallable +namespace EOBot.Interpreter.Variables { - private readonly Action _referenceFunc; - - public string StringValue { get; } - - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; - } - - public void Call(params IIdentifiable[] parameters) + public class VoidFunction : ICallable { - if (parameters.Length != 0) - throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); + private readonly Action _referenceFunc; - _referenceFunc(); - } -} + public string StringValue { get; } -public class VoidFunction : ICallable -{ - private readonly Action _referenceFunc; + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public void Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 0) + throw new ArgumentException($"Calling parameterless function '{StringValue}' with parameters"); - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + _referenceFunc(); + } } - public void Call(params IIdentifiable[] parameters) + public class VoidFunction : ICallable { - if (parameters.Length != 1) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Action _referenceFunc; - // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface - _referenceFunc((TParam1)(dynamic)parameters[0]); - } -} + public string StringValue { get; } -public class VoidFunction : ICallable -{ - private readonly Action _referenceFunc; + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public void Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 1) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + // This has to be dynamic because otherwise there is an InvalidCastException trying to use a user-defined conversion operator when the source type is an interface + _referenceFunc((TParam1)(dynamic)parameters[0]); + } } - public void Call(params IIdentifiable[] parameters) + public class VoidFunction : ICallable { - if (parameters.Length != 2) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Action _referenceFunc; - _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); - } -} + public string StringValue { get; } -public class VoidFunction : ICallable -{ - private readonly Action _referenceFunc; + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public void Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 2) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1]); + } } - public void Call(params IIdentifiable[] parameters) + public class VoidFunction : ICallable { - if (parameters.Length != 3) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Action _referenceFunc; - _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); - } -} + public string StringValue { get; } -public class VoidFunction : ICallable -{ - private readonly Action _referenceFunc; + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public void Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 3) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2]); + } } - public void Call(params IIdentifiable[] parameters) + public class VoidFunction : ICallable { - if (parameters.Length != 4) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Action _referenceFunc; - _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); - } -} + public string StringValue { get; } -public class VoidFunction : ICallable -{ - private readonly Action _referenceFunc; + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } - public string StringValue { get; } + public void Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 4) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - public VoidFunction(string functionName, Action referenceFunc) - { - StringValue = functionName; - _referenceFunc = referenceFunc; + _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3]); + } } - public void Call(params IIdentifiable[] parameters) + public class VoidFunction : ICallable { - if (parameters.Length != 5) - throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); + private readonly Action _referenceFunc; + + public string StringValue { get; } + + public VoidFunction(string functionName, Action referenceFunc) + { + StringValue = functionName; + _referenceFunc = referenceFunc; + } + + public void Call(params IIdentifiable[] parameters) + { + if (parameters.Length != 5) + throw new ArgumentException($"Calling function '{StringValue}' with wrong number of parameters"); - _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); + _referenceFunc((TParam1)(dynamic)parameters[0], (TParam2)(dynamic)parameters[1], (TParam3)(dynamic)parameters[2], (TParam4)(dynamic)parameters[3], (TParam5)(dynamic)parameters[4]); + } } } \ No newline at end of file diff --git a/EOBot/NamesList.cs b/EOBot/NamesList.cs index ae851ccf1..0c1a91aea 100644 --- a/EOBot/NamesList.cs +++ b/EOBot/NamesList.cs @@ -1,54 +1,55 @@ using System; -namespace EOBot; - -static class NamesList +namespace EOBot { - private static readonly string[] namesArray = + static class NamesList { - "AlphaAA", - "BravoBB", - "Charlie", - "DeltaDD", - "EchoEE", - "Foxtrot", - "GolfGG", - "HotelHH", - "IndiaII", - "Juliett", - "KiloKK", - "LimaLL", - "MikeMM", - "November", - "OscarOO", - "PapaPO", - "Quebec", - "RomeoRR", - "Sierra", - "TangoTT", - "Uniform", - "Victor", - "Whiskey", - "XrayXX", - "Yankee" - }; + private static readonly string[] namesArray = + { + "AlphaAA", + "BravoBB", + "Charlie", + "DeltaDD", + "EchoEE", + "Foxtrot", + "GolfGG", + "HotelHH", + "IndiaII", + "Juliett", + "KiloKK", + "LimaLL", + "MikeMM", + "November", + "OscarOO", + "PapaPO", + "Quebec", + "RomeoRR", + "Sierra", + "TangoTT", + "Uniform", + "Victor", + "Whiskey", + "XrayXX", + "Yankee" + }; - public static string Get(int index) - { - if (index < 0 || index >= namesArray.Length) - index = 0; - return namesArray[index]; - } + public static string Get(int index) + { + if (index < 0 || index >= namesArray.Length) + index = 0; + return namesArray[index]; + } - public static string Rand() - { - Random gen = new Random(); - int len = gen.Next(5, 11); - string ret = ""; - for (int i = 0; i < len; ++i) + public static string Rand() { - ret += Convert.ToChar(Convert.ToInt32('a') + gen.Next(0, 25)); + Random gen = new Random(); + int len = gen.Next(5, 11); + string ret = ""; + for (int i = 0; i < len; ++i) + { + ret += Convert.ToChar(Convert.ToInt32('a') + gen.Next(0, 25)); + } + return ret; } - return ret; } } \ No newline at end of file diff --git a/EOBot/Program.cs b/EOBot/Program.cs index 491231f2e..48acacfc4 100644 --- a/EOBot/Program.cs +++ b/EOBot/Program.cs @@ -14,322 +14,322 @@ using System.Linq; using System.Threading.Tasks; -namespace EOBot; - -static class Program +namespace EOBot { - private static BotFramework f; - - [AutoMappedType] - class NpcWalkNotifier : INPCActionNotifier + static class Program { - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly ICharacterProvider _characterProvider; - private readonly IENFFileProvider _enfFileProvider; - - public NpcWalkNotifier(ICurrentMapStateRepository currentMapStateRepository, - ICharacterProvider characterProvider, - IENFFileProvider enfFileProvider) - { - _currentMapStateRepository = currentMapStateRepository; - _characterProvider = characterProvider; - _enfFileProvider = enfFileProvider; - } + private static BotFramework f; - public void NPCTakeDamage(int npcIndex, int fromPlayerId, int damageToNpc, int npcPctHealth, Option spellId) + [AutoMappedType] + class NpcWalkNotifier : INPCActionNotifier { - if (fromPlayerId != _characterProvider.MainCharacter.ID) - return; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly ICharacterProvider _characterProvider; + private readonly IENFFileProvider _enfFileProvider; - var npc = _currentMapStateRepository.NPCs.SingleOrDefault(x => x.Index == npcIndex); - var npcName = _enfFileProvider.ENFFile.SingleOrDefault(x => npc != null && npc.ID == x.ID)?.Name; + public NpcWalkNotifier(ICurrentMapStateRepository currentMapStateRepository, + ICharacterProvider characterProvider, + IENFFileProvider enfFileProvider) + { + _currentMapStateRepository = currentMapStateRepository; + _characterProvider = characterProvider; + _enfFileProvider = enfFileProvider; + } - var color = npcPctHealth < 25 - ? ConsoleColor.Red - : npcPctHealth < 50 - ? ConsoleColor.Yellow - : ConsoleColor.Green; + public void NPCTakeDamage(int npcIndex, int fromPlayerId, int damageToNpc, int npcPctHealth, Option spellId) + { + if (fromPlayerId != _characterProvider.MainCharacter.ID) + return; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Hit, $"{damageToNpc,7} - {npcPctHealth,3}% HP - {npcIndex,2} - {npcName ?? string.Empty}", color); - } + var npc = _currentMapStateRepository.NPCs.SingleOrDefault(x => x.Index == npcIndex); + var npcName = _enfFileProvider.ENFFile.SingleOrDefault(x => npc != null && npc.ID == x.ID)?.Name; - public void RemoveNPCFromView(int npcIndex, int playerId, Option spellId, Option damage, bool showDeathAnimation) - { - } + var color = npcPctHealth < 25 + ? ConsoleColor.Red + : npcPctHealth < 50 + ? ConsoleColor.Yellow + : ConsoleColor.Green; - public void ShowNPCSpeechBubble(int npcIndex, string message) - { - } + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Hit, $"{damageToNpc,7} - {npcPctHealth,3}% HP - {npcIndex,2} - {npcName ?? string.Empty}", color); + } - public void StartNPCAttackAnimation(int npcIndex) - { - } + public void RemoveNPCFromView(int npcIndex, int playerId, Option spellId, Option damage, bool showDeathAnimation) + { + } - public void StartNPCWalkAnimation(int npcIndex) - { - // immediately walk the NPC to the destination index - var npc = _currentMapStateRepository.NPCs.SingleOrDefault(x => x.Index == npcIndex); - if (npc == null) return; + public void ShowNPCSpeechBubble(int npcIndex, string message) + { + } - var newNpc = npc.WithX(npc.GetDestinationX()).WithY(npc.GetDestinationY()).WithFrame(NPCFrame.Standing); - _currentMapStateRepository.NPCs.Remove(npc); - _currentMapStateRepository.NPCs.Add(newNpc); - } + public void StartNPCAttackAnimation(int npcIndex) + { + } - public void NPCDropItem(MapItem item) - { - } - } + public void StartNPCWalkAnimation(int npcIndex) + { + // immediately walk the NPC to the destination index + var npc = _currentMapStateRepository.NPCs.SingleOrDefault(x => x.Index == npcIndex); + if (npc == null) return; - [AutoMappedType] - class CharacterTakeDamageNotifier : IMainCharacterEventNotifier - { - private readonly ICharacterProvider _characterProvider; - private readonly IExperienceTableProvider _experienceTableProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; + var newNpc = npc.WithX(npc.GetDestinationX()).WithY(npc.GetDestinationY()).WithFrame(NPCFrame.Standing); + _currentMapStateRepository.NPCs.Remove(npc); + _currentMapStateRepository.NPCs.Add(newNpc); + } - public CharacterTakeDamageNotifier(ICharacterProvider characterProvider, - IExperienceTableProvider experienceTableProvider, - ICharacterInventoryProvider characterInventoryProvider) - { - _characterProvider = characterProvider; - _experienceTableProvider = experienceTableProvider; - _characterInventoryProvider = characterInventoryProvider; + public void NPCDropItem(MapItem item) + { + } } - public void NotifyGainedExp(int expDifference) + [AutoMappedType] + class CharacterTakeDamageNotifier : IMainCharacterEventNotifier { - var nextLevelExp = _experienceTableProvider.ExperienceByLevel[_characterProvider.MainCharacter.Stats[CharacterStat.Level] + 1]; - var tnl = nextLevelExp - _characterProvider.MainCharacter.Stats[CharacterStat.Experience] - expDifference; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Experience, $"{expDifference,7} - {tnl} TNL", ConsoleColor.DarkCyan); - } + private readonly ICharacterProvider _characterProvider; + private readonly IExperienceTableProvider _experienceTableProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; - public void NotifyTakeDamage(int damageTaken, int playerPercentHealth, bool isHeal) - { - var type = isHeal ? ConsoleHelper.Type.Heal : ConsoleHelper.Type.Damage; - var color = isHeal ? ConsoleColor.DarkGreen - : playerPercentHealth < 25 - ? ConsoleColor.Red - : playerPercentHealth < 50 - ? ConsoleColor.Yellow - : ConsoleColor.Green; + public CharacterTakeDamageNotifier(ICharacterProvider characterProvider, + IExperienceTableProvider experienceTableProvider, + ICharacterInventoryProvider characterInventoryProvider) + { + _characterProvider = characterProvider; + _experienceTableProvider = experienceTableProvider; + _characterInventoryProvider = characterInventoryProvider; + } - ConsoleHelper.WriteMessage(type, $"{damageTaken,7} - {playerPercentHealth,3}% HP", color); + public void NotifyGainedExp(int expDifference) + { + var nextLevelExp = _experienceTableProvider.ExperienceByLevel[_characterProvider.MainCharacter.Stats[CharacterStat.Level] + 1]; + var tnl = nextLevelExp - _characterProvider.MainCharacter.Stats[CharacterStat.Experience] - expDifference; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Experience, $"{expDifference,7} - {tnl} TNL", ConsoleColor.DarkCyan); + } - var hp = _characterProvider.MainCharacter.Stats[CharacterStat.HP]; - if (!isHeal && hp - damageTaken <= 0) + public void NotifyTakeDamage(int damageTaken, int playerPercentHealth, bool isHeal) { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Dead, "**** YOU DIED ****", ConsoleColor.DarkRed); + var type = isHeal ? ConsoleHelper.Type.Heal : ConsoleHelper.Type.Damage; + var color = isHeal ? ConsoleColor.DarkGreen + : playerPercentHealth < 25 + ? ConsoleColor.Red + : playerPercentHealth < 50 + ? ConsoleColor.Yellow + : ConsoleColor.Green; + + ConsoleHelper.WriteMessage(type, $"{damageTaken,7} - {playerPercentHealth,3}% HP", color); + + var hp = _characterProvider.MainCharacter.Stats[CharacterStat.HP]; + if (!isHeal && hp - damageTaken <= 0) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Dead, "**** YOU DIED ****", ConsoleColor.DarkRed); + } } - } - public void TakeItemFromMap(int id, int amountTaken) - { - var inventoryCount = _characterInventoryProvider.ItemInventory.SingleOrDefault(x => x.ItemID == id); - var weight = _characterProvider.MainCharacter.Stats[CharacterStat.Weight]; - var maxWeight = _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Item, $"{weight,3}/{maxWeight,3} - weight - {inventoryCount.Amount} in inventory"); - } + public void TakeItemFromMap(int id, int amountTaken) + { + var inventoryCount = _characterInventoryProvider.ItemInventory.SingleOrDefault(x => x.ItemID == id); + var weight = _characterProvider.MainCharacter.Stats[CharacterStat.Weight]; + var maxWeight = _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Item, $"{weight,3}/{maxWeight,3} - weight - {inventoryCount.Amount} in inventory"); + } - public void DropItem(int id, int amountDropped) - { + public void DropItem(int id, int amountDropped) + { + } + + public void JunkItem(int id, int amountRemoved) + { + var inventoryCount = _characterInventoryProvider.ItemInventory.SingleOrDefault(x => x.ItemID == id); + var weight = _characterProvider.MainCharacter.Stats[CharacterStat.Weight]; + var maxWeight = _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.JunkItem, $"{weight,3}/{maxWeight,3} - weight - {inventoryCount?.Amount ?? 0} in inventory"); + } + + public void MakeDrunk() { } } - public void JunkItem(int id, int amountRemoved) + [AutoMappedType] + class CharacterAnimationNotifier : IOtherCharacterAnimationNotifier { - var inventoryCount = _characterInventoryProvider.ItemInventory.SingleOrDefault(x => x.ItemID == id); - var weight = _characterProvider.MainCharacter.Stats[CharacterStat.Weight]; - var maxWeight = _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.JunkItem, $"{weight,3}/{maxWeight,3} - weight - {inventoryCount?.Amount ?? 0} in inventory"); - } + private readonly ICharacterProvider _characterProvider; - public void MakeDrunk() { } - } + public CharacterAnimationNotifier(ICharacterProvider characterProvider) + { + _characterProvider = characterProvider; + } - [AutoMappedType] - class CharacterAnimationNotifier : IOtherCharacterAnimationNotifier - { - private readonly ICharacterProvider _characterProvider; + public void NotifySelfSpellCast(int playerId, int spellId, int spellHp, int percentHealth) + { + if (playerId == _characterProvider.MainCharacter.ID && spellHp > 0) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Heal, $"{spellHp,7} - {percentHealth}% HP", ConsoleColor.DarkGreen); + } - public CharacterAnimationNotifier(ICharacterProvider characterProvider) - { - _characterProvider = characterProvider; + public void NotifyStartSpellCast(int playerId, int spellId) { } + public void NotifyTargetNpcSpellCast(int playerId) { } + public void NotifyTargetOtherSpellCast(int sourcePlayerID, int targetPlayerID, int spellId, int recoveredHP, int targetPercentHealth) { } + public void StartOtherCharacterAttackAnimation(int characterID, int noteIndex) { } + public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) { } + public void NotifyGroupSpellCast(int playerId, int spellId, int spellHp, List spellTargets) { } } - public void NotifySelfSpellCast(int playerId, int spellId, int spellHp, int percentHealth) + static async Task Main(string[] args) { - if (playerId == _characterProvider.MainCharacter.ID && spellHp > 0) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Heal, $"{spellHp,7} - {percentHealth}% HP", ConsoleColor.DarkGreen); - } + var assemblyNames = new[] + { + "EOBot", + "EOLib", + "EOLib.Config", + "EOLib.IO", + "EOLib.Localization", + "EOLib.Logger" + }; - public void NotifyStartSpellCast(int playerId, int spellId) { } - public void NotifyTargetNpcSpellCast(int playerId) { } - public void NotifyTargetOtherSpellCast(int sourcePlayerID, int targetPlayerID, int spellId, int recoveredHP, int targetPercentHealth) { } - public void StartOtherCharacterAttackAnimation(int characterID, int noteIndex) { } - public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) { } - public void NotifyGroupSpellCast(int playerId, int spellId, int spellHp, List spellTargets) { } - } + Console.CancelKeyPress += HandleCtrlC; - static async Task Main(string[] args) - { - var assemblyNames = new[] - { - "EOBot", - "EOLib", - "EOLib.Config", - "EOLib.IO", - "EOLib.Localization", - "EOLib.Logger" - }; + ArgumentsParser parsedArgs = new ArgumentsParser(args); - Console.CancelKeyPress += HandleCtrlC; + if (parsedArgs.Error != ArgsError.NoError || parsedArgs.ExtendedHelp) + { + ShowError(parsedArgs); + return 1; + } - ArgumentsParser parsedArgs = new ArgumentsParser(args); + DependencyMaster.TypeRegistry = new ITypeRegistry[parsedArgs.NumBots]; + for (int i = 0; i < parsedArgs.NumBots; ++i) + { + DependencyMaster.TypeRegistry[i] = new UnityRegistry(assemblyNames); + DependencyMaster.TypeRegistry[i].RegisterDiscoveredTypes(); + } - if (parsedArgs.Error != ArgsError.NoError || parsedArgs.ExtendedHelp) - { - ShowError(parsedArgs); - return 1; - } + IBotFactory botFactory; + if (parsedArgs.ScriptFile != null) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Executing script {parsedArgs.ScriptFile}..."); + botFactory = new ScriptedBotFactory(parsedArgs); + } + else + { + botFactory = new TrainerBotFactory(parsedArgs); + } - DependencyMaster.TypeRegistry = new ITypeRegistry[parsedArgs.NumBots]; - for (int i = 0; i < parsedArgs.NumBots; ++i) - { - DependencyMaster.TypeRegistry[i] = new UnityRegistry(assemblyNames); - DependencyMaster.TypeRegistry[i].RegisterDiscoveredTypes(); - } + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "Starting bots..."); - IBotFactory botFactory; - if (parsedArgs.ScriptFile != null) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Executing script {parsedArgs.ScriptFile}..."); - botFactory = new ScriptedBotFactory(parsedArgs); - } - else - { - botFactory = new TrainerBotFactory(parsedArgs); - } + try + { + using (f = new BotFramework(parsedArgs)) + { + await f.InitializeAsync(botFactory, parsedArgs.InitDelay); + await f.RunAsync(); + } + + Console.WriteLine(); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "All bots completed."); + } + catch (BotException bex) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, bex.Message, ConsoleColor.DarkRed); + return 1; + } + catch (BotScriptErrorException bse) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, bse.Message, ConsoleColor.DarkRed); + return 1; + } + catch (AggregateException ae) + { + var botExceptions = ae.InnerExceptions.OfType().ToList(); + foreach (var ie in botExceptions) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, ie.Message, ConsoleColor.DarkRed); - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "Starting bots..."); + var otherExceptions = ae.InnerExceptions.Except(botExceptions); + foreach (var ie in otherExceptions) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Unhandled error: {ie.Message}\nStack Trace:\n{ie.StackTrace}", ConsoleColor.DarkRed); - try - { - using (f = new BotFramework(parsedArgs)) + return 1; + } + catch (Exception ex) { - await f.InitializeAsync(botFactory, parsedArgs.InitDelay); - await f.RunAsync(); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Unhandled error: {ex.Message}\nStack Trace:\n{ex.StackTrace}", ConsoleColor.DarkRed); + return 1; } - Console.WriteLine(); - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "All bots completed."); + return 0; } - catch (BotException bex) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, bex.Message, ConsoleColor.DarkRed); - return 1; - } - catch (BotScriptErrorException bse) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, bse.Message, ConsoleColor.DarkRed); - return 1; - } - catch (AggregateException ae) - { - var botExceptions = ae.InnerExceptions.OfType().ToList(); - foreach (var ie in botExceptions) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, ie.Message, ConsoleColor.DarkRed); - - var otherExceptions = ae.InnerExceptions.Except(botExceptions); - foreach (var ie in otherExceptions) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Unhandled error: {ie.Message}\nStack Trace:\n{ie.StackTrace}", ConsoleColor.DarkRed); - return 1; - } - catch (Exception ex) + static void HandleCtrlC(object sender, ConsoleCancelEventArgs e) { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"Unhandled error: {ex.Message}\nStack Trace:\n{ex.StackTrace}", ConsoleColor.DarkRed); - return 1; - } - - return 0; - } + var name = Enum.GetName(e.SpecialKey.GetType(), e.SpecialKey); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Exiting due to {name} event from system"); - static void HandleCtrlC(object sender, ConsoleCancelEventArgs e) - { - var name = Enum.GetName(e.SpecialKey.GetType(), e.SpecialKey); - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Exiting due to {name} event from system"); - - f?.TerminateBots(); - } + f?.TerminateBots(); + } - static void ShowError(ArgumentsParser args) - { - switch (args.Error) + static void ShowError(ArgumentsParser args) { - case ArgsError.WrongNumberOfArgs: - Console.WriteLine("Invalid: specify host, port, and the number of bots to run"); - break; - case ArgsError.InvalidPort: - Console.WriteLine("Invalid: port number could not be parsed!"); - break; - case ArgsError.InvalidNumberOfBots: - Console.WriteLine("Invalid: specify an integer argument for number of bots."); - break; - case ArgsError.TooManyBots: - Console.WriteLine("Invalid: unable to launch > 25 threads of execution. Please use 25 or less."); - break; - case ArgsError.NotEnoughBots: - Console.WriteLine("Invalid: unable to launch < 1 thread of execution. Please use 1 or more."); - break; - case ArgsError.BadFormat: - Console.WriteLine("Badly formatted argument. Enter args like \"argument=value\"."); - break; - case ArgsError.InvalidSimultaneousNumberOfBots: - Console.WriteLine("Invalid: Simultaneous number of bots must not be more than total number of bots."); - break; - case ArgsError.InvalidWaitFlag: - Console.WriteLine("Invalid: Wait flag could not be parsed. Use 0, 1, false, true, no, or yes."); - break; - case ArgsError.InvalidInitDelay: - Console.WriteLine("Invalid: specify an integer argument for delay between inits (> 1100ms)."); - break; - case ArgsError.InvalidPath: - Console.WriteLine("Invalid: Script file does not exist or is not a valid path."); - break; - case ArgsError.InvalidScriptArgs: - Console.WriteLine("Invalid: User-defined arguments and disabling autoconnect require a script."); - break; - case ArgsError.AutoConnectRequired: - Console.WriteLine("Invalid: AutoConnect is required when using a script with more than 1 bot due to eoserv connection throttling."); - break; - } + switch (args.Error) + { + case ArgsError.WrongNumberOfArgs: + Console.WriteLine("Invalid: specify host, port, and the number of bots to run"); + break; + case ArgsError.InvalidPort: + Console.WriteLine("Invalid: port number could not be parsed!"); + break; + case ArgsError.InvalidNumberOfBots: + Console.WriteLine("Invalid: specify an integer argument for number of bots."); + break; + case ArgsError.TooManyBots: + Console.WriteLine("Invalid: unable to launch > 25 threads of execution. Please use 25 or less."); + break; + case ArgsError.NotEnoughBots: + Console.WriteLine("Invalid: unable to launch < 1 thread of execution. Please use 1 or more."); + break; + case ArgsError.BadFormat: + Console.WriteLine("Badly formatted argument. Enter args like \"argument=value\"."); + break; + case ArgsError.InvalidSimultaneousNumberOfBots: + Console.WriteLine("Invalid: Simultaneous number of bots must not be more than total number of bots."); + break; + case ArgsError.InvalidWaitFlag: + Console.WriteLine("Invalid: Wait flag could not be parsed. Use 0, 1, false, true, no, or yes."); + break; + case ArgsError.InvalidInitDelay: + Console.WriteLine("Invalid: specify an integer argument for delay between inits (> 1100ms)."); + break; + case ArgsError.InvalidPath: + Console.WriteLine("Invalid: Script file does not exist or is not a valid path."); + break; + case ArgsError.InvalidScriptArgs: + Console.WriteLine("Invalid: User-defined arguments and disabling autoconnect require a script."); + break; + case ArgsError.AutoConnectRequired: + Console.WriteLine("Invalid: AutoConnect is required when using a script with more than 1 bot due to eoserv connection throttling."); + break; + } - Console.WriteLine("\n\nUsage: (enter arguments in any order) (angle brackets is entry) (square brackets is optional)"); - Console.WriteLine("EOBot.exe host=\n" + - " port=\n" + - " bots=[,]\n" + - " initDelay=\n" + - " account=\n" + - " password=\n" + - " character=\n" + - " script=\n" + - " autoconnect=" + - " [-- arg1, [arg2..argn]]"); - Console.WriteLine("\t host: hostname or IP address"); - Console.WriteLine("\t port: port to connect on (probably 8078)"); - Console.WriteLine("\t bots: number of bots to execute. \n\t numBots is the total number, simultaneousBots is how many will run at once"); - Console.WriteLine("\t initDelay: time in milliseconds to delay between doing the INIT handshake with the server"); - Console.WriteLine("\t account: account to connect with (created if it does not exist)"); - Console.WriteLine("\t password: password for account"); - Console.WriteLine("\t character: character to use (created if it does not exist)"); - Console.WriteLine("\t script: script file to execute\n\t if script is not specified, default trainer bot will be used"); - Console.WriteLine("\t autoconnect: (default true) true to automatically connect/disconnect to server with initDelay timeout between connection attempts for bots, false otherwise"); - Console.WriteLine("\t --: Any arguments passed after '--' will be available in a script under the '$args' array"); - - if (!args.ExtendedHelp) - return; - - Console.WriteLine(@" + Console.WriteLine("\n\nUsage: (enter arguments in any order) (angle brackets is entry) (square brackets is optional)"); + Console.WriteLine("EOBot.exe host=\n" + + " port=\n" + + " bots=[,]\n" + + " initDelay=\n" + + " account=\n" + + " password=\n" + + " character=\n" + + " script=\n" + + " autoconnect=" + + " [-- arg1, [arg2..argn]]"); + Console.WriteLine("\t host: hostname or IP address"); + Console.WriteLine("\t port: port to connect on (probably 8078)"); + Console.WriteLine("\t bots: number of bots to execute. \n\t numBots is the total number, simultaneousBots is how many will run at once"); + Console.WriteLine("\t initDelay: time in milliseconds to delay between doing the INIT handshake with the server"); + Console.WriteLine("\t account: account to connect with (created if it does not exist)"); + Console.WriteLine("\t password: password for account"); + Console.WriteLine("\t character: character to use (created if it does not exist)"); + Console.WriteLine("\t script: script file to execute\n\t if script is not specified, default trainer bot will be used"); + Console.WriteLine("\t autoconnect: (default true) true to automatically connect/disconnect to server with initDelay timeout between connection attempts for bots, false otherwise"); + Console.WriteLine("\t --: Any arguments passed after '--' will be available in a script under the '$args' array"); + + if (!args.ExtendedHelp) + return; + + Console.WriteLine(@" =============================================================== Bot Script Info =============================================================== @@ -409,5 +409,6 @@ TIME THE SCRIPT FINISHES EXECUTING $character - object: reserved $mapstate - object : reserved "); + } } } \ No newline at end of file diff --git a/EOBot/ScriptedBot.cs b/EOBot/ScriptedBot.cs index 6bbbe8194..bd5c2a5d5 100644 --- a/EOBot/ScriptedBot.cs +++ b/EOBot/ScriptedBot.cs @@ -5,52 +5,53 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot; - -public class ScriptedBot : BotBase +namespace EOBot { - private readonly BotInterpreter _interpreter; - private readonly ArgumentsParser _parsedArgs; - private ProgramState _programState; - - public ScriptedBot(int index, ArgumentsParser parsedArgs) - : base(index) - { - _interpreter = new BotInterpreter(parsedArgs.ScriptFile); - _parsedArgs = parsedArgs; - } - - public override async Task InitializeAsync(string host, int port) + public class ScriptedBot : BotBase { - var tokens = _interpreter.Parse(); - _programState = _interpreter.Prepare(_index, _parsedArgs, tokens); + private readonly BotInterpreter _interpreter; + private readonly ArgumentsParser _parsedArgs; + private ProgramState _programState; - if (_parsedArgs.AutoConnect) + public ScriptedBot(int index, ArgumentsParser parsedArgs) + : base(index) { - var connectFunction = _programState.SymbolTable[PredefinedIdentifiers.CONNECT_FUNC].Identifiable as AsyncVoidFunction; - if (connectFunction == null) - throw new InvalidOperationException("Something went wrong getting the connect function out of the symbol table"); + _interpreter = new BotInterpreter(parsedArgs.ScriptFile); + _parsedArgs = parsedArgs; + } - // call connect function that uses user-defined $version variable instead of base logic that has it hard-coded - await connectFunction.CallAsync(new StringVariable(_parsedArgs.Host), new IntVariable(_parsedArgs.Port)); + public override async Task InitializeAsync(string host, int port) + { + var tokens = _interpreter.Parse(); + _programState = _interpreter.Prepare(_index, _parsedArgs, tokens); - WorkCompleted += () => + if (_parsedArgs.AutoConnect) { - Thread.Sleep(2000); + var connectFunction = _programState.SymbolTable[PredefinedIdentifiers.CONNECT_FUNC].Identifiable as AsyncVoidFunction; + if (connectFunction == null) + throw new InvalidOperationException("Something went wrong getting the connect function out of the symbol table"); - var disconnectionFunction = _programState.SymbolTable[PredefinedIdentifiers.DISCONNECT_FUNC].Identifiable as VoidFunction; - disconnectionFunction.Call(); - }; - } + // call connect function that uses user-defined $version variable instead of base logic that has it hard-coded + await connectFunction.CallAsync(new StringVariable(_parsedArgs.Host), new IntVariable(_parsedArgs.Port)); - _initialized = true; - } + WorkCompleted += () => + { + Thread.Sleep(2000); - protected override async Task DoWorkAsync(CancellationToken ct) - { - if (_programState == null) - throw new InvalidOperationException("Scripted bot must be initialized before it is run"); + var disconnectionFunction = _programState.SymbolTable[PredefinedIdentifiers.DISCONNECT_FUNC].Identifiable as VoidFunction; + disconnectionFunction.Call(); + }; + } + + _initialized = true; + } - await _interpreter.Run(_programState); + protected override async Task DoWorkAsync(CancellationToken ct) + { + if (_programState == null) + throw new InvalidOperationException("Scripted bot must be initialized before it is run"); + + await _interpreter.Run(_programState); + } } } \ No newline at end of file diff --git a/EOBot/ScriptedBotFactory.cs b/EOBot/ScriptedBotFactory.cs index 062fd62b9..fa27d634e 100644 --- a/EOBot/ScriptedBotFactory.cs +++ b/EOBot/ScriptedBotFactory.cs @@ -1,16 +1,17 @@ -namespace EOBot; - -public class ScriptedBotFactory : IBotFactory +namespace EOBot { - private readonly ArgumentsParser _parser; - - public ScriptedBotFactory(ArgumentsParser parser) + public class ScriptedBotFactory : IBotFactory { - _parser = parser; - } + private readonly ArgumentsParser _parser; - public IBot CreateBot(int index) - { - return new ScriptedBot(index, _parser); + public ScriptedBotFactory(ArgumentsParser parser) + { + _parser = parser; + } + + public IBot CreateBot(int index) + { + return new ScriptedBot(index, _parser); + } } } \ No newline at end of file diff --git a/EOBot/TrainerBot.cs b/EOBot/TrainerBot.cs index c2316e998..ad1245c55 100644 --- a/EOBot/TrainerBot.cs +++ b/EOBot/TrainerBot.cs @@ -18,394 +18,395 @@ using System.Threading; using System.Threading.Tasks; -namespace EOBot; - -internal class TrainerBot : BotBase +namespace EOBot { - private const int CONSECUTIVE_ATTACK_COUNT = 150; - private const int ATTACK_BACKOFF_MS = 600; - private const int WALK_BACKOFF_MS = 480; - private const int FACE_BACKOFF_MS = 120; - - private static readonly int[] JunkItemIds = new[] + internal class TrainerBot : BotBase { - // Dragon Blade, enchanted boots (red/green/blue) - 37, 124, 125, 126 - // cava staff - //329 - }; + private const int CONSECUTIVE_ATTACK_COUNT = 150; + private const int ATTACK_BACKOFF_MS = 600; + private const int WALK_BACKOFF_MS = 480; + private const int FACE_BACKOFF_MS = 120; - private readonly string _account; - private readonly string _password; - private readonly string _character; + private static readonly int[] JunkItemIds = new[] + { + // Dragon Blade, enchanted boots (red/green/blue) + 37, 124, 125, 126 + // cava staff + //329 + }; - private ICharacterActions _characterActions; - private IMapActions _mapActions; - private IItemActions _itemActions; + private readonly string _account; + private readonly string _password; + private readonly string _character; - private ICharacterRepository _characterRepository; - private IFixedTimeStepRepository _fixedTimeStepRepository; + private ICharacterActions _characterActions; + private IMapActions _mapActions; + private IItemActions _itemActions; - private IPubFile _itemData; - private IPubFile _npcData; - private IPubFile _spellData; + private ICharacterRepository _characterRepository; + private IFixedTimeStepRepository _fixedTimeStepRepository; - private IChatProvider _chatProvider; - private HashSet _cachedChat; + private IPubFile _itemData; + private IPubFile _npcData; + private IPubFile _spellData; - public TrainerBot(int botIndex, string account, string password, string character) - : base(botIndex) - { - _account = account; - _password = password; - _character = character; - } + private IChatProvider _chatProvider; + private HashSet _cachedChat; - protected override async Task DoWorkAsync(CancellationToken ct) - { - var helper = new BotHelper(_index); + public TrainerBot(int botIndex, string account, string password, string character) + : base(botIndex) + { + _account = account; + _password = password; + _character = character; + } - var res = await helper.LoginToAccountAsync(_account, _password); - if (res == LoginReply.WrongUser) + protected override async Task DoWorkAsync(CancellationToken ct) { - var createRes = await helper.CreateAccountAsync(_account, _password); - if (createRes != AccountReply.Created) - throw new InvalidOperationException($"Unable to create account: invalid response {Enum.GetName(typeof(AccountReply), createRes)}"); + var helper = new BotHelper(_index); - res = await helper.LoginToAccountAsync(_account, _password); - } + var res = await helper.LoginToAccountAsync(_account, _password); + if (res == LoginReply.WrongUser) + { + var createRes = await helper.CreateAccountAsync(_account, _password); + if (createRes != AccountReply.Created) + throw new InvalidOperationException($"Unable to create account: invalid response {Enum.GetName(typeof(AccountReply), createRes)}"); - if (res != LoginReply.Ok) - throw new InvalidOperationException($"Unable to log in to account: invalid response {Enum.GetName(typeof(LoginReply), res)}"); + res = await helper.LoginToAccountAsync(_account, _password); + } - await helper.LoginToCharacterAsync(_character); + if (res != LoginReply.Ok) + throw new InvalidOperationException($"Unable to log in to account: invalid response {Enum.GetName(typeof(LoginReply), res)}"); - var c = DependencyMaster.TypeRegistry[_index]; + await helper.LoginToCharacterAsync(_character); - _mapActions = c.Resolve(); - _itemActions = c.Resolve(); - _characterRepository = c.Resolve(); - _characterActions = c.Resolve(); - var mapCellStateProvider = c.Resolve(); - var mapStateProvider = c.Resolve(); - var handler = c.Resolve(); - _itemData = c.Resolve().EIFFile; - _npcData = c.Resolve().ENFFile; - _spellData = c.Resolve().ESFFile; - var charInventoryRepo = c.Resolve(); - var walkValidator = c.Resolve(); + var c = DependencyMaster.TypeRegistry[_index]; - _chatProvider = c.Resolve(); - _cachedChat = new HashSet(); + _mapActions = c.Resolve(); + _itemActions = c.Resolve(); + _characterRepository = c.Resolve(); + _characterActions = c.Resolve(); + var mapCellStateProvider = c.Resolve(); + var mapStateProvider = c.Resolve(); + var handler = c.Resolve(); + _itemData = c.Resolve().EIFFile; + _npcData = c.Resolve().ENFFile; + _spellData = c.Resolve().ESFFile; + var charInventoryRepo = c.Resolve(); + var walkValidator = c.Resolve(); - _fixedTimeStepRepository = c.Resolve(); + _chatProvider = c.Resolve(); + _cachedChat = new HashSet(); - var healItems = new List(); - var healSpells = new List(); + _fixedTimeStepRepository = c.Resolve(); - int attackCount = 0, cachedPlayerCount = 0; - bool time_to_die = false; + var healItems = new List(); + var healSpells = new List(); - MapCoordinate? priorityCoord = null; - while (!ct.IsCancellationRequested) - { - handler.PollForPacketsAndHandle(); + int attackCount = 0, cachedPlayerCount = 0; + bool time_to_die = false; - if (!_cachedChat.SetEquals(_chatProvider.AllChat[ChatTab.Local])) + MapCoordinate? priorityCoord = null; + while (!ct.IsCancellationRequested) { - foreach (var message in _chatProvider.AllChat[ChatTab.Local].Except(_cachedChat)) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Chat, $"{message.Who}: {message.Message}", ConsoleColor.Cyan); + handler.PollForPacketsAndHandle(); - _cachedChat = _chatProvider.AllChat[ChatTab.Local].ToHashSet(); - if (OperatingSystem.IsWindows()) + if (!_cachedChat.SetEquals(_chatProvider.AllChat[ChatTab.Local])) { - Console.Beep(261, 1500); - } - } + foreach (var message in _chatProvider.AllChat[ChatTab.Local].Except(_cachedChat)) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Chat, $"{message.Who}: {message.Message}", ConsoleColor.Cyan); - var character = _characterRepository.MainCharacter; - var charRenderProps = character.RenderProperties; + _cachedChat = _chatProvider.AllChat[ChatTab.Local].ToHashSet(); + if (OperatingSystem.IsWindows()) + { + Console.Beep(261, 1500); + } + } - var currentPositionCellState = mapCellStateProvider.GetCellStateAt(charRenderProps.MapX, charRenderProps.MapY); + var character = _characterRepository.MainCharacter; + var charRenderProps = character.RenderProperties; - if (cachedPlayerCount != mapStateProvider.Characters.Count()) - { - cachedPlayerCount = mapStateProvider.Characters.Count(); - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"{cachedPlayerCount,7} - Players on map - You may not be able to train here", ConsoleColor.DarkYellow); + var currentPositionCellState = mapCellStateProvider.GetCellStateAt(charRenderProps.MapX, charRenderProps.MapY); - if (OperatingSystem.IsWindows()) + if (cachedPlayerCount != mapStateProvider.Characters.Count()) { - Console.Beep(220, 500); - Console.Beep(247, 500); - Console.Beep(220, 500); - } - } + cachedPlayerCount = mapStateProvider.Characters.Count(); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"{cachedPlayerCount,7} - Players on map - You may not be able to train here", ConsoleColor.DarkYellow); - var coords = new MapCoordinate[] - { - new MapCoordinate(charRenderProps.MapX + 1, charRenderProps.MapY), - new MapCoordinate(charRenderProps.MapX - 1, charRenderProps.MapY), - new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY + 1), - new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY - 1) - }; - - if (priorityCoord != null) - { - // ensure if there's an attack in progress that we finish killing that NPC before moving around - var tmp = new[] { priorityCoord.Value }; - coords = tmp.Concat(coords.Except(tmp)).ToArray(); - } + if (OperatingSystem.IsWindows()) + { + Console.Beep(220, 500); + Console.Beep(247, 500); + Console.Beep(220, 500); + } + } - var action_taken = false; - foreach (var coord in coords) - { - if (action_taken) - break; + var coords = new MapCoordinate[] + { + new MapCoordinate(charRenderProps.MapX + 1, charRenderProps.MapY), + new MapCoordinate(charRenderProps.MapX - 1, charRenderProps.MapY), + new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY + 1), + new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY - 1) + }; - if (!time_to_die) + if (priorityCoord != null) { - var cellState = mapCellStateProvider.GetCellStateAt(coord.X, coord.Y); + // ensure if there's an attack in progress that we finish killing that NPC before moving around + var tmp = new[] { priorityCoord.Value }; + coords = tmp.Concat(coords.Except(tmp)).ToArray(); + } - if (priorityCoord.HasValue && !cellState.NPC.HasValue) - priorityCoord = null; + var action_taken = false; + foreach (var coord in coords) + { + if (action_taken) + break; - if (character.Stats[CharacterStat.Weight] >= character.Stats[CharacterStat.MaxWeight]) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"OVER WEIGHT LIMIT - TIME TO DIE", ConsoleColor.DarkYellow); - await ToggleSit(); - action_taken = true; - time_to_die = true; - } - else if ((attackCount < CONSECUTIVE_ATTACK_COUNT && !currentPositionCellState.NPC.HasValue) || cellState.NPC.HasValue) + if (!time_to_die) { - if (cellState.NPC.HasValue && character.Stats[CharacterStat.HP] > character.Stats[CharacterStat.MaxHP] * .1) - { - await FaceCoordinateIfNeeded(new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY), coord); - await Attack(cellState); - attackCount++; - action_taken = true; - priorityCoord = coord; - } - else if (cellState.Items.Any()) + var cellState = mapCellStateProvider.GetCellStateAt(coord.X, coord.Y); + + if (priorityCoord.HasValue && !cellState.NPC.HasValue) + priorityCoord = null; + + if (character.Stats[CharacterStat.Weight] >= character.Stats[CharacterStat.MaxWeight]) { - await PickUpItems(cellState); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"OVER WEIGHT LIMIT - TIME TO DIE", ConsoleColor.DarkYellow); + await ToggleSit(); action_taken = true; + time_to_die = true; } - else if (healItems.Any() && character.Stats[CharacterStat.HP] < character.Stats[CharacterStat.MaxHP] * .3) + else if ((attackCount < CONSECUTIVE_ATTACK_COUNT && !currentPositionCellState.NPC.HasValue) || cellState.NPC.HasValue) { - var stats = _characterRepository.MainCharacter.Stats; - while (!ct.IsCancellationRequested && stats[CharacterStat.HP] < stats[CharacterStat.MaxHP] * .6) + if (cellState.NPC.HasValue && character.Stats[CharacterStat.HP] > character.Stats[CharacterStat.MaxHP] * .1) { - await UseHealItem(healItems); - handler.PollForPacketsAndHandle(); - stats = _characterRepository.MainCharacter.Stats; + await FaceCoordinateIfNeeded(new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY), coord); + await Attack(cellState); + attackCount++; + action_taken = true; + priorityCoord = coord; + } + else if (cellState.Items.Any()) + { + await PickUpItems(cellState); + action_taken = true; + } + else if (healItems.Any() && character.Stats[CharacterStat.HP] < character.Stats[CharacterStat.MaxHP] * .3) + { + var stats = _characterRepository.MainCharacter.Stats; + while (!ct.IsCancellationRequested && stats[CharacterStat.HP] < stats[CharacterStat.MaxHP] * .6) + { + await UseHealItem(healItems); + handler.PollForPacketsAndHandle(); + stats = _characterRepository.MainCharacter.Stats; + } + + action_taken = true; + } + else if (healSpells.Any() && character.Stats[CharacterStat.HP] < character.Stats[CharacterStat.MaxHP] * .9 + && character.Stats[CharacterStat.TP] > character.Stats[CharacterStat.MaxTP] * .5) + { + await CastHealSpell(healSpells); + action_taken = true; } - action_taken = true; - } - else if (healSpells.Any() && character.Stats[CharacterStat.HP] < character.Stats[CharacterStat.MaxHP] * .9 - && character.Stats[CharacterStat.TP] > character.Stats[CharacterStat.MaxTP] * .5) - { - await CastHealSpell(healSpells); - action_taken = true; - } - - healItems = charInventoryRepo.ItemInventory - .Where(x => _itemData.Any(y => y.ID == x.ItemID && y.Type == ItemType.Heal)) - .ToList(); + healItems = charInventoryRepo.ItemInventory + .Where(x => _itemData.Any(y => y.ID == x.ItemID && y.Type == ItemType.Heal)) + .ToList(); - healSpells = charInventoryRepo.SpellInventory - .Where(x => _spellData.Any(y => y.ID == x.ID && y.Type == SpellType.Heal)) - .ToList(); - } - else - { - if (!currentPositionCellState.NPC.HasValue) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Move, $"Walking due to consecutive attacks: {attackCount}"); + healSpells = charInventoryRepo.SpellInventory + .Where(x => _spellData.Any(y => y.ID == x.ID && y.Type == SpellType.Heal)) + .ToList(); + } else - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Move, $"Killing NPC at player location"); - - // find a direction that's open to walk to - var targetWalkCell = coords.Select(z => mapCellStateProvider.GetCellStateAt(z.X, z.Y)) - .FirstOrDefault(z => walkValidator.IsCellStateWalkable(z) == WalkValidationResult.Walkable); - if (targetWalkCell == null) { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Couldn't find open space to walk!", ConsoleColor.DarkYellow); - break; - } + if (!currentPositionCellState.NPC.HasValue) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Move, $"Walking due to consecutive attacks: {attackCount}"); + else + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Move, $"Killing NPC at player location"); + + // find a direction that's open to walk to + var targetWalkCell = coords.Select(z => mapCellStateProvider.GetCellStateAt(z.X, z.Y)) + .FirstOrDefault(z => walkValidator.IsCellStateWalkable(z) == WalkValidationResult.Walkable); + if (targetWalkCell == null) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Couldn't find open space to walk!", ConsoleColor.DarkYellow); + break; + } - await FaceCoordinateIfNeeded(new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY), targetWalkCell.Coordinate); + await FaceCoordinateIfNeeded(new MapCoordinate(charRenderProps.MapX, charRenderProps.MapY), targetWalkCell.Coordinate); - var originalDirection = charRenderProps.Direction; - await Walk(); - await Face(originalDirection.Opposite()); + var originalDirection = charRenderProps.Direction; + await Walk(); + await Face(originalDirection.Opposite()); - // kill NPC if it was in our starting point - while (currentPositionCellState.NPC.HasValue && !ct.IsCancellationRequested) - { - await Attack(currentPositionCellState); + // kill NPC if it was in our starting point + while (currentPositionCellState.NPC.HasValue && !ct.IsCancellationRequested) + { + await Attack(currentPositionCellState); - handler.PollForPacketsAndHandle(); - currentPositionCellState = mapCellStateProvider.GetCellStateAt(charRenderProps.MapX, charRenderProps.MapY); - } + handler.PollForPacketsAndHandle(); + currentPositionCellState = mapCellStateProvider.GetCellStateAt(charRenderProps.MapX, charRenderProps.MapY); + } - await PickUpItems(currentPositionCellState); + await PickUpItems(currentPositionCellState); - await Walk(); - await Face(originalDirection); + await Walk(); + await Face(originalDirection); - attackCount = 0; - action_taken = true; + attackCount = 0; + action_taken = true; + } } } - } - await Delay(120); + await Delay(120); + } } - } - private async Task Attack(IMapCellState cellState) - { - cellState.NPC.MatchSome(npc => ConsoleHelper.WriteMessage(ConsoleHelper.Type.Attack, $"{npc.Index,7} - {_npcData.Single(x => x.ID == npc.ID).Name}")); - await TrySend(_characterActions.Attack); - await Delay(ATTACK_BACKOFF_MS); - } + private async Task Attack(IMapCellState cellState) + { + cellState.NPC.MatchSome(npc => ConsoleHelper.WriteMessage(ConsoleHelper.Type.Attack, $"{npc.Index,7} - {_npcData.Single(x => x.ID == npc.ID).Name}")); + await TrySend(_characterActions.Attack); + await Delay(ATTACK_BACKOFF_MS); + } - private async Task Walk() - { - var renderProps = _characterRepository.MainCharacter.RenderProperties; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Walk, $"{renderProps.GetDestinationX(),3},{renderProps.GetDestinationY(),3}"); - await TrySend(() => _characterActions.Walk(false)); - await Delay(WALK_BACKOFF_MS); - } + private async Task Walk() + { + var renderProps = _characterRepository.MainCharacter.RenderProperties; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Walk, $"{renderProps.GetDestinationX(),3},{renderProps.GetDestinationY(),3}"); + await TrySend(() => _characterActions.Walk(false)); + await Delay(WALK_BACKOFF_MS); + } - private async Task Face(EODirection direction) - { - var rp = _characterRepository.MainCharacter.RenderProperties; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Face, $"{Enum.GetName(typeof(EODirection), direction),7} - at {rp.MapX},{rp.MapY}"); - await TrySend(() => _characterActions.Face(direction)); + private async Task Face(EODirection direction) + { + var rp = _characterRepository.MainCharacter.RenderProperties; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Face, $"{Enum.GetName(typeof(EODirection), direction),7} - at {rp.MapX},{rp.MapY}"); + await TrySend(() => _characterActions.Face(direction)); - // todo: character actions Face() should also change the character's direction instead of relying on client to update it separately - _characterRepository.MainCharacter = _characterRepository.MainCharacter - .WithRenderProperties(_characterRepository.MainCharacter.RenderProperties.WithDirection(direction)); + // todo: character actions Face() should also change the character's direction instead of relying on client to update it separately + _characterRepository.MainCharacter = _characterRepository.MainCharacter + .WithRenderProperties(_characterRepository.MainCharacter.RenderProperties.WithDirection(direction)); - await Delay(FACE_BACKOFF_MS); - } + await Delay(FACE_BACKOFF_MS); + } - private async Task FaceCoordinateIfNeeded(MapCoordinate originalCoord, MapCoordinate targetCoord) - { - var charRenderProps = _characterRepository.MainCharacter.RenderProperties; - var nextCoord = new MapCoordinate(charRenderProps.GetDestinationX(), charRenderProps.GetDestinationY()); - if (nextCoord != targetCoord) + private async Task FaceCoordinateIfNeeded(MapCoordinate originalCoord, MapCoordinate targetCoord) { - var diff = targetCoord - originalCoord; - var direction = diff.X > 0 ? EODirection.Right - : diff.X < 0 ? EODirection.Left - : diff.Y > 0 ? EODirection.Down - : diff.Y < 0 ? EODirection.Up : charRenderProps.Direction; - - if (direction != charRenderProps.Direction) - await Face(direction); + var charRenderProps = _characterRepository.MainCharacter.RenderProperties; + var nextCoord = new MapCoordinate(charRenderProps.GetDestinationX(), charRenderProps.GetDestinationY()); + if (nextCoord != targetCoord) + { + var diff = targetCoord - originalCoord; + var direction = diff.X > 0 ? EODirection.Right + : diff.X < 0 ? EODirection.Left + : diff.Y > 0 ? EODirection.Down + : diff.Y < 0 ? EODirection.Up : charRenderProps.Direction; + + if (direction != charRenderProps.Direction) + await Face(direction); + } } - } - private async Task PickUpItems(IMapCellState cellState) - { - foreach (var item in cellState.Items) + private async Task PickUpItems(IMapCellState cellState) { - await PickUpItem(item); - - if (JunkItemIds.Contains(item.ItemID)) + foreach (var item in cellState.Items) { - await Delay(1000); - await JunkItem(item); + await PickUpItem(item); + + if (JunkItemIds.Contains(item.ItemID)) + { + await Delay(1000); + await JunkItem(item); + } } } - } - private async Task PickUpItem(MapItem item) - { - await TrySend(() => + private async Task PickUpItem(MapItem item) { - var itemName = _itemData.Single(x => x.ID == item.ItemID).Name; - var pickupResult = _mapActions.PickUpItem(item); - if (pickupResult == ItemPickupResult.Ok) - ConsoleHelper.WriteMessage(ConsoleHelper.Type.TakeItem, $"{item.Amount,7} - {itemName}"); - else - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Ignoring item {itemName} x{item.Amount} due to pickup error {pickupResult}", ConsoleColor.DarkYellow); - }); - await Delay(ATTACK_BACKOFF_MS); - } + await TrySend(() => + { + var itemName = _itemData.Single(x => x.ID == item.ItemID).Name; + var pickupResult = _mapActions.PickUpItem(item); + if (pickupResult == ItemPickupResult.Ok) + ConsoleHelper.WriteMessage(ConsoleHelper.Type.TakeItem, $"{item.Amount,7} - {itemName}"); + else + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, $"Ignoring item {itemName} x{item.Amount} due to pickup error {pickupResult}", ConsoleColor.DarkYellow); + }); + await Delay(ATTACK_BACKOFF_MS); + } - private async Task JunkItem(MapItem item) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.JunkItem, $"{item.Amount,7} - {_itemData.Single(x => x.ID == item.ItemID).Name}"); - await TrySend(() => _itemActions.JunkItem(item.ItemID, item.Amount)); - await Delay(ATTACK_BACKOFF_MS); - } + private async Task JunkItem(MapItem item) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.JunkItem, $"{item.Amount,7} - {_itemData.Single(x => x.ID == item.ItemID).Name}"); + await TrySend(() => _itemActions.JunkItem(item.ItemID, item.Amount)); + await Delay(ATTACK_BACKOFF_MS); + } - private async Task CastHealSpell(IEnumerable healSpells) - { - var spellToUse = _spellData - .Where(x => healSpells.Any(y => y.ID == x.ID) && x.Target != SpellTarget.Group) - .OrderByDescending(x => x.HP) - .First(); + private async Task CastHealSpell(IEnumerable healSpells) + { + var spellToUse = _spellData + .Where(x => healSpells.Any(y => y.ID == x.ID) && x.Target != SpellTarget.Group) + .OrderByDescending(x => x.HP) + .First(); - var stats = _characterRepository.MainCharacter.Stats.Stats; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Cast, $"{spellToUse.HP,4} HP - {spellToUse.Name} - TP {stats[CharacterStat.TP]}/{stats[CharacterStat.MaxTP]}"); + var stats = _characterRepository.MainCharacter.Stats.Stats; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Cast, $"{spellToUse.HP,4} HP - {spellToUse.Name} - TP {stats[CharacterStat.TP]}/{stats[CharacterStat.MaxTP]}"); - await TrySend(() => _characterActions.PrepareCastSpell(spellToUse.ID)); - await Delay((uint)spellToUse.CastTime * 480); + await TrySend(() => _characterActions.PrepareCastSpell(spellToUse.ID)); + await Delay((uint)spellToUse.CastTime * 480); - await TrySend(() => _characterActions.CastSpell(spellToUse.ID, _characterRepository.MainCharacter)); - await Delay(ATTACK_BACKOFF_MS); // 600ms cooldown between spell casts - } + await TrySend(() => _characterActions.CastSpell(spellToUse.ID, _characterRepository.MainCharacter)); + await Delay(ATTACK_BACKOFF_MS); // 600ms cooldown between spell casts + } - private async Task UseHealItem(IEnumerable healItems) - { - var itemToUse = _itemData - .Where(x => healItems.Any(y => y.ItemID == x.ID)) - .OrderBy(x => x.HP) - .First(); - var amount = healItems.Single(x => x.ItemID == itemToUse.ID).Amount; + private async Task UseHealItem(IEnumerable healItems) + { + var itemToUse = _itemData + .Where(x => healItems.Any(y => y.ItemID == x.ID)) + .OrderBy(x => x.HP) + .First(); + var amount = healItems.Single(x => x.ItemID == itemToUse.ID).Amount; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.UseItem, $"{itemToUse.Name} - {itemToUse.HP} HP - inventory: {amount - 1} - (other heal item types: {healItems.Count() - 1})"); + ConsoleHelper.WriteMessage(ConsoleHelper.Type.UseItem, $"{itemToUse.Name} - {itemToUse.HP} HP - inventory: {amount - 1} - (other heal item types: {healItems.Count() - 1})"); - await TrySend(() => _itemActions.UseItem(itemToUse.ID)); - await Delay(ATTACK_BACKOFF_MS); - } + await TrySend(() => _itemActions.UseItem(itemToUse.ID)); + await Delay(ATTACK_BACKOFF_MS); + } - private async Task ToggleSit() - { - var renderProps = _characterRepository.MainCharacter.RenderProperties; - var nextState = renderProps.SitState == EOLib.Domain.Character.SitState.Standing ? "Floor" : "Stand"; - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Sit, $"{nextState,7} - Toggling from: {Enum.GetName(typeof(EOLib.Domain.Character.SitState), renderProps.SitState)}"); - await TrySend(() => _characterActions.Sit(MapCoordinate.Zero)); - } + private async Task ToggleSit() + { + var renderProps = _characterRepository.MainCharacter.RenderProperties; + var nextState = renderProps.SitState == EOLib.Domain.Character.SitState.Standing ? "Floor" : "Stand"; + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Sit, $"{nextState,7} - Toggling from: {Enum.GetName(typeof(EOLib.Domain.Character.SitState), renderProps.SitState)}"); + await TrySend(() => _characterActions.Sit(MapCoordinate.Zero)); + } - private async Task TrySend(Action action, uint attempts = 3) - { - for (uint i = 1; i <= attempts; i++) + private async Task TrySend(Action action, uint attempts = 3) { - try + for (uint i = 1; i <= attempts; i++) { - action(); - break; - } - catch (NoDataSentException) - { - ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"{i} / {attempts} - No data sent", ConsoleColor.DarkRed); - if (i == attempts) - throw; + try + { + action(); + break; + } + catch (NoDataSentException) + { + ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, $"{i} / {attempts} - No data sent", ConsoleColor.DarkRed); + if (i == attempts) + throw; - await Delay(i * i * 1000); + await Delay(i * i * 1000); + } } } - } - private Task Delay(uint milliseconds) - { - _fixedTimeStepRepository.Tick(milliseconds / 10); - return Task.Delay((int)milliseconds); + private Task Delay(uint milliseconds) + { + _fixedTimeStepRepository.Tick(milliseconds / 10); + return Task.Delay((int)milliseconds); + } } } \ No newline at end of file diff --git a/EOBot/TrainerBotFactory.cs b/EOBot/TrainerBotFactory.cs index 87c077216..68df168fa 100644 --- a/EOBot/TrainerBotFactory.cs +++ b/EOBot/TrainerBotFactory.cs @@ -1,16 +1,17 @@ -namespace EOBot; - -public class TrainerBotFactory : IBotFactory +namespace EOBot { - private readonly ArgumentsParser _parser; - - public TrainerBotFactory(ArgumentsParser parser) + public class TrainerBotFactory : IBotFactory { - _parser = parser; - } + private readonly ArgumentsParser _parser; - public IBot CreateBot(int index) - { - return new TrainerBot(index, _parser.Account, _parser.Password, _parser.Character); + public TrainerBotFactory(ArgumentsParser parser) + { + _parser = parser; + } + + public IBot CreateBot(int index) + { + return new TrainerBot(index, _parser.Account, _parser.Password, _parser.Character); + } } } \ No newline at end of file diff --git a/EOLib.Config.Test/ConfigFileLoadActionsTest.cs b/EOLib.Config.Test/ConfigFileLoadActionsTest.cs index c795ae784..3b7fa6496 100644 --- a/EOLib.Config.Test/ConfigFileLoadActionsTest.cs +++ b/EOLib.Config.Test/ConfigFileLoadActionsTest.cs @@ -2,73 +2,73 @@ using System.Diagnostics.CodeAnalysis; using System.IO; -namespace EOLib.Config.Test; - -[TestFixture, ExcludeFromCodeCoverage] -public class ConfigFileLoadActionsTest +namespace EOLib.Config.Test { - private const string ConfigDirectory = "config"; - - private IConfigFileLoadActions _configFileLoadActions; - private IConfigurationRepository _configurationRepository; - - [SetUp] - public void SetUp() - { - _configurationRepository = new ConfigurationRepository(); - _configFileLoadActions = new ConfigFileLoadActions(_configurationRepository); - } - - [TearDown] - public static void TearDown() - { - if (Directory.Exists(ConfigDirectory)) - Directory.Delete(ConfigDirectory, true); - } - - [Test] - public void MissingConfigurationFile_ThrowsConfigLoadException() - { - Assert.Throws(() => _configFileLoadActions.LoadConfigFile()); - } - - [Test] - public void InvalidConfigFileThatExists_UsesConfigurationValueDefaults() + [TestFixture, ExcludeFromCodeCoverage] + public class ConfigFileLoadActionsTest { - CreateTestConfigurationInDirectory("[Invalid]\nContents=heyayayayay"); - _configFileLoadActions.LoadConfigFile(); - - Assert.AreEqual(ConfigDefaults.MajorVersion, _configurationRepository.VersionMajor); - Assert.AreEqual(ConfigDefaults.MinorVersion, _configurationRepository.VersionMinor); - Assert.AreEqual(ConfigDefaults.ClientVersion, _configurationRepository.VersionBuild); - - Assert.AreEqual(ConfigDefaults.Host, _configurationRepository.Host); - Assert.AreEqual(ConfigDefaults.Port, _configurationRepository.Port); - - Assert.AreEqual(ConfigDefaults.NPCDropProtectionSeconds, _configurationRepository.NPCDropProtectTime); - Assert.AreEqual(ConfigDefaults.PlayerDropProtectionSeconds, _configurationRepository.PlayerDropProtectTime); - - Assert.AreEqual(EOLanguage.English, _configurationRepository.Language); - Assert.IsFalse(_configurationRepository.CurseFilterEnabled); - Assert.IsFalse(_configurationRepository.StrictFilterEnabled); - - Assert.IsTrue(_configurationRepository.ShowShadows); - Assert.IsTrue(_configurationRepository.ShowChatBubbles); - Assert.IsFalse(_configurationRepository.ShowTransition); - - Assert.IsFalse(_configurationRepository.MusicEnabled); - Assert.IsFalse(_configurationRepository.SoundEnabled); - - Assert.IsTrue(_configurationRepository.HearWhispers); - Assert.IsTrue(_configurationRepository.Interaction); - Assert.IsFalse(_configurationRepository.LogChatToFile); - Assert.IsFalse(_configurationRepository.EnableLog); - } - - [Test] - public void ValidConfigFile_LoadsSpecifiedSettings() - { - const string contents = @"[CONNECTION] + private const string ConfigDirectory = "config"; + + private IConfigFileLoadActions _configFileLoadActions; + private IConfigurationRepository _configurationRepository; + + [SetUp] + public void SetUp() + { + _configurationRepository = new ConfigurationRepository(); + _configFileLoadActions = new ConfigFileLoadActions(_configurationRepository); + } + + [TearDown] + public static void TearDown() + { + if (Directory.Exists(ConfigDirectory)) + Directory.Delete(ConfigDirectory, true); + } + + [Test] + public void MissingConfigurationFile_ThrowsConfigLoadException() + { + Assert.Throws(() => _configFileLoadActions.LoadConfigFile()); + } + + [Test] + public void InvalidConfigFileThatExists_UsesConfigurationValueDefaults() + { + CreateTestConfigurationInDirectory("[Invalid]\nContents=heyayayayay"); + _configFileLoadActions.LoadConfigFile(); + + Assert.AreEqual(ConfigDefaults.MajorVersion, _configurationRepository.VersionMajor); + Assert.AreEqual(ConfigDefaults.MinorVersion, _configurationRepository.VersionMinor); + Assert.AreEqual(ConfigDefaults.ClientVersion, _configurationRepository.VersionBuild); + + Assert.AreEqual(ConfigDefaults.Host, _configurationRepository.Host); + Assert.AreEqual(ConfigDefaults.Port, _configurationRepository.Port); + + Assert.AreEqual(ConfigDefaults.NPCDropProtectionSeconds, _configurationRepository.NPCDropProtectTime); + Assert.AreEqual(ConfigDefaults.PlayerDropProtectionSeconds, _configurationRepository.PlayerDropProtectTime); + + Assert.AreEqual(EOLanguage.English, _configurationRepository.Language); + Assert.IsFalse(_configurationRepository.CurseFilterEnabled); + Assert.IsFalse(_configurationRepository.StrictFilterEnabled); + + Assert.IsTrue(_configurationRepository.ShowShadows); + Assert.IsTrue(_configurationRepository.ShowChatBubbles); + Assert.IsFalse(_configurationRepository.ShowTransition); + + Assert.IsFalse(_configurationRepository.MusicEnabled); + Assert.IsFalse(_configurationRepository.SoundEnabled); + + Assert.IsTrue(_configurationRepository.HearWhispers); + Assert.IsTrue(_configurationRepository.Interaction); + Assert.IsFalse(_configurationRepository.LogChatToFile); + Assert.IsFalse(_configurationRepository.EnableLog); + } + + [Test] + public void ValidConfigFile_LoadsSpecifiedSettings() + { + const string contents = @"[CONNECTION] Host=ewmoffat.ddns.net Port=12345 [VERSION] @@ -96,44 +96,45 @@ public void ValidConfigFile_LoadsSpecifiedSettings() LogFile=CHATLOG.TXT HearWhisper=off Interaction=false"; - CreateTestConfigurationInDirectory(contents); + CreateTestConfigurationInDirectory(contents); - _configFileLoadActions.LoadConfigFile(); + _configFileLoadActions.LoadConfigFile(); - Assert.AreEqual(10, _configurationRepository.VersionMajor); - Assert.AreEqual(20, _configurationRepository.VersionMinor); - Assert.AreEqual(30, _configurationRepository.VersionBuild); + Assert.AreEqual(10, _configurationRepository.VersionMajor); + Assert.AreEqual(20, _configurationRepository.VersionMinor); + Assert.AreEqual(30, _configurationRepository.VersionBuild); - Assert.AreEqual("ewmoffat.ddns.net", _configurationRepository.Host); - Assert.AreEqual(12345, _configurationRepository.Port); + Assert.AreEqual("ewmoffat.ddns.net", _configurationRepository.Host); + Assert.AreEqual(12345, _configurationRepository.Port); - Assert.AreEqual(5000, _configurationRepository.NPCDropProtectTime); - Assert.AreEqual(10000, _configurationRepository.PlayerDropProtectTime); + Assert.AreEqual(5000, _configurationRepository.NPCDropProtectTime); + Assert.AreEqual(10000, _configurationRepository.PlayerDropProtectTime); - Assert.AreEqual(EOLanguage.Swedish, _configurationRepository.Language); - Assert.IsTrue(_configurationRepository.CurseFilterEnabled); - Assert.IsTrue(_configurationRepository.StrictFilterEnabled); + Assert.AreEqual(EOLanguage.Swedish, _configurationRepository.Language); + Assert.IsTrue(_configurationRepository.CurseFilterEnabled); + Assert.IsTrue(_configurationRepository.StrictFilterEnabled); - Assert.IsFalse(_configurationRepository.ShowShadows); - Assert.IsFalse(_configurationRepository.ShowChatBubbles); - Assert.IsTrue(_configurationRepository.ShowTransition); - Assert.AreEqual(123, _configurationRepository.InGameWidth); - Assert.AreEqual(321, _configurationRepository.InGameHeight); + Assert.IsFalse(_configurationRepository.ShowShadows); + Assert.IsFalse(_configurationRepository.ShowChatBubbles); + Assert.IsTrue(_configurationRepository.ShowTransition); + Assert.AreEqual(123, _configurationRepository.InGameWidth); + Assert.AreEqual(321, _configurationRepository.InGameHeight); - Assert.IsTrue(_configurationRepository.MusicEnabled); - Assert.IsTrue(_configurationRepository.SoundEnabled); + Assert.IsTrue(_configurationRepository.MusicEnabled); + Assert.IsTrue(_configurationRepository.SoundEnabled); - Assert.IsFalse(_configurationRepository.HearWhispers); - Assert.IsFalse(_configurationRepository.Interaction); - Assert.IsTrue(_configurationRepository.LogChatToFile); - Assert.IsTrue(_configurationRepository.EnableLog); - } + Assert.IsFalse(_configurationRepository.HearWhispers); + Assert.IsFalse(_configurationRepository.Interaction); + Assert.IsTrue(_configurationRepository.LogChatToFile); + Assert.IsTrue(_configurationRepository.EnableLog); + } - private static void CreateTestConfigurationInDirectory(string contents) - { - if (!Directory.Exists(ConfigDirectory)) - Directory.CreateDirectory(ConfigDirectory); + private static void CreateTestConfigurationInDirectory(string contents) + { + if (!Directory.Exists(ConfigDirectory)) + Directory.CreateDirectory(ConfigDirectory); - File.WriteAllText(ConfigStrings.Default_Config_File, contents); + File.WriteAllText(ConfigStrings.Default_Config_File, contents); + } } } \ No newline at end of file diff --git a/EOLib.Config.Test/IniReaderTest.cs b/EOLib.Config.Test/IniReaderTest.cs index 91d1f47e4..3b45a75d1 100644 --- a/EOLib.Config.Test/IniReaderTest.cs +++ b/EOLib.Config.Test/IniReaderTest.cs @@ -2,308 +2,309 @@ using System.Diagnostics.CodeAnalysis; using System.IO; -namespace EOLib.Config.Test; - -[TestFixture, ExcludeFromCodeCoverage] -public class IniReaderTest +namespace EOLib.Config.Test { - private const string TestDirectory = "IniReaderTest"; - private const string TestFile = "SomeFile.ini"; - private static readonly string FullPath = Path.Combine(TestDirectory, TestFile); - - [TearDown] - public void TearDown() + [TestFixture, ExcludeFromCodeCoverage] + public class IniReaderTest { - if (Directory.Exists(TestDirectory)) - Directory.Delete(TestDirectory, true); - } + private const string TestDirectory = "IniReaderTest"; + private const string TestFile = "SomeFile.ini"; + private static readonly string FullPath = Path.Combine(TestDirectory, TestFile); - [Test] - public void Load_CreatesDirectoryAndFile_IfTheyDoNotExist_AndReturnsFalse() - { - var reader = new IniReader(FullPath); - - Assert.IsFalse(Directory.Exists(TestDirectory)); - Assert.IsFalse(File.Exists(FullPath)); - - var result = reader.Load(); + [TearDown] + public void TearDown() + { + if (Directory.Exists(TestDirectory)) + Directory.Delete(TestDirectory, true); + } - Assert.IsFalse(result); - Assert.IsTrue(Directory.Exists(TestDirectory)); - Assert.IsTrue(File.Exists(FullPath)); - } + [Test] + public void Load_CreatesDirectoryAndFile_IfTheyDoNotExist_AndReturnsFalse() + { + var reader = new IniReader(FullPath); - [Test] - public void Load_HandlesEmptyLines() - { - var contents = "[Header]\nTestdata=aaaa\n\nTest2=bbbb"; - CreateTestFileWithData(contents); + Assert.IsFalse(Directory.Exists(TestDirectory)); + Assert.IsFalse(File.Exists(FullPath)); - var reader = new IniReader(FullPath); - var result = reader.Load(); + var result = reader.Load(); - Assert.IsTrue(result); - } + Assert.IsFalse(result); + Assert.IsTrue(Directory.Exists(TestDirectory)); + Assert.IsTrue(File.Exists(FullPath)); + } - [Test] - public void Load_HandlesCommentLines() - { - var contents = "[Header]\nTestdata=aaaa\n#this is a comment line\nTest2=bbbb"; - CreateTestFileWithData(contents); + [Test] + public void Load_HandlesEmptyLines() + { + var contents = "[Header]\nTestdata=aaaa\n\nTest2=bbbb"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var result = reader.Load(); + var reader = new IniReader(FullPath); + var result = reader.Load(); - Assert.IsTrue(result); - } + Assert.IsTrue(result); + } - [Test] - public void Load_HandlesCommentsOnHeaderLines() - { - var contents = "[Header]#some header comment\nTestdata=aaaa\n\n#this is a comment line\nTest2=bbbb"; - CreateTestFileWithData(contents); + [Test] + public void Load_HandlesCommentLines() + { + var contents = "[Header]\nTestdata=aaaa\n#this is a comment line\nTest2=bbbb"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var result = reader.Load(); + var reader = new IniReader(FullPath); + var result = reader.Load(); - Assert.IsTrue(result); - } + Assert.IsTrue(result); + } - [Test] - public void Load_HandlesCommentsOnDataLines() - { - var contents = "[Header]\nTestdata=aaaa #some other comment\n\n#this is a comment line\nTest2=bbbb"; - CreateTestFileWithData(contents); + [Test] + public void Load_HandlesCommentsOnHeaderLines() + { + var contents = "[Header]#some header comment\nTestdata=aaaa\n\n#this is a comment line\nTest2=bbbb"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var result = reader.Load(); + var reader = new IniReader(FullPath); + var result = reader.Load(); - Assert.IsTrue(result); - } + Assert.IsTrue(result); + } - [Test] - public void Load_HandlesMultipleEqualsOnDataLines() - { - var contents = "[Header]\nTestdata=aaaa=something #some other comment\n\n#this is a comment line\nTest2=bbbb"; - CreateTestFileWithData(contents); + [Test] + public void Load_HandlesCommentsOnDataLines() + { + var contents = "[Header]\nTestdata=aaaa #some other comment\n\n#this is a comment line\nTest2=bbbb"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var result = reader.Load(); + var reader = new IniReader(FullPath); + var result = reader.Load(); - Assert.IsTrue(result); - } + Assert.IsTrue(result); + } - [Test] - public void GetValue_String_FalseIfNonExistentSection() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + [Test] + public void Load_HandlesMultipleEqualsOnDataLines() + { + var contents = "[Header]\nTestdata=aaaa=something #some other comment\n\n#this is a comment line\nTest2=bbbb"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var result = reader.Load(); - string value; - var result = reader.GetValue("BadHeader", "Testdata", out value); - Assert.IsFalse(result); - } + Assert.IsTrue(result); + } - [Test] - public void GetValue_String_FalseIfNonExistentKey() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_String_FalseIfNonExistentSection() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - string value; - var result = reader.GetValue("Header", "BadTestdata", out value); - Assert.IsFalse(result); - } + string value; + var result = reader.GetValue("BadHeader", "Testdata", out value); + Assert.IsFalse(result); + } - [Test] - public void GetValue_Int_FalseIfNonExistentSection() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_String_FalseIfNonExistentKey() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - int value; - var result = reader.GetValue("BadHeader", "Testdata", out value); - Assert.IsFalse(result); - } + string value; + var result = reader.GetValue("Header", "BadTestdata", out value); + Assert.IsFalse(result); + } - [Test] - public void GetValue_Int_FalseIfNonExistentKey() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_Int_FalseIfNonExistentSection() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - int value; - var result = reader.GetValue("Header", "BadTestdata", out value); - Assert.IsFalse(result); - } + int value; + var result = reader.GetValue("BadHeader", "Testdata", out value); + Assert.IsFalse(result); + } - [Test] - public void GetValue_Int_FalseIfNotAnInteger() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_Int_FalseIfNonExistentKey() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - int value; - var result = reader.GetValue("Header", "Testdata", out value); - Assert.IsFalse(result); - } + int value; + var result = reader.GetValue("Header", "BadTestdata", out value); + Assert.IsFalse(result); + } - [Test] - public void GetValue_Bool_FalseIfNonExistentSection() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_Int_FalseIfNotAnInteger() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - bool value; - var result = reader.GetValue("BadHeader", "Testdata", out value); - Assert.IsFalse(result); - } + int value; + var result = reader.GetValue("Header", "Testdata", out value); + Assert.IsFalse(result); + } - [Test] - public void GetValue_Bool_FalseIfNonExistentKey() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_Bool_FalseIfNonExistentSection() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - bool value; - var result = reader.GetValue("Header", "BadTestdata", out value); - Assert.IsFalse(result); - } + bool value; + var result = reader.GetValue("BadHeader", "Testdata", out value); + Assert.IsFalse(result); + } - [Test] - public void GetValue_Bool_FalseIfNotBoolean() - { - var contents = "[Header]\nTestdata=aaaa"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_Bool_FalseIfNonExistentKey() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - bool value; - var result = reader.GetValue("Header", "Testdata", out value); - Assert.IsFalse(result); - } + bool value; + var result = reader.GetValue("Header", "BadTestdata", out value); + Assert.IsFalse(result); + } - [Test] - public void GetValue_String_ReturnsValueAsString() - { - var contents = "[Header]\nTestdata=123"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_Bool_FalseIfNotBoolean() + { + var contents = "[Header]\nTestdata=aaaa"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - string value; - var result = reader.GetValue("Header", "Testdata", out value); - Assert.IsTrue(result); - Assert.AreEqual("123", value); - } + bool value; + var result = reader.GetValue("Header", "Testdata", out value); + Assert.IsFalse(result); + } - [Test] - public void GetValue_Int_ReturnsValueAsInteger() - { - var contents = "[Header]\nTestdata=123"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_String_ReturnsValueAsString() + { + var contents = "[Header]\nTestdata=123"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - int value; - var result = reader.GetValue("Header", "Testdata", out value); - Assert.IsTrue(result); - Assert.AreEqual(123, value); - } + string value; + var result = reader.GetValue("Header", "Testdata", out value); + Assert.IsTrue(result); + Assert.AreEqual("123", value); + } - [Test] - public void GetValue_Bool_ReturnsValueAsBoolean() - { - var contents = "[Header]\nTestdata=true"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_Int_ReturnsValueAsInteger() + { + var contents = "[Header]\nTestdata=123"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - bool value; - var result = reader.GetValue("Header", "Testdata", out value); - Assert.IsTrue(result); - Assert.IsTrue(value); - } + int value; + var result = reader.GetValue("Header", "Testdata", out value); + Assert.IsTrue(result); + Assert.AreEqual(123, value); + } - [Test] - public void GetValue_Bool_ConvertsBoolEquivalentsToTrue() - { - var contents = "[Header]\nItem1=yes\nItem2=1\nItem3=on"; - CreateTestFileWithData(contents); + [Test] + public void GetValue_Bool_ReturnsValueAsBoolean() + { + var contents = "[Header]\nTestdata=true"; + CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); - for (int i = 1; i <= 3; ++i) - { bool value; - var result = reader.GetValue("Header", "Item" + i, out value); + var result = reader.GetValue("Header", "Testdata", out value); Assert.IsTrue(result); Assert.IsTrue(value); } - } - - [Test] - public void GetValue_Bool_ConvertsBoolEquivalentsToFalse() - { - var contents = "[Header]\nItem1=no\nItem2=0\nItem3=off"; - CreateTestFileWithData(contents); - var reader = new IniReader(FullPath); - var loadResult = reader.Load(); - Assert.IsTrue(loadResult); + [Test] + public void GetValue_Bool_ConvertsBoolEquivalentsToTrue() + { + var contents = "[Header]\nItem1=yes\nItem2=1\nItem3=on"; + CreateTestFileWithData(contents); + + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); + + for (int i = 1; i <= 3; ++i) + { + bool value; + var result = reader.GetValue("Header", "Item" + i, out value); + Assert.IsTrue(result); + Assert.IsTrue(value); + } + } - for (int i = 1; i <= 3; ++i) + [Test] + public void GetValue_Bool_ConvertsBoolEquivalentsToFalse() { - bool value; - var result = reader.GetValue("Header", "Item" + i, out value); - Assert.IsTrue(result); - Assert.IsFalse(value); + var contents = "[Header]\nItem1=no\nItem2=0\nItem3=off"; + CreateTestFileWithData(contents); + + var reader = new IniReader(FullPath); + var loadResult = reader.Load(); + Assert.IsTrue(loadResult); + + for (int i = 1; i <= 3; ++i) + { + bool value; + var result = reader.GetValue("Header", "Item" + i, out value); + Assert.IsTrue(result); + Assert.IsFalse(value); + } } - } - private static void CreateTestFileWithData(string contents) - { - if (!Directory.Exists(TestDirectory)) - Directory.CreateDirectory(TestDirectory); + private static void CreateTestFileWithData(string contents) + { + if (!Directory.Exists(TestDirectory)) + Directory.CreateDirectory(TestDirectory); - File.WriteAllText(FullPath, contents); + File.WriteAllText(FullPath, contents); + } } } \ No newline at end of file diff --git a/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs b/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs index 28dda8191..b0d45a271 100644 --- a/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs +++ b/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs @@ -4,39 +4,40 @@ using System.ComponentModel.Design; using System.Diagnostics.CodeAnalysis; -namespace EOLib.Graphics.Test; - -[ExcludeFromCodeCoverage] -internal sealed class GraphicsDeviceTestHelper : IDisposable +namespace EOLib.Graphics.Test { - private readonly Game _game; + [ExcludeFromCodeCoverage] + internal sealed class GraphicsDeviceTestHelper : IDisposable + { + private readonly Game _game; - public GraphicsDeviceManager GraphicsDeviceManager { get; } + public GraphicsDeviceManager GraphicsDeviceManager { get; } - public GraphicsDeviceTestHelper() - { - _game = new Game(); - GraphicsDeviceManager = new GraphicsDeviceManager(_game); - _game.RunOneFrame(); - } + public GraphicsDeviceTestHelper() + { + _game = new Game(); + GraphicsDeviceManager = new GraphicsDeviceManager(_game); + _game.RunOneFrame(); + } - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } - ~GraphicsDeviceTestHelper() - { - Dispose(false); - } + ~GraphicsDeviceTestHelper() + { + Dispose(false); + } - private void Dispose(bool disposing) - { - if (disposing) + private void Dispose(bool disposing) { - GraphicsDeviceManager.Dispose(); - _game.Dispose(); + if (disposing) + { + GraphicsDeviceManager.Dispose(); + _game.Dispose(); + } } } } \ No newline at end of file diff --git a/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs b/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs index 24cff60e3..e0442036c 100644 --- a/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs +++ b/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs @@ -6,72 +6,73 @@ using System.Diagnostics.CodeAnalysis; using System.IO; -namespace EOLib.Graphics.Test; - -[TestFixture, ExcludeFromCodeCoverage, Category("GraphicsDevice")] -public class NativeGraphicsLoaderTest +namespace EOLib.Graphics.Test { - private IPEFileCollection _modules; - private INativeGraphicsLoader _nativeGraphicsLoader; + [TestFixture, ExcludeFromCodeCoverage, Category("GraphicsDevice")] + public class NativeGraphicsLoaderTest + { + private IPEFileCollection _modules; + private INativeGraphicsLoader _nativeGraphicsLoader; - private const int ExpectedCulture = -1; + private const int ExpectedCulture = -1; - [SetUp] - public void SetUp() - { - _modules = Mock.Of(); - _nativeGraphicsLoader = new NativeGraphicsLoader(_modules); - } + [SetUp] + public void SetUp() + { + _modules = Mock.Of(); + _nativeGraphicsLoader = new NativeGraphicsLoader(_modules); + } - [Test] - public void WhenLoadGFX_CallsPEFile_GetEmbeddedBitmapResourceByID() - { - var peFileMock = SetupPEFileForGFXType(GFXTypes.PreLoginUI, CreateDataArrayForBitmap()); + [Test] + public void WhenLoadGFX_CallsPEFile_GetEmbeddedBitmapResourceByID() + { + var peFileMock = SetupPEFileForGFXType(GFXTypes.PreLoginUI, CreateDataArrayForBitmap()); - var data = _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, 1); - peFileMock.Verify(x => x.GetEmbeddedBitmapResourceByID(It.IsAny(), ExpectedCulture), Times.Once()); - } + var data = _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, 1); + peFileMock.Verify(x => x.GetEmbeddedBitmapResourceByID(It.IsAny(), ExpectedCulture), Times.Once()); + } - [Test] - public void WhenLoadGFX_CallsPEFile_WithResourceValueIncreasedBy100() - { - const int requestedResourceID = 1; - const int expectedResourceID = 101; + [Test] + public void WhenLoadGFX_CallsPEFile_WithResourceValueIncreasedBy100() + { + const int requestedResourceID = 1; + const int expectedResourceID = 101; - var peFileMock = SetupPEFileForGFXType(GFXTypes.PreLoginUI, CreateDataArrayForBitmap()); + var peFileMock = SetupPEFileForGFXType(GFXTypes.PreLoginUI, CreateDataArrayForBitmap()); - var data = _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID); - peFileMock.Verify(x => x.GetEmbeddedBitmapResourceByID(expectedResourceID, ExpectedCulture)); - } + var data = _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID); + peFileMock.Verify(x => x.GetEmbeddedBitmapResourceByID(expectedResourceID, ExpectedCulture)); + } - [Test] - public void WhenLoadGFX_EmptyDataArray_ThrowsInDebug_EmptyInRelease() - { - const int requestedResourceID = 1; + [Test] + public void WhenLoadGFX_EmptyDataArray_ThrowsInDebug_EmptyInRelease() + { + const int requestedResourceID = 1; - SetupPEFileForGFXType(GFXTypes.PreLoginUI, new byte[] { }); + SetupPEFileForGFXType(GFXTypes.PreLoginUI, new byte[] { }); #if DEBUG - Assert.Throws(() => _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID)); + Assert.Throws(() => _nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID)); #else - Assert.That(_nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID), Has.Length.EqualTo(0)); + Assert.That(_nativeGraphicsLoader.LoadGFX(GFXTypes.PreLoginUI, requestedResourceID), Has.Length.EqualTo(0)); #endif - } + } - private byte[] CreateDataArrayForBitmap() - { - return new byte[1]; - } + private byte[] CreateDataArrayForBitmap() + { + return new byte[1]; + } - private Mock SetupPEFileForGFXType(GFXTypes type, byte[] array) - { - var collectionMock = Mock.Get(_modules); - var peFile = new Mock(); - collectionMock.Setup(x => x[type]).Returns(peFile.Object); + private Mock SetupPEFileForGFXType(GFXTypes type, byte[] array) + { + var collectionMock = Mock.Get(_modules); + var peFile = new Mock(); + collectionMock.Setup(x => x[type]).Returns(peFile.Object); - peFile.Setup(x => x.GetEmbeddedBitmapResourceByID(It.IsAny(), ExpectedCulture)) - .Returns(array); + peFile.Setup(x => x.GetEmbeddedBitmapResourceByID(It.IsAny(), ExpectedCulture)) + .Returns(array); - return peFile; + return peFile; + } } } \ No newline at end of file diff --git a/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs b/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs index 143224144..2373ed3d6 100644 --- a/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs +++ b/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs @@ -6,234 +6,235 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.Graphics.Test; - -[TestFixture, ExcludeFromCodeCoverage, Category("GraphicsDevice")] -public class NativeGraphicsManagerTest +namespace EOLib.Graphics.Test { - private GraphicsDeviceTestHelper _graphicsDeviceTestHelper; + [TestFixture, ExcludeFromCodeCoverage, Category("GraphicsDevice")] + public class NativeGraphicsManagerTest + { + private GraphicsDeviceTestHelper _graphicsDeviceTestHelper; - private INativeGraphicsLoader _graphicsLoader; - private IGraphicsDeviceProvider _graphicsDeviceProvider; + private INativeGraphicsLoader _graphicsLoader; + private IGraphicsDeviceProvider _graphicsDeviceProvider; - private bool _keepFromInfiniteLoop = false; + private bool _keepFromInfiniteLoop = false; - private INativeGraphicsManager _nativeGraphicsManager; + private INativeGraphicsManager _nativeGraphicsManager; - [SetUp] - public void SetUp() - { - _graphicsDeviceTestHelper = new GraphicsDeviceTestHelper(); - - _graphicsLoader = Mock.Of(); + [SetUp] + public void SetUp() + { + _graphicsDeviceTestHelper = new GraphicsDeviceTestHelper(); - var graphicsDeviceProviderMock = new Mock(); - graphicsDeviceProviderMock.Setup(x => x.GraphicsDevice) - .Returns(_graphicsDeviceTestHelper.GraphicsDeviceManager.GraphicsDevice); + _graphicsLoader = Mock.Of(); - _graphicsDeviceProvider = graphicsDeviceProviderMock.Object; + var graphicsDeviceProviderMock = new Mock(); + graphicsDeviceProviderMock.Setup(x => x.GraphicsDevice) + .Returns(_graphicsDeviceTestHelper.GraphicsDeviceManager.GraphicsDevice); - _nativeGraphicsManager = new NativeGraphicsManager(_graphicsLoader, _graphicsDeviceProvider); - } + _graphicsDeviceProvider = graphicsDeviceProviderMock.Object; - [TearDown] - public void TearDown() - { - _nativeGraphicsManager.Dispose(); - _graphicsDeviceTestHelper.Dispose(); - } + _nativeGraphicsManager = new NativeGraphicsManager(_graphicsLoader, _graphicsDeviceProvider); + } - [Test] - public void WhenLoadTexture_CallGraphicsLoader() - { - const int requestedResource = 1; + [TearDown] + public void TearDown() + { + _nativeGraphicsManager.Dispose(); + _graphicsDeviceTestHelper.Dispose(); + } - var graphicsLoaderMock = Mock.Get(_graphicsLoader); - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + [Test] + public void WhenLoadTexture_CallGraphicsLoader() + { + const int requestedResource = 1; - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Once()); - } + var graphicsLoaderMock = Mock.Get(_graphicsLoader); + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - [Test] - public void WhenLoadCachedTexture_DoNotCallGraphicsLoader() - { - const int requestedResource = 1; + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Once()); + } - var graphicsLoaderMock = Mock.Get(_graphicsLoader); - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + [Test] + public void WhenLoadCachedTexture_DoNotCallGraphicsLoader() + { + const int requestedResource = 1; - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Once()); - } + var graphicsLoaderMock = Mock.Get(_graphicsLoader); + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - [Test] - public void WhenLoadCachedTexture_WhenReloadFromFile_CallGraphicsLoader() - { - const int requestedResource = 1; + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Once()); + } - var graphicsLoaderMock = Mock.Get(_graphicsLoader); - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, reloadFromFile: true); + [Test] + public void WhenLoadCachedTexture_WhenReloadFromFile_CallGraphicsLoader() + { + const int requestedResource = 1; - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Exactly(2)); - } + var graphicsLoaderMock = Mock.Get(_graphicsLoader); + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, reloadFromFile: true); - [Test] - public void WhenLoadCachedTexture_WhenReloadFromFile_DisposesOriginalTextue() - { - const int requestedResource = 1; + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, requestedResource), Times.Exactly(2)); + } - var textureHasBeenDisposed = false; + [Test] + public void WhenLoadCachedTexture_WhenReloadFromFile_DisposesOriginalTextue() + { + const int requestedResource = 1; - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - var texture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - texture.Disposing += (o, e) => textureHasBeenDisposed = true; + var textureHasBeenDisposed = false; - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, reloadFromFile: true); + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + var texture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + texture.Disposing += (o, e) => textureHasBeenDisposed = true; - Assert.IsTrue(textureHasBeenDisposed); - } + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, reloadFromFile: true); - [Test] - public void WhenLoadManyTextures_CallsGraphicsLoaderSameNumberOfTimes() - { - var graphicsLoaderMock = Mock.Get(_graphicsLoader); + Assert.IsTrue(textureHasBeenDisposed); + } - const int totalRequestedResources = 100; - for (int requestedResource = 1; requestedResource <= totalRequestedResources; ++requestedResource) + [Test] + public void WhenLoadManyTextures_CallsGraphicsLoaderSameNumberOfTimes() { - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + var graphicsLoaderMock = Mock.Get(_graphicsLoader); - var localRequestedResource = requestedResource; - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, localRequestedResource), Times.Once()); - } + const int totalRequestedResources = 100; + for (int requestedResource = 1; requestedResource <= totalRequestedResources; ++requestedResource) + { + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, It.IsAny()), Times.Exactly(totalRequestedResources)); - } + var localRequestedResource = requestedResource; + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, localRequestedResource), Times.Once()); + } - [Test] - public void WhenLoadCachedTexture_ManyTimes_CallsGraphicsLoaderOnce() - { - var graphicsLoaderMock = Mock.Get(_graphicsLoader); + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, It.IsAny()), Times.Exactly(totalRequestedResources)); + } - const int requestedResource = 1; - for (int i = 1; i <= 100; ++i) + [Test] + public void WhenLoadCachedTexture_ManyTimes_CallsGraphicsLoaderOnce() { - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - } + var graphicsLoaderMock = Mock.Get(_graphicsLoader); - graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, It.IsAny()), Times.Once()); - } + const int requestedResource = 1; + for (int i = 1; i <= 100; ++i) + { + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + } - [Test] - public void WhenLoadTexture_Transparent_SetsBlackToTransparent() - { - const int requestedResource = 1; + graphicsLoaderMock.Verify(x => x.LoadGFX(GFXTypes.PreLoginUI, It.IsAny()), Times.Once()); + } - Texture2D resultTexture; - var bmp = LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); - FillBitmapWithColor(bmp, Color.Black); - resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, true); + [Test] + public void WhenLoadTexture_Transparent_SetsBlackToTransparent() + { + const int requestedResource = 1; - var data = new Microsoft.Xna.Framework.Color[resultTexture.Width * resultTexture.Height]; - resultTexture.GetData(data); + Texture2D resultTexture; + var bmp = LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource); + FillBitmapWithColor(bmp, Color.Black); + resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource, true); - Assert.IsTrue(data.All(x => x.A == 0)); - } + var data = new Microsoft.Xna.Framework.Color[resultTexture.Width * resultTexture.Height]; + resultTexture.GetData(data); - [Test] - public void WhenLoadTexture_MaleHat_Transparent_SetsSpecialColorToTransparent() - { - const int requestedResource = 1; + Assert.IsTrue(data.All(x => x.A == 0)); + } - Texture2D resultTexture; - var bmp = LoadGFXReturnsBitmap(GFXTypes.MaleHat, requestedResource); - FillBitmapWithColor(bmp, new Color(0xff000008)); - resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MaleHat, requestedResource, true); + [Test] + public void WhenLoadTexture_MaleHat_Transparent_SetsSpecialColorToTransparent() + { + const int requestedResource = 1; - var data = new Microsoft.Xna.Framework.Color[resultTexture.Width * resultTexture.Height]; - resultTexture.GetData(data); + Texture2D resultTexture; + var bmp = LoadGFXReturnsBitmap(GFXTypes.MaleHat, requestedResource); + FillBitmapWithColor(bmp, new Color(0xff000008)); + resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MaleHat, requestedResource, true); - Assert.IsTrue(data.All(x => x.A == 0)); - } + var data = new Microsoft.Xna.Framework.Color[resultTexture.Width * resultTexture.Height]; + resultTexture.GetData(data); - [Test] - public void WhenLoadTexture_FemaleHat_Transparent_SetsSpecialColorToTransparent() - { - const int requestedResource = 1; + Assert.IsTrue(data.All(x => x.A == 0)); + } - Texture2D resultTexture; - var bmp = LoadGFXReturnsBitmap(GFXTypes.FemaleHat, requestedResource); - FillBitmapWithColor(bmp, new Color(0xff000008)); - resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.FemaleHat, requestedResource, true); + [Test] + public void WhenLoadTexture_FemaleHat_Transparent_SetsSpecialColorToTransparent() + { + const int requestedResource = 1; - var data = new Color[resultTexture.Width * resultTexture.Height]; - resultTexture.GetData(data); + Texture2D resultTexture; + var bmp = LoadGFXReturnsBitmap(GFXTypes.FemaleHat, requestedResource); + FillBitmapWithColor(bmp, new Color(0xff000008)); + resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.FemaleHat, requestedResource, true); - Assert.IsTrue(data.All(x => x.A == 0)); - } + var data = new Color[resultTexture.Width * resultTexture.Height]; + resultTexture.GetData(data); - [Test] - public void WhenLoadTexture_RaceCondition_DisposesExistingCachedTextureAndReturnsSecondOne() - { - const int requestedResource = 1; + Assert.IsTrue(data.All(x => x.A == 0)); + } - Texture2D resultTexture; - LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource, () => GetTextureAgain(GFXTypes.PreLoginUI, requestedResource)); - resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); + [Test] + public void WhenLoadTexture_RaceCondition_DisposesExistingCachedTextureAndReturnsSecondOne() + { + const int requestedResource = 1; - Assert.IsFalse(resultTexture.IsDisposed); - } + Texture2D resultTexture; + LoadGFXReturnsBitmap(GFXTypes.PreLoginUI, requestedResource, () => GetTextureAgain(GFXTypes.PreLoginUI, requestedResource)); + resultTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, requestedResource); - // Manually builds a byte array that is a valid bitmap image (10x10 pixels, 32bpp) - // Mocks the native graphics loader to return this array, and passes it back to the caller - private Memory LoadGFXReturnsBitmap(GFXTypes whichFile, int requestedResource, Action loadCallback = null) - { - // 32bpp 10x10 image + 14 byte BMP header + 40 byte BITMAPINFO header - // (4 * 100) + 14 + 40 = 454 - var bitmapToReturn = new byte[454]; - Array.Copy(new[] { (byte)'B', (byte)'M', }, bitmapToReturn, 2); - Array.Copy(BitConverter.GetBytes(454), 0, bitmapToReturn, 2, 4); // total image size [2..5] - Array.Copy(BitConverter.GetBytes(54), 0, bitmapToReturn, 10, 4); // image data offset [10..13] - - Array.Copy(BitConverter.GetBytes(40), 0, bitmapToReturn, 14, 4); // bitmap header size [14..17] - Array.Copy(BitConverter.GetBytes(10), 0, bitmapToReturn, 18, 4); // width [18..21] - Array.Copy(BitConverter.GetBytes(10), 0, bitmapToReturn, 22, 4); // height [22..25] - Array.Copy(BitConverter.GetBytes((short)1), 0, bitmapToReturn, 26, 2); // planes (1) [26..27] - Array.Copy(BitConverter.GetBytes((short)32), 0, bitmapToReturn, 28, 2); // bpp [28..29] - - var graphicsLoaderMock = Mock.Get(_graphicsLoader); - graphicsLoaderMock.Setup(x => x.LoadGFX(whichFile, requestedResource)) - .Returns(bitmapToReturn) - .Callback(loadCallback ?? (() => { })); - - return bitmapToReturn; - } + Assert.IsFalse(resultTexture.IsDisposed); + } - private static void FillBitmapWithColor(Memory image, Color color) - { - for (int i = 54; i < image.Length; i += 4) + // Manually builds a byte array that is a valid bitmap image (10x10 pixels, 32bpp) + // Mocks the native graphics loader to return this array, and passes it back to the caller + private Memory LoadGFXReturnsBitmap(GFXTypes whichFile, int requestedResource, Action loadCallback = null) { - image.Span[i] = color.B; - image.Span[i + 1] = color.G; - image.Span[i + 2] = color.R; - image.Span[i + 3] = color.A; + // 32bpp 10x10 image + 14 byte BMP header + 40 byte BITMAPINFO header + // (4 * 100) + 14 + 40 = 454 + var bitmapToReturn = new byte[454]; + Array.Copy(new[] { (byte)'B', (byte)'M', }, bitmapToReturn, 2); + Array.Copy(BitConverter.GetBytes(454), 0, bitmapToReturn, 2, 4); // total image size [2..5] + Array.Copy(BitConverter.GetBytes(54), 0, bitmapToReturn, 10, 4); // image data offset [10..13] + + Array.Copy(BitConverter.GetBytes(40), 0, bitmapToReturn, 14, 4); // bitmap header size [14..17] + Array.Copy(BitConverter.GetBytes(10), 0, bitmapToReturn, 18, 4); // width [18..21] + Array.Copy(BitConverter.GetBytes(10), 0, bitmapToReturn, 22, 4); // height [22..25] + Array.Copy(BitConverter.GetBytes((short)1), 0, bitmapToReturn, 26, 2); // planes (1) [26..27] + Array.Copy(BitConverter.GetBytes((short)32), 0, bitmapToReturn, 28, 2); // bpp [28..29] + + var graphicsLoaderMock = Mock.Get(_graphicsLoader); + graphicsLoaderMock.Setup(x => x.LoadGFX(whichFile, requestedResource)) + .Returns(bitmapToReturn) + .Callback(loadCallback ?? (() => { })); + + return bitmapToReturn; } - } - private void GetTextureAgain(GFXTypes whichFile, int requestedResource) - { - if (_keepFromInfiniteLoop) return; - _keepFromInfiniteLoop = true; + private static void FillBitmapWithColor(Memory image, Color color) + { + for (int i = 54; i < image.Length; i += 4) + { + image.Span[i] = color.B; + image.Span[i + 1] = color.G; + image.Span[i + 2] = color.R; + image.Span[i + 3] = color.A; + } + } + + private void GetTextureAgain(GFXTypes whichFile, int requestedResource) + { + if (_keepFromInfiniteLoop) return; + _keepFromInfiniteLoop = true; - LoadGFXReturnsBitmap(whichFile, requestedResource); - _nativeGraphicsManager.TextureFromResource(whichFile, requestedResource); + LoadGFXReturnsBitmap(whichFile, requestedResource); + _nativeGraphicsManager.TextureFromResource(whichFile, requestedResource); + } } } \ No newline at end of file diff --git a/EOLib.Graphics.Test/PEFileCollectionTest.cs b/EOLib.Graphics.Test/PEFileCollectionTest.cs index 4f089f5f4..229246829 100644 --- a/EOLib.Graphics.Test/PEFileCollectionTest.cs +++ b/EOLib.Graphics.Test/PEFileCollectionTest.cs @@ -6,71 +6,72 @@ using System.IO; using System.Linq; -namespace EOLib.Graphics.Test; - -[TestFixture, ExcludeFromCodeCoverage] -public class PEFileCollectionTest +namespace EOLib.Graphics.Test { - private const string ExpectedDirectory = "gfx"; + [TestFixture, ExcludeFromCodeCoverage] + public class PEFileCollectionTest + { + private const string ExpectedDirectory = "gfx"; - private IPEFileCollection _collection; + private IPEFileCollection _collection; - [SetUp] - public void SetUp() - { - _collection = new PEFileCollection(); - } + [SetUp] + public void SetUp() + { + _collection = new PEFileCollection(); + } - [TearDown] - public void TearDown() - { - _collection.Dispose(); + [TearDown] + public void TearDown() + { + _collection.Dispose(); - if (Directory.Exists(ExpectedDirectory)) - Directory.Delete(ExpectedDirectory, true); - } + if (Directory.Exists(ExpectedDirectory)) + Directory.Delete(ExpectedDirectory, true); + } - [Test] - public void PopulateCollection_ThrowsDirectoryNotFound_ForMissingDirectory() - { - Assert.Throws(() => _collection.PopulateCollectionWithStandardGFX()); - } + [Test] + public void PopulateCollection_ThrowsDirectoryNotFound_ForMissingDirectory() + { + Assert.Throws(() => _collection.PopulateCollectionWithStandardGFX()); + } - [Test] - public void PopulateCollection_ThrowsFileNotFound_ForMissingFilesInDirectory() - { - CreateExpectedDirectoryWithFiles(5); - Assert.Throws(() => _collection.PopulateCollectionWithStandardGFX()); - } + [Test] + public void PopulateCollection_ThrowsFileNotFound_ForMissingFilesInDirectory() + { + CreateExpectedDirectoryWithFiles(5); + Assert.Throws(() => _collection.PopulateCollectionWithStandardGFX()); + } - [Test] - public void Constructor_FillsCollection_WithExpectedPEFiles() - { - var expectedKeys = Enum.GetValues(typeof(GFXTypes)); - CreateExpectedDirectoryWithFiles(25); + [Test] + public void Constructor_FillsCollection_WithExpectedPEFiles() + { + var expectedKeys = Enum.GetValues(typeof(GFXTypes)); + CreateExpectedDirectoryWithFiles(25); - _collection.PopulateCollectionWithStandardGFX(); + _collection.PopulateCollectionWithStandardGFX(); - Assert.AreEqual(25, _collection.Count); - CollectionAssert.AreEqual(expectedKeys, _collection.Keys.ToList()); - } + Assert.AreEqual(25, _collection.Count); + CollectionAssert.AreEqual(expectedKeys, _collection.Keys.ToList()); + } - [Test] - public void Dispose_DisposesAllFiles() - { - _collection.Add(GFXTypes.PreLoginUI, Mock.Of()); - _collection.Add(GFXTypes.PostLoginUI, Mock.Of()); + [Test] + public void Dispose_DisposesAllFiles() + { + _collection.Add(GFXTypes.PreLoginUI, Mock.Of()); + _collection.Add(GFXTypes.PostLoginUI, Mock.Of()); - _collection.Dispose(); + _collection.Dispose(); - foreach (var file in _collection.Values) - Mock.Get(file).Verify(x => x.Dispose(), Times.Once); - } + foreach (var file in _collection.Values) + Mock.Get(file).Verify(x => x.Dispose(), Times.Once); + } - private void CreateExpectedDirectoryWithFiles(int numFiles = 0, string fileNameFormat = "gfx{0:D3}.egf") - { - Directory.CreateDirectory(ExpectedDirectory); - for (int i = 1; i <= numFiles; ++i) - File.WriteAllText(string.Format(Path.Combine(ExpectedDirectory, fileNameFormat), i), "test contents"); + private void CreateExpectedDirectoryWithFiles(int numFiles = 0, string fileNameFormat = "gfx{0:D3}.egf") + { + Directory.CreateDirectory(ExpectedDirectory); + for (int i = 1; i <= numFiles; ++i) + File.WriteAllText(string.Format(Path.Combine(ExpectedDirectory, fileNameFormat), i), "test contents"); + } } } \ No newline at end of file diff --git a/EOLib.Graphics.Test/RectangleExtensionTest.cs b/EOLib.Graphics.Test/RectangleExtensionTest.cs index 126a54b5a..173fed9df 100644 --- a/EOLib.Graphics.Test/RectangleExtensionTest.cs +++ b/EOLib.Graphics.Test/RectangleExtensionTest.cs @@ -2,40 +2,41 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.Graphics.Test; - -[TestFixture, ExcludeFromCodeCoverage] -public class RectangleExtensionTest +namespace EOLib.Graphics.Test { - [Test] - public void WithPosition_ReturnsNewRectangle_WithExpectedSizeAndOffset() + [TestFixture, ExcludeFromCodeCoverage] + public class RectangleExtensionTest { - var rectangle = new Rectangle(5, 10, 15, 20); - var newX = 105; - var newY = 110; + [Test] + public void WithPosition_ReturnsNewRectangle_WithExpectedSizeAndOffset() + { + var rectangle = new Rectangle(5, 10, 15, 20); + var newX = 105; + var newY = 110; - var newRectangle = rectangle.WithPosition(new Vector2(newX, newY)); + var newRectangle = rectangle.WithPosition(new Vector2(newX, newY)); - Assert.AreEqual(105, newRectangle.X); - Assert.AreEqual(110, newRectangle.Y); - Assert.AreEqual(15, newRectangle.Width); - Assert.AreEqual(20, newRectangle.Height); - Assert.AreNotEqual(newRectangle, rectangle); - } + Assert.AreEqual(105, newRectangle.X); + Assert.AreEqual(110, newRectangle.Y); + Assert.AreEqual(15, newRectangle.Width); + Assert.AreEqual(20, newRectangle.Height); + Assert.AreNotEqual(newRectangle, rectangle); + } - [Test] - public void WithPosition_DoesNotModify_OriginalRectangle() - { - var rectangle = new Rectangle(5, 10, 15, 20); - var newX = 105; - var newY = 110; + [Test] + public void WithPosition_DoesNotModify_OriginalRectangle() + { + var rectangle = new Rectangle(5, 10, 15, 20); + var newX = 105; + var newY = 110; - var newRectangle = rectangle.WithPosition(new Vector2(newX, newY)); + var newRectangle = rectangle.WithPosition(new Vector2(newX, newY)); - Assert.AreEqual(5, rectangle.X); - Assert.AreEqual(10, rectangle.Y); - Assert.AreEqual(15, rectangle.Width); - Assert.AreEqual(20, rectangle.Height); - Assert.AreNotEqual(newRectangle, rectangle); + Assert.AreEqual(5, rectangle.X); + Assert.AreEqual(10, rectangle.Y); + Assert.AreEqual(15, rectangle.Width); + Assert.AreEqual(20, rectangle.Height); + Assert.AreNotEqual(newRectangle, rectangle); + } } } \ No newline at end of file diff --git a/EOLib.Graphics/ColorConstants.cs b/EOLib.Graphics/ColorConstants.cs index ffd9e45fb..263e332c4 100644 --- a/EOLib.Graphics/ColorConstants.cs +++ b/EOLib.Graphics/ColorConstants.cs @@ -1,15 +1,16 @@ using Microsoft.Xna.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.Graphics; - -[ExcludeFromCodeCoverage] -public static class ColorConstants +namespace EOLib.Graphics { - public static readonly Color LightGrayText = Color.FromNonPremultiplied(0xc8, 0xc8, 0xc8, 0xff); - public static readonly Color LightYellowText = Color.FromNonPremultiplied(0xf0, 0xf0, 0xc8, 0xff); - public static readonly Color BeigeText = Color.FromNonPremultiplied(0xb4, 0xa0, 0x8c, 0xff); - public static readonly Color LightBeigeText = Color.FromNonPremultiplied(0xdc, 0xc8, 0xb4, 0xff); - public static readonly Color LightGrayDialogMessage = Color.FromNonPremultiplied(0xe6, 0xe6, 0xd6, 0xff); - public static readonly Color MediumGrayText = Color.FromNonPremultiplied(0xb9, 0xb9, 0xb9, 0xff); + [ExcludeFromCodeCoverage] + public static class ColorConstants + { + public static readonly Color LightGrayText = Color.FromNonPremultiplied(0xc8, 0xc8, 0xc8, 0xff); + public static readonly Color LightYellowText = Color.FromNonPremultiplied(0xf0, 0xf0, 0xc8, 0xff); + public static readonly Color BeigeText = Color.FromNonPremultiplied(0xb4, 0xa0, 0x8c, 0xff); + public static readonly Color LightBeigeText = Color.FromNonPremultiplied(0xdc, 0xc8, 0xb4, 0xff); + public static readonly Color LightGrayDialogMessage = Color.FromNonPremultiplied(0xe6, 0xe6, 0xd6, 0xff); + public static readonly Color MediumGrayText = Color.FromNonPremultiplied(0xb9, 0xb9, 0xb9, 0xff); + } } \ No newline at end of file diff --git a/EOLib.Graphics/GFXTypes.cs b/EOLib.Graphics/GFXTypes.cs index 9fa480375..7e63789c0 100644 --- a/EOLib.Graphics/GFXTypes.cs +++ b/EOLib.Graphics/GFXTypes.cs @@ -1,105 +1,106 @@ -namespace EOLib.Graphics; - -public enum GFXTypes +namespace EOLib.Graphics { - /// - /// 001 - /// - PreLoginUI = 1, - /// - /// 002 - /// - PostLoginUI, - /// - /// 003 - /// - MapTiles, - /// - /// 004 - /// - MapObjects, - /// - /// 005 - /// - MapOverlay, - /// - /// 006 - /// - MapWalls, - /// - /// 007 - /// - MapWallTop, - /// - /// 008 - /// - SkinSprites, - /// - /// 009 - /// - MaleHair, - /// - /// 010 - /// - FemaleHair, - /// - /// 011 - /// - MaleShoes, - /// - /// 012 - /// - FemaleShoes, - /// - /// 013 - /// - MaleArmor, - /// - /// 014 - /// - FemaleArmor, - /// - /// 015 - /// - MaleHat, - /// - /// 016 - /// - FemaleHat, - /// - /// 017 - /// - MaleWeapons, - /// - /// 018 - /// - FemaleWeapons, - /// - /// 019 - /// - MaleBack, - /// - /// 020 - /// - FemaleBack, - /// - /// 021 - /// - NPC, - /// - /// 022 - /// - Shadows, - /// - /// 023 - /// - Items, - /// - /// 024 - /// - Spells, - /// - /// 025 - /// - SpellIcons + public enum GFXTypes + { + /// + /// 001 + /// + PreLoginUI = 1, + /// + /// 002 + /// + PostLoginUI, + /// + /// 003 + /// + MapTiles, + /// + /// 004 + /// + MapObjects, + /// + /// 005 + /// + MapOverlay, + /// + /// 006 + /// + MapWalls, + /// + /// 007 + /// + MapWallTop, + /// + /// 008 + /// + SkinSprites, + /// + /// 009 + /// + MaleHair, + /// + /// 010 + /// + FemaleHair, + /// + /// 011 + /// + MaleShoes, + /// + /// 012 + /// + FemaleShoes, + /// + /// 013 + /// + MaleArmor, + /// + /// 014 + /// + FemaleArmor, + /// + /// 015 + /// + MaleHat, + /// + /// 016 + /// + FemaleHat, + /// + /// 017 + /// + MaleWeapons, + /// + /// 018 + /// + FemaleWeapons, + /// + /// 019 + /// + MaleBack, + /// + /// 020 + /// + FemaleBack, + /// + /// 021 + /// + NPC, + /// + /// 022 + /// + Shadows, + /// + /// 023 + /// + Items, + /// + /// 024 + /// + Spells, + /// + /// 025 + /// + SpellIcons + } } \ No newline at end of file diff --git a/EOLib.Graphics/IGraphicsDeviceRepository.cs b/EOLib.Graphics/IGraphicsDeviceRepository.cs index d28a88bdd..994b89848 100644 --- a/EOLib.Graphics/IGraphicsDeviceRepository.cs +++ b/EOLib.Graphics/IGraphicsDeviceRepository.cs @@ -2,27 +2,28 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EOLib.Graphics; - -public interface IGraphicsDeviceRepository +namespace EOLib.Graphics { - GraphicsDevice GraphicsDevice { get; set; } + public interface IGraphicsDeviceRepository + { + GraphicsDevice GraphicsDevice { get; set; } - GraphicsDeviceManager GraphicsDeviceManager { get; set; } -} + GraphicsDeviceManager GraphicsDeviceManager { get; set; } + } -public interface IGraphicsDeviceProvider -{ - GraphicsDevice GraphicsDevice { get; } + public interface IGraphicsDeviceProvider + { + GraphicsDevice GraphicsDevice { get; } - GraphicsDeviceManager GraphicsDeviceManager { get; } -} + GraphicsDeviceManager GraphicsDeviceManager { get; } + } -[MappedType(BaseType = typeof(IGraphicsDeviceRepository), IsSingleton = true)] -[MappedType(BaseType = typeof(IGraphicsDeviceProvider), IsSingleton = true)] -public class GraphicsDeviceRepository : IGraphicsDeviceRepository, IGraphicsDeviceProvider -{ - public GraphicsDevice GraphicsDevice { get; set; } + [MappedType(BaseType = typeof(IGraphicsDeviceRepository), IsSingleton = true)] + [MappedType(BaseType = typeof(IGraphicsDeviceProvider), IsSingleton = true)] + public class GraphicsDeviceRepository : IGraphicsDeviceRepository, IGraphicsDeviceProvider + { + public GraphicsDevice GraphicsDevice { get; set; } - public GraphicsDeviceManager GraphicsDeviceManager { get; set; } + public GraphicsDeviceManager GraphicsDeviceManager { get; set; } + } } \ No newline at end of file diff --git a/EOLib.Graphics/INativeGraphicsLoader.cs b/EOLib.Graphics/INativeGraphicsLoader.cs index 77d2474ab..e1f6b4613 100644 --- a/EOLib.Graphics/INativeGraphicsLoader.cs +++ b/EOLib.Graphics/INativeGraphicsLoader.cs @@ -1,8 +1,9 @@ using System; -namespace EOLib.Graphics; - -public interface INativeGraphicsLoader +namespace EOLib.Graphics { - ReadOnlyMemory LoadGFX(GFXTypes file, int resourceValue); + public interface INativeGraphicsLoader + { + ReadOnlyMemory LoadGFX(GFXTypes file, int resourceValue); + } } \ No newline at end of file diff --git a/EOLib.Graphics/INativeGraphicsManager.cs b/EOLib.Graphics/INativeGraphicsManager.cs index d256dc3ea..369272294 100644 --- a/EOLib.Graphics/INativeGraphicsManager.cs +++ b/EOLib.Graphics/INativeGraphicsManager.cs @@ -1,19 +1,20 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EOLib.Graphics; - -public interface INativeGraphicsManager : IDisposable +namespace EOLib.Graphics { - /// - /// Returns a byte array of image data from a single image within an endless online *.egf file - /// Image is specified by the library file (GFXTypes) and the resourceName (number) - /// - /// Name (number) of the image resource - /// File type to load from - /// Whether or not to make the background black color transparent - /// True to force reload the gfx from the gfx file, false to use the in-memory cache - /// True to make the gfx "fully" transparent; that is, to hide all transparent colors (0x08 blacks and full black) - /// Texture2D containing the image from the *.egf file - Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transparent = false, bool reloadFromFile = false, bool fullTransparent = false); + public interface INativeGraphicsManager : IDisposable + { + /// + /// Returns a byte array of image data from a single image within an endless online *.egf file + /// Image is specified by the library file (GFXTypes) and the resourceName (number) + /// + /// Name (number) of the image resource + /// File type to load from + /// Whether or not to make the background black color transparent + /// True to force reload the gfx from the gfx file, false to use the in-memory cache + /// True to make the gfx "fully" transparent; that is, to hide all transparent colors (0x08 blacks and full black) + /// Texture2D containing the image from the *.egf file + Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transparent = false, bool reloadFromFile = false, bool fullTransparent = false); + } } \ No newline at end of file diff --git a/EOLib.Graphics/LibraryLoadException.cs b/EOLib.Graphics/LibraryLoadException.cs index ad2d5299f..313fe9bf5 100644 --- a/EOLib.Graphics/LibraryLoadException.cs +++ b/EOLib.Graphics/LibraryLoadException.cs @@ -1,18 +1,19 @@ using System; using System.Runtime.InteropServices; -namespace EOLib.Graphics; - -public class LibraryLoadException : Exception +namespace EOLib.Graphics { - public GFXTypes WhichGFX { get; private set; } - - public LibraryLoadException(string libraryNumber, GFXTypes which) - : base(string.Format("Error {1} when loading library {0}\n{2}", - libraryNumber, - Marshal.GetLastWin32Error(), - new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message)) + public class LibraryLoadException : Exception { - WhichGFX = which; + public GFXTypes WhichGFX { get; private set; } + + public LibraryLoadException(string libraryNumber, GFXTypes which) + : base(string.Format("Error {1} when loading library {0}\n{2}", + libraryNumber, + Marshal.GetLastWin32Error(), + new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message)) + { + WhichGFX = which; + } } } \ No newline at end of file diff --git a/EOLib.Graphics/NativeGraphicsLoader.cs b/EOLib.Graphics/NativeGraphicsLoader.cs index f37d99058..208c961b4 100644 --- a/EOLib.Graphics/NativeGraphicsLoader.cs +++ b/EOLib.Graphics/NativeGraphicsLoader.cs @@ -1,41 +1,42 @@ using AutomaticTypeMapper; using System; -namespace EOLib.Graphics; - -[MappedType(BaseType = typeof(INativeGraphicsLoader), IsSingleton = true)] -public class NativeGraphicsLoader : INativeGraphicsLoader +namespace EOLib.Graphics { - private readonly IPEFileCollection _modules; - - public NativeGraphicsLoader(IPEFileCollection modules) + [MappedType(BaseType = typeof(INativeGraphicsLoader), IsSingleton = true)] + public class NativeGraphicsLoader : INativeGraphicsLoader { - _modules = modules; - } + private readonly IPEFileCollection _modules; - public ReadOnlyMemory LoadGFX(GFXTypes file, int resourceValue) - { - var fileBytes = ReadOnlyMemory.Empty; - try + public NativeGraphicsLoader(IPEFileCollection modules) { - fileBytes = _modules[file].GetEmbeddedBitmapResourceByID(resourceValue + 100); + _modules = modules; } - catch (ArgumentException) + + public ReadOnlyMemory LoadGFX(GFXTypes file, int resourceValue) { + var fileBytes = ReadOnlyMemory.Empty; + try + { + fileBytes = _modules[file].GetEmbeddedBitmapResourceByID(resourceValue + 100); + } + catch (ArgumentException) + { #if DEBUG - throw; + throw; #endif - } + } - if (fileBytes.Length == 0) - { + if (fileBytes.Length == 0) + { #if DEBUG - throw new GFXLoadException(resourceValue, file); + throw new GFXLoadException(resourceValue, file); #else - return Array.Empty(); + return Array.Empty(); #endif - } + } - return fileBytes; + return fileBytes; + } } } \ No newline at end of file diff --git a/EOLib.Graphics/NativeGraphicsManager.cs b/EOLib.Graphics/NativeGraphicsManager.cs index 08f03b824..9e68c5513 100644 --- a/EOLib.Graphics/NativeGraphicsManager.cs +++ b/EOLib.Graphics/NativeGraphicsManager.cs @@ -7,134 +7,135 @@ using System.Collections.Generic; using System.Linq; -namespace EOLib.Graphics; - -[MappedType(BaseType = typeof(INativeGraphicsManager), IsSingleton = true)] -public sealed class NativeGraphicsManager : INativeGraphicsManager +namespace EOLib.Graphics { - private readonly ConcurrentDictionary> _cache; + [MappedType(BaseType = typeof(INativeGraphicsManager), IsSingleton = true)] + public sealed class NativeGraphicsManager : INativeGraphicsManager + { + private readonly ConcurrentDictionary> _cache; - private readonly INativeGraphicsLoader _gfxLoader; - private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; + private readonly INativeGraphicsLoader _gfxLoader; + private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; - public NativeGraphicsManager(INativeGraphicsLoader gfxLoader, IGraphicsDeviceProvider graphicsDeviceProvider) - { - _cache = new ConcurrentDictionary>(); - _gfxLoader = gfxLoader; - _graphicsDeviceProvider = graphicsDeviceProvider; - } + public NativeGraphicsManager(INativeGraphicsLoader gfxLoader, IGraphicsDeviceProvider graphicsDeviceProvider) + { + _cache = new ConcurrentDictionary>(); + _gfxLoader = gfxLoader; + _graphicsDeviceProvider = graphicsDeviceProvider; + } - // todo: instead of having a bunch of bool params, maybe an enum param with [Flags] for the different options would be better - public Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transparent = false, bool reloadFromFile = false, bool fullTransparent = false) - { - if (_cache.ContainsKey(file) && _cache[file].ContainsKey(resourceVal)) + // todo: instead of having a bunch of bool params, maybe an enum param with [Flags] for the different options would be better + public Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transparent = false, bool reloadFromFile = false, bool fullTransparent = false) { - if (reloadFromFile) + if (_cache.ContainsKey(file) && _cache[file].ContainsKey(resourceVal)) { - _cache[file][resourceVal]?.Dispose(); - _cache[file].Remove(resourceVal, out _); + if (reloadFromFile) + { + _cache[file][resourceVal]?.Dispose(); + _cache[file].Remove(resourceVal, out _); + } + else + { + return _cache[file][resourceVal]; + } } - else + + var ret = LoadTexture(file, resourceVal, transparent, fullTransparent); + if (_cache.ContainsKey(file) || + _cache.TryAdd(file, new ConcurrentDictionary())) { - return _cache[file][resourceVal]; + _cache[file].TryAdd(resourceVal, ret); } - } - var ret = LoadTexture(file, resourceVal, transparent, fullTransparent); - if (_cache.ContainsKey(file) || - _cache.TryAdd(file, new ConcurrentDictionary())) - { - _cache[file].TryAdd(resourceVal, ret); + return ret; } - return ret; - } - - private Texture2D LoadTexture(GFXTypes file, int resourceVal, bool transparent, bool fullTransparent) - { - var rawData = _gfxLoader.LoadGFX(file, resourceVal); - - if (rawData.IsEmpty) - return new Texture2D(_graphicsDeviceProvider.GraphicsDevice, 1, 1); + private Texture2D LoadTexture(GFXTypes file, int resourceVal, bool transparent, bool fullTransparent) + { + var rawData = _gfxLoader.LoadGFX(file, resourceVal); - Action processAction = null; + if (rawData.IsEmpty) + return new Texture2D(_graphicsDeviceProvider.GraphicsDevice, 1, 1); - if (transparent) - { - processAction = data => CrossPlatformMakeTransparent(data); + Action processAction = null; - if (fullTransparent) - { - processAction = data => CrossPlatformMakeTransparent(data, isHat: true); - } - else if (file == GFXTypes.FemaleHat || file == GFXTypes.MaleHat) + if (transparent) { - processAction = data => CrossPlatformMakeTransparent(data, checkClip: true, isHat: true); + processAction = data => CrossPlatformMakeTransparent(data); + + if (fullTransparent) + { + processAction = data => CrossPlatformMakeTransparent(data, isHat: true); + } + else if (file == GFXTypes.FemaleHat || file == GFXTypes.MaleHat) + { + processAction = data => CrossPlatformMakeTransparent(data, checkClip: true, isHat: true); + } } - } - using var ms = rawData.AsStream(); - var ret = Texture2D.FromStream(_graphicsDeviceProvider.GraphicsDevice, ms, processAction); + using var ms = rawData.AsStream(); + var ret = Texture2D.FromStream(_graphicsDeviceProvider.GraphicsDevice, ms, processAction); - return ret; - } + return ret; + } - private static unsafe void CrossPlatformMakeTransparent(byte[] data, bool isHat = false, bool checkClip = false) - { - var shouldClip = false; - if (checkClip) + private static unsafe void CrossPlatformMakeTransparent(byte[] data, bool isHat = false, bool checkClip = false) { - fixed (byte* ptr = data) + var shouldClip = false; + if (checkClip) { - for (int i = 0; i < data.Length; i += 4) + fixed (byte* ptr = data) { - uint* addr = (uint*)(ptr + i); - if (*addr == 0xff000008) + for (int i = 0; i < data.Length; i += 4) { - shouldClip = true; - break; + uint* addr = (uint*)(ptr + i); + if (*addr == 0xff000008) + { + shouldClip = true; + break; + } } } } - } - // for all gfx: 0,0,0 is transparent + // for all gfx: 0,0,0 is transparent - // for some hats: 8,0,0 and 0,0,0 are both transparent + // for some hats: 8,0,0 and 0,0,0 are both transparent - // for hats: R=8 G=0 B=0 is transparent - // some default gfx use R=0 G=8 B=0 as black - // 0,0,0 clips pixels below it if 8,0,0 is present on the frame + // for hats: R=8 G=0 B=0 is transparent + // some default gfx use R=0 G=8 B=0 as black + // 0,0,0 clips pixels below it if 8,0,0 is present on the frame - var transparentColors = isHat - ? shouldClip - ? new Color[] { new Color(0xff000008) } // check clip: make ff000008 transparent only, use black for clipping if present - : new Color[] { Color.Black, new Color(0xff000008) } // isHat: make both colors transparent - : new Color[] { Color.Black }; // default: make only black transparent + var transparentColors = isHat + ? shouldClip + ? new Color[] { new Color(0xff000008) } // check clip: make ff000008 transparent only, use black for clipping if present + : new Color[] { Color.Black, new Color(0xff000008) } // isHat: make both colors transparent + : new Color[] { Color.Black }; // default: make only black transparent - fixed (byte* ptr = data) - { - for (int i = 0; i < data.Length; i += 4) + fixed (byte* ptr = data) { - uint* addr = (uint*)(ptr + i); - if (transparentColors.Contains(new Color(*addr))) - *addr = 0; + for (int i = 0; i < data.Length; i += 4) + { + uint* addr = (uint*)(ptr + i); + if (transparentColors.Contains(new Color(*addr))) + *addr = 0; + } } } - } - public void Dispose() - { - foreach (var text in _cache.SelectMany(x => x.Value.Values)) - text.Dispose(); + public void Dispose() + { + foreach (var text in _cache.SelectMany(x => x.Value.Values)) + text.Dispose(); - _cache.Clear(); + _cache.Clear(); + } } -} -[Serializable] -public class GFXLoadException : Exception -{ - public GFXLoadException(int resource, GFXTypes gfx) - : base($"Unable to load graphic {resource + 100} from file gfx{(int)gfx:000}.egf") { } + [Serializable] + public class GFXLoadException : Exception + { + public GFXLoadException(int resource, GFXTypes gfx) + : base($"Unable to load graphic {resource + 100} from file gfx{(int)gfx:000}.egf") { } + } } \ No newline at end of file diff --git a/EOLib.Graphics/PEFileCollection.cs b/EOLib.Graphics/PEFileCollection.cs index e20c527e4..01671d0d4 100644 --- a/EOLib.Graphics/PEFileCollection.cs +++ b/EOLib.Graphics/PEFileCollection.cs @@ -4,34 +4,35 @@ using System.Collections.Generic; using System.IO; -namespace EOLib.Graphics; - -[MappedType(BaseType = typeof(IPEFileCollection), IsSingleton = true)] -public sealed class PEFileCollection : Dictionary, IPEFileCollection +namespace EOLib.Graphics { - public void PopulateCollectionWithStandardGFX() + [MappedType(BaseType = typeof(IPEFileCollection), IsSingleton = true)] + public sealed class PEFileCollection : Dictionary, IPEFileCollection { - var gfxTypes = (GFXTypes[])Enum.GetValues(typeof(GFXTypes)); - foreach (var type in gfxTypes) - Add(type, CreateGFXFile(type)); - } + public void PopulateCollectionWithStandardGFX() + { + var gfxTypes = (GFXTypes[])Enum.GetValues(typeof(GFXTypes)); + foreach (var type in gfxTypes) + Add(type, CreateGFXFile(type)); + } - private IPEFile CreateGFXFile(GFXTypes file) - { - var number = ((int)file).ToString("D3"); - var fName = Path.Combine("gfx", "gfx" + number + ".egf"); + private IPEFile CreateGFXFile(GFXTypes file) + { + var number = ((int)file).ToString("D3"); + var fName = Path.Combine("gfx", "gfx" + number + ".egf"); - return new PEFile(fName); + return new PEFile(fName); + } + + public void Dispose() + { + foreach (var pair in this) + pair.Value.Dispose(); + } } - public void Dispose() + public interface IPEFileCollection : IDictionary, IDisposable { - foreach (var pair in this) - pair.Value.Dispose(); + void PopulateCollectionWithStandardGFX(); } -} - -public interface IPEFileCollection : IDictionary, IDisposable -{ - void PopulateCollectionWithStandardGFX(); } \ No newline at end of file diff --git a/EOLib.Graphics/RectangleExtension.cs b/EOLib.Graphics/RectangleExtension.cs index 3fbfd12bc..c170f2c29 100644 --- a/EOLib.Graphics/RectangleExtension.cs +++ b/EOLib.Graphics/RectangleExtension.cs @@ -1,29 +1,30 @@ using Microsoft.Xna.Framework; -namespace EOLib.Graphics; - -public static class RectangleExtension +namespace EOLib.Graphics { - /// - /// Returns a new rectangle with the position set to the specified location - /// - /// - /// New position for the rectangle - /// - public static Rectangle WithPosition(this Rectangle orig, Vector2 loc) + public static class RectangleExtension { - return new Rectangle((int)loc.X, (int)loc.Y, orig.Width, orig.Height); - } + /// + /// Returns a new rectangle with the position set to the specified location + /// + /// + /// New position for the rectangle + /// + public static Rectangle WithPosition(this Rectangle orig, Vector2 loc) + { + return new Rectangle((int)loc.X, (int)loc.Y, orig.Width, orig.Height); + } - /// - /// Returns a new rectangle with the size set to the specified dimensions - /// - /// - /// Width of the new rectangle - /// Height of the new rectangle - /// - public static Rectangle WithSize(this Rectangle orig, int width, int height) - { - return new Rectangle(orig.X, orig.Y, width, height); + /// + /// Returns a new rectangle with the size set to the specified dimensions + /// + /// + /// Width of the new rectangle + /// Height of the new rectangle + /// + public static Rectangle WithSize(this Rectangle orig, int width, int height) + { + return new Rectangle(orig.X, orig.Y, width, height); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/EIFRecordExtensionsTest.cs b/EOLib.IO.Test/EIFRecordExtensionsTest.cs index fa86b36d1..d0dc6f4d2 100644 --- a/EOLib.IO.Test/EIFRecordExtensionsTest.cs +++ b/EOLib.IO.Test/EIFRecordExtensionsTest.cs @@ -3,45 +3,46 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test; - -[TestFixture, ExcludeFromCodeCoverage] -public class EIFRecordExtensionsTest +namespace EOLib.IO.Test { - [TestCase(EquipLocation.Accessory, ItemType.Accessory)] - [TestCase(EquipLocation.Armlet1, ItemType.Armlet)] - [TestCase(EquipLocation.Armor, ItemType.Armor)] - [TestCase(EquipLocation.Belt, ItemType.Belt)] - [TestCase(EquipLocation.Boots, ItemType.Boots)] - [TestCase(EquipLocation.Bracer1, ItemType.Bracer)] - [TestCase(EquipLocation.Gloves, ItemType.Gloves)] - [TestCase(EquipLocation.Hat, ItemType.Hat)] - [TestCase(EquipLocation.Necklace, ItemType.Necklace)] - [TestCase(EquipLocation.Ring1, ItemType.Ring)] - [TestCase(EquipLocation.Shield, ItemType.Shield)] - [TestCase(EquipLocation.Weapon, ItemType.Weapon)] - public void GetEquipLocation_Matches_ItemType(EquipLocation equipLocation, ItemType itemType) + [TestFixture, ExcludeFromCodeCoverage] + public class EIFRecordExtensionsTest { - Assert.That(WithItemType(itemType).GetEquipLocation(), Is.EqualTo(equipLocation)); - } + [TestCase(EquipLocation.Accessory, ItemType.Accessory)] + [TestCase(EquipLocation.Armlet1, ItemType.Armlet)] + [TestCase(EquipLocation.Armor, ItemType.Armor)] + [TestCase(EquipLocation.Belt, ItemType.Belt)] + [TestCase(EquipLocation.Boots, ItemType.Boots)] + [TestCase(EquipLocation.Bracer1, ItemType.Bracer)] + [TestCase(EquipLocation.Gloves, ItemType.Gloves)] + [TestCase(EquipLocation.Hat, ItemType.Hat)] + [TestCase(EquipLocation.Necklace, ItemType.Necklace)] + [TestCase(EquipLocation.Ring1, ItemType.Ring)] + [TestCase(EquipLocation.Shield, ItemType.Shield)] + [TestCase(EquipLocation.Weapon, ItemType.Weapon)] + public void GetEquipLocation_Matches_ItemType(EquipLocation equipLocation, ItemType itemType) + { + Assert.That(WithItemType(itemType).GetEquipLocation(), Is.EqualTo(equipLocation)); + } - [TestCase(ItemType.Beer)] - [TestCase(ItemType.CureCurse)] - [TestCase(ItemType.EXPReward)] - [TestCase(ItemType.EffectPotion)] - [TestCase(ItemType.HairDye)] - [TestCase(ItemType.Heal)] - [TestCase(ItemType.Key)] - [TestCase(ItemType.Money)] - [TestCase(ItemType.SkillReward)] - [TestCase(ItemType.StatReward)] - [TestCase(ItemType.Static)] - [TestCase(ItemType.Teleport)] - [TestCase(ItemType.UnknownType1)] - public void GetEquipLocation_Unsupported_ReturnsPaperdollMax(ItemType type) - { - Assert.That(WithItemType(type).GetEquipLocation(), Is.EqualTo(EquipLocation.PAPERDOLL_MAX)); - } + [TestCase(ItemType.Beer)] + [TestCase(ItemType.CureCurse)] + [TestCase(ItemType.EXPReward)] + [TestCase(ItemType.EffectPotion)] + [TestCase(ItemType.HairDye)] + [TestCase(ItemType.Heal)] + [TestCase(ItemType.Key)] + [TestCase(ItemType.Money)] + [TestCase(ItemType.SkillReward)] + [TestCase(ItemType.StatReward)] + [TestCase(ItemType.Static)] + [TestCase(ItemType.Teleport)] + [TestCase(ItemType.UnknownType1)] + public void GetEquipLocation_Unsupported_ReturnsPaperdollMax(ItemType type) + { + Assert.That(WithItemType(type).GetEquipLocation(), Is.EqualTo(EquipLocation.PAPERDOLL_MAX)); + } - private static EIFRecord WithItemType(ItemType type) => (EIFRecord)new EIFRecord().WithProperty(PubRecordProperty.ItemType, (int)type); + private static EIFRecord WithItemType(ItemType type) => (EIFRecord)new EIFRecord().WithProperty(PubRecordProperty.ItemType, (int)type); + } } \ No newline at end of file diff --git a/EOLib.IO.Test/Map/MapFilePropertiesTest.cs b/EOLib.IO.Test/Map/MapFilePropertiesTest.cs index eb46d4015..08a70bc5f 100644 --- a/EOLib.IO.Test/Map/MapFilePropertiesTest.cs +++ b/EOLib.IO.Test/Map/MapFilePropertiesTest.cs @@ -10,134 +10,135 @@ using System.Reflection; using System.Text; -namespace EOLib.IO.Test.Map; - -[TestFixture, ExcludeFromCodeCoverage] -public class MapFilePropertiesTest +namespace EOLib.IO.Test.Map { - private IMapEntitySerializer _mapPropertiesSerializer; - private IMapFileProperties _props; - - [SetUp] - public void SetUp() + [TestFixture, ExcludeFromCodeCoverage] + public class MapFilePropertiesTest { - _props = new MapFileProperties(); + private IMapEntitySerializer _mapPropertiesSerializer; + private IMapFileProperties _props; - _mapPropertiesSerializer = new MapPropertiesSerializer( - new NumberEncoderService(), new MapStringEncoderService()); - } - - [Test] - public void MapFileProperties_HasExpectedFileHeader() - { - Assert.AreEqual("EMF", _props.FileType); - } + [SetUp] + public void SetUp() + { + _props = new MapFileProperties(); - [Test] - public void MapFileProperties_SerializeToByteArray_HasExpectedFormat() - { - _props = CreateMapPropertiesWithSomeTestData(_props); + _mapPropertiesSerializer = new MapPropertiesSerializer( + new NumberEncoderService(), new MapStringEncoderService()); + } - var expectedBytes = CreateExpectedBytes(_props); - var actualBytes = _mapPropertiesSerializer.SerializeToByteArray(_props); + [Test] + public void MapFileProperties_HasExpectedFileHeader() + { + Assert.AreEqual("EMF", _props.FileType); + } - CollectionAssert.AreEqual(expectedBytes, actualBytes); - } + [Test] + public void MapFileProperties_SerializeToByteArray_HasExpectedFormat() + { + _props = CreateMapPropertiesWithSomeTestData(_props); - [Test] - public void MapFileProperties_DeserializeFromByteArray_HasExpectedValues() - { - var expected = CreateMapPropertiesWithSomeTestData(_props); - var bytes = CreateExpectedBytes(expected); + var expectedBytes = CreateExpectedBytes(_props); + var actualBytes = _mapPropertiesSerializer.SerializeToByteArray(_props); - _props = _mapPropertiesSerializer.DeserializeFromByteArray(bytes); + CollectionAssert.AreEqual(expectedBytes, actualBytes); + } - foreach (var property in expected.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) + [Test] + public void MapFileProperties_DeserializeFromByteArray_HasExpectedValues() { - var expectedValue = property.GetValue(expected); - var actualValue = property.GetValue(_props); + var expected = CreateMapPropertiesWithSomeTestData(_props); + var bytes = CreateExpectedBytes(expected); - if (expectedValue is ICollection && actualValue is ICollection) - CollectionAssert.AreEqual((ICollection)expectedValue, (ICollection)actualValue); - else - Assert.AreEqual(expectedValue, actualValue, "Property {0} is not equal!", property.Name); + _props = _mapPropertiesSerializer.DeserializeFromByteArray(bytes); + + foreach (var property in expected.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) + { + var expectedValue = property.GetValue(expected); + var actualValue = property.GetValue(_props); + + if (expectedValue is ICollection && actualValue is ICollection) + CollectionAssert.AreEqual((ICollection)expectedValue, (ICollection)actualValue); + else + Assert.AreEqual(expectedValue, actualValue, "Property {0} is not equal!", property.Name); + } } - } - [Test] - public void MapFileProperties_CustomProperties_NotChangedWhenDeserialized() - { - var expected = CreateMapPropertiesWithSomeTestData(_props); - var bytes = CreateExpectedBytes(expected); + [Test] + public void MapFileProperties_CustomProperties_NotChangedWhenDeserialized() + { + var expected = CreateMapPropertiesWithSomeTestData(_props); + var bytes = CreateExpectedBytes(expected); - _props = _mapPropertiesSerializer.DeserializeFromByteArray(bytes); + _props = _mapPropertiesSerializer.DeserializeFromByteArray(bytes); - Assert.AreEqual(new MapFileProperties().MapID, _props.MapID); - Assert.AreEqual(new MapFileProperties().FileSize, _props.FileSize); - Assert.AreEqual(new MapFileProperties().HasTimedSpikes, _props.HasTimedSpikes); - } + Assert.AreEqual(new MapFileProperties().MapID, _props.MapID); + Assert.AreEqual(new MapFileProperties().FileSize, _props.FileSize); + Assert.AreEqual(new MapFileProperties().HasTimedSpikes, _props.HasTimedSpikes); + } - [Test] - public void MapFileProperties_DeserializeFromByteArray_ThrowsExceptionWhenIncorrectSize() - { - var bytes = new byte[] { 1, 2 }; - Assert.Throws(() => _mapPropertiesSerializer.DeserializeFromByteArray(bytes)); - } + [Test] + public void MapFileProperties_DeserializeFromByteArray_ThrowsExceptionWhenIncorrectSize() + { + var bytes = new byte[] { 1, 2 }; + Assert.Throws(() => _mapPropertiesSerializer.DeserializeFromByteArray(bytes)); + } - [Test] - public void MapFileProperties_DeserializeFromByteArray_ThrowsExceptionWhenNotEMF() - { - var bytes = Enumerable.Repeat((byte)254, MapFileProperties.DATA_SIZE).ToArray(); - Assert.Throws(() => _mapPropertiesSerializer.DeserializeFromByteArray(bytes)); - } + [Test] + public void MapFileProperties_DeserializeFromByteArray_ThrowsExceptionWhenNotEMF() + { + var bytes = Enumerable.Repeat((byte)254, MapFileProperties.DATA_SIZE).ToArray(); + Assert.Throws(() => _mapPropertiesSerializer.DeserializeFromByteArray(bytes)); + } - private static IMapFileProperties CreateMapPropertiesWithSomeTestData(IMapFileProperties props) - { - return props.WithChecksum(new List { 1, 2 }) - .WithName("Some test name") - .WithWidth(200) - .WithHeight(100) - .WithEffect(MapEffect.Quake1) - .WithMusic(123) - .WithControl(MusicControl.InterruptIfDifferentPlayOnce) - .WithAmbientNoise(4567) - .WithFillTile(6969) - .WithRelogX(33) - .WithRelogY(22) - .WithUnknown2(100) - .WithMapAvailable(true) - .WithScrollAvailable(false) - .WithPKAvailable(true); - } + private static IMapFileProperties CreateMapPropertiesWithSomeTestData(IMapFileProperties props) + { + return props.WithChecksum(new List { 1, 2 }) + .WithName("Some test name") + .WithWidth(200) + .WithHeight(100) + .WithEffect(MapEffect.Quake1) + .WithMusic(123) + .WithControl(MusicControl.InterruptIfDifferentPlayOnce) + .WithAmbientNoise(4567) + .WithFillTile(6969) + .WithRelogX(33) + .WithRelogY(22) + .WithUnknown2(100) + .WithMapAvailable(true) + .WithScrollAvailable(false) + .WithPKAvailable(true); + } - private static byte[] CreateExpectedBytes(IMapFileProperties props) - { - var numberEncoderService = new NumberEncoderService(); - var mapStringEncoderService = new MapStringEncoderService(); - var ret = new List(); - - ret.AddRange(Encoding.ASCII.GetBytes(props.FileType)); - ret.AddRange(props.Checksum.SelectMany(x => numberEncoderService.EncodeNumber(x, 2))); - - var fullName = Enumerable.Repeat((byte)0xFF, 24).ToArray(); - var encodedName = mapStringEncoderService.EncodeMapString(props.Name, props.Name.Length); - Array.Copy(encodedName, 0, fullName, fullName.Length - encodedName.Length, encodedName.Length); - ret.AddRange(fullName); - - ret.AddRange(numberEncoderService.EncodeNumber(props.PKAvailable ? 3 : 0, 1)); - ret.AddRange(numberEncoderService.EncodeNumber((int)props.Effect, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.Music, 1)); - ret.AddRange(numberEncoderService.EncodeNumber((int)props.Control, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.AmbientNoise, 2)); - ret.AddRange(numberEncoderService.EncodeNumber(props.Width, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.Height, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.FillTile, 2)); - ret.AddRange(numberEncoderService.EncodeNumber(props.MapAvailable ? 1 : 0, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.CanScroll ? 1 : 0, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.RelogX, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.RelogY, 1)); - ret.AddRange(numberEncoderService.EncodeNumber(props.Unknown2, 1)); - - return ret.ToArray(); + private static byte[] CreateExpectedBytes(IMapFileProperties props) + { + var numberEncoderService = new NumberEncoderService(); + var mapStringEncoderService = new MapStringEncoderService(); + var ret = new List(); + + ret.AddRange(Encoding.ASCII.GetBytes(props.FileType)); + ret.AddRange(props.Checksum.SelectMany(x => numberEncoderService.EncodeNumber(x, 2))); + + var fullName = Enumerable.Repeat((byte)0xFF, 24).ToArray(); + var encodedName = mapStringEncoderService.EncodeMapString(props.Name, props.Name.Length); + Array.Copy(encodedName, 0, fullName, fullName.Length - encodedName.Length, encodedName.Length); + ret.AddRange(fullName); + + ret.AddRange(numberEncoderService.EncodeNumber(props.PKAvailable ? 3 : 0, 1)); + ret.AddRange(numberEncoderService.EncodeNumber((int)props.Effect, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.Music, 1)); + ret.AddRange(numberEncoderService.EncodeNumber((int)props.Control, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.AmbientNoise, 2)); + ret.AddRange(numberEncoderService.EncodeNumber(props.Width, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.Height, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.FillTile, 2)); + ret.AddRange(numberEncoderService.EncodeNumber(props.MapAvailable ? 1 : 0, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.CanScroll ? 1 : 0, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.RelogX, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.RelogY, 1)); + ret.AddRange(numberEncoderService.EncodeNumber(props.Unknown2, 1)); + + return ret.ToArray(); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Map/MapFileTest.cs b/EOLib.IO.Test/Map/MapFileTest.cs index 93237d607..7b4d7e272 100644 --- a/EOLib.IO.Test/Map/MapFileTest.cs +++ b/EOLib.IO.Test/Map/MapFileTest.cs @@ -7,166 +7,167 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.IO.Test.Map; - -[TestFixture, ExcludeFromCodeCoverage] -public class MapFileTest +namespace EOLib.IO.Test.Map { - private IMapFile _mapFile; - private IMapStringEncoderService ses; - private INumberEncoderService nes; + [TestFixture, ExcludeFromCodeCoverage] + public class MapFileTest + { + private IMapFile _mapFile; + private IMapStringEncoderService ses; + private INumberEncoderService nes; - private IMapFileSerializer _serializer; + private IMapFileSerializer _serializer; - [SetUp] - public void SetUp() - { - ses = new MapStringEncoderService(); - nes = new NumberEncoderService(); - - _serializer = new MapFileSerializer( - new MapPropertiesSerializer(nes, ses), - new NPCSpawnMapEntitySerializer(nes), - new ChestSpawnMapEntitySerializer(nes), - new WarpMapEntitySerializer(nes), - new SignMapEntitySerializer(nes, ses), - new UnknownMapEntitySerializer(nes), - nes); - } + [SetUp] + public void SetUp() + { + ses = new MapStringEncoderService(); + nes = new NumberEncoderService(); + + _serializer = new MapFileSerializer( + new MapPropertiesSerializer(nes, ses), + new NPCSpawnMapEntitySerializer(nes), + new ChestSpawnMapEntitySerializer(nes), + new WarpMapEntitySerializer(nes), + new SignMapEntitySerializer(nes, ses), + new UnknownMapEntitySerializer(nes), + nes); + } - [Test] - public void MapFile_Properties_HasExpectedInitialParameters() - { - _mapFile = new MapFile().WithMapID(123); - - Assert.AreEqual(123, _mapFile.Properties.MapID); - Assert.IsNotNull(_mapFile.NPCSpawns); - Assert.IsNotNull(_mapFile.Unknowns); - Assert.IsNotNull(_mapFile.Chests); - Assert.IsNotNull(_mapFile.Tiles); - Assert.IsNotNull(_mapFile.Warps); - Assert.IsNotNull(_mapFile.GFX); - Assert.IsNotNull(_mapFile.Signs); - } + [Test] + public void MapFile_Properties_HasExpectedInitialParameters() + { + _mapFile = new MapFile().WithMapID(123); + + Assert.AreEqual(123, _mapFile.Properties.MapID); + Assert.IsNotNull(_mapFile.NPCSpawns); + Assert.IsNotNull(_mapFile.Unknowns); + Assert.IsNotNull(_mapFile.Chests); + Assert.IsNotNull(_mapFile.Tiles); + Assert.IsNotNull(_mapFile.Warps); + Assert.IsNotNull(_mapFile.GFX); + Assert.IsNotNull(_mapFile.Signs); + } - [Test] - public void MapFile_DeserializeFromByteArray_HasCorrectFileSizeInMapProperties() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_DeserializeFromByteArray_HasCorrectFileSizeInMapProperties() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.None); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.None); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.AreEqual(mapData.Length, _mapFile.Properties.FileSize); - } + Assert.AreEqual(mapData.Length, _mapFile.Properties.FileSize); + } - [Test] - public void MapFile_DeserializeFromByteArray_NoTileSpecIsTimedSpikes_FlagIsNotSetInProperties() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_DeserializeFromByteArray_NoTileSpecIsTimedSpikes_FlagIsNotSetInProperties() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.AmbientSource); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.AmbientSource); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.IsFalse(_mapFile.Properties.HasTimedSpikes); - } + Assert.IsFalse(_mapFile.Properties.HasTimedSpikes); + } - [Test] - public void MapFile_DeserializeFromByteArray_AnyTileSpecIsTimedSpikes_FlagIsSetInProperties() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_DeserializeFromByteArray_AnyTileSpecIsTimedSpikes_FlagIsSetInProperties() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.SpikesTimed); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.SpikesTimed); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.IsTrue(_mapFile.Properties.HasTimedSpikes); - } + Assert.IsTrue(_mapFile.Properties.HasTimedSpikes); + } - [Test] - public void MapFile_SerializeToByteArray_HasCorrectFormat() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_SerializeToByteArray_HasCorrectFormat() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(2).WithHeight(2), TileSpec.Arena, 432); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(2).WithHeight(2), TileSpec.Arena, 432); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - var actualData = _serializer.SerializeToByteArray(_mapFile, rewriteChecksum: false); + var actualData = _serializer.SerializeToByteArray(_mapFile, rewriteChecksum: false); - CollectionAssert.AreEqual(mapData, actualData); - } + CollectionAssert.AreEqual(mapData, actualData); + } - [Test] - public void MapFile_Width1Height1_HasExpectedGFXAndTiles() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_Width1Height1_HasExpectedGFXAndTiles() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.Board5, 999); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.Board5, 999); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.AreEqual(TileSpec.Board5, _mapFile.Tiles[1, 1]); - foreach (var kvp in _mapFile.GFX) - Assert.AreEqual(999, kvp.Value[1, 1]); - } + Assert.AreEqual(TileSpec.Board5, _mapFile.Tiles[1, 1]); + foreach (var kvp in _mapFile.GFX) + Assert.AreEqual(999, kvp.Value[1, 1]); + } - [Test] - public void MapFile_StoresEmptyWarpRows() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_StoresEmptyWarpRows() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.BankVault, 1234); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.BankVault, 1234); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.That(_mapFile.EmptyWarpRows, Has.Count.EqualTo(1)); - } + Assert.That(_mapFile.EmptyWarpRows, Has.Count.EqualTo(1)); + } - [Test] - public void MapFile_StoresEmptyTileRows() - { - _mapFile = new MapFile().WithMapID(1); + [Test] + public void MapFile_StoresEmptyTileRows() + { + _mapFile = new MapFile().WithMapID(1); - var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.VultTypo, 4321); - _mapFile = _serializer.DeserializeFromByteArray(mapData); + var mapData = CreateDataForMap(new MapFileProperties().WithWidth(1).WithHeight(1), TileSpec.VultTypo, 4321); + _mapFile = _serializer.DeserializeFromByteArray(mapData); - Assert.That(_mapFile.EmptyTileRows, Has.Count.EqualTo(1)); - } + Assert.That(_mapFile.EmptyTileRows, Has.Count.EqualTo(1)); + } - private byte[] CreateDataForMap(IMapFileProperties mapFileProperties, TileSpec spec, int gfx = 1) - { - var ret = new List(); - - var serializer = new MapPropertiesSerializer(nes, ses); - - ret.AddRange(serializer.SerializeToByteArray(mapFileProperties)); - ret.AddRange(nes.EncodeNumber(0, 1)); //npc spawns - ret.AddRange(nes.EncodeNumber(0, 1)); //unknowns - ret.AddRange(nes.EncodeNumber(0, 1)); //chest spawns - - //tiles - ret.AddRange(nes.EncodeNumber(2, 1)); //count (rows) - ret.AddRange(nes.EncodeNumber(1, 1)); //y - ret.AddRange(nes.EncodeNumber(1, 1)); //count (cols) - ret.AddRange(nes.EncodeNumber(1, 1)); //x - ret.AddRange(nes.EncodeNumber((int)spec, 1)); //tilespec - ret.AddRange(nes.EncodeNumber(0, 1)); //y - ret.AddRange(nes.EncodeNumber(0, 1)); //count (cols) (empty row) - - //warps (empty row) - ret.AddRange(nes.EncodeNumber(1, 1)); //count - ret.AddRange(nes.EncodeNumber(1, 1)); //y - ret.AddRange(nes.EncodeNumber(0, 1)); //count - - //gfx - foreach (var layer in (MapLayer[])Enum.GetValues(typeof(MapLayer))) + private byte[] CreateDataForMap(IMapFileProperties mapFileProperties, TileSpec spec, int gfx = 1) { - ret.AddRange(nes.EncodeNumber(1, 1)); //count + var ret = new List(); + + var serializer = new MapPropertiesSerializer(nes, ses); + + ret.AddRange(serializer.SerializeToByteArray(mapFileProperties)); + ret.AddRange(nes.EncodeNumber(0, 1)); //npc spawns + ret.AddRange(nes.EncodeNumber(0, 1)); //unknowns + ret.AddRange(nes.EncodeNumber(0, 1)); //chest spawns + + //tiles + ret.AddRange(nes.EncodeNumber(2, 1)); //count (rows) ret.AddRange(nes.EncodeNumber(1, 1)); //y - ret.AddRange(nes.EncodeNumber(1, 1)); //count + ret.AddRange(nes.EncodeNumber(1, 1)); //count (cols) ret.AddRange(nes.EncodeNumber(1, 1)); //x - ret.AddRange(nes.EncodeNumber(gfx, 2)); //gfx value - } + ret.AddRange(nes.EncodeNumber((int)spec, 1)); //tilespec + ret.AddRange(nes.EncodeNumber(0, 1)); //y + ret.AddRange(nes.EncodeNumber(0, 1)); //count (cols) (empty row) + + //warps (empty row) + ret.AddRange(nes.EncodeNumber(1, 1)); //count + ret.AddRange(nes.EncodeNumber(1, 1)); //y + ret.AddRange(nes.EncodeNumber(0, 1)); //count + + //gfx + foreach (var layer in (MapLayer[])Enum.GetValues(typeof(MapLayer))) + { + ret.AddRange(nes.EncodeNumber(1, 1)); //count + ret.AddRange(nes.EncodeNumber(1, 1)); //y + ret.AddRange(nes.EncodeNumber(1, 1)); //count + ret.AddRange(nes.EncodeNumber(1, 1)); //x + ret.AddRange(nes.EncodeNumber(gfx, 2)); //gfx value + } - ret.AddRange(nes.EncodeNumber(0, 1)); //signs + ret.AddRange(nes.EncodeNumber(0, 1)); //signs - return ret.ToArray(); + return ret.ToArray(); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs b/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs index e890cb352..c335b98c5 100644 --- a/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs +++ b/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs @@ -5,89 +5,90 @@ using System.Linq; using System.Text; -namespace EOLib.IO.Test.Map; - -[TestFixture, ExcludeFromCodeCoverage] -public class MapStringEncoderServiceTest +namespace EOLib.IO.Test.Map { - private IMapStringEncoderService _service; - - [SetUp] - public void SetUp() + [TestFixture, ExcludeFromCodeCoverage] + public class MapStringEncoderServiceTest { - _service = new MapStringEncoderService(); - } + private IMapStringEncoderService _service; - [Test] - public void EncodeThenDecode_ReturnsOriginalString() - { - const string expected = "Test map string to encode"; + [SetUp] + public void SetUp() + { + _service = new MapStringEncoderService(); + } - var bytes = _service.EncodeMapString(expected, expected.Length); - var actual = _service.DecodeMapString(bytes); + [Test] + public void EncodeThenDecode_ReturnsOriginalString() + { + const string expected = "Test map string to encode"; - Assert.AreEqual(expected, actual); - } + var bytes = _service.EncodeMapString(expected, expected.Length); + var actual = _service.DecodeMapString(bytes); - [Test] - public void EncodeString_ReturnsExpectedBytes_FromKnownString() - { - var name = "Aeven" + Encoding.ASCII.GetString(Enumerable.Repeat((byte)0, 19).ToArray()); - var expectedBytes = new byte[] + Assert.AreEqual(expected, actual); + } + + [Test] + public void EncodeString_ReturnsExpectedBytes_FromKnownString() { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 104, 41, 104, 94 - }; + var name = "Aeven" + Encoding.ASCII.GetString(Enumerable.Repeat((byte)0, 19).ToArray()); + var expectedBytes = new byte[] + { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 104, 41, 104, 94 + }; - var actualBytes = _service.EncodeMapString(name, name.Length); + var actualBytes = _service.EncodeMapString(name, name.Length); - CollectionAssert.AreEqual(expectedBytes, actualBytes); - } + CollectionAssert.AreEqual(expectedBytes, actualBytes); + } - [Test] - public void DecodeString_ReturnsExpectedString_FromKnownBytes() - { - const string expected = "Aeven"; + [Test] + public void DecodeString_ReturnsExpectedString_FromKnownBytes() + { + const string expected = "Aeven"; - var bytes = new byte[] { 49, 104, 41, 104, 94 }; - var fullBytes = Enumerable.Repeat((byte)255, 24).ToArray(); - Array.Copy(bytes, 0, fullBytes, fullBytes.Length - bytes.Length, bytes.Length); + var bytes = new byte[] { 49, 104, 41, 104, 94 }; + var fullBytes = Enumerable.Repeat((byte)255, 24).ToArray(); + Array.Copy(bytes, 0, fullBytes, fullBytes.Length - bytes.Length, bytes.Length); - var actual = _service.DecodeMapString(fullBytes); + var actual = _service.DecodeMapString(fullBytes); - Assert.AreEqual(expected, actual); - } + Assert.AreEqual(expected, actual); + } - [Test] - public void EncodeString_InvalidLength_Throws() - { - Assert.That(() => _service.EncodeMapString("123", 0), Throws.ArgumentException); - } + [Test] + public void EncodeString_InvalidLength_Throws() + { + Assert.That(() => _service.EncodeMapString("123", 0), Throws.ArgumentException); + } - [Test] - public void EncodeString_ExtraLength_PadsData() - { - const string TestString = "12345"; - const int LengthWithPadding = 8; + [Test] + public void EncodeString_ExtraLength_PadsData() + { + const string TestString = "12345"; + const int LengthWithPadding = 8; - var actual = _service.EncodeMapString(TestString, LengthWithPadding); + var actual = _service.EncodeMapString(TestString, LengthWithPadding); - Assert.That(actual, Has.Length.EqualTo(LengthWithPadding)); + Assert.That(actual, Has.Length.EqualTo(LengthWithPadding)); - int i = 0; - for (; i < LengthWithPadding - TestString.Length; i++) - Assert.That(actual[i], Is.EqualTo((byte)0xFF)); - Assert.That(actual[i], Is.Not.EqualTo((byte)0xFF)); - } + int i = 0; + for (; i < LengthWithPadding - TestString.Length; i++) + Assert.That(actual[i], Is.EqualTo((byte)0xFF)); + Assert.That(actual[i], Is.Not.EqualTo((byte)0xFF)); + } - [Test] - public void EncodeString_ExtraLength_DecodesToExpectedValue() - { - const string TestString = "12345"; - const int LengthWithPadding = 8; + [Test] + public void EncodeString_ExtraLength_DecodesToExpectedValue() + { + const string TestString = "12345"; + const int LengthWithPadding = 8; - var encoded = _service.EncodeMapString(TestString, LengthWithPadding); - var original = _service.DecodeMapString(encoded); + var encoded = _service.EncodeMapString(TestString, LengthWithPadding); + var original = _service.DecodeMapString(encoded); - Assert.That(original, Is.EqualTo(TestString)); + Assert.That(original, Is.EqualTo(TestString)); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/BasePubFileTest.cs b/EOLib.IO.Test/Pub/BasePubFileTest.cs index c3167486e..e134471e7 100644 --- a/EOLib.IO.Test/Pub/BasePubFileTest.cs +++ b/EOLib.IO.Test/Pub/BasePubFileTest.cs @@ -3,172 +3,173 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test.Pub; - -[TestFixture] -public class BasePubFileTest_EIFImpl : BasePubFileTest { } - -[TestFixture] -public class BasePubFileTest_ENFImpl : BasePubFileTest { } - -[TestFixture] -public class BasePubFileTest_ESFImpl : BasePubFileTest { } - -[TestFixture] -public class BasePubFileTest_ECFImpl : BasePubFileTest { } - -// These tests are run from the implementations -[ExcludeFromCodeCoverage] -public abstract class BasePubFileTest - where T : IPubFile, new() - where U : class, IPubRecord, new() +namespace EOLib.IO.Test.Pub { - [Test] - public void WithAddedRecord_AddsRecord() - { - var file = new T(); - var record = (U)new U().WithID(1).WithName("My record"); - - var updatedFile = file.WithAddedRecord(record); - - Assert.That(file, Is.Empty); - Assert.That(updatedFile, Has.Length.EqualTo(1)); - Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record)); - } - - [Test] - public void WithAddedRecord_DuplicateID_ThrowsArgumentException() - { - var file = new T(); - var record = (U)new U().WithID(1).WithName("My record"); - - var updatedFile = file.WithAddedRecord(record); - - Assert.That(() => updatedFile.WithAddedRecord(record), Throws.ArgumentException); - } - - [Test] - public void WithAddedRecord_IDOutOfBounds_ThrowsArgumentException() - { - var file = new T(); - var record = (U)new U().WithID(400); - - Assert.That(() => file.WithAddedRecord(record), Throws.ArgumentException); - } - - [Test] - public void WithInsertedRecord_InsertsRecordAtPosition_SpecifiedByID() - { - IPubFile file = new T(); - var record = (U)new U().WithID(1); - - file = file.WithAddedRecord(record); - - var updatedRecord = (U)record.WithName("updated"); - var updatedFile = file.WithInsertedRecord(updatedRecord); - - Assert.That(file, Has.Length.EqualTo(1)); - Assert.That(updatedFile, Has.Length.EqualTo(2)); - Assert.That(updatedFile[1].Name, Is.EqualTo("updated")); - } - - [Test] - public void WithInsertedRecord_UpdatesExistingRecordIDs() - { - IPubFile file = new T(); - var record = (U)new U().WithID(1); - - file = file.WithAddedRecord(record); - - var updatedRecord = (U)record.WithName("updated"); - var updatedFile = file.WithInsertedRecord(updatedRecord) - .WithInsertedRecord((U)updatedRecord.WithName("updated 2")) - .WithInsertedRecord((U)updatedRecord.WithName("updated 3")); - - Assert.That(file, Has.Length.EqualTo(1)); - Assert.That(updatedFile, Has.Length.EqualTo(4)); - Assert.That(updatedFile[1], Has.Property("Name").EqualTo("updated 3").And.Property("ID").EqualTo(1)); - Assert.That(updatedFile[2], Has.Property("Name").EqualTo("updated 2").And.Property("ID").EqualTo(2)); - Assert.That(updatedFile[3], Has.Property("Name").EqualTo("updated").And.Property("ID").EqualTo(3)); - Assert.That(updatedFile[4], Has.Property("Name").EqualTo(string.Empty).And.Property("ID").EqualTo(4)); - } - - [Test] - public void WithInsertedRecord_IDOutOfRange_ThrowsArgumentException() - { - IPubFile file = new T(); - var record = (U)new U().WithID(2); + [TestFixture] + public class BasePubFileTest_EIFImpl : BasePubFileTest { } - Assert.That(() => file.WithInsertedRecord(record), Throws.ArgumentException); - } - - [Test] - public void WithUpdatedRecord_UpdatesRecordProperties_ByRecordID() - { - IPubFile file = new T(); - var record = (U)new U().WithID(1); - file = file.WithAddedRecord(record); + [TestFixture] + public class BasePubFileTest_ENFImpl : BasePubFileTest { } - var updatedRecord = (U)record.WithName("Some name"); - var updatedFile = file.WithUpdatedRecord(updatedRecord); + [TestFixture] + public class BasePubFileTest_ESFImpl : BasePubFileTest { } - Assert.That(updatedFile[1].Name, Is.EqualTo("Some name")); - } + [TestFixture] + public class BasePubFileTest_ECFImpl : BasePubFileTest { } - [Test] - public void WithUpdatedRecord_IDOutOfRange_ThrowsArgumentException() + // These tests are run from the implementations + [ExcludeFromCodeCoverage] + public abstract class BasePubFileTest + where T : IPubFile, new() + where U : class, IPubRecord, new() { - IPubFile file = new T(); - var record = (U)new U().WithID(1); - file = file.WithAddedRecord(record); - - Assert.That(() => file.WithUpdatedRecord((U)record.WithID(2)), Throws.ArgumentException); - } - - [Test] - public void WithRemovedRecord_RemovesRecord() - { - var record = (U)new U().WithID(1).WithName("My record"); - - var file = new T().WithAddedRecord(record); - var updatedFile = file.WithRemovedRecord(record); - - Assert.That(updatedFile, Is.Empty); - Assert.That(file, Has.Length.EqualTo(1)); - } - - [Test] - public void WithRemovedRecord_RemovesRecord_UpdatesIDs() - { - var record = (U)new U().WithID(1).WithName("My record"); - var record2 = (U)new U().WithID(2).WithName("My record 2"); - var record3 = (U)new U().WithID(3).WithName("My record 3"); - var record4 = (U)new U().WithID(4).WithName("My record 4"); - - var file = new T().WithAddedRecord(record) - .WithAddedRecord(record2) - .WithAddedRecord(record3) - .WithAddedRecord(record4); - var updatedFile = file.WithRemovedRecord(record); - - Assert.That(file, Has.Length.EqualTo(4)); - Assert.That(updatedFile, Has.Length.EqualTo(3)); - - Assert.That(updatedFile[1].ID, Is.EqualTo(1)); - - Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record2.WithID(1))); - Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record3.WithID(2))); - Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record4.WithID(3))); - Assert.That(updatedFile, Has.None.With.Property("ID").EqualTo(4)); - } - - [Test] - public void WithRemovedRecord_IDOutOfrange_ThrowsArgumentException() - { - IPubFile file = new T(); - var record = (U)new U().WithID(1); - file = file.WithAddedRecord(record); - - Assert.That(() => file.WithRemovedRecord((U)record.WithID(2)), Throws.ArgumentException); + [Test] + public void WithAddedRecord_AddsRecord() + { + var file = new T(); + var record = (U)new U().WithID(1).WithName("My record"); + + var updatedFile = file.WithAddedRecord(record); + + Assert.That(file, Is.Empty); + Assert.That(updatedFile, Has.Length.EqualTo(1)); + Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record)); + } + + [Test] + public void WithAddedRecord_DuplicateID_ThrowsArgumentException() + { + var file = new T(); + var record = (U)new U().WithID(1).WithName("My record"); + + var updatedFile = file.WithAddedRecord(record); + + Assert.That(() => updatedFile.WithAddedRecord(record), Throws.ArgumentException); + } + + [Test] + public void WithAddedRecord_IDOutOfBounds_ThrowsArgumentException() + { + var file = new T(); + var record = (U)new U().WithID(400); + + Assert.That(() => file.WithAddedRecord(record), Throws.ArgumentException); + } + + [Test] + public void WithInsertedRecord_InsertsRecordAtPosition_SpecifiedByID() + { + IPubFile file = new T(); + var record = (U)new U().WithID(1); + + file = file.WithAddedRecord(record); + + var updatedRecord = (U)record.WithName("updated"); + var updatedFile = file.WithInsertedRecord(updatedRecord); + + Assert.That(file, Has.Length.EqualTo(1)); + Assert.That(updatedFile, Has.Length.EqualTo(2)); + Assert.That(updatedFile[1].Name, Is.EqualTo("updated")); + } + + [Test] + public void WithInsertedRecord_UpdatesExistingRecordIDs() + { + IPubFile file = new T(); + var record = (U)new U().WithID(1); + + file = file.WithAddedRecord(record); + + var updatedRecord = (U)record.WithName("updated"); + var updatedFile = file.WithInsertedRecord(updatedRecord) + .WithInsertedRecord((U)updatedRecord.WithName("updated 2")) + .WithInsertedRecord((U)updatedRecord.WithName("updated 3")); + + Assert.That(file, Has.Length.EqualTo(1)); + Assert.That(updatedFile, Has.Length.EqualTo(4)); + Assert.That(updatedFile[1], Has.Property("Name").EqualTo("updated 3").And.Property("ID").EqualTo(1)); + Assert.That(updatedFile[2], Has.Property("Name").EqualTo("updated 2").And.Property("ID").EqualTo(2)); + Assert.That(updatedFile[3], Has.Property("Name").EqualTo("updated").And.Property("ID").EqualTo(3)); + Assert.That(updatedFile[4], Has.Property("Name").EqualTo(string.Empty).And.Property("ID").EqualTo(4)); + } + + [Test] + public void WithInsertedRecord_IDOutOfRange_ThrowsArgumentException() + { + IPubFile file = new T(); + var record = (U)new U().WithID(2); + + Assert.That(() => file.WithInsertedRecord(record), Throws.ArgumentException); + } + + [Test] + public void WithUpdatedRecord_UpdatesRecordProperties_ByRecordID() + { + IPubFile file = new T(); + var record = (U)new U().WithID(1); + file = file.WithAddedRecord(record); + + var updatedRecord = (U)record.WithName("Some name"); + var updatedFile = file.WithUpdatedRecord(updatedRecord); + + Assert.That(updatedFile[1].Name, Is.EqualTo("Some name")); + } + + [Test] + public void WithUpdatedRecord_IDOutOfRange_ThrowsArgumentException() + { + IPubFile file = new T(); + var record = (U)new U().WithID(1); + file = file.WithAddedRecord(record); + + Assert.That(() => file.WithUpdatedRecord((U)record.WithID(2)), Throws.ArgumentException); + } + + [Test] + public void WithRemovedRecord_RemovesRecord() + { + var record = (U)new U().WithID(1).WithName("My record"); + + var file = new T().WithAddedRecord(record); + var updatedFile = file.WithRemovedRecord(record); + + Assert.That(updatedFile, Is.Empty); + Assert.That(file, Has.Length.EqualTo(1)); + } + + [Test] + public void WithRemovedRecord_RemovesRecord_UpdatesIDs() + { + var record = (U)new U().WithID(1).WithName("My record"); + var record2 = (U)new U().WithID(2).WithName("My record 2"); + var record3 = (U)new U().WithID(3).WithName("My record 3"); + var record4 = (U)new U().WithID(4).WithName("My record 4"); + + var file = new T().WithAddedRecord(record) + .WithAddedRecord(record2) + .WithAddedRecord(record3) + .WithAddedRecord(record4); + var updatedFile = file.WithRemovedRecord(record); + + Assert.That(file, Has.Length.EqualTo(4)); + Assert.That(updatedFile, Has.Length.EqualTo(3)); + + Assert.That(updatedFile[1].ID, Is.EqualTo(1)); + + Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record2.WithID(1))); + Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record3.WithID(2))); + Assert.That(updatedFile, Has.Exactly(1).Items.EqualTo(record4.WithID(3))); + Assert.That(updatedFile, Has.None.With.Property("ID").EqualTo(4)); + } + + [Test] + public void WithRemovedRecord_IDOutOfrange_ThrowsArgumentException() + { + IPubFile file = new T(); + var record = (U)new U().WithID(1); + file = file.WithAddedRecord(record); + + Assert.That(() => file.WithRemovedRecord((U)record.WithID(2)), Throws.ArgumentException); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ECFFileTest.cs b/EOLib.IO.Test/Pub/ECFFileTest.cs index 4ff8ccf61..62f571cb2 100644 --- a/EOLib.IO.Test/Pub/ECFFileTest.cs +++ b/EOLib.IO.Test/Pub/ECFFileTest.cs @@ -2,14 +2,15 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test.Pub; - -[TestFixture, ExcludeFromCodeCoverage] -public class ECFFileTest +namespace EOLib.IO.Test.Pub { - [Test] - public void HasCorrectFileType() + [TestFixture, ExcludeFromCodeCoverage] + public class ECFFileTest { - Assert.That(new ECFFile().FileType, Is.EqualTo("ECF")); + [Test] + public void HasCorrectFileType() + { + Assert.That(new ECFFile().FileType, Is.EqualTo("ECF")); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ECFRecordTest.cs b/EOLib.IO.Test/Pub/ECFRecordTest.cs index 9174eb636..76566a938 100644 --- a/EOLib.IO.Test/Pub/ECFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ECFRecordTest.cs @@ -4,30 +4,31 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.IO.Test.Pub; - -[TestFixture, ExcludeFromCodeCoverage] -public class ECFRecordTest +namespace EOLib.IO.Test.Pub { - [Test] - public void ECFRecord_HasAllExpectedProperties() + [TestFixture, ExcludeFromCodeCoverage] + public class ECFRecordTest { - var record = new ECFRecord(); + [Test] + public void ECFRecord_HasAllExpectedProperties() + { + var record = new ECFRecord(); - var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) - .Where(x => x.HasFlag(PubRecordProperty.Class)) - .Except(new[] { PubRecordProperty.Class }); + var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) + .Where(x => x.HasFlag(PubRecordProperty.Class)) + .Except(new[] { PubRecordProperty.Class }); - Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); + Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); - foreach (var p in expectedProperties) - Assert.That(record.Bag, Does.ContainKey(p)); - } + foreach (var p in expectedProperties) + Assert.That(record.Bag, Does.ContainKey(p)); + } - [Test] - public void ECFRecord_HasExpectedDataSize() - { - const int ExpectedDataSize = 14; - Assert.That(new ECFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); + [Test] + public void ECFRecord_HasExpectedDataSize() + { + const int ExpectedDataSize = 14; + Assert.That(new ECFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/EIFFileTest.cs b/EOLib.IO.Test/Pub/EIFFileTest.cs index d1e376899..bb2f90cac 100644 --- a/EOLib.IO.Test/Pub/EIFFileTest.cs +++ b/EOLib.IO.Test/Pub/EIFFileTest.cs @@ -2,14 +2,15 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test.Pub; - -[TestFixture, ExcludeFromCodeCoverage] -public class EIFFileTest +namespace EOLib.IO.Test.Pub { - [Test] - public void HasCorrectFileType() + [TestFixture, ExcludeFromCodeCoverage] + public class EIFFileTest { - Assert.That(new EIFFile().FileType, Is.EqualTo("EIF")); + [Test] + public void HasCorrectFileType() + { + Assert.That(new EIFFile().FileType, Is.EqualTo("EIF")); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/EIFRecordTest.cs b/EOLib.IO.Test/Pub/EIFRecordTest.cs index fb15d5f00..e3840beea 100644 --- a/EOLib.IO.Test/Pub/EIFRecordTest.cs +++ b/EOLib.IO.Test/Pub/EIFRecordTest.cs @@ -4,30 +4,31 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.IO.Test.Pub; - -[TestFixture, ExcludeFromCodeCoverage] -public class EIFRecordTest +namespace EOLib.IO.Test.Pub { - [Test] - public void EIFRecord_HasAllExpectedProperties() + [TestFixture, ExcludeFromCodeCoverage] + public class EIFRecordTest { - var record = new EIFRecord(); + [Test] + public void EIFRecord_HasAllExpectedProperties() + { + var record = new EIFRecord(); - var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) - .Where(x => x.HasFlag(PubRecordProperty.Item)) - .Except(new[] { PubRecordProperty.Item }); + var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) + .Where(x => x.HasFlag(PubRecordProperty.Item)) + .Except(new[] { PubRecordProperty.Item }); - Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); + Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); - foreach (var p in expectedProperties) - Assert.That(record.Bag, Does.ContainKey(p)); - } + foreach (var p in expectedProperties) + Assert.That(record.Bag, Does.ContainKey(p)); + } - [Test] - public void EIFRecord_HasExpectedDataSize() - { - const int ExpectedDataSize = 58; - Assert.That(new EIFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); + [Test] + public void EIFRecord_HasExpectedDataSize() + { + const int ExpectedDataSize = 58; + Assert.That(new EIFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ENFFileTest.cs b/EOLib.IO.Test/Pub/ENFFileTest.cs index d1fce9566..89d74be44 100644 --- a/EOLib.IO.Test/Pub/ENFFileTest.cs +++ b/EOLib.IO.Test/Pub/ENFFileTest.cs @@ -2,14 +2,15 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test.Pub; - -[TestFixture, ExcludeFromCodeCoverage] -public class ENFFileTest +namespace EOLib.IO.Test.Pub { - [Test] - public void HasCorrectFileType() + [TestFixture, ExcludeFromCodeCoverage] + public class ENFFileTest { - Assert.That(new ENFFile().FileType, Is.EqualTo("ENF")); + [Test] + public void HasCorrectFileType() + { + Assert.That(new ENFFile().FileType, Is.EqualTo("ENF")); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ENFRecordTest.cs b/EOLib.IO.Test/Pub/ENFRecordTest.cs index acc905143..175effd1c 100644 --- a/EOLib.IO.Test/Pub/ENFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ENFRecordTest.cs @@ -4,30 +4,31 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.IO.Test.Pub; - -[TestFixture, ExcludeFromCodeCoverage] -public class ENFRecordTest +namespace EOLib.IO.Test.Pub { - [Test] - public void ENFRecord_HasAllExpectedProperties() + [TestFixture, ExcludeFromCodeCoverage] + public class ENFRecordTest { - var record = new ENFRecord(); + [Test] + public void ENFRecord_HasAllExpectedProperties() + { + var record = new ENFRecord(); - var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) - .Where(x => x.HasFlag(PubRecordProperty.NPC)) - .Except(new[] { PubRecordProperty.NPC }); + var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) + .Where(x => x.HasFlag(PubRecordProperty.NPC)) + .Except(new[] { PubRecordProperty.NPC }); - Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); + Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); - foreach (var p in expectedProperties) - Assert.That(record.Bag, Does.ContainKey(p)); - } + foreach (var p in expectedProperties) + Assert.That(record.Bag, Does.ContainKey(p)); + } - [Test] - public void ENFRecord_HasExpectedDataSize() - { - const int ExpectedDataSize = 39; - Assert.That(new ENFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); + [Test] + public void ENFRecord_HasExpectedDataSize() + { + const int ExpectedDataSize = 39; + Assert.That(new ENFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ESFFileTest.cs b/EOLib.IO.Test/Pub/ESFFileTest.cs index 317c5f4e3..ec0bfca2d 100644 --- a/EOLib.IO.Test/Pub/ESFFileTest.cs +++ b/EOLib.IO.Test/Pub/ESFFileTest.cs @@ -2,14 +2,15 @@ using NUnit.Framework; using System.Diagnostics.CodeAnalysis; -namespace EOLib.IO.Test.Pub; - -[TestFixture, ExcludeFromCodeCoverage] -public class ESFFileTest +namespace EOLib.IO.Test.Pub { - [Test] - public void HasCorrectFileType() + [TestFixture, ExcludeFromCodeCoverage] + public class ESFFileTest { - Assert.That(new ESFFile().FileType, Is.EqualTo("ESF")); + [Test] + public void HasCorrectFileType() + { + Assert.That(new ESFFile().FileType, Is.EqualTo("ESF")); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Pub/ESFRecordTest.cs b/EOLib.IO.Test/Pub/ESFRecordTest.cs index d75a27bdf..361c8c8b5 100644 --- a/EOLib.IO.Test/Pub/ESFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ESFRecordTest.cs @@ -4,30 +4,31 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; -namespace EOLib.IO.Test.Pub; - -[TestFixture, ExcludeFromCodeCoverage] -public class ESFRecordTest +namespace EOLib.IO.Test.Pub { - [Test] - public void ESFRecord_HasAllExpectedProperties() + [TestFixture, ExcludeFromCodeCoverage] + public class ESFRecordTest { - var record = new ESFRecord(); + [Test] + public void ESFRecord_HasAllExpectedProperties() + { + var record = new ESFRecord(); - var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) - .Where(x => x.HasFlag(PubRecordProperty.Spell)) - .Except(new[] { PubRecordProperty.Spell }); + var expectedProperties = ((PubRecordProperty[])Enum.GetValues(typeof(PubRecordProperty))) + .Where(x => x.HasFlag(PubRecordProperty.Spell)) + .Except(new[] { PubRecordProperty.Spell }); - Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); + Assert.That(record.Bag.Count, Is.EqualTo(expectedProperties.Count())); - foreach (var p in expectedProperties) - Assert.That(record.Bag, Does.ContainKey(p)); - } + foreach (var p in expectedProperties) + Assert.That(record.Bag, Does.ContainKey(p)); + } - [Test] - public void ESFRecord_HasExpectedDataSize() - { - const int ExpectedDataSize = 51; - Assert.That(new ESFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); + [Test] + public void ESFRecord_HasExpectedDataSize() + { + const int ExpectedDataSize = 51; + Assert.That(new ESFRecord().DataSize, Is.EqualTo(ExpectedDataSize)); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs b/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs index 4770995e8..d27c0a779 100644 --- a/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs +++ b/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs @@ -8,135 +8,136 @@ using System.Linq; using System.Text; -namespace EOLib.IO.Test.Services.Serializers; - -[TestFixture] -public class PubFileSerializerTest_EIFImpl : PubFileSerializerTest { } +namespace EOLib.IO.Test.Services.Serializers +{ + [TestFixture] + public class PubFileSerializerTest_EIFImpl : PubFileSerializerTest { } -[TestFixture] -public class PubFileSerializerTest_ENFImpl : PubFileSerializerTest { } + [TestFixture] + public class PubFileSerializerTest_ENFImpl : PubFileSerializerTest { } -[TestFixture] -public class PubFileSerializerTest_ESFImpl : PubFileSerializerTest { } + [TestFixture] + public class PubFileSerializerTest_ESFImpl : PubFileSerializerTest { } -[TestFixture] -public class PubFileSerializerTest_ECFImpl : PubFileSerializerTest { } + [TestFixture] + public class PubFileSerializerTest_ECFImpl : PubFileSerializerTest { } -[ExcludeFromCodeCoverage] -public abstract class PubFileSerializerTest - where T : IPubFile, new() - where U : class, IPubRecord, new() -{ - [Test] - public void DeserializeFromByteArray_WrongLength_Throws() + [ExcludeFromCodeCoverage] + public abstract class PubFileSerializerTest + where T : IPubFile, new() + where U : class, IPubRecord, new() { - const int ExpectedChecksum1 = 12345; - const int ExpectedChecksum2 = 6789; - const int ExpectedLength = 4; + [Test] + public void DeserializeFromByteArray_WrongLength_Throws() + { + const int ExpectedChecksum1 = 12345; + const int ExpectedChecksum2 = 6789; + const int ExpectedLength = 4; + + var expectedChecksum = new List { ExpectedChecksum1, ExpectedChecksum2 }; + + var records = new[] + { + new U().WithID(1).WithName("Rec_1"), + new U().WithID(2).WithName("Rec_2"), + new U().WithID(3).WithName("Rec_3"), + new U().WithID(4).WithName("Rec_4"), + }; + + var pubBytesShort = MakePubFileBytes(expectedChecksum, ExpectedLength - 1, records); + Assert.That(() => CreateSerializer().DeserializeFromByteArray(1, pubBytesShort, () => new T()), Throws.InstanceOf()); + } + + [Test] + public void DeserializeFromByteArray_HasExpectedHeader() + { + const int ExpectedChecksum1 = 12345; + const int ExpectedChecksum2 = 6789; + const int ExpectedLength = 4; - var expectedChecksum = new List { ExpectedChecksum1, ExpectedChecksum2 }; + var expectedChecksum = new List { ExpectedChecksum1, ExpectedChecksum2 }; - var records = new[] - { - new U().WithID(1).WithName("Rec_1"), - new U().WithID(2).WithName("Rec_2"), - new U().WithID(3).WithName("Rec_3"), - new U().WithID(4).WithName("Rec_4"), - }; - - var pubBytesShort = MakePubFileBytes(expectedChecksum, ExpectedLength - 1, records); - Assert.That(() => CreateSerializer().DeserializeFromByteArray(1, pubBytesShort, () => new T()), Throws.InstanceOf()); - } + var records = new[] + { + new U().WithID(1).WithName("Rec_1"), + new U().WithID(2).WithName("Rec_2"), + new U().WithID(3).WithName("Rec_3"), + new U().WithID(4).WithName("Rec_4"), + }; - [Test] - public void DeserializeFromByteArray_HasExpectedHeader() - { - const int ExpectedChecksum1 = 12345; - const int ExpectedChecksum2 = 6789; - const int ExpectedLength = 4; + var pubBytes = MakePubFileBytes(expectedChecksum, ExpectedLength, records); + var file = CreateSerializer().DeserializeFromByteArray(1, pubBytes, () => new T()); - var expectedChecksum = new List { ExpectedChecksum1, ExpectedChecksum2 }; + Assert.That(file.CheckSum, Is.EqualTo(expectedChecksum)); + Assert.That(file.Length, Is.EqualTo(ExpectedLength)); + } - var records = new[] + [Test] + public void SerializeToByteArray_ReturnsExpectedBytes() + { + var expectedBytes = MakePubFileBytes(new List { 5556, 5554 }, + 9, + new U().WithID(1).WithName("TestFixture"), + new U().WithID(2).WithName("Test2"), + new U().WithID(3).WithName("Test3"), + new U().WithID(4).WithName("Test4"), + new U().WithID(5).WithName("Test5"), + new U().WithID(6).WithName("Test6"), + new U().WithID(7).WithName("Test7"), + new U().WithID(8).WithName("Test8"), + new U().WithID(9).WithName("eof")); + + var serializer = CreateSerializer(); + var file = serializer.DeserializeFromByteArray(1, expectedBytes, () => new T()); + + var actualBytes = serializer.SerializeToByteArray(file, rewriteChecksum: false); + + CollectionAssert.AreEqual(expectedBytes, actualBytes); + } + + [Test] + public void DeserializeFromByteArray_HasExpectedIDAndNames() { - new U().WithID(1).WithName("Rec_1"), - new U().WithID(2).WithName("Rec_2"), - new U().WithID(3).WithName("Rec_3"), - new U().WithID(4).WithName("Rec_4"), - }; + var records = new[] + { + new U().WithID(1).WithName("TestFixture"), + new U().WithID(2).WithName("Test2"), + new U().WithID(3).WithName("Test3"), + new U().WithID(4).WithName("Test4"), + new U().WithID(5).WithName("Test5"), + new U().WithID(6).WithName("Test6"), + new U().WithID(7).WithName("Test7"), + new U().WithID(8).WithName("Test8"), + new U().WithID(9).WithName("eof") + }; + var bytes = MakePubFileBytes(new List { 5556, 5554 }, 9, records); + + var serializer = CreateSerializer(); + var file = serializer.DeserializeFromByteArray(1, bytes, () => new T()); + + CollectionAssert.AreEqual(records.Select(x => new { x.ID, x.Name }).ToList(), + file.Select(x => new { x.ID, x.Name }).ToList()); + } + + private byte[] MakePubFileBytes(List checksum, int length, params IPubRecord[] records) + { + var numberEncoderService = new NumberEncoderService(); + var recordSerializer = new PubRecordSerializer(numberEncoderService); - var pubBytes = MakePubFileBytes(expectedChecksum, ExpectedLength, records); - var file = CreateSerializer().DeserializeFromByteArray(1, pubBytes, () => new T()); + var bytes = new List(); + bytes.AddRange(Encoding.ASCII.GetBytes(new T().FileType)); + bytes.AddRange(checksum.SelectMany(x => numberEncoderService.EncodeNumber(x, 2))); + bytes.AddRange(numberEncoderService.EncodeNumber(length, 2)); + bytes.Add(numberEncoderService.EncodeNumber(1, 1)[0]); + foreach (var record in records) + bytes.AddRange(recordSerializer.SerializeToByteArray(record)); - Assert.That(file.CheckSum, Is.EqualTo(expectedChecksum)); - Assert.That(file.Length, Is.EqualTo(ExpectedLength)); - } + return bytes.ToArray(); + } - [Test] - public void SerializeToByteArray_ReturnsExpectedBytes() - { - var expectedBytes = MakePubFileBytes(new List { 5556, 5554 }, - 9, - new U().WithID(1).WithName("TestFixture"), - new U().WithID(2).WithName("Test2"), - new U().WithID(3).WithName("Test3"), - new U().WithID(4).WithName("Test4"), - new U().WithID(5).WithName("Test5"), - new U().WithID(6).WithName("Test6"), - new U().WithID(7).WithName("Test7"), - new U().WithID(8).WithName("Test8"), - new U().WithID(9).WithName("eof")); - - var serializer = CreateSerializer(); - var file = serializer.DeserializeFromByteArray(1, expectedBytes, () => new T()); - - var actualBytes = serializer.SerializeToByteArray(file, rewriteChecksum: false); - - CollectionAssert.AreEqual(expectedBytes, actualBytes); - } - - [Test] - public void DeserializeFromByteArray_HasExpectedIDAndNames() - { - var records = new[] + private static IPubFileSerializer CreateSerializer() { - new U().WithID(1).WithName("TestFixture"), - new U().WithID(2).WithName("Test2"), - new U().WithID(3).WithName("Test3"), - new U().WithID(4).WithName("Test4"), - new U().WithID(5).WithName("Test5"), - new U().WithID(6).WithName("Test6"), - new U().WithID(7).WithName("Test7"), - new U().WithID(8).WithName("Test8"), - new U().WithID(9).WithName("eof") - }; - var bytes = MakePubFileBytes(new List { 5556, 5554 }, 9, records); - - var serializer = CreateSerializer(); - var file = serializer.DeserializeFromByteArray(1, bytes, () => new T()); - - CollectionAssert.AreEqual(records.Select(x => new { x.ID, x.Name }).ToList(), - file.Select(x => new { x.ID, x.Name }).ToList()); - } - - private byte[] MakePubFileBytes(List checksum, int length, params IPubRecord[] records) - { - var numberEncoderService = new NumberEncoderService(); - var recordSerializer = new PubRecordSerializer(numberEncoderService); - - var bytes = new List(); - bytes.AddRange(Encoding.ASCII.GetBytes(new T().FileType)); - bytes.AddRange(checksum.SelectMany(x => numberEncoderService.EncodeNumber(x, 2))); - bytes.AddRange(numberEncoderService.EncodeNumber(length, 2)); - bytes.Add(numberEncoderService.EncodeNumber(1, 1)[0]); - foreach (var record in records) - bytes.AddRange(recordSerializer.SerializeToByteArray(record)); - - return bytes.ToArray(); - } - - private static IPubFileSerializer CreateSerializer() - { - return new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); + return new PubFileSerializer(new NumberEncoderService(), new PubRecordSerializer(new NumberEncoderService())); + } } } \ No newline at end of file diff --git a/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs b/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs index 0a0e4ee35..cc0efb3b0 100644 --- a/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs +++ b/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs @@ -4,58 +4,59 @@ using NUnit.Framework; using System.Collections.Generic; -namespace EOLib.IO.Test.Services.Serializers; - -[TestFixture] -public class PubRecordSerializerTest_EIFRecordImpl : PubRecordSerializerTest { } +namespace EOLib.IO.Test.Services.Serializers +{ + [TestFixture] + public class PubRecordSerializerTest_EIFRecordImpl : PubRecordSerializerTest { } -[TestFixture] -public class PubRecordSerializerTest_ENFRecordImpl : PubRecordSerializerTest { } + [TestFixture] + public class PubRecordSerializerTest_ENFRecordImpl : PubRecordSerializerTest { } -[TestFixture] -public class PubRecordSerializerTest_ESFRecordImpl : PubRecordSerializerTest { } + [TestFixture] + public class PubRecordSerializerTest_ESFRecordImpl : PubRecordSerializerTest { } -[TestFixture] -public class PubRecordSerializerTest_ECFRecordImpl : PubRecordSerializerTest { } + [TestFixture] + public class PubRecordSerializerTest_ECFRecordImpl : PubRecordSerializerTest { } -public abstract class PubRecordSerializerTest - where T : class, IPubRecord, new() -{ - [Test] - public void SerializeAndDeserialize_HasExpectedProperties() + public abstract class PubRecordSerializerTest + where T : class, IPubRecord, new() { - var record = new T(); + [Test] + public void SerializeAndDeserialize_HasExpectedProperties() + { + var record = new T(); - var names = new List(); - for (int nameNdx = 0; nameNdx < record.NumberOfNames; nameNdx++) - names.Add($"name {nameNdx + 1}"); - record = (T)record.WithNames(names); + var names = new List(); + for (int nameNdx = 0; nameNdx < record.NumberOfNames; nameNdx++) + names.Add($"name {nameNdx + 1}"); + record = (T)record.WithNames(names); - int i = 1; - var expectedValues = new List<(PubRecordProperty Key, int Value)>(record.Bag.Count); - var offsets = new HashSet(); - foreach (var property in record.Bag.Keys) - { - // don't overwrite values for duplicate offsets (unions in records) - if (offsets.Contains(record.Bag[property].Offset)) - continue; + int i = 1; + var expectedValues = new List<(PubRecordProperty Key, int Value)>(record.Bag.Count); + var offsets = new HashSet(); + foreach (var property in record.Bag.Keys) + { + // don't overwrite values for duplicate offsets (unions in records) + if (offsets.Contains(record.Bag[property].Offset)) + continue; - offsets.Add(record.Bag[property].Offset); + offsets.Add(record.Bag[property].Offset); - record = (T)record.WithProperty(property, i); - expectedValues.Add((property, i++)); - } + record = (T)record.WithProperty(property, i); + expectedValues.Add((property, i++)); + } - var serializer = Create(); - var bytes = serializer.SerializeToByteArray(record); + var serializer = Create(); + var bytes = serializer.SerializeToByteArray(record); - var loadedRecord = serializer.DeserializeFromByteArray(bytes, () => new T()); + var loadedRecord = serializer.DeserializeFromByteArray(bytes, () => new T()); - Assert.That(record, Is.EqualTo(loadedRecord)); - } + Assert.That(record, Is.EqualTo(loadedRecord)); + } - private static IPubRecordSerializer Create() - { - return new PubRecordSerializer(new NumberEncoderService()); + private static IPubRecordSerializer Create() + { + return new PubRecordSerializer(new NumberEncoderService()); + } } } \ No newline at end of file diff --git a/EOLib.Localization.Test/DataFileLoadActionsTest.cs b/EOLib.Localization.Test/DataFileLoadActionsTest.cs index 92f43c242..ae1b6cb45 100644 --- a/EOLib.Localization.Test/DataFileLoadActionsTest.cs +++ b/EOLib.Localization.Test/DataFileLoadActionsTest.cs @@ -2,76 +2,77 @@ using System.Diagnostics.CodeAnalysis; using System.IO; -namespace EOLib.Localization.Test; - -[TestFixture, ExcludeFromCodeCoverage] -public class DataFileLoadActionsTest +namespace EOLib.Localization.Test { - private IDataFileLoadActions _actions; - private IDataFileRepository _dataFileRepository; - private IEDFLoaderService _edfLoaderService; - - [SetUp] - public void SetUp() + [TestFixture, ExcludeFromCodeCoverage] + public class DataFileLoadActionsTest { - _dataFileRepository = new DataFileRepository(); - _edfLoaderService = new EDFLoaderService(); - _actions = new DataFileLoadActions(_dataFileRepository, _edfLoaderService); - } + private IDataFileLoadActions _actions; + private IDataFileRepository _dataFileRepository; + private IEDFLoaderService _edfLoaderService; - [TearDown] - public void TearDown() - { - if (Directory.Exists(DataFileConstants.DataFilePath)) - Directory.Delete(DataFileConstants.DataFilePath, true); - } + [SetUp] + public void SetUp() + { + _dataFileRepository = new DataFileRepository(); + _edfLoaderService = new EDFLoaderService(); + _actions = new DataFileLoadActions(_dataFileRepository, _edfLoaderService); + } - [Test] - public void GivenMissingDataDirectory_WhenLoadDataFiles_ExpectDataFileLoadException() - { - Assert.Throws(() => _actions.LoadDataFiles()); - } + [TearDown] + public void TearDown() + { + if (Directory.Exists(DataFileConstants.DataFilePath)) + Directory.Delete(DataFileConstants.DataFilePath, true); + } - [Test] - public void GivenIncorrectNumberOfDataFiles_WhenLoadDataFiles_ExpectDataFileLoadException() - { - CreateRequiredDirectory(); - GivenEDFFilesInRequiredDirectory(5, "{0}.edf"); + [Test] + public void GivenMissingDataDirectory_WhenLoadDataFiles_ExpectDataFileLoadException() + { + Assert.Throws(() => _actions.LoadDataFiles()); + } - Assert.Throws(() => _actions.LoadDataFiles()); - } + [Test] + public void GivenIncorrectNumberOfDataFiles_WhenLoadDataFiles_ExpectDataFileLoadException() + { + CreateRequiredDirectory(); + GivenEDFFilesInRequiredDirectory(5, "{0}.edf"); - [Test] - public void WhenLoadDataFiles_DataFilesHaveIncorrectNameFormat_ExpectDataFileLoadException() - { - CreateRequiredDirectory(); - GivenEDFFilesInRequiredDirectory(nameFormat: "{0}.edf"); + Assert.Throws(() => _actions.LoadDataFiles()); + } - Assert.Throws(() => _actions.LoadDataFiles()); - } + [Test] + public void WhenLoadDataFiles_DataFilesHaveIncorrectNameFormat_ExpectDataFileLoadException() + { + CreateRequiredDirectory(); + GivenEDFFilesInRequiredDirectory(nameFormat: "{0}.edf"); - [Test] - public void WhenLoadDataFiles_RepositoryHasExpectedNumberOfFiles() - { - CreateRequiredDirectory(); - GivenEDFFilesInRequiredDirectory(); - _dataFileRepository.DataFiles.Add(DataFiles.Credits, new EDFFile(DataFiles.Credits)); + Assert.Throws(() => _actions.LoadDataFiles()); + } - _actions.LoadDataFiles(); + [Test] + public void WhenLoadDataFiles_RepositoryHasExpectedNumberOfFiles() + { + CreateRequiredDirectory(); + GivenEDFFilesInRequiredDirectory(); + _dataFileRepository.DataFiles.Add(DataFiles.Credits, new EDFFile(DataFiles.Credits)); - Assert.AreEqual(DataFileConstants.ExpectedNumberOfDataFiles, _dataFileRepository.DataFiles.Count); - } + _actions.LoadDataFiles(); - private void CreateRequiredDirectory() - { - if (!Directory.Exists(DataFileConstants.DataFilePath)) - Directory.CreateDirectory(DataFileConstants.DataFilePath); - } + Assert.AreEqual(DataFileConstants.ExpectedNumberOfDataFiles, _dataFileRepository.DataFiles.Count); + } - private void GivenEDFFilesInRequiredDirectory(int numberOfFiles = DataFileConstants.ExpectedNumberOfDataFiles, - string nameFormat = "dat0{0:00}.edf") - { - for (int i = 1; i <= numberOfFiles; ++i) - File.Create(string.Format(Path.Combine(DataFileConstants.DataFilePath, nameFormat), i)).Close(); + private void CreateRequiredDirectory() + { + if (!Directory.Exists(DataFileConstants.DataFilePath)) + Directory.CreateDirectory(DataFileConstants.DataFilePath); + } + + private void GivenEDFFilesInRequiredDirectory(int numberOfFiles = DataFileConstants.ExpectedNumberOfDataFiles, + string nameFormat = "dat0{0:00}.edf") + { + for (int i = 1; i <= numberOfFiles; ++i) + File.Create(string.Format(Path.Combine(DataFileConstants.DataFilePath, nameFormat), i)).Close(); + } } } \ No newline at end of file diff --git a/EOLib.Localization.Test/EDFLoaderServiceTest.cs b/EOLib.Localization.Test/EDFLoaderServiceTest.cs index a3911ee6e..763494618 100644 --- a/EOLib.Localization.Test/EDFLoaderServiceTest.cs +++ b/EOLib.Localization.Test/EDFLoaderServiceTest.cs @@ -5,204 +5,205 @@ using System.IO; using System.Linq; -namespace EOLib.Localization.Test; - -[TestFixture, ExcludeFromCodeCoverage] -public class EDFLoaderServiceTest +namespace EOLib.Localization.Test { - private const string FILE_NAME = "test.edf"; - - private IEDFLoaderService _edfLoaderService; - - [SetUp] - public void SetUp() + [TestFixture, ExcludeFromCodeCoverage] + public class EDFLoaderServiceTest { - _edfLoaderService = new EDFLoaderService(); - } + private const string FILE_NAME = "test.edf"; - public void TearDown() - { - if (File.Exists(FILE_NAME)) - File.Delete(FILE_NAME); - } + private IEDFLoaderService _edfLoaderService; - [Test] - public void GivenNonExistingFile_Load_ExpectFileNotFoundException() - { - Assert.Throws(() => _edfLoaderService.LoadFile("fileThatDoesNotExist", DataFiles.Checksum)); - } + [SetUp] + public void SetUp() + { + _edfLoaderService = new EDFLoaderService(); + } - [Test] - public void GivenCurseFile_DecodeStringDelimitedByColons() - { - const string curseString = "CsusrAs:e5:4C3uErSsReU2C:"; - GivenDataFileWithContents(FILE_NAME, curseString); + public void TearDown() + { + if (File.Exists(FILE_NAME)) + File.Delete(FILE_NAME); + } - var file = _edfLoaderService.LoadFile(FILE_NAME, DataFiles.CurseFilter); + [Test] + public void GivenNonExistingFile_Load_ExpectFileNotFoundException() + { + Assert.Throws(() => _edfLoaderService.LoadFile("fileThatDoesNotExist", DataFiles.Checksum)); + } - var expectedCurses = new[] + [Test] + public void GivenCurseFile_DecodeStringDelimitedByColons() { - "Curse", "Curse2", "CURSE345", "Ass" - }; + const string curseString = "CsusrAs:e5:4C3uErSsReU2C:"; + GivenDataFileWithContents(FILE_NAME, curseString); - CollectionAssert.AreEqual(expectedCurses, file.Data.Values); - } + var file = _edfLoaderService.LoadFile(FILE_NAME, DataFiles.CurseFilter); - [Test] - public void GivenCurseFile_EncodeStringDelimitedByColons() - { - const string ExpectedCurseString = "CsusrAs:e5:4C3uErSsReU2C:"; + var expectedCurses = new[] + { + "Curse", "Curse2", "CURSE345", "Ass" + }; - var curses = new[] { "Curse", "Curse2", "CURSE345", "Ass" }; - var edfFile = new EDFFile(DataFiles.CurseFilter, new Dictionary(curses.Select((x, i) => KeyValuePair.Create(i, x)))); + CollectionAssert.AreEqual(expectedCurses, file.Data.Values); + } - _edfLoaderService.SaveFile(FILE_NAME, edfFile); + [Test] + public void GivenCurseFile_EncodeStringDelimitedByColons() + { + const string ExpectedCurseString = "CsusrAs:e5:4C3uErSsReU2C:"; - AssertFileContent(FILE_NAME, ExpectedCurseString); - } + var curses = new[] { "Curse", "Curse2", "CURSE345", "Ass" }; + var edfFile = new EDFFile(DataFiles.CurseFilter, new Dictionary(curses.Select((x, i) => KeyValuePair.Create(i, x)))); - [Test] - public void GivenCurseFile_DecodeStringDelimitedByColons_HandlesMultipleLines() - { - const string curseString = "CsusrAs:e5:4C3uErSsReU2C:\nARBQCPDOEN:MF:GLHKIJ:"; - GivenDataFileWithContents(FILE_NAME, curseString); + _edfLoaderService.SaveFile(FILE_NAME, edfFile); - var file = _edfLoaderService.LoadFile(FILE_NAME, DataFiles.CurseFilter); + AssertFileContent(FILE_NAME, ExpectedCurseString); + } - var expectedCurses = new[] + [Test] + public void GivenCurseFile_DecodeStringDelimitedByColons_HandlesMultipleLines() { - "Curse", "Curse2", "CURSE345", "Ass", - "ABCDE", "FGHI", "JKL", "MNOPQR" - }; + const string curseString = "CsusrAs:e5:4C3uErSsReU2C:\nARBQCPDOEN:MF:GLHKIJ:"; + GivenDataFileWithContents(FILE_NAME, curseString); - CollectionAssert.AreEqual(expectedCurses, file.Data.Values); - } + var file = _edfLoaderService.LoadFile(FILE_NAME, DataFiles.CurseFilter); - [TestCase(DataFiles.Credits, "Created By\nMe :)\nMe again!")] - [TestCase(DataFiles.Checksum, "218:13:2:176")] - public void GivenUnencodedFile_DoesNotDecodeFileContents_SplitsByLines(DataFiles whichFile, string content) - { - GivenDataFileWithContents(FILE_NAME, content); + var expectedCurses = new[] + { + "Curse", "Curse2", "CURSE345", "Ass", + "ABCDE", "FGHI", "JKL", "MNOPQR" + }; - var file = _edfLoaderService.LoadFile(FILE_NAME, whichFile); + CollectionAssert.AreEqual(expectedCurses, file.Data.Values); + } - var expectedLines = content.Split('\n'); - CollectionAssert.AreEqual(expectedLines, file.Data.Values); - } + [TestCase(DataFiles.Credits, "Created By\nMe :)\nMe again!")] + [TestCase(DataFiles.Checksum, "218:13:2:176")] + public void GivenUnencodedFile_DoesNotDecodeFileContents_SplitsByLines(DataFiles whichFile, string content) + { + GivenDataFileWithContents(FILE_NAME, content); - [TestCase(DataFiles.Credits, new[] { "Created By", "Me :)", "Me again!" })] - [TestCase(DataFiles.Checksum, new[] { "218:13:2:176" })] - public void GivenUnencodedFile_DoesNotEncodeFileContents_SplitsByDataKeys(DataFiles whichFile, string[] content) - { - var edfFile = new EDFFile(whichFile, new Dictionary(content.Select((x, i) => KeyValuePair.Create(i, x)))); + var file = _edfLoaderService.LoadFile(FILE_NAME, whichFile); - _edfLoaderService.SaveFile(FILE_NAME, edfFile); + var expectedLines = content.Split('\n'); + CollectionAssert.AreEqual(expectedLines, file.Data.Values); + } - AssertFileContent(FILE_NAME, string.Join(Environment.NewLine, content)); - } + [TestCase(DataFiles.Credits, new[] { "Created By", "Me :)", "Me again!" })] + [TestCase(DataFiles.Checksum, new[] { "218:13:2:176" })] + public void GivenUnencodedFile_DoesNotEncodeFileContents_SplitsByDataKeys(DataFiles whichFile, string[] content) + { + var edfFile = new EDFFile(whichFile, new Dictionary(content.Select((x, i) => KeyValuePair.Create(i, x)))); - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_AreDecodedCorrectly(DataFiles whichFile) - { - const string fileData = "a7b6cg1f2e3d4 5"; - const string expectedString = "abc12345 defg67"; + _edfLoaderService.SaveFile(FILE_NAME, edfFile); - GivenDataFileWithContents(FILE_NAME, fileData); + AssertFileContent(FILE_NAME, string.Join(Environment.NewLine, content)); + } - var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); - Assert.AreEqual(expectedString, edf.Data.Values.Single()); - } + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_AreDecodedCorrectly(DataFiles whichFile) + { + const string fileData = "a7b6cg1f2e3d4 5"; + const string expectedString = "abc12345 defg67"; - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_AreDecodedCorrectly_MultipleLines(DataFiles whichFile) - { - const string fileData = "a7b6cg1f2e3d4 5\na7b6cg1f2e3d4 5"; - var expectedStrings = new[] { "abc12345 defg67", "abc12345 defg67" }; + GivenDataFileWithContents(FILE_NAME, fileData); - GivenDataFileWithContents(FILE_NAME, fileData); + var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); + Assert.AreEqual(expectedString, edf.Data.Values.Single()); + } - var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); - CollectionAssert.AreEqual(expectedStrings, edf.Data.Values); - } + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_AreDecodedCorrectly_MultipleLines(DataFiles whichFile) + { + const string fileData = "a7b6cg1f2e3d4 5\na7b6cg1f2e3d4 5"; + var expectedStrings = new[] { "abc12345 defg67", "abc12345 defg67" }; - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_Decode_SwapAdjacentCharacterValues_MultiplesOfSeven(DataFiles whichFile) - { - //p, p, and i are adjacent multiples of 7 in this example - //see https://eoserv.net/wiki/EDF_Data_Files for more info - //the expected string would be Crazy steippng without this step - const string fileData = "Cgrnapzpyi est"; - var expectedString = "Crazy stepping"; + GivenDataFileWithContents(FILE_NAME, fileData); - GivenDataFileWithContents(FILE_NAME, fileData); + var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); + CollectionAssert.AreEqual(expectedStrings, edf.Data.Values); + } - var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); - Assert.AreEqual(expectedString, edf.Data.Values.Single()); - } + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_Decode_SwapAdjacentCharacterValues_MultiplesOfSeven(DataFiles whichFile) + { + //p, p, and i are adjacent multiples of 7 in this example + //see https://eoserv.net/wiki/EDF_Data_Files for more info + //the expected string would be Crazy steippng without this step + const string fileData = "Cgrnapzpyi est"; + var expectedString = "Crazy stepping"; - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_AreEncodedCorrectly(DataFiles whichFile) - { - const string ExpectedFileData = "a7b6cg1f2e3d4 5"; + GivenDataFileWithContents(FILE_NAME, fileData); - const string Input = "abc12345 defg67"; - var edfFile = new EDFFile(whichFile, new Dictionary { { 0, Input } }); + var edf = _edfLoaderService.LoadFile(FILE_NAME, whichFile); + Assert.AreEqual(expectedString, edf.Data.Values.Single()); + } - _edfLoaderService.SaveFile(FILE_NAME, edfFile); + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_AreEncodedCorrectly(DataFiles whichFile) + { + const string ExpectedFileData = "a7b6cg1f2e3d4 5"; - AssertFileContent(FILE_NAME, ExpectedFileData); - } + const string Input = "abc12345 defg67"; + var edfFile = new EDFFile(whichFile, new Dictionary { { 0, Input } }); - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_AreEncodedCorrectly_MultipleLines(DataFiles whichFile) - { - var expectedFileData = $"a7b6cg1f2e3d4 5{Environment.NewLine}a7b6cg1f2e3d4 5"; + _edfLoaderService.SaveFile(FILE_NAME, edfFile); - var decodedStrings = new Dictionary { { 0, "abc12345 defg67" }, { 1, "abc12345 defg67" } }; - var edfFile = new EDFFile(whichFile, decodedStrings); + AssertFileContent(FILE_NAME, ExpectedFileData); + } - _edfLoaderService.SaveFile(FILE_NAME, edfFile); + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_AreEncodedCorrectly_MultipleLines(DataFiles whichFile) + { + var expectedFileData = $"a7b6cg1f2e3d4 5{Environment.NewLine}a7b6cg1f2e3d4 5"; - AssertFileContent(FILE_NAME, expectedFileData); - } + var decodedStrings = new Dictionary { { 0, "abc12345 defg67" }, { 1, "abc12345 defg67" } }; + var edfFile = new EDFFile(whichFile, decodedStrings); - [TestCaseSource(nameof(GetStandardEDFFiles))] - public void NonSpecialDataFiles_Encode_SwapAdjacentCharacterValues_MultiplesOfSeven(DataFiles whichFile) - { - const string ExpectedFileData = "Cgrnapzpyi est"; + _edfLoaderService.SaveFile(FILE_NAME, edfFile); - const string Input = "Crazy stepping"; - var edfFile = new EDFFile(whichFile, new Dictionary { { 0, Input } }); + AssertFileContent(FILE_NAME, expectedFileData); + } - _edfLoaderService.SaveFile(FILE_NAME, edfFile); + [TestCaseSource(nameof(GetStandardEDFFiles))] + public void NonSpecialDataFiles_Encode_SwapAdjacentCharacterValues_MultiplesOfSeven(DataFiles whichFile) + { + const string ExpectedFileData = "Cgrnapzpyi est"; - AssertFileContent(FILE_NAME, ExpectedFileData); - } + const string Input = "Crazy stepping"; + var edfFile = new EDFFile(whichFile, new Dictionary { { 0, Input } }); - public static DataFiles[] GetStandardEDFFiles() - { - return new[] - { - DataFiles.JukeBoxSongs, - DataFiles.EnglishStatus1, - DataFiles.EnglishStatus2, - DataFiles.DutchStatus1, - DataFiles.DutchStatus2, - DataFiles.SwedishStatus1, - DataFiles.SwedishStatus2, - DataFiles.PortugueseStatus1, - DataFiles.PortugueseStatus2 - }; - } + _edfLoaderService.SaveFile(FILE_NAME, edfFile); - private void GivenDataFileWithContents(string fileName, string fileData) - { - File.WriteAllText(fileName, fileData); - } + AssertFileContent(FILE_NAME, ExpectedFileData); + } - private void AssertFileContent(string fileName, string fileData) - { - var text = File.ReadAllText(fileName).Trim(); - Assert.That(text, Is.EqualTo(fileData)); + public static DataFiles[] GetStandardEDFFiles() + { + return new[] + { + DataFiles.JukeBoxSongs, + DataFiles.EnglishStatus1, + DataFiles.EnglishStatus2, + DataFiles.DutchStatus1, + DataFiles.DutchStatus2, + DataFiles.SwedishStatus1, + DataFiles.SwedishStatus2, + DataFiles.PortugueseStatus1, + DataFiles.PortugueseStatus2 + }; + } + + private void GivenDataFileWithContents(string fileName, string fileData) + { + File.WriteAllText(fileName, fileData); + } + + private void AssertFileContent(string fileName, string fileData) + { + var text = File.ReadAllText(fileName).Trim(); + Assert.That(text, Is.EqualTo(fileData)); + } } } \ No newline at end of file diff --git a/EOLib.Localization.Test/LocalizedStringServiceTest.cs b/EOLib.Localization.Test/LocalizedStringServiceTest.cs index ada9ede7a..389b1ef31 100644 --- a/EOLib.Localization.Test/LocalizedStringServiceTest.cs +++ b/EOLib.Localization.Test/LocalizedStringServiceTest.cs @@ -5,129 +5,130 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -namespace EOLib.Localization.Test; - -[TestFixture, ExcludeFromCodeCoverage] -public class LocalizedStringFinderTest +namespace EOLib.Localization.Test { - private IConfigurationProvider _configurationProvider; - private DataFileRepository _dataFileRepository; - - private ILocalizedStringFinder _localizedStringFinder; - - [SetUp] - public void SetUp() - { - _configurationProvider = Mock.Of(); - _dataFileRepository = new DataFileRepository(); - - _localizedStringFinder = new LocalizedStringFinder( - _configurationProvider, - _dataFileRepository); - } - - [Test] - public void GetString_Dialog_InvalidLanguage_ThrowsArgumentOutOfRangeException() - { - Assert.Throws(() => _localizedStringFinder.GetString((EOLanguage)50, DialogResourceID.ACCOUNT_CREATE_ACCEPTED)); - } - - [Test] - public void GetString_Resource_InvalidLanguage_ThrowsArgumentOutOfRangeException() - { - Assert.Throws(() => _localizedStringFinder.GetString((EOLanguage)50, EOResourceID.STRING_SERVER)); - } - - [Test] - public void GetString_DialogID_ByLanguage_MapsToCorrectFile() - { - const DialogResourceID testID = DialogResourceID.ACCOUNT_CREATE_ACCEPTED; - - GivenFileHasStringForResourceID(DataFiles.DutchStatus1, testID, "dutch"); - GivenFileHasStringForResourceID(DataFiles.EnglishStatus1, testID, "english"); - GivenFileHasStringForResourceID(DataFiles.PortugueseStatus1, testID, "portuguese"); - GivenFileHasStringForResourceID(DataFiles.SwedishStatus1, testID, "swedish"); - - var dutchActual = _localizedStringFinder.GetString(EOLanguage.Dutch, testID); - var englishActual = _localizedStringFinder.GetString(EOLanguage.English, testID); - var portugueseActual = _localizedStringFinder.GetString(EOLanguage.Portuguese, testID); - var swedishActual = _localizedStringFinder.GetString(EOLanguage.Swedish, testID); - - Assert.AreEqual("dutch", dutchActual); - Assert.AreEqual("english", englishActual); - Assert.AreEqual("portuguese", portugueseActual); - Assert.AreEqual("swedish", swedishActual); - } - - [Test] - public void GetString_ResourceID_ByLanguage_MapsToCorrectFile() - { - const EOResourceID testID = EOResourceID.STATUS_LABEL_YOU_GAINED_EXP; - - GivenFileHasStringForResourceID(DataFiles.DutchStatus2, testID, "dutch"); - GivenFileHasStringForResourceID(DataFiles.EnglishStatus2, testID, "english"); - GivenFileHasStringForResourceID(DataFiles.PortugueseStatus2, testID, "portuguese"); - GivenFileHasStringForResourceID(DataFiles.SwedishStatus2, testID, "swedish"); - - var dutchActual = _localizedStringFinder.GetString(EOLanguage.Dutch, testID); - var englishActual = _localizedStringFinder.GetString(EOLanguage.English, testID); - var portugueseActual = _localizedStringFinder.GetString(EOLanguage.Portuguese, testID); - var swedishActual = _localizedStringFinder.GetString(EOLanguage.Swedish, testID); - - Assert.AreEqual("dutch", dutchActual); - Assert.AreEqual("english", englishActual); - Assert.AreEqual("portuguese", portugueseActual); - Assert.AreEqual("swedish", swedishActual); - } - - [Test] - public void GetString_DialogID_UsesLanguageSetInConfig() - { - const DialogResourceID testID = DialogResourceID.ACCOUNT_CREATE_ACCEPTED; - const string expectedResourceString = "language test"; - - GivenLanguageSetInConfig(EOLanguage.Dutch); - GivenFileHasStringForResourceID(DataFiles.DutchStatus1, testID, expectedResourceString); - - var actualString = _localizedStringFinder.GetString(testID); - - Assert.AreEqual(expectedResourceString, actualString); - } - - [Test] - public void GetString_ResourceID_UsesLanguageSetInConfig() - { - const EOResourceID testID = EOResourceID.STRING_SERVER; - const string expectedResourceString = "language test"; - - GivenLanguageSetInConfig(EOLanguage.Dutch); - GivenFileHasStringForResourceID(DataFiles.DutchStatus2, testID, expectedResourceString); - - var actualString = _localizedStringFinder.GetString(testID); - - Assert.AreEqual(expectedResourceString, actualString); - } - - private void GivenFileHasStringForResourceID(DataFiles file, DialogResourceID id, string str) - { - if (!_dataFileRepository.DataFiles.ContainsKey(file)) - _dataFileRepository.DataFiles.Add(file, new EDFFile(file)); - - _dataFileRepository.DataFiles[file] = _dataFileRepository.DataFiles[file].WithDataEntry((int)id, str); - } - - private void GivenFileHasStringForResourceID(DataFiles file, EOResourceID id, string str) - { - if (!_dataFileRepository.DataFiles.ContainsKey(file)) - _dataFileRepository.DataFiles.Add(file, new EDFFile(file)); - - _dataFileRepository.DataFiles[file] = _dataFileRepository.DataFiles[file].WithDataEntry((int)id, str); - } - - private void GivenLanguageSetInConfig(EOLanguage language) + [TestFixture, ExcludeFromCodeCoverage] + public class LocalizedStringFinderTest { - Mock.Get(_configurationProvider) - .Setup(x => x.Language) - .Returns(language); + private IConfigurationProvider _configurationProvider; + private DataFileRepository _dataFileRepository; + + private ILocalizedStringFinder _localizedStringFinder; + + [SetUp] + public void SetUp() + { + _configurationProvider = Mock.Of(); + _dataFileRepository = new DataFileRepository(); + + _localizedStringFinder = new LocalizedStringFinder( + _configurationProvider, + _dataFileRepository); + } + + [Test] + public void GetString_Dialog_InvalidLanguage_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => _localizedStringFinder.GetString((EOLanguage)50, DialogResourceID.ACCOUNT_CREATE_ACCEPTED)); + } + + [Test] + public void GetString_Resource_InvalidLanguage_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => _localizedStringFinder.GetString((EOLanguage)50, EOResourceID.STRING_SERVER)); + } + + [Test] + public void GetString_DialogID_ByLanguage_MapsToCorrectFile() + { + const DialogResourceID testID = DialogResourceID.ACCOUNT_CREATE_ACCEPTED; + + GivenFileHasStringForResourceID(DataFiles.DutchStatus1, testID, "dutch"); + GivenFileHasStringForResourceID(DataFiles.EnglishStatus1, testID, "english"); + GivenFileHasStringForResourceID(DataFiles.PortugueseStatus1, testID, "portuguese"); + GivenFileHasStringForResourceID(DataFiles.SwedishStatus1, testID, "swedish"); + + var dutchActual = _localizedStringFinder.GetString(EOLanguage.Dutch, testID); + var englishActual = _localizedStringFinder.GetString(EOLanguage.English, testID); + var portugueseActual = _localizedStringFinder.GetString(EOLanguage.Portuguese, testID); + var swedishActual = _localizedStringFinder.GetString(EOLanguage.Swedish, testID); + + Assert.AreEqual("dutch", dutchActual); + Assert.AreEqual("english", englishActual); + Assert.AreEqual("portuguese", portugueseActual); + Assert.AreEqual("swedish", swedishActual); + } + + [Test] + public void GetString_ResourceID_ByLanguage_MapsToCorrectFile() + { + const EOResourceID testID = EOResourceID.STATUS_LABEL_YOU_GAINED_EXP; + + GivenFileHasStringForResourceID(DataFiles.DutchStatus2, testID, "dutch"); + GivenFileHasStringForResourceID(DataFiles.EnglishStatus2, testID, "english"); + GivenFileHasStringForResourceID(DataFiles.PortugueseStatus2, testID, "portuguese"); + GivenFileHasStringForResourceID(DataFiles.SwedishStatus2, testID, "swedish"); + + var dutchActual = _localizedStringFinder.GetString(EOLanguage.Dutch, testID); + var englishActual = _localizedStringFinder.GetString(EOLanguage.English, testID); + var portugueseActual = _localizedStringFinder.GetString(EOLanguage.Portuguese, testID); + var swedishActual = _localizedStringFinder.GetString(EOLanguage.Swedish, testID); + + Assert.AreEqual("dutch", dutchActual); + Assert.AreEqual("english", englishActual); + Assert.AreEqual("portuguese", portugueseActual); + Assert.AreEqual("swedish", swedishActual); + } + + [Test] + public void GetString_DialogID_UsesLanguageSetInConfig() + { + const DialogResourceID testID = DialogResourceID.ACCOUNT_CREATE_ACCEPTED; + const string expectedResourceString = "language test"; + + GivenLanguageSetInConfig(EOLanguage.Dutch); + GivenFileHasStringForResourceID(DataFiles.DutchStatus1, testID, expectedResourceString); + + var actualString = _localizedStringFinder.GetString(testID); + + Assert.AreEqual(expectedResourceString, actualString); + } + + [Test] + public void GetString_ResourceID_UsesLanguageSetInConfig() + { + const EOResourceID testID = EOResourceID.STRING_SERVER; + const string expectedResourceString = "language test"; + + GivenLanguageSetInConfig(EOLanguage.Dutch); + GivenFileHasStringForResourceID(DataFiles.DutchStatus2, testID, expectedResourceString); + + var actualString = _localizedStringFinder.GetString(testID); + + Assert.AreEqual(expectedResourceString, actualString); + } + + private void GivenFileHasStringForResourceID(DataFiles file, DialogResourceID id, string str) + { + if (!_dataFileRepository.DataFiles.ContainsKey(file)) + _dataFileRepository.DataFiles.Add(file, new EDFFile(file)); + + _dataFileRepository.DataFiles[file] = _dataFileRepository.DataFiles[file].WithDataEntry((int)id, str); + } + + private void GivenFileHasStringForResourceID(DataFiles file, EOResourceID id, string str) + { + if (!_dataFileRepository.DataFiles.ContainsKey(file)) + _dataFileRepository.DataFiles.Add(file, new EDFFile(file)); + + _dataFileRepository.DataFiles[file] = _dataFileRepository.DataFiles[file].WithDataEntry((int)id, str); + } + + private void GivenLanguageSetInConfig(EOLanguage language) + { + Mock.Get(_configurationProvider) + .Setup(x => x.Language) + .Returns(language); + } } } \ No newline at end of file diff --git a/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs b/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs index 0a2d76fc0..390f36ff0 100644 --- a/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs +++ b/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs @@ -19,262 +19,263 @@ using System.Linq; using System.Text; -namespace EOLib.Test.Net.FileTransfer; - -[TestFixture, ExcludeFromCodeCoverage] -public class FileRequestServiceTest +namespace EOLib.Test.Net.FileTransfer { - private IFileRequestService _fileRequestService; + [TestFixture, ExcludeFromCodeCoverage] + public class FileRequestServiceTest + { + private IFileRequestService _fileRequestService; - private IPacketSendService _packetSendService; - private INumberEncoderService _numberEncoderService; - private IMapDeserializer _mapFileSerializer; - private IPubFileDeserializer _pubFileDeserializer; + private IPacketSendService _packetSendService; + private INumberEncoderService _numberEncoderService; + private IMapDeserializer _mapFileSerializer; + private IPubFileDeserializer _pubFileDeserializer; - [SetUp] - public void SetUp() - { - _packetSendService = Mock.Of(); - _numberEncoderService = new NumberEncoderService(); - _mapFileSerializer = Mock.Of>(); - _pubFileDeserializer = Mock.Of(); - - _fileRequestService = new FileRequestService(_packetSendService, - _mapFileSerializer, - _pubFileDeserializer); - } + [SetUp] + public void SetUp() + { + _packetSendService = Mock.Of(); + _numberEncoderService = new NumberEncoderService(); + _mapFileSerializer = Mock.Of>(); + _pubFileDeserializer = Mock.Of(); + + _fileRequestService = new FileRequestService(_packetSendService, + _mapFileSerializer, + _pubFileDeserializer); + } - #region RequestFile Tests + #region RequestFile Tests - [Test] - public void RequestFile_ResponsePacketHasInvalidHeader_ThrowsEmptyPacketReceivedException() - { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(); - Assert.ThrowsAsync(async () => await _fileRequestService.RequestFile(FileType.Eif, 1)); - } + [Test] + public void RequestFile_ResponsePacketHasInvalidHeader_ThrowsEmptyPacketReceivedException() + { + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(); + Assert.ThrowsAsync(async () => await _fileRequestService.RequestFile(FileType.Eif, 1)); + } - [Test] - public void RequestFile_ResponsePacketInvalidExtraByte_ThrowsMalformedPacketException() - { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader((byte)InitReply.FileEif, 33); - Assert.ThrowsAsync(async () => await _fileRequestService.RequestFile(FileType.Eif, 1)); - } + [Test] + public void RequestFile_ResponsePacketInvalidExtraByte_ThrowsMalformedPacketException() + { + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader((byte)InitReply.FileEif, 33); + Assert.ThrowsAsync(async () => await _fileRequestService.RequestFile(FileType.Eif, 1)); + } - [Test] - public void RequestFile_SendsPacket_BasedOnSpecifiedType() - { - var types = new[] { FileType.Eif, FileType.Enf, FileType.Esf, FileType.Ecf }; - foreach (var type in types) + [Test] + public void RequestFile_SendsPacket_BasedOnSpecifiedType() { - var packetIsCorrect = false; - var localType = type; - Mock.Get(_packetSendService).Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) - .Callback((IPacket packet) => packetIsCorrect = IsCorrectFileRequestPacket(packet, localType)); + var types = new[] { FileType.Eif, FileType.Enf, FileType.Esf, FileType.Ecf }; + foreach (var type in types) + { + var packetIsCorrect = false; + var localType = type; + Mock.Get(_packetSendService).Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) + .Callback((IPacket packet) => packetIsCorrect = IsCorrectFileRequestPacket(packet, localType)); - _fileRequestService.RequestFile(type, 1); + _fileRequestService.RequestFile(type, 1); - Assert.IsTrue(packetIsCorrect, "Incorrect packet for {0}", type); + Assert.IsTrue(packetIsCorrect, "Incorrect packet for {0}", type); + } } - } - [Test] - public void RequestFile_CorrectResponse_ExecutesWithoutFault() - { - var types = new[] { FileType.Eif, FileType.Enf, FileType.Esf, FileType.Ecf }; - foreach (var type in types) + [Test] + public void RequestFile_CorrectResponse_ExecutesWithoutFault() { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(CreateFilePacket(type)); - - AggregateException aggEx = null; - switch (type) + var types = new[] { FileType.Eif, FileType.Enf, FileType.Esf, FileType.Ecf }; + foreach (var type in types) { - case FileType.Eif: - Mock.Get(_pubFileDeserializer) - .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) - .Returns(new EIFFile()); - aggEx = _fileRequestService.RequestFile(type, 1).Exception; - break; - case FileType.Enf: - Mock.Get(_pubFileDeserializer) - .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) - .Returns(new ENFFile()); - aggEx = _fileRequestService.RequestFile(type, 1).Exception; - break; - case FileType.Esf: - Mock.Get(_pubFileDeserializer) - .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) - .Returns(new ESFFile()); - aggEx = _fileRequestService.RequestFile(type, 1).Exception; - break; - case FileType.Ecf: - Mock.Get(_pubFileDeserializer) - .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) - .Returns(new ECFFile()); - aggEx = _fileRequestService.RequestFile(type, 1).Exception; - break; - } + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(CreateFilePacket(type)); - if (aggEx != null) - throw aggEx.InnerException; + AggregateException aggEx = null; + switch (type) + { + case FileType.Eif: + Mock.Get(_pubFileDeserializer) + .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) + .Returns(new EIFFile()); + aggEx = _fileRequestService.RequestFile(type, 1).Exception; + break; + case FileType.Enf: + Mock.Get(_pubFileDeserializer) + .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) + .Returns(new ENFFile()); + aggEx = _fileRequestService.RequestFile(type, 1).Exception; + break; + case FileType.Esf: + Mock.Get(_pubFileDeserializer) + .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) + .Returns(new ESFFile()); + aggEx = _fileRequestService.RequestFile(type, 1).Exception; + break; + case FileType.Ecf: + Mock.Get(_pubFileDeserializer) + .Setup(x => x.DeserializeFromByteArray(1, It.IsAny(), It.IsAny>>())) + .Returns(new ECFFile()); + aggEx = _fileRequestService.RequestFile(type, 1).Exception; + break; + } + + if (aggEx != null) + throw aggEx.InnerException; + } } - } - #endregion + #endregion - #region RequestMapFile Tests + #region RequestMapFile Tests - [Test] - public void RequestMapFile_ResponsePacketHasInvalidHeader_ThrowsEmptyPacketReceivedException() - { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(); - Assert.ThrowsAsync(async () => await _fileRequestService.RequestMapFile(1, 1)); - } - - [Test] - public void RequestMapFile_ResponsePacketHasIncorrectFileType_ThrowsMalformedPacketException() - { - Mock.Get(_packetSendService).SetupReceivedPacketHasHeader((byte)InitReply.FileEsf, 33); - Assert.ThrowsAsync(async () => await _fileRequestService.RequestMapFile(1, 1)); - } + [Test] + public void RequestMapFile_ResponsePacketHasInvalidHeader_ThrowsEmptyPacketReceivedException() + { + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader(); + Assert.ThrowsAsync(async () => await _fileRequestService.RequestMapFile(1, 1)); + } - [Test] - public void RequestMapFile_SendsPacket_BasedOnSpecifiedMap() - { - var packetIsCorrect = false; - Mock.Get(_packetSendService).Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())).Callback((IPacket packet) => packetIsCorrect = IsCorrectFileRequestPacket(packet, FileType.Emf)); + [Test] + public void RequestMapFile_ResponsePacketHasIncorrectFileType_ThrowsMalformedPacketException() + { + Mock.Get(_packetSendService).SetupReceivedPacketHasHeader((byte)InitReply.FileEsf, 33); + Assert.ThrowsAsync(async () => await _fileRequestService.RequestMapFile(1, 1)); + } - _fileRequestService.RequestMapFile(1, 1); + [Test] + public void RequestMapFile_SendsPacket_BasedOnSpecifiedMap() + { + var packetIsCorrect = false; + Mock.Get(_packetSendService).Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())).Callback((IPacket packet) => packetIsCorrect = IsCorrectFileRequestPacket(packet, FileType.Emf)); - Assert.That(packetIsCorrect, Is.True); - } + _fileRequestService.RequestMapFile(1, 1); - [Test] - public void RequestMapFile_HasPlayerAndMapID() - { - const short PlayerID = 1234; - const short MapID = 333; + Assert.That(packetIsCorrect, Is.True); + } - var packetIsCorrect = false; - Mock.Get(_packetSendService) - .Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) - .Callback((IPacket p) => packetIsCorrect = IsCorrectFileRequestPacket(p, FileType.Emf, PlayerID, MapID)); + [Test] + public void RequestMapFile_HasPlayerAndMapID() + { + const short PlayerID = 1234; + const short MapID = 333; - _fileRequestService.RequestMapFile(MapID, PlayerID); + var packetIsCorrect = false; + Mock.Get(_packetSendService) + .Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) + .Callback((IPacket p) => packetIsCorrect = IsCorrectFileRequestPacket(p, FileType.Emf, PlayerID, MapID)); - Assert.That(packetIsCorrect, Is.True); - } + _fileRequestService.RequestMapFile(MapID, PlayerID); - #endregion + Assert.That(packetIsCorrect, Is.True); + } - #region Helper Methods + #endregion - private static bool IsCorrectFileRequestPacket(IPacket packet, FileType type, short sessionId = 0, short mapId = 0) - { - var waPacket = packet as WelcomeAgreeClientPacket; - var correctTyping = waPacket.FileType == type; + #region Helper Methods - var correctData = true; - if (mapId > 0 && sessionId > 0) + private static bool IsCorrectFileRequestPacket(IPacket packet, FileType type, short sessionId = 0, short mapId = 0) { - var emfData = waPacket.FileTypeData as WelcomeAgreeClientPacket.FileTypeDataEmf; - correctData = emfData.FileId == mapId && waPacket.SessionId == sessionId; - } - - return correctTyping && correctData; - } + var waPacket = packet as WelcomeAgreeClientPacket; + var correctTyping = waPacket.FileType == type; - private static byte[] CreateFilePacket(FileType type) - { - var ret = new InitInitServerPacket(); + var correctData = true; + if (mapId > 0 && sessionId > 0) + { + var emfData = waPacket.FileTypeData as WelcomeAgreeClientPacket.FileTypeDataEmf; + correctData = emfData.FileId == mapId && waPacket.SessionId == sessionId; + } - var nes = new NumberEncoderService(); - var rs = new PubRecordSerializer(nes); + return correctTyping && correctData; + } - var eoWriter = new EoWriter(); - switch (type) + private static byte[] CreateFilePacket(FileType type) { - case FileType.Eif: - ret.ReplyCode = InitReply.FileEif; + var ret = new InitInitServerPacket(); - eoWriter.AddString("EIF"); - eoWriter.AddInt(1); // RID - eoWriter.AddShort(2); // length - eoWriter.AddByte(1); // version - eoWriter.AddBytes(rs.SerializeToByteArray(new EIFRecord().WithID(1).WithName("Test1"))); - eoWriter.AddBytes(rs.SerializeToByteArray(new EIFRecord().WithID(2).WithName("eof"))); + var nes = new NumberEncoderService(); + var rs = new PubRecordSerializer(nes); - ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEif - { - PubFile = new PubFile + var eoWriter = new EoWriter(); + switch (type) + { + case FileType.Eif: + ret.ReplyCode = InitReply.FileEif; + + eoWriter.AddString("EIF"); + eoWriter.AddInt(1); // RID + eoWriter.AddShort(2); // length + eoWriter.AddByte(1); // version + eoWriter.AddBytes(rs.SerializeToByteArray(new EIFRecord().WithID(1).WithName("Test1"))); + eoWriter.AddBytes(rs.SerializeToByteArray(new EIFRecord().WithID(2).WithName("eof"))); + + ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEif { - FileId = 1, - Content = eoWriter.ToByteArray() - } - }; - break; - case FileType.Enf: - ret.ReplyCode = InitReply.FileEnf; - - eoWriter.AddString("ENF"); - eoWriter.AddInt(1); // RID - eoWriter.AddShort(2); // length - eoWriter.AddByte(1); // version - eoWriter.AddBytes(rs.SerializeToByteArray(new ENFRecord().WithID(1).WithName("Test1"))); - eoWriter.AddBytes(rs.SerializeToByteArray(new ENFRecord().WithID(2).WithName("eof"))); - - ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEnf - { - PubFile = new PubFile + PubFile = new PubFile + { + FileId = 1, + Content = eoWriter.ToByteArray() + } + }; + break; + case FileType.Enf: + ret.ReplyCode = InitReply.FileEnf; + + eoWriter.AddString("ENF"); + eoWriter.AddInt(1); // RID + eoWriter.AddShort(2); // length + eoWriter.AddByte(1); // version + eoWriter.AddBytes(rs.SerializeToByteArray(new ENFRecord().WithID(1).WithName("Test1"))); + eoWriter.AddBytes(rs.SerializeToByteArray(new ENFRecord().WithID(2).WithName("eof"))); + + ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEnf { - FileId = 1, - Content = eoWriter.ToByteArray() - } - }; - break; - case FileType.Esf: - ret.ReplyCode = InitReply.FileEsf; - - eoWriter.AddString("ESF"); - eoWriter.AddInt(1); // RID - eoWriter.AddShort(2); // length - eoWriter.AddByte(1); // version - eoWriter.AddBytes(rs.SerializeToByteArray(new ESFRecord().WithID(1).WithName("Test1"))); - eoWriter.AddBytes(rs.SerializeToByteArray(new ESFRecord().WithID(2).WithName("eof"))); - - ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEsf - { - PubFile = new PubFile + PubFile = new PubFile + { + FileId = 1, + Content = eoWriter.ToByteArray() + } + }; + break; + case FileType.Esf: + ret.ReplyCode = InitReply.FileEsf; + + eoWriter.AddString("ESF"); + eoWriter.AddInt(1); // RID + eoWriter.AddShort(2); // length + eoWriter.AddByte(1); // version + eoWriter.AddBytes(rs.SerializeToByteArray(new ESFRecord().WithID(1).WithName("Test1"))); + eoWriter.AddBytes(rs.SerializeToByteArray(new ESFRecord().WithID(2).WithName("eof"))); + + ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEsf { - FileId = 1, - Content = eoWriter.ToByteArray() - } - }; - break; - case FileType.Ecf: - ret.ReplyCode = InitReply.FileEcf; - - eoWriter.AddString("ECF"); - eoWriter.AddInt(1); // RID - eoWriter.AddShort(2); // length - eoWriter.AddByte(1); // version - eoWriter.AddBytes(rs.SerializeToByteArray(new ECFRecord().WithID(1).WithName("Test1"))); - eoWriter.AddBytes(rs.SerializeToByteArray(new ECFRecord().WithID(2).WithName("eof"))); - - ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEcf - { - PubFile = new PubFile + PubFile = new PubFile + { + FileId = 1, + Content = eoWriter.ToByteArray() + } + }; + break; + case FileType.Ecf: + ret.ReplyCode = InitReply.FileEcf; + + eoWriter.AddString("ECF"); + eoWriter.AddInt(1); // RID + eoWriter.AddShort(2); // length + eoWriter.AddByte(1); // version + eoWriter.AddBytes(rs.SerializeToByteArray(new ECFRecord().WithID(1).WithName("Test1"))); + eoWriter.AddBytes(rs.SerializeToByteArray(new ECFRecord().WithID(2).WithName("eof"))); + + ret.ReplyCodeData = new InitInitServerPacket.ReplyCodeDataFileEcf { - FileId = 1, - Content = eoWriter.ToByteArray() - } - }; - break; + PubFile = new PubFile + { + FileId = 1, + Content = eoWriter.ToByteArray() + } + }; + break; + } + + eoWriter = new EoWriter(); + ret.Serialize(eoWriter); + return eoWriter.ToByteArray(); } - eoWriter = new EoWriter(); - ret.Serialize(eoWriter); - return eoWriter.ToByteArray(); + #endregion } - - #endregion } \ No newline at end of file diff --git a/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs b/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs index d87fccd24..ad022e3dd 100644 --- a/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs +++ b/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs @@ -6,22 +6,23 @@ using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; -namespace EOLib.Test.TestHelpers; - -[ExcludeFromCodeCoverage] -internal static class PacketSendServiceHelpers +namespace EOLib.Test.TestHelpers { - /// - /// Setup the PacketSendService mock to return a packet with the specified family/action/data from SendEncodedPacketAndWaitAsync - /// - /// The mocked packet send service - /// Packet data payload (any additional data that should be in the packet) - internal static void SetupReceivedPacketHasHeader(this Mock packetSendServiceMock, params byte[] data) - where T : IPacket + [ExcludeFromCodeCoverage] + internal static class PacketSendServiceHelpers { - IPacket receivedPacket = (IPacket)Activator.CreateInstance(typeof(T)); - receivedPacket.Deserialize(new EoReader(data)); - packetSendServiceMock.Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) - .Returns(Task.FromResult(receivedPacket)); + /// + /// Setup the PacketSendService mock to return a packet with the specified family/action/data from SendEncodedPacketAndWaitAsync + /// + /// The mocked packet send service + /// Packet data payload (any additional data that should be in the packet) + internal static void SetupReceivedPacketHasHeader(this Mock packetSendServiceMock, params byte[] data) + where T : IPacket + { + IPacket receivedPacket = (IPacket)Activator.CreateInstance(typeof(T)); + receivedPacket.Deserialize(new EoReader(data)); + packetSendServiceMock.Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny())) + .Returns(Task.FromResult(receivedPacket)); + } } } \ No newline at end of file diff --git a/EndlessClient/Audio/AudioActions.cs b/EndlessClient/Audio/AudioActions.cs index 758ef1801..17ead27e8 100644 --- a/EndlessClient/Audio/AudioActions.cs +++ b/EndlessClient/Audio/AudioActions.cs @@ -4,72 +4,73 @@ using EOLib.Domain.Notifiers; using EOLib.IO.Map; -namespace EndlessClient.Audio; - -[AutoMappedType] -public class AudioActions : IAudioActions, ISoundNotifier +namespace EndlessClient.Audio { - private readonly IConfigurationProvider _configurationProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IMfxPlayer _mfxPlayer; - private readonly ISfxPlayer _sfxPlayer; - - public AudioActions(IConfigurationProvider configurationProvider, - ICurrentMapProvider currentMapProvider, - IMfxPlayer mfxPlayer, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class AudioActions : IAudioActions, ISoundNotifier { - _configurationProvider = configurationProvider; - _currentMapProvider = currentMapProvider; - _mfxPlayer = mfxPlayer; - _sfxPlayer = sfxPlayer; - } + private readonly IConfigurationProvider _configurationProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IMfxPlayer _mfxPlayer; + private readonly ISfxPlayer _sfxPlayer; - public void ToggleBackgroundMusic() - { - if (!_configurationProvider.MusicEnabled) + public AudioActions(IConfigurationProvider configurationProvider, + ICurrentMapProvider currentMapProvider, + IMfxPlayer mfxPlayer, + ISfxPlayer sfxPlayer) { - _mfxPlayer.StopBackgroundMusic(); - return; + _configurationProvider = configurationProvider; + _currentMapProvider = currentMapProvider; + _mfxPlayer = mfxPlayer; + _sfxPlayer = sfxPlayer; } - var music = _currentMapProvider.CurrentMap.Properties.Music; - var musicControl = _currentMapProvider.CurrentMap.Properties.Control; - if (music > 0) - _mfxPlayer.PlayBackgroundMusic(_currentMapProvider.CurrentMap.Properties.Music, musicControl); - else - _mfxPlayer.StopBackgroundMusic(); - } + public void ToggleBackgroundMusic() + { + if (!_configurationProvider.MusicEnabled) + { + _mfxPlayer.StopBackgroundMusic(); + return; + } - public void ToggleSound() - { - if (!_configurationProvider.SoundEnabled) + var music = _currentMapProvider.CurrentMap.Properties.Music; + var musicControl = _currentMapProvider.CurrentMap.Properties.Control; + if (music > 0) + _mfxPlayer.PlayBackgroundMusic(_currentMapProvider.CurrentMap.Properties.Music, musicControl); + else + _mfxPlayer.StopBackgroundMusic(); + } + + public void ToggleSound() + { + if (!_configurationProvider.SoundEnabled) + { + _sfxPlayer.StopLoopingSfx(); + return; + } + + var noise = _currentMapProvider.CurrentMap.Properties.AmbientNoise; + if (noise > 0) + _sfxPlayer.PlayLoopingSfx((SoundEffectID)noise); + else + _sfxPlayer.StopLoopingSfx(); + } + + public void NotifySoundEffect(int soundEffectId) { - _sfxPlayer.StopLoopingSfx(); - return; + _sfxPlayer.PlaySfx((SoundEffectID)soundEffectId); } - var noise = _currentMapProvider.CurrentMap.Properties.AmbientNoise; - if (noise > 0) - _sfxPlayer.PlayLoopingSfx((SoundEffectID)noise); - else - _sfxPlayer.StopLoopingSfx(); + public void NotifyMusic(int musicEffectId, bool isJukebox) + { + _mfxPlayer.PlayBackgroundMusic(musicEffectId, MusicControl.InterruptIfDifferentPlayOnce, isJukebox); + } } - public void NotifySoundEffect(int soundEffectId) + public interface IAudioActions { - _sfxPlayer.PlaySfx((SoundEffectID)soundEffectId); - } + void ToggleBackgroundMusic(); - public void NotifyMusic(int musicEffectId, bool isJukebox) - { - _mfxPlayer.PlayBackgroundMusic(musicEffectId, MusicControl.InterruptIfDifferentPlayOnce, isJukebox); + void ToggleSound(); } -} - -public interface IAudioActions -{ - void ToggleBackgroundMusic(); - - void ToggleSound(); } \ No newline at end of file diff --git a/EndlessClient/Audio/MfxPlayer.cs b/EndlessClient/Audio/MfxPlayer.cs index aba180ce8..fd3cd231f 100644 --- a/EndlessClient/Audio/MfxPlayer.cs +++ b/EndlessClient/Audio/MfxPlayer.cs @@ -7,131 +7,132 @@ using System.IO; using System.Linq; -namespace EndlessClient.Audio; - -[AutoMappedType(IsSingleton = true)] -public sealed class MfxPlayer : IMfxPlayer +namespace EndlessClient.Audio { - private readonly IConfigurationProvider _configurationProvider; - - private readonly string[] _mfxFiles; - private readonly string[] _jboxFiles; - private readonly IMidiOutput _output; - private MidiPlayer _activePlayer; - private int _activeId; - - public MfxPlayer(IConfigurationProvider configurationProvider) + [AutoMappedType(IsSingleton = true)] + public sealed class MfxPlayer : IMfxPlayer { - _configurationProvider = configurationProvider; + private readonly IConfigurationProvider _configurationProvider; - _mfxFiles = Directory.GetFiles(Constants.MfxDirectory, "*.mid"); - Array.Sort(_mfxFiles); + private readonly string[] _mfxFiles; + private readonly string[] _jboxFiles; + private readonly IMidiOutput _output; + private MidiPlayer _activePlayer; + private int _activeId; - _jboxFiles = Directory.GetFiles(Constants.JboxDirectory, "*.mid"); - Array.Sort(_jboxFiles); - - try - { - var access = MidiAccessManager.Default; - _output = access.OpenOutputAsync(access.Outputs.Last().Id).Result; - } - catch + public MfxPlayer(IConfigurationProvider configurationProvider) { - Console.WriteLine("WARNING: Unable to initialize the midi sound system. Background music will not play."); - } - } + _configurationProvider = configurationProvider; - public void PlayBackgroundMusic(int id, MusicControl musicControl, bool isJukebox = false) - { - if (!_configurationProvider.MusicEnabled) - return; + _mfxFiles = Directory.GetFiles(Constants.MfxDirectory, "*.mid"); + Array.Sort(_mfxFiles); - if ((!isJukebox && (id < 1 || id > _mfxFiles.Length)) || - (isJukebox && (id < 1 || id > _jboxFiles.Length))) - throw new ArgumentException("ID should be 1-based index", nameof(id)); + _jboxFiles = Directory.GetFiles(Constants.JboxDirectory, "*.mid"); + Array.Sort(_jboxFiles); - var interrupt = false; - var repeat = false; + try + { + var access = MidiAccessManager.Default; + _output = access.OpenOutputAsync(access.Outputs.Last().Id).Result; + } + catch + { + Console.WriteLine("WARNING: Unable to initialize the midi sound system. Background music will not play."); + } + } - switch (musicControl) + public void PlayBackgroundMusic(int id, MusicControl musicControl, bool isJukebox = false) { - case MusicControl.InterruptIfDifferentPlayOnce: - interrupt = id != _activeId; - break; - case MusicControl.InterruptPlayOnce: - interrupt = true; - break; - case MusicControl.FinishPlayOnce: - break; - case MusicControl.InterruptIfDifferentPlayRepeat: - interrupt = id != _activeId; - repeat = true; - break; - case MusicControl.InterruptPlayRepeat: - interrupt = repeat = true; - break; - case MusicControl.FinishPlayRepeat: - repeat = true; - break; - case MusicControl.TurnOff: - StopBackgroundMusic(); + if (!_configurationProvider.MusicEnabled) return; - } - if (_activePlayer != null) - { - if (interrupt || _activePlayer.State == PlayerState.Stopped) + if ((!isJukebox && (id < 1 || id > _mfxFiles.Length)) || + (isJukebox && (id < 1 || id > _jboxFiles.Length))) + throw new ArgumentException("ID should be 1-based index", nameof(id)); + + var interrupt = false; + var repeat = false; + + switch (musicControl) + { + case MusicControl.InterruptIfDifferentPlayOnce: + interrupt = id != _activeId; + break; + case MusicControl.InterruptPlayOnce: + interrupt = true; + break; + case MusicControl.FinishPlayOnce: + break; + case MusicControl.InterruptIfDifferentPlayRepeat: + interrupt = id != _activeId; + repeat = true; + break; + case MusicControl.InterruptPlayRepeat: + interrupt = repeat = true; + break; + case MusicControl.FinishPlayRepeat: + repeat = true; + break; + case MusicControl.TurnOff: + StopBackgroundMusic(); + return; + } + + if (_activePlayer != null) + { + if (interrupt || _activePlayer.State == PlayerState.Stopped) + { + StopBackgroundMusic(); + StartPlaying(); + } + } + else { - StopBackgroundMusic(); StartPlaying(); } - } - else - { - StartPlaying(); - } - _activePlayer.PlaybackCompletedToEnd -= PlaybackCompleteAction; - if (repeat) - { - _activePlayer.PlaybackCompletedToEnd += PlaybackCompleteAction; - } + _activePlayer.PlaybackCompletedToEnd -= PlaybackCompleteAction; + if (repeat) + { + _activePlayer.PlaybackCompletedToEnd += PlaybackCompleteAction; + } - void StartPlaying() - { - if (_output != null) + void StartPlaying() { - var music = MidiMusic.Read(File.OpenRead(isJukebox ? _jboxFiles[id - 1] : _mfxFiles[id - 1])); - _activePlayer = new MidiPlayer(music, _output); - _activePlayer.Play(); + if (_output != null) + { + var music = MidiMusic.Read(File.OpenRead(isJukebox ? _jboxFiles[id - 1] : _mfxFiles[id - 1])); + _activePlayer = new MidiPlayer(music, _output); + _activePlayer.Play(); + } + + _activeId = id; } - _activeId = id; + void PlaybackCompleteAction() + { + PlayBackgroundMusic(id, musicControl); + } } - void PlaybackCompleteAction() + public void StopBackgroundMusic() { - PlayBackgroundMusic(id, musicControl); + _activePlayer?.Stop(); + _activePlayer?.Dispose(); + _activePlayer = null; } - } - public void StopBackgroundMusic() - { - _activePlayer?.Stop(); - _activePlayer?.Dispose(); - _activePlayer = null; + public void Dispose() + { + StopBackgroundMusic(); + _output?.Dispose(); + } } - public void Dispose() + public interface IMfxPlayer : IDisposable { - StopBackgroundMusic(); - _output?.Dispose(); - } -} + void PlayBackgroundMusic(int id, MusicControl musicControl, bool isJukebox = false); -public interface IMfxPlayer : IDisposable -{ - void PlayBackgroundMusic(int id, MusicControl musicControl, bool isJukebox = false); - - void StopBackgroundMusic(); + void StopBackgroundMusic(); + } } \ No newline at end of file diff --git a/EndlessClient/Audio/SfxPlayer.cs b/EndlessClient/Audio/SfxPlayer.cs index b36458f3d..4ae6db01d 100644 --- a/EndlessClient/Audio/SfxPlayer.cs +++ b/EndlessClient/Audio/SfxPlayer.cs @@ -4,92 +4,93 @@ using Microsoft.Xna.Framework.Audio; using System; -namespace EndlessClient.Audio; - -[AutoMappedType(IsSingleton = true)] -public sealed class SfxPlayer : ISfxPlayer +namespace EndlessClient.Audio { - private readonly IContentProvider _contentProvider; - private readonly IConfigurationProvider _configurationProvider; - - private SoundEffectInstance _loopingSfx; - - public SfxPlayer(IContentProvider contentProvider, - IConfigurationProvider configurationProvider) + [AutoMappedType(IsSingleton = true)] + public sealed class SfxPlayer : ISfxPlayer { - _contentProvider = contentProvider; - _configurationProvider = configurationProvider; + private readonly IContentProvider _contentProvider; + private readonly IConfigurationProvider _configurationProvider; + + private SoundEffectInstance _loopingSfx; + + public SfxPlayer(IContentProvider contentProvider, + IConfigurationProvider configurationProvider) + { + _contentProvider = contentProvider; + _configurationProvider = configurationProvider; + } + + public void PlaySfx(SoundEffectID id) + { + if (!_configurationProvider.SoundEnabled) + return; + + _contentProvider.SFX[id - 1].Play(); + } + + public void PlayHarpNote(int index) + { + if (!_configurationProvider.SoundEnabled || index < 0 || index >= _contentProvider.HarpNotes.Count) + return; + + _contentProvider.HarpNotes[index].Play(); + } + + public void PlayGuitarNote(int index) + { + if (!_configurationProvider.SoundEnabled || index < 0 || index >= _contentProvider.GuitarNotes.Count) + return; + + _contentProvider.GuitarNotes[index].Play(); + } + + public void PlayLoopingSfx(SoundEffectID id) + { + if (!_configurationProvider.SoundEnabled || (_loopingSfx != null && _loopingSfx.State != SoundState.Stopped)) + return; + + StopLoopingSfx(); + + _loopingSfx = _contentProvider.SFX[id - 1].CreateInstance(); + _loopingSfx.IsLooped = true; + _loopingSfx.Volume = 0.5f; + _loopingSfx.Play(); + } + + public void SetLoopingSfxVolume(float volume) + { + if (volume < 0 || volume > 1) + throw new ArgumentException($"Volume {volume} must be between 0 and 1", nameof(volume)); + + if (_loopingSfx != null) + _loopingSfx.Volume = volume; + } + + public void StopLoopingSfx() + { + _loopingSfx?.Stop(); + _loopingSfx?.Dispose(); + } + + public void Dispose() + { + StopLoopingSfx(); + } } - public void PlaySfx(SoundEffectID id) + public interface ISfxPlayer : IDisposable { - if (!_configurationProvider.SoundEnabled) - return; + void PlaySfx(SoundEffectID id); - _contentProvider.SFX[id - 1].Play(); - } + void PlayHarpNote(int index); - public void PlayHarpNote(int index) - { - if (!_configurationProvider.SoundEnabled || index < 0 || index >= _contentProvider.HarpNotes.Count) - return; + void PlayGuitarNote(int index); - _contentProvider.HarpNotes[index].Play(); - } + void PlayLoopingSfx(SoundEffectID id); - public void PlayGuitarNote(int index) - { - if (!_configurationProvider.SoundEnabled || index < 0 || index >= _contentProvider.GuitarNotes.Count) - return; + void SetLoopingSfxVolume(float volume); - _contentProvider.GuitarNotes[index].Play(); + void StopLoopingSfx(); } - - public void PlayLoopingSfx(SoundEffectID id) - { - if (!_configurationProvider.SoundEnabled || (_loopingSfx != null && _loopingSfx.State != SoundState.Stopped)) - return; - - StopLoopingSfx(); - - _loopingSfx = _contentProvider.SFX[id - 1].CreateInstance(); - _loopingSfx.IsLooped = true; - _loopingSfx.Volume = 0.5f; - _loopingSfx.Play(); - } - - public void SetLoopingSfxVolume(float volume) - { - if (volume < 0 || volume > 1) - throw new ArgumentException($"Volume {volume} must be between 0 and 1", nameof(volume)); - - if (_loopingSfx != null) - _loopingSfx.Volume = volume; - } - - public void StopLoopingSfx() - { - _loopingSfx?.Stop(); - _loopingSfx?.Dispose(); - } - - public void Dispose() - { - StopLoopingSfx(); - } -} - -public interface ISfxPlayer : IDisposable -{ - void PlaySfx(SoundEffectID id); - - void PlayHarpNote(int index); - - void PlayGuitarNote(int index); - - void PlayLoopingSfx(SoundEffectID id); - - void SetLoopingSfxVolume(float volume); - - void StopLoopingSfx(); } \ No newline at end of file diff --git a/EndlessClient/Audio/SoundEffectID.cs b/EndlessClient/Audio/SoundEffectID.cs index 24a56bbcd..16ad15708 100644 --- a/EndlessClient/Audio/SoundEffectID.cs +++ b/EndlessClient/Audio/SoundEffectID.cs @@ -1,103 +1,104 @@ -namespace EndlessClient.Audio; - -// These are 0 based indexes even though the files start at sfx001 -// sfx001 will be id 0 -// sfx060 will be id 59 -public enum SoundEffectID +namespace EndlessClient.Audio { - NONE, - LayeredTechIntro = 1, - ButtonClick, - DialogButtonClick, - TextBoxFocus = 4, - ChestOpen = TextBoxFocus, - SpellActivate = TextBoxFocus, - ServerCommand = TextBoxFocus, - TradeItemOfferChanged = TextBoxFocus, - Login, - ServerMessage = Login, - DeleteCharacter, - MapMutation = DeleteCharacter, - Banned, - Reboot = Banned, - ScreenCapture = 8, - PrivateMessageReceived, - PunchAttack, - UnknownWarpSound, - UnknownPingSound = 12, - HudStatusBarClick, - AdminAnnounceReceived, - MeleeWeaponAttack, - MemberLeftParty = 16, - TradeAccepted, - JoinParty = TradeAccepted, - GroupChatReceived, - PrivateMessageSent, - InventoryPickup = 20, - InventoryPlace, - Earthquake, - DoorClose, - DoorOpen = 24, - DoorOrChestLocked, - BuySell, - Craft, - UnknownBuzzSound = 28, - AdminChatReceived, - AlternateMeleeAttack, - PotionOfFlamesEffect, - AdminWarp = 32, - NoWallWalk, - GhostPlayer = NoWallWalk, - ScrollTeleport = NoWallWalk, - PotionOfEvilTerrorEffect, - PotionOfFireworksEffect, - PotionOfSparklesEffect = 36, - LearnNewSpell, - PotionOfLoveEffect = LearnNewSpell, - InnSignUp = LearnNewSpell, - AttackBow, - LevelUp, - Dead = 40, - JumpStone, - Water, - Heal, - Harp1 = 44, - Harp2, - Harp3, - Guitar1, - Guitar2 = 48, - Guitar3, - Thunder, - MapEvacTimer, - ArenaTickSound = MapEvacTimer, - ArenaWin = 52, - Gun, - UltimaBlastSpell, - ShieldSpell, - RingOfFireSpell = 56, - IceBlastSpell1, - EnergyBallSpell, - WhirlSpell, - BouldersSpell = 60, - AuraSpell, - HeavenSpell, - IceBlastSpell2, - MapAmbientNoiseWater = 64, - MapAmbientNoiseDrone1, - AdminHide, - MapAmbientNoiseLavaBubbles1, - AdminRequestSent = 68, - MapAmbientNoiseFactory, - MapEffectHPDrain, - MapEffectTPDrain, - Spikes = 72, - NoArrows, - EnterPkMap, - UnknownMapAmbientNoise5, - DarkHandSpell = 76, - TentaclesSpell, - MagicWhirlSpell, - PowerWindSpell, - FireBlastSpell = 80, - MapAmbientNoiseLavaBubbles2, + // These are 0 based indexes even though the files start at sfx001 + // sfx001 will be id 0 + // sfx060 will be id 59 + public enum SoundEffectID + { + NONE, + LayeredTechIntro = 1, + ButtonClick, + DialogButtonClick, + TextBoxFocus = 4, + ChestOpen = TextBoxFocus, + SpellActivate = TextBoxFocus, + ServerCommand = TextBoxFocus, + TradeItemOfferChanged = TextBoxFocus, + Login, + ServerMessage = Login, + DeleteCharacter, + MapMutation = DeleteCharacter, + Banned, + Reboot = Banned, + ScreenCapture = 8, + PrivateMessageReceived, + PunchAttack, + UnknownWarpSound, + UnknownPingSound = 12, + HudStatusBarClick, + AdminAnnounceReceived, + MeleeWeaponAttack, + MemberLeftParty = 16, + TradeAccepted, + JoinParty = TradeAccepted, + GroupChatReceived, + PrivateMessageSent, + InventoryPickup = 20, + InventoryPlace, + Earthquake, + DoorClose, + DoorOpen = 24, + DoorOrChestLocked, + BuySell, + Craft, + UnknownBuzzSound = 28, + AdminChatReceived, + AlternateMeleeAttack, + PotionOfFlamesEffect, + AdminWarp = 32, + NoWallWalk, + GhostPlayer = NoWallWalk, + ScrollTeleport = NoWallWalk, + PotionOfEvilTerrorEffect, + PotionOfFireworksEffect, + PotionOfSparklesEffect = 36, + LearnNewSpell, + PotionOfLoveEffect = LearnNewSpell, + InnSignUp = LearnNewSpell, + AttackBow, + LevelUp, + Dead = 40, + JumpStone, + Water, + Heal, + Harp1 = 44, + Harp2, + Harp3, + Guitar1, + Guitar2 = 48, + Guitar3, + Thunder, + MapEvacTimer, + ArenaTickSound = MapEvacTimer, + ArenaWin = 52, + Gun, + UltimaBlastSpell, + ShieldSpell, + RingOfFireSpell = 56, + IceBlastSpell1, + EnergyBallSpell, + WhirlSpell, + BouldersSpell = 60, + AuraSpell, + HeavenSpell, + IceBlastSpell2, + MapAmbientNoiseWater = 64, + MapAmbientNoiseDrone1, + AdminHide, + MapAmbientNoiseLavaBubbles1, + AdminRequestSent = 68, + MapAmbientNoiseFactory, + MapEffectHPDrain, + MapEffectTPDrain, + Spikes = 72, + NoArrows, + EnterPkMap, + UnknownMapAmbientNoise5, + DarkHandSpell = 76, + TentaclesSpell, + MagicWhirlSpell, + PowerWindSpell, + FireBlastSpell = 80, + MapAmbientNoiseLavaBubbles2, + } } \ No newline at end of file diff --git a/EndlessClient/Audio/WAVFileValidator.cs b/EndlessClient/Audio/WAVFileValidator.cs index 08bd492be..23a3ad59a 100644 --- a/EndlessClient/Audio/WAVFileValidator.cs +++ b/EndlessClient/Audio/WAVFileValidator.cs @@ -2,31 +2,32 @@ using System.IO; using System.Text; -namespace EndlessClient.Audio; - -public static class WAVFileValidator +namespace EndlessClient.Audio { - //some of the original SFX files will fail to load because the file length is stored incorrectly in the WAV header. - //this helper method returns a stream around the corrected raw bytes of the file. - public static Stream GetStreamWithCorrectLengthHeader(string filename) + public static class WAVFileValidator { - var wavBuffer = File.ReadAllBytes(filename); + //some of the original SFX files will fail to load because the file length is stored incorrectly in the WAV header. + //this helper method returns a stream around the corrected raw bytes of the file. + public static Stream GetStreamWithCorrectLengthHeader(string filename) + { + var wavBuffer = File.ReadAllBytes(filename); - var riff = Encoding.ASCII.GetString(wavBuffer[..4]); - if (riff != "RIFF" || wavBuffer.Length < 8) //check for RIFF tag and length - throw new ArgumentException("Invalid WAV file", nameof(filename)); + var riff = Encoding.ASCII.GetString(wavBuffer[..4]); + if (riff != "RIFF" || wavBuffer.Length < 8) //check for RIFF tag and length + throw new ArgumentException("Invalid WAV file", nameof(filename)); - var reportedLength = wavBuffer[4] + wavBuffer[5] * 256 + wavBuffer[6] * 65536 + wavBuffer[7] * 16777216; - var actualLength = wavBuffer.Length - 8; + var reportedLength = wavBuffer[4] + wavBuffer[5] * 256 + wavBuffer[6] * 65536 + wavBuffer[7] * 16777216; + var actualLength = wavBuffer.Length - 8; - if (reportedLength != actualLength) - { - wavBuffer[4] = (byte)(actualLength & 0xFF); - wavBuffer[5] = (byte)((actualLength >> 8) & 0xFF); - wavBuffer[6] = (byte)((actualLength >> 16) & 0xFF); - wavBuffer[7] = (byte)((actualLength >> 24) & 0xFF); - } + if (reportedLength != actualLength) + { + wavBuffer[4] = (byte)(actualLength & 0xFF); + wavBuffer[5] = (byte)((actualLength >> 8) & 0xFF); + wavBuffer[6] = (byte)((actualLength >> 16) & 0xFF); + wavBuffer[7] = (byte)((actualLength >> 24) & 0xFF); + } - return new MemoryStream(wavBuffer); + return new MemoryStream(wavBuffer); + } } } \ No newline at end of file diff --git a/EndlessClient/Content/ContentProvider.cs b/EndlessClient/Content/ContentProvider.cs index 3cb5f44cd..a7aacd0e4 100644 --- a/EndlessClient/Content/ContentProvider.cs +++ b/EndlessClient/Content/ContentProvider.cs @@ -9,158 +9,159 @@ using System.IO; using System.Linq; -namespace EndlessClient.Content; - -public interface IContentProvider +namespace EndlessClient.Content { - IReadOnlyDictionary Textures { get; } - - IReadOnlyDictionary Fonts { get; } + public interface IContentProvider + { + IReadOnlyDictionary Textures { get; } - IReadOnlyDictionary SFX { get; } + IReadOnlyDictionary Fonts { get; } - IReadOnlyList HarpNotes { get; } + IReadOnlyDictionary SFX { get; } - IReadOnlyList GuitarNotes { get; } + IReadOnlyList HarpNotes { get; } - void SetContentManager(ContentManager content); + IReadOnlyList GuitarNotes { get; } - void Load(); -} + void SetContentManager(ContentManager content); -[AutoMappedType(IsSingleton = true)] -public class ContentProvider : IContentProvider -{ - private readonly Dictionary _textures; - private readonly Dictionary _fonts; - private readonly Dictionary _sfx; - private readonly List _harpNotes; - private readonly List _guitarNotes; + void Load(); + } - private ContentManager _content; + [AutoMappedType(IsSingleton = true)] + public class ContentProvider : IContentProvider + { + private readonly Dictionary _textures; + private readonly Dictionary _fonts; + private readonly Dictionary _sfx; + private readonly List _harpNotes; + private readonly List _guitarNotes; - public const string Cursor = "cursor"; + private ContentManager _content; - public const string TBBack = "tbBack"; - public const string TBLeft = "tbLeft"; - public const string TBRight = "tbRight"; + public const string Cursor = "cursor"; - public const string ChatTL = @"ChatBubble\TL"; - public const string ChatTM = @"ChatBubble\TM"; - public const string ChatTR = @"ChatBubble\TR"; - public const string ChatML = @"ChatBubble\ML"; - public const string ChatMM = @"ChatBubble\MM"; - public const string ChatMR = @"ChatBubble\MR"; - public const string ChatRL = @"ChatBubble\RL"; - public const string ChatRM = @"ChatBubble\RM"; - public const string ChatRR = @"ChatBubble\RR"; - public const string ChatNUB = @"ChatBubble\NUB"; + public const string TBBack = "tbBack"; + public const string TBLeft = "tbLeft"; + public const string TBRight = "tbRight"; - public const string HPOutline = @"Party\hp-outline"; - public const string HPRed = @"Party\hp-red"; - public const string HPYellow = @"Party\hp-yellow"; - public const string HPGreen = @"Party\hp-green"; + public const string ChatTL = @"ChatBubble\TL"; + public const string ChatTM = @"ChatBubble\TM"; + public const string ChatTR = @"ChatBubble\TR"; + public const string ChatML = @"ChatBubble\ML"; + public const string ChatMM = @"ChatBubble\MM"; + public const string ChatMR = @"ChatBubble\MR"; + public const string ChatRL = @"ChatBubble\RL"; + public const string ChatRM = @"ChatBubble\RM"; + public const string ChatRR = @"ChatBubble\RR"; + public const string ChatNUB = @"ChatBubble\NUB"; - public IReadOnlyDictionary Textures => _textures; + public const string HPOutline = @"Party\hp-outline"; + public const string HPRed = @"Party\hp-red"; + public const string HPYellow = @"Party\hp-yellow"; + public const string HPGreen = @"Party\hp-green"; - public IReadOnlyDictionary Fonts => _fonts; + public IReadOnlyDictionary Textures => _textures; - public IReadOnlyDictionary SFX => _sfx; + public IReadOnlyDictionary Fonts => _fonts; - public IReadOnlyList HarpNotes => _harpNotes; + public IReadOnlyDictionary SFX => _sfx; - public IReadOnlyList GuitarNotes => _guitarNotes; + public IReadOnlyList HarpNotes => _harpNotes; - public ContentProvider() - { - _textures = new Dictionary(); - _fonts = new Dictionary(); - _sfx = new Dictionary(); - _harpNotes = new List(); - _guitarNotes = new List(); - } + public IReadOnlyList GuitarNotes => _guitarNotes; - public void SetContentManager(ContentManager content) - { - _content = content; - } + public ContentProvider() + { + _textures = new Dictionary(); + _fonts = new Dictionary(); + _sfx = new Dictionary(); + _harpNotes = new List(); + _guitarNotes = new List(); + } - public void Load() - { - RefreshTextures(); - RefreshFonts(); - LoadSFX(); - LoadHarp(); - LoadGuitar(); - } + public void SetContentManager(ContentManager content) + { + _content = content; + } - private void RefreshTextures() - { - if (_content == null) - return; - - _textures[Cursor] = _content.Load(Cursor); - - _textures[TBBack] = _content.Load(TBBack); - _textures[TBLeft] = _content.Load(TBLeft); - _textures[TBRight] = _content.Load(TBRight); - - _textures[ChatTL] = _content.Load(ChatTL); - _textures[ChatTM] = _content.Load(ChatTM); - _textures[ChatTR] = _content.Load(ChatTR); - _textures[ChatML] = _content.Load(ChatML); - _textures[ChatMM] = _content.Load(ChatMM); - _textures[ChatMR] = _content.Load(ChatMR); - _textures[ChatRL] = _content.Load(ChatRL); - _textures[ChatRM] = _content.Load(ChatRM); - _textures[ChatRR] = _content.Load(ChatRR); - _textures[ChatNUB] = _content.Load(ChatNUB); - - _textures[HPOutline] = _content.Load(HPOutline); - _textures[HPRed] = _content.Load(HPRed); - _textures[HPYellow] = _content.Load(HPYellow); - _textures[HPGreen] = _content.Load(HPGreen); - } + public void Load() + { + RefreshTextures(); + RefreshFonts(); + LoadSFX(); + LoadHarp(); + LoadGuitar(); + } - private void RefreshFonts() - { - _fonts[Constants.FontSize08] = _content.Load(Constants.FontSize08); - _fonts[Constants.FontSize08pt5] = _content.Load(Constants.FontSize08pt5); - _fonts[Constants.FontSize09] = _content.Load(Constants.FontSize09); - } + private void RefreshTextures() + { + if (_content == null) + return; + + _textures[Cursor] = _content.Load(Cursor); + + _textures[TBBack] = _content.Load(TBBack); + _textures[TBLeft] = _content.Load(TBLeft); + _textures[TBRight] = _content.Load(TBRight); + + _textures[ChatTL] = _content.Load(ChatTL); + _textures[ChatTM] = _content.Load(ChatTM); + _textures[ChatTR] = _content.Load(ChatTR); + _textures[ChatML] = _content.Load(ChatML); + _textures[ChatMM] = _content.Load(ChatMM); + _textures[ChatMR] = _content.Load(ChatMR); + _textures[ChatRL] = _content.Load(ChatRL); + _textures[ChatRM] = _content.Load(ChatRM); + _textures[ChatRR] = _content.Load(ChatRR); + _textures[ChatNUB] = _content.Load(ChatNUB); + + _textures[HPOutline] = _content.Load(HPOutline); + _textures[HPRed] = _content.Load(HPRed); + _textures[HPYellow] = _content.Load(HPYellow); + _textures[HPGreen] = _content.Load(HPGreen); + } - private void LoadSFX() - { - var id = (SoundEffectID)0; - foreach (var sfxFile in GetSoundEffects("sfx*.wav")) - _sfx[id++] = sfxFile; - if (_sfx.Count < 81) - throw new FileNotFoundException("Unexpected number of SFX"); - } + private void RefreshFonts() + { + _fonts[Constants.FontSize08] = _content.Load(Constants.FontSize08); + _fonts[Constants.FontSize08pt5] = _content.Load(Constants.FontSize08pt5); + _fonts[Constants.FontSize09] = _content.Load(Constants.FontSize09); + } - private void LoadHarp() - { - _harpNotes.AddRange(GetSoundEffects("har*.wav")); - if (_harpNotes.Count != 36) - throw new FileNotFoundException("Unexpected number of harp SFX"); - } + private void LoadSFX() + { + var id = (SoundEffectID)0; + foreach (var sfxFile in GetSoundEffects("sfx*.wav")) + _sfx[id++] = sfxFile; + if (_sfx.Count < 81) + throw new FileNotFoundException("Unexpected number of SFX"); + } - private void LoadGuitar() - { - _guitarNotes.AddRange(GetSoundEffects("gui*.wav")); - if (_guitarNotes.Count != 36) - throw new FileNotFoundException("Unexpected number of guitar SFX"); - } + private void LoadHarp() + { + _harpNotes.AddRange(GetSoundEffects("har*.wav")); + if (_harpNotes.Count != 36) + throw new FileNotFoundException("Unexpected number of harp SFX"); + } - private static IEnumerable GetSoundEffects(string filter) - { - var sfxFiles = Directory.GetFiles(Constants.SfxDirectory, filter).ToList(); - sfxFiles.Sort(); + private void LoadGuitar() + { + _guitarNotes.AddRange(GetSoundEffects("gui*.wav")); + if (_guitarNotes.Count != 36) + throw new FileNotFoundException("Unexpected number of guitar SFX"); + } - foreach (var file in sfxFiles) + private static IEnumerable GetSoundEffects(string filter) { - using var wavStream = WAVFileValidator.GetStreamWithCorrectLengthHeader(file); - yield return SoundEffect.FromStream(wavStream); + var sfxFiles = Directory.GetFiles(Constants.SfxDirectory, filter).ToList(); + sfxFiles.Sort(); + + foreach (var file in sfxFiles) + { + using var wavStream = WAVFileValidator.GetStreamWithCorrectLengthHeader(file); + yield return SoundEffect.FromStream(wavStream); + } } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/BackButtonControlSet.cs b/EndlessClient/ControlSets/BackButtonControlSet.cs index 515265653..c4ad0cd9f 100644 --- a/EndlessClient/ControlSets/BackButtonControlSet.cs +++ b/EndlessClient/ControlSets/BackButtonControlSet.cs @@ -7,61 +7,62 @@ using System; using XNAControls; -namespace EndlessClient.ControlSets; - -public abstract class BackButtonControlSet : BaseControlSet +namespace EndlessClient.ControlSets { - protected readonly IMainButtonController _mainButtonController; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private Texture2D _backButtonTexture; - - private XNAButton _backButton; - - protected BackButtonControlSet(IMainButtonController mainButtonController, - IClientWindowSizeRepository clientWindowSizeRepository) + public abstract class BackButtonControlSet : BaseControlSet { - _mainButtonController = mainButtonController; - _clientWindowSizeRepository = clientWindowSizeRepository; - } + protected readonly IMainButtonController _mainButtonController; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private Texture2D _backButtonTexture; - public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - base.InitializeResources(gfxManager, contentProvider); + private XNAButton _backButton; - _backButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 24, true); - } + protected BackButtonControlSet(IMainButtonController mainButtonController, + IClientWindowSizeRepository clientWindowSizeRepository) + { + _mainButtonController = mainButtonController; + _clientWindowSizeRepository = clientWindowSizeRepository; + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - _backButton = GetControl(currentControlSet, GameControlIdentifier.BackButton, GetBackButton); + public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + base.InitializeResources(gfxManager, contentProvider); - _allComponents.Add(_backButton); - } + _backButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 24, true); + } - private XNAButton GetBackButton() - { - var button = new XNAButton( - _backButtonTexture, - new Vector2(_clientWindowSizeRepository.Width - _backButtonTexture.Width, 0), - new Rectangle(0, 0, _backButtonTexture.Width, _backButtonTexture.Height / 2), - new Rectangle(0, _backButtonTexture.Height / 2, _backButtonTexture.Width, _backButtonTexture.Height / 2)) + protected override void InitializeControlsHelper(IControlSet currentControlSet) { - UpdateOrder = -1, - DrawOrder = 100, - ClickArea = new Rectangle(4, 16, 16, 16) - }; - button.OnClick += DoBackButtonClick; + _backButton = GetControl(currentControlSet, GameControlIdentifier.BackButton, GetBackButton); + + _allComponents.Add(_backButton); + } - _clientWindowSizeRepository.GameWindowSizeChanged += (o, e) => + private XNAButton GetBackButton() { - button.DrawPosition = new Vector2(_clientWindowSizeRepository.Width - _backButtonTexture.Width, 0); - }; + var button = new XNAButton( + _backButtonTexture, + new Vector2(_clientWindowSizeRepository.Width - _backButtonTexture.Width, 0), + new Rectangle(0, 0, _backButtonTexture.Width, _backButtonTexture.Height / 2), + new Rectangle(0, _backButtonTexture.Height / 2, _backButtonTexture.Width, _backButtonTexture.Height / 2)) + { + UpdateOrder = -1, + DrawOrder = 100, + ClickArea = new Rectangle(4, 16, 16, 16) + }; + button.OnClick += DoBackButtonClick; - return button; - } + _clientWindowSizeRepository.GameWindowSizeChanged += (o, e) => + { + button.DrawPosition = new Vector2(_clientWindowSizeRepository.Width - _backButtonTexture.Width, 0); + }; - protected virtual void DoBackButtonClick(object sender, EventArgs e) - { - _mainButtonController.GoToInitialState(); + return button; + } + + protected virtual void DoBackButtonClick(object sender, EventArgs e) + { + _mainButtonController.GoToInitialState(); + } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/BaseControlSet.cs b/EndlessClient/ControlSets/BaseControlSet.cs index 6676537fd..c0e9e109e 100644 --- a/EndlessClient/ControlSets/BaseControlSet.cs +++ b/EndlessClient/ControlSets/BaseControlSet.cs @@ -8,119 +8,120 @@ using System.Linq; using XNAControls; -namespace EndlessClient.ControlSets; - -public abstract class BaseControlSet : IControlSet +namespace EndlessClient.ControlSets { - #region IGameStateControlSet implementation - - protected readonly List _allComponents; + public abstract class BaseControlSet : IControlSet + { + #region IGameStateControlSet implementation - public IReadOnlyList AllComponents => _allComponents; + protected readonly List _allComponents; - public IReadOnlyList XNAControlComponents => _allComponents.OfType().ToList(); + public IReadOnlyList AllComponents => _allComponents; - public abstract GameStates GameState { get; } + public IReadOnlyList XNAControlComponents => _allComponents.OfType().ToList(); - #endregion + public abstract GameStates GameState { get; } - protected Texture2D _mainButtonTexture; - protected Texture2D _secondaryButtonTexture; - protected Texture2D _smallButtonSheet; - protected Texture2D _textBoxCursor; - protected Texture2D _textBoxRight; - protected Texture2D _textBoxLeft; - protected Texture2D _textBoxBackground; + #endregion - private Texture2D[] _backgroundImages; - private IXNAPictureBox _backgroundImage; + protected Texture2D _mainButtonTexture; + protected Texture2D _secondaryButtonTexture; + protected Texture2D _smallButtonSheet; + protected Texture2D _textBoxCursor; + protected Texture2D _textBoxRight; + protected Texture2D _textBoxLeft; + protected Texture2D _textBoxBackground; - private bool _resourcesInitialized, _controlsInitialized; + private Texture2D[] _backgroundImages; + private IXNAPictureBox _backgroundImage; - protected BaseControlSet() - { - _allComponents = new List(16); - } + private bool _resourcesInitialized, _controlsInitialized; - public virtual void InitializeResources(INativeGraphicsManager gfxManager, - IContentProvider contentProvider) - { - if (_resourcesInitialized) - throw new InvalidOperationException("Error initializing resources: resources have already been initialized"); + protected BaseControlSet() + { + _allComponents = new List(16); + } - _mainButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 13, true); - _secondaryButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 14, true); - _smallButtonSheet = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 15, true); + public virtual void InitializeResources(INativeGraphicsManager gfxManager, + IContentProvider contentProvider) + { + if (_resourcesInitialized) + throw new InvalidOperationException("Error initializing resources: resources have already been initialized"); - _textBoxBackground = contentProvider.Textures[ContentProvider.TBBack]; - _textBoxLeft = contentProvider.Textures[ContentProvider.TBLeft]; - _textBoxRight = contentProvider.Textures[ContentProvider.TBRight]; - _textBoxCursor = contentProvider.Textures[ContentProvider.Cursor]; + _mainButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 13, true); + _secondaryButtonTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 14, true); + _smallButtonSheet = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 15, true); - _backgroundImages = new Texture2D[7]; - for (int i = 0; i < _backgroundImages.Length; ++i) - _backgroundImages[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 30 + i); + _textBoxBackground = contentProvider.Textures[ContentProvider.TBBack]; + _textBoxLeft = contentProvider.Textures[ContentProvider.TBLeft]; + _textBoxRight = contentProvider.Textures[ContentProvider.TBRight]; + _textBoxCursor = contentProvider.Textures[ContentProvider.Cursor]; - _resourcesInitialized = true; - } + _backgroundImages = new Texture2D[7]; + for (int i = 0; i < _backgroundImages.Length; ++i) + _backgroundImages[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 30 + i); - public void InitializeControls(IControlSet currentControlSet) - { - if (!_resourcesInitialized) - throw new InvalidOperationException("Error initializing controls: resources have not yet been initialized"); - if (_controlsInitialized) - throw new InvalidOperationException("Error initializing controls: controls have already been initialized"); + _resourcesInitialized = true; + } - if (GameState != GameStates.PlayingTheGame) + public void InitializeControls(IControlSet currentControlSet) { - _backgroundImage = GetControl(currentControlSet, GameControlIdentifier.BackgroundImage, GetBackgroundImage); - _allComponents.Add(_backgroundImage); - } + if (!_resourcesInitialized) + throw new InvalidOperationException("Error initializing controls: resources have not yet been initialized"); + if (_controlsInitialized) + throw new InvalidOperationException("Error initializing controls: controls have already been initialized"); - InitializeControlsHelper(currentControlSet); + if (GameState != GameStates.PlayingTheGame) + { + _backgroundImage = GetControl(currentControlSet, GameControlIdentifier.BackgroundImage, GetBackgroundImage); + _allComponents.Add(_backgroundImage); + } - foreach (var control in XNAControlComponents) - control.AddControlToDefaultGame(); + InitializeControlsHelper(currentControlSet); - _controlsInitialized = true; - } + foreach (var control in XNAControlComponents) + control.AddControlToDefaultGame(); - protected abstract void InitializeControlsHelper(IControlSet currentControlSet); + _controlsInitialized = true; + } - protected static T GetControl(IControlSet currentControlSet, - GameControlIdentifier whichControl, - Func componentFactory) - where T : class, IGameComponent - { - return (T)currentControlSet.FindComponentByControlIdentifier(whichControl) ?? componentFactory(); - } + protected abstract void InitializeControlsHelper(IControlSet currentControlSet); - public virtual IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) - { - return control == GameControlIdentifier.BackgroundImage ? _backgroundImage : null; - } + protected static T GetControl(IControlSet currentControlSet, + GameControlIdentifier whichControl, + Func componentFactory) + where T : class, IGameComponent + { + return (T)currentControlSet.FindComponentByControlIdentifier(whichControl) ?? componentFactory(); + } - private IXNAPictureBox GetBackgroundImage() - { - var rnd = new Random(); - var texture = _backgroundImages[rnd.Next(7)]; - return new XNAPictureBox + public virtual IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) { - Texture = texture, - DrawArea = new Rectangle(0, 0, texture.Width, texture.Height), - DrawOrder = 0 - }; - } + return control == GameControlIdentifier.BackgroundImage ? _backgroundImage : null; + } - public void Dispose() - { - Dispose(true); - } + private IXNAPictureBox GetBackgroundImage() + { + var rnd = new Random(); + var texture = _backgroundImages[rnd.Next(7)]; + return new XNAPictureBox + { + Texture = texture, + DrawArea = new Rectangle(0, 0, texture.Width, texture.Height), + DrawOrder = 0 + }; + } - ~BaseControlSet() - { - Dispose(false); - } + public void Dispose() + { + Dispose(true); + } - protected virtual void Dispose(bool disposing) { } + ~BaseControlSet() + { + Dispose(false); + } + + protected virtual void Dispose(bool disposing) { } + } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/ControlSetFactory.cs b/EndlessClient/ControlSets/ControlSetFactory.cs index b542fc96e..ea25b2924 100644 --- a/EndlessClient/ControlSets/ControlSetFactory.cs +++ b/EndlessClient/ControlSets/ControlSetFactory.cs @@ -13,99 +13,100 @@ using EOLib.Graphics; using System; -namespace EndlessClient.ControlSets; - -[MappedType(BaseType = typeof(IControlSetFactory), IsSingleton = true)] -public class ControlSetFactory : IControlSetFactory +namespace EndlessClient.ControlSets { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IHudControlsFactory _hudControlsFactory; - private readonly IContentProvider _contentProvider; - private readonly IConfigurationProvider _configProvider; - private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; - private readonly ICharacterSelectorProvider _characterSelectorProvider; - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IUserInputRepository _userInputRepository; - private readonly IActiveDialogRepository _activeDialogRepository; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + [MappedType(BaseType = typeof(IControlSetFactory), IsSingleton = true)] + public class ControlSetFactory : IControlSetFactory + { + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IHudControlsFactory _hudControlsFactory; + private readonly IContentProvider _contentProvider; + private readonly IConfigurationProvider _configProvider; + private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; + private readonly ICharacterSelectorProvider _characterSelectorProvider; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IUserInputRepository _userInputRepository; + private readonly IActiveDialogRepository _activeDialogRepository; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private IMainButtonController _mainButtonController; - private IAccountController _accountController; - private ILoginController _loginController; - private ICharacterManagementController _characterManagementController; + private IMainButtonController _mainButtonController; + private IAccountController _accountController; + private ILoginController _loginController; + private ICharacterManagementController _characterManagementController; - public ControlSetFactory(INativeGraphicsManager nativeGraphicsManager, - IEOMessageBoxFactory messageBoxFactory, - IHudControlsFactory hudControlsFactory, - IContentProvider contentProvider, - IConfigurationProvider configProvider, - ICharacterInfoPanelFactory characterInfoPanelFactory, - ICharacterSelectorProvider characterSelectorProvider, - IEndlessGameProvider endlessGameProvider, - IUserInputRepository userInputRepository, - IActiveDialogRepository activeDialogRepository, - IClientWindowSizeRepository clientWindowSizeRepository) - { - _nativeGraphicsManager = nativeGraphicsManager; - _messageBoxFactory = messageBoxFactory; - _hudControlsFactory = hudControlsFactory; - _contentProvider = contentProvider; - _configProvider = configProvider; - _characterInfoPanelFactory = characterInfoPanelFactory; - _characterSelectorProvider = characterSelectorProvider; - _endlessGameProvider = endlessGameProvider; - _userInputRepository = userInputRepository; - _activeDialogRepository = activeDialogRepository; - _clientWindowSizeRepository = clientWindowSizeRepository; - } + public ControlSetFactory(INativeGraphicsManager nativeGraphicsManager, + IEOMessageBoxFactory messageBoxFactory, + IHudControlsFactory hudControlsFactory, + IContentProvider contentProvider, + IConfigurationProvider configProvider, + ICharacterInfoPanelFactory characterInfoPanelFactory, + ICharacterSelectorProvider characterSelectorProvider, + IEndlessGameProvider endlessGameProvider, + IUserInputRepository userInputRepository, + IActiveDialogRepository activeDialogRepository, + IClientWindowSizeRepository clientWindowSizeRepository) + { + _nativeGraphicsManager = nativeGraphicsManager; + _messageBoxFactory = messageBoxFactory; + _hudControlsFactory = hudControlsFactory; + _contentProvider = contentProvider; + _configProvider = configProvider; + _characterInfoPanelFactory = characterInfoPanelFactory; + _characterSelectorProvider = characterSelectorProvider; + _endlessGameProvider = endlessGameProvider; + _userInputRepository = userInputRepository; + _activeDialogRepository = activeDialogRepository; + _clientWindowSizeRepository = clientWindowSizeRepository; + } - public IControlSet CreateControlsForState(GameStates newState, IControlSet currentControlSet) - { - if (_mainButtonController == null || _accountController == null || - _loginController == null || _characterManagementController == null) - throw new InvalidOperationException("Missing controllers - the Unity container was initialized incorrectly"); + public IControlSet CreateControlsForState(GameStates newState, IControlSet currentControlSet) + { + if (_mainButtonController == null || _accountController == null || + _loginController == null || _characterManagementController == null) + throw new InvalidOperationException("Missing controllers - the Unity container was initialized incorrectly"); - var controlSet = GetSetBasedOnState(newState); - controlSet.InitializeResources(_nativeGraphicsManager, _contentProvider); - controlSet.InitializeControls(currentControlSet); - return controlSet; - } + var controlSet = GetSetBasedOnState(newState); + controlSet.InitializeResources(_nativeGraphicsManager, _contentProvider); + controlSet.InitializeControls(currentControlSet); + return controlSet; + } - public void InjectControllers(IMainButtonController mainButtonController, - IAccountController accountController, - ILoginController loginController, - ICharacterManagementController characterManagementController) - { - _mainButtonController = mainButtonController; - _accountController = accountController; - _loginController = loginController; - _characterManagementController = characterManagementController; - } + public void InjectControllers(IMainButtonController mainButtonController, + IAccountController accountController, + ILoginController loginController, + ICharacterManagementController characterManagementController) + { + _mainButtonController = mainButtonController; + _accountController = accountController; + _loginController = loginController; + _characterManagementController = characterManagementController; + } - private IControlSet GetSetBasedOnState(GameStates newState) - { - switch (newState) + private IControlSet GetSetBasedOnState(GameStates newState) { - case GameStates.Initial: return new InitialControlSet(_configProvider, _mainButtonController); - case GameStates.CreateAccount: - return new CreateAccountControlSet(_mainButtonController, _accountController, _clientWindowSizeRepository); - case GameStates.Login: - return new LoginPromptControlSet(_configProvider, _mainButtonController, _loginController); - case GameStates.ViewCredits: return new ViewCreditsControlSet(_configProvider, _mainButtonController); - case GameStates.LoggedIn: - return new LoggedInControlSet( - _mainButtonController, - _characterInfoPanelFactory, - _characterSelectorProvider, - _characterManagementController, - _accountController, - _endlessGameProvider, - _userInputRepository, - _clientWindowSizeRepository); - case GameStates.PlayingTheGame: - return new InGameControlSet(_mainButtonController, _messageBoxFactory, _hudControlsFactory, _activeDialogRepository, _clientWindowSizeRepository); - default: throw new ArgumentOutOfRangeException(nameof(newState), newState, null); + switch (newState) + { + case GameStates.Initial: return new InitialControlSet(_configProvider, _mainButtonController); + case GameStates.CreateAccount: + return new CreateAccountControlSet(_mainButtonController, _accountController, _clientWindowSizeRepository); + case GameStates.Login: + return new LoginPromptControlSet(_configProvider, _mainButtonController, _loginController); + case GameStates.ViewCredits: return new ViewCreditsControlSet(_configProvider, _mainButtonController); + case GameStates.LoggedIn: + return new LoggedInControlSet( + _mainButtonController, + _characterInfoPanelFactory, + _characterSelectorProvider, + _characterManagementController, + _accountController, + _endlessGameProvider, + _userInputRepository, + _clientWindowSizeRepository); + case GameStates.PlayingTheGame: + return new InGameControlSet(_mainButtonController, _messageBoxFactory, _hudControlsFactory, _activeDialogRepository, _clientWindowSizeRepository); + default: throw new ArgumentOutOfRangeException(nameof(newState), newState, null); + } } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/CreateAccountControlSet.cs b/EndlessClient/ControlSets/CreateAccountControlSet.cs index a8799ecff..51bda50cc 100644 --- a/EndlessClient/ControlSets/CreateAccountControlSet.cs +++ b/EndlessClient/ControlSets/CreateAccountControlSet.cs @@ -13,201 +13,202 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.ControlSets; - -public class CreateAccountControlSet : IntermediateControlSet +namespace EndlessClient.ControlSets { - private readonly IAccountController _accountController; - - private Texture2D _labelsTexture; + public class CreateAccountControlSet : IntermediateControlSet + { + private readonly IAccountController _accountController; - private IXNATextBox _tbAccountName, - _tbPassword, - _tbConfirm, - _tbRealName, - _tbLocation, - _tbEmail; - private IXNAButton _btnCancel; - private IXNAPanel _labels; + private Texture2D _labelsTexture; - private Task _createAccountTask; + private IXNATextBox _tbAccountName, + _tbPassword, + _tbConfirm, + _tbRealName, + _tbLocation, + _tbEmail; + private IXNAButton _btnCancel; + private IXNAPanel _labels; - public override GameStates GameState => GameStates.CreateAccount; + private Task _createAccountTask; - public CreateAccountControlSet(IMainButtonController mainButtonController, - IAccountController accountController, - IClientWindowSizeRepository clientWindowSizeRepository) - : base(mainButtonController, clientWindowSizeRepository) - { - _accountController = accountController; - } + public override GameStates GameState => GameStates.CreateAccount; - public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - base.InitializeResources(gfxManager, contentProvider); + public CreateAccountControlSet(IMainButtonController mainButtonController, + IAccountController accountController, + IClientWindowSizeRepository clientWindowSizeRepository) + : base(mainButtonController, clientWindowSizeRepository) + { + _accountController = accountController; + } - _labelsTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 12, true); - } + public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + base.InitializeResources(gfxManager, contentProvider); - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - _tbAccountName = GetControl(currentControlSet, GameControlIdentifier.CreateAccountName, GetCreateAccountNameTextBox); - _tbPassword = GetControl(currentControlSet, GameControlIdentifier.CreateAccountPassword, GetCreateAccountPasswordTextBox); - _tbConfirm = GetControl(currentControlSet, GameControlIdentifier.CreateAccountPasswordConfirm, GetCreateAccountConfirmTextBox); - _tbRealName = GetControl(currentControlSet, GameControlIdentifier.CreateAccountRealName, GetCreateAccountRealNameTextBox); - _tbLocation = GetControl(currentControlSet, GameControlIdentifier.CreateAccountLocation, GetCreateAccountLocationTextBox); - _tbEmail = GetControl(currentControlSet, GameControlIdentifier.CreateAccountEmail, GetCreateAccountEmailTextBox); - _btnCancel = GetControl(currentControlSet, GameControlIdentifier.CreateAccountCancelButton, GetCreateAccountCancelButton); - _labels = GetControl(currentControlSet, GameControlIdentifier.CreateAccountLabels, GetCreateAccountLabels); - - _allComponents.Add(_tbAccountName); - _allComponents.Add(_tbPassword); - _allComponents.Add(_tbConfirm); - _allComponents.Add(_tbRealName); - _allComponents.Add(_tbLocation); - _allComponents.Add(_tbEmail); - _allComponents.Add(_btnCancel); - _allComponents.Add(_labels); - - var textBoxes = _allComponents.OfType().ToArray(); - - _tbAccountName.Selected = true; - - base.InitializeControlsHelper(currentControlSet); - } + _labelsTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 12, true); + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) - { - switch (control) + protected override void InitializeControlsHelper(IControlSet currentControlSet) { - case GameControlIdentifier.CreateAccountLabels: return _labels; - case GameControlIdentifier.CreateAccountName: return _tbAccountName; - case GameControlIdentifier.CreateAccountPassword: return _tbPassword; - case GameControlIdentifier.CreateAccountPasswordConfirm: return _tbConfirm; - case GameControlIdentifier.CreateAccountRealName: return _tbRealName; - case GameControlIdentifier.CreateAccountLocation: return _tbLocation; - case GameControlIdentifier.CreateAccountEmail: return _tbEmail; - case GameControlIdentifier.CreateAccountCancelButton: return _btnCancel; - default: return base.FindComponentByControlIdentifier(control); + _tbAccountName = GetControl(currentControlSet, GameControlIdentifier.CreateAccountName, GetCreateAccountNameTextBox); + _tbPassword = GetControl(currentControlSet, GameControlIdentifier.CreateAccountPassword, GetCreateAccountPasswordTextBox); + _tbConfirm = GetControl(currentControlSet, GameControlIdentifier.CreateAccountPasswordConfirm, GetCreateAccountConfirmTextBox); + _tbRealName = GetControl(currentControlSet, GameControlIdentifier.CreateAccountRealName, GetCreateAccountRealNameTextBox); + _tbLocation = GetControl(currentControlSet, GameControlIdentifier.CreateAccountLocation, GetCreateAccountLocationTextBox); + _tbEmail = GetControl(currentControlSet, GameControlIdentifier.CreateAccountEmail, GetCreateAccountEmailTextBox); + _btnCancel = GetControl(currentControlSet, GameControlIdentifier.CreateAccountCancelButton, GetCreateAccountCancelButton); + _labels = GetControl(currentControlSet, GameControlIdentifier.CreateAccountLabels, GetCreateAccountLabels); + + _allComponents.Add(_tbAccountName); + _allComponents.Add(_tbPassword); + _allComponents.Add(_tbConfirm); + _allComponents.Add(_tbRealName); + _allComponents.Add(_tbLocation); + _allComponents.Add(_tbEmail); + _allComponents.Add(_btnCancel); + _allComponents.Add(_labels); + + var textBoxes = _allComponents.OfType().ToArray(); + + _tbAccountName.Selected = true; + + base.InitializeControlsHelper(currentControlSet); } - } - private IXNATextBox GetCreateAccountNameTextBox() - { - var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountName); - tb.MaxChars = 16; - return tb; - } + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + switch (control) + { + case GameControlIdentifier.CreateAccountLabels: return _labels; + case GameControlIdentifier.CreateAccountName: return _tbAccountName; + case GameControlIdentifier.CreateAccountPassword: return _tbPassword; + case GameControlIdentifier.CreateAccountPasswordConfirm: return _tbConfirm; + case GameControlIdentifier.CreateAccountRealName: return _tbRealName; + case GameControlIdentifier.CreateAccountLocation: return _tbLocation; + case GameControlIdentifier.CreateAccountEmail: return _tbEmail; + case GameControlIdentifier.CreateAccountCancelButton: return _btnCancel; + default: return base.FindComponentByControlIdentifier(control); + } + } - private IXNATextBox GetCreateAccountPasswordTextBox() - { - var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountPassword); - tb.PasswordBox = true; - tb.MaxChars = 12; - return tb; - } + private IXNATextBox GetCreateAccountNameTextBox() + { + var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountName); + tb.MaxChars = 16; + return tb; + } - private IXNATextBox GetCreateAccountConfirmTextBox() - { - var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountPasswordConfirm); - tb.PasswordBox = true; - tb.MaxChars = 12; - return tb; - } + private IXNATextBox GetCreateAccountPasswordTextBox() + { + var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountPassword); + tb.PasswordBox = true; + tb.MaxChars = 12; + return tb; + } - private IXNATextBox GetCreateAccountRealNameTextBox() - { - return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountRealName); - } + private IXNATextBox GetCreateAccountConfirmTextBox() + { + var tb = AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountPasswordConfirm); + tb.PasswordBox = true; + tb.MaxChars = 12; + return tb; + } - private IXNATextBox GetCreateAccountLocationTextBox() - { - return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountLocation); - } + private IXNATextBox GetCreateAccountRealNameTextBox() + { + return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountRealName); + } - private IXNATextBox GetCreateAccountEmailTextBox() - { - return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountEmail); - } + private IXNATextBox GetCreateAccountLocationTextBox() + { + return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountLocation); + } - private IXNATextBox AccountInputTextBoxCreationHelper(GameControlIdentifier whichControl) - { - int i; - switch (whichControl) + private IXNATextBox GetCreateAccountEmailTextBox() { - case GameControlIdentifier.CreateAccountName: i = 0; break; - case GameControlIdentifier.CreateAccountPassword: i = 1; break; - case GameControlIdentifier.CreateAccountPasswordConfirm: i = 2; break; - case GameControlIdentifier.CreateAccountRealName: i = 3; break; - case GameControlIdentifier.CreateAccountLocation: i = 4; break; - case GameControlIdentifier.CreateAccountEmail: i = 5; break; - default: throw new ArgumentException("Invalid control specified for helper", nameof(whichControl)); + return AccountInputTextBoxCreationHelper(GameControlIdentifier.CreateAccountEmail); } - //set the first 3 Y coord to start at 69 and move up by 51 each time - //set the second 3 Y coord to start at 260 and move up by 51 each time - var txtYCoord = (i < 3 ? 69 : 260) + i % 3 * 51; - var drawArea = new Rectangle(358, txtYCoord, 240, _textBoxBackground.Height); - return new XNATextBox(drawArea, - Constants.FontSize08, - _textBoxBackground, - _textBoxLeft, - _textBoxRight, - _textBoxCursor) + private IXNATextBox AccountInputTextBoxCreationHelper(GameControlIdentifier whichControl) { - LeftPadding = 4, - MaxChars = 35, - Text = "", - DefaultText = " ", - TabOrder = whichControl - GameControlIdentifier.CreateAccountName - }; - } + int i; + switch (whichControl) + { + case GameControlIdentifier.CreateAccountName: i = 0; break; + case GameControlIdentifier.CreateAccountPassword: i = 1; break; + case GameControlIdentifier.CreateAccountPasswordConfirm: i = 2; break; + case GameControlIdentifier.CreateAccountRealName: i = 3; break; + case GameControlIdentifier.CreateAccountLocation: i = 4; break; + case GameControlIdentifier.CreateAccountEmail: i = 5; break; + default: throw new ArgumentException("Invalid control specified for helper", nameof(whichControl)); + } + + //set the first 3 Y coord to start at 69 and move up by 51 each time + //set the second 3 Y coord to start at 260 and move up by 51 each time + var txtYCoord = (i < 3 ? 69 : 260) + i % 3 * 51; + var drawArea = new Rectangle(358, txtYCoord, 240, _textBoxBackground.Height); + return new XNATextBox(drawArea, + Constants.FontSize08, + _textBoxBackground, + _textBoxLeft, + _textBoxRight, + _textBoxCursor) + { + LeftPadding = 4, + MaxChars = 35, + Text = "", + DefaultText = " ", + TabOrder = whichControl - GameControlIdentifier.CreateAccountName + }; + } - private IXNAButton GetCreateAccountCancelButton() - { - var button = new XNAButton(_secondaryButtonTexture, - new Vector2(481, 417), - new Rectangle(0, 40, 120, 40), - new Rectangle(120, 40, 120, 40)); - button.OnClick += (o, e) => _mainButtonController.GoToInitialState(); - return button; - } + private IXNAButton GetCreateAccountCancelButton() + { + var button = new XNAButton(_secondaryButtonTexture, + new Vector2(481, 417), + new Rectangle(0, 40, 120, 40), + new Rectangle(120, 40, 120, 40)); + button.OnClick += (o, e) => _mainButtonController.GoToInitialState(); + return button; + } - private IXNAPanel GetCreateAccountLabels() - { - var labelsPanel = new XNAPanel(); - for (int srcYIndex = 0; srcYIndex < 6; ++srcYIndex) + private IXNAPanel GetCreateAccountLabels() { - var texturePictureBox = new XNAPictureBox + var labelsPanel = new XNAPanel(); + for (int srcYIndex = 0; srcYIndex < 6; ++srcYIndex) { - Texture = _labelsTexture, - SourceRectangle = new Rectangle(0, srcYIndex * (srcYIndex < 2 ? 14 : 15), 149, 15), - DrawPosition = new Vector2(430, (srcYIndex < 3 ? 50 : 241) + 10 + srcYIndex % 3 * 51) - }; - texturePictureBox.SetParentControl(labelsPanel); + var texturePictureBox = new XNAPictureBox + { + Texture = _labelsTexture, + SourceRectangle = new Rectangle(0, srcYIndex * (srcYIndex < 2 ? 14 : 15), 149, 15), + DrawPosition = new Vector2(430, (srcYIndex < 3 ? 50 : 241) + 10 + srcYIndex % 3 * 51) + }; + texturePictureBox.SetParentControl(labelsPanel); + } + return labelsPanel; } - return labelsPanel; - } - protected override IXNAButton GetCreateButton() - { - var button = base.GetCreateButton(); - button.OnClick += DoCreateAccount; - return button; - } + protected override IXNAButton GetCreateButton() + { + var button = base.GetCreateButton(); + button.OnClick += DoCreateAccount; + return button; + } - private void DoCreateAccount(object sender, EventArgs e) - { - if (_createAccountTask == null) + private void DoCreateAccount(object sender, EventArgs e) { - _createAccountTask = _accountController.CreateAccount( - new CreateAccountParameters(_tbAccountName.Text, - _tbPassword.Text, - _tbConfirm.Text, - _tbRealName.Text, - _tbLocation.Text, - _tbEmail.Text)); - _createAccountTask.ContinueWith(_ => _createAccountTask = null); + if (_createAccountTask == null) + { + _createAccountTask = _accountController.CreateAccount( + new CreateAccountParameters(_tbAccountName.Text, + _tbPassword.Text, + _tbConfirm.Text, + _tbRealName.Text, + _tbLocation.Text, + _tbEmail.Text)); + _createAccountTask.ContinueWith(_ => _createAccountTask = null); + } } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/EmptyControlSet.cs b/EndlessClient/ControlSets/EmptyControlSet.cs index 33f7a76be..1fe96ebbe 100644 --- a/EndlessClient/ControlSets/EmptyControlSet.cs +++ b/EndlessClient/ControlSets/EmptyControlSet.cs @@ -6,33 +6,34 @@ using System.Linq; using XNAControls; -namespace EndlessClient.ControlSets; - -/// -/// An empty control set that represents the initial state of the game with no controls -/// -public class EmptyControlSet : IControlSet +namespace EndlessClient.ControlSets { - public GameStates GameState => GameStates.None; + /// + /// An empty control set that represents the initial state of the game with no controls + /// + public class EmptyControlSet : IControlSet + { + public GameStates GameState => GameStates.None; - public IReadOnlyList AllComponents => Enumerable.Empty().ToList(); + public IReadOnlyList AllComponents => Enumerable.Empty().ToList(); - public IReadOnlyList XNAControlComponents => AllComponents.OfType().ToList(); + public IReadOnlyList XNAControlComponents => AllComponents.OfType().ToList(); - public void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - } + public void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + } - public void InitializeControls(IControlSet currentControlSet) - { - } + public void InitializeControls(IControlSet currentControlSet) + { + } - public IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) - { - return null; - } + public IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + return null; + } - public void Dispose() - { + public void Dispose() + { + } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/GameControlIdentifier.cs b/EndlessClient/ControlSets/GameControlIdentifier.cs index 15259325f..19f429449 100644 --- a/EndlessClient/ControlSets/GameControlIdentifier.cs +++ b/EndlessClient/ControlSets/GameControlIdentifier.cs @@ -1,40 +1,41 @@ -namespace EndlessClient.ControlSets; - -public enum GameControlIdentifier +namespace EndlessClient.ControlSets { - InitialCreateAccount, - InitialLogin, - InitialViewCredits, - InitialExitGame, - InitialVersionLabel, + public enum GameControlIdentifier + { + InitialCreateAccount, + InitialLogin, + InitialViewCredits, + InitialExitGame, + InitialVersionLabel, - CreateAccountLabels, - CreateAccountName, - CreateAccountPassword, - CreateAccountPasswordConfirm, - CreateAccountRealName, - CreateAccountLocation, - CreateAccountEmail, - CreateAccountButton, - CreateAccountCancelButton, + CreateAccountLabels, + CreateAccountName, + CreateAccountPassword, + CreateAccountPasswordConfirm, + CreateAccountRealName, + CreateAccountLocation, + CreateAccountEmail, + CreateAccountButton, + CreateAccountCancelButton, - LoginPanelBackground, - LoginAccountName, - LoginPassword, - LoginButton, - LoginCancel, + LoginPanelBackground, + LoginAccountName, + LoginPassword, + LoginButton, + LoginCancel, - CreditsLabel, + CreditsLabel, - BackButton, - PersonDisplay1, - PersonDisplay2, - BackgroundImage, + BackButton, + PersonDisplay1, + PersonDisplay2, + BackgroundImage, - CreateCharacterButton, - ChangePasswordButton, + CreateCharacterButton, + ChangePasswordButton, - Character1Panel, - Character2Panel, - Character3Panel + Character1Panel, + Character2Panel, + Character3Panel + } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/IControlSet.cs b/EndlessClient/ControlSets/IControlSet.cs index d2ce1acbd..c77c536a4 100644 --- a/EndlessClient/ControlSets/IControlSet.cs +++ b/EndlessClient/ControlSets/IControlSet.cs @@ -6,42 +6,43 @@ using System.Collections.Generic; using XNAControls; -namespace EndlessClient.ControlSets; - -public interface IControlSet : IDisposable +namespace EndlessClient.ControlSets { - /// - /// The game state that this control set represents - /// - GameStates GameState { get; } + public interface IControlSet : IDisposable + { + /// + /// The game state that this control set represents + /// + GameStates GameState { get; } - /// - /// All components in this control set - /// - IReadOnlyList AllComponents { get; } + /// + /// All components in this control set + /// + IReadOnlyList AllComponents { get; } - /// - /// Components in this control set that are XNAControls - /// - IReadOnlyList XNAControlComponents { get; } + /// + /// Components in this control set that are XNAControls + /// + IReadOnlyList XNAControlComponents { get; } - /// - /// Initialize the required resources for the control set from the resource dependencies. Should be called before InitializeControls() - /// - /// An initialized native graphics manager - /// The ContentProvider for the game - void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider); + /// + /// Initialize the required resources for the control set from the resource dependencies. Should be called before InitializeControls() + /// + /// An initialized native graphics manager + /// The ContentProvider for the game + void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider); - /// - /// Create the controls for this IControlSet based on an existing set of controls - /// - /// The current active set of controls - void InitializeControls(IControlSet currentControlSet); + /// + /// Create the controls for this IControlSet based on an existing set of controls + /// + /// The current active set of controls + void InitializeControls(IControlSet currentControlSet); - /// - /// Find an existing component from this game control set - /// - /// The control specification - /// The matching control - IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control); + /// + /// Find an existing component from this game control set + /// + /// The control specification + /// The matching control + IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control); + } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/IControlSetFactory.cs b/EndlessClient/ControlSets/IControlSetFactory.cs index e8759d5d3..7117fc67f 100644 --- a/EndlessClient/ControlSets/IControlSetFactory.cs +++ b/EndlessClient/ControlSets/IControlSetFactory.cs @@ -1,14 +1,15 @@ using EndlessClient.Controllers; using EndlessClient.GameExecution; -namespace EndlessClient.ControlSets; - -public interface IControlSetFactory +namespace EndlessClient.ControlSets { - IControlSet CreateControlsForState(GameStates newState, IControlSet currentControlSet); + public interface IControlSetFactory + { + IControlSet CreateControlsForState(GameStates newState, IControlSet currentControlSet); - void InjectControllers(IMainButtonController mainButtonController, - IAccountController accountController, - ILoginController loginController, - ICharacterManagementController characterManagementController); + void InjectControllers(IMainButtonController mainButtonController, + IAccountController accountController, + ILoginController loginController, + ICharacterManagementController characterManagementController); + } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/IControlSetRepository.cs b/EndlessClient/ControlSets/IControlSetRepository.cs index cc76e581d..efddacb41 100644 --- a/EndlessClient/ControlSets/IControlSetRepository.cs +++ b/EndlessClient/ControlSets/IControlSetRepository.cs @@ -1,25 +1,26 @@ using AutomaticTypeMapper; -namespace EndlessClient.ControlSets; - -public interface IControlSetRepository -{ - IControlSet CurrentControlSet { get; set; } -} - -public interface IControlSetProvider +namespace EndlessClient.ControlSets { - IControlSet CurrentControlSet { get; } -} + public interface IControlSetRepository + { + IControlSet CurrentControlSet { get; set; } + } -[MappedType(BaseType = typeof(IControlSetRepository), IsSingleton = true)] -[MappedType(BaseType = typeof(IControlSetProvider), IsSingleton = true)] -public class ControlSetRepository : IControlSetRepository, IControlSetProvider -{ - public IControlSet CurrentControlSet { get; set; } + public interface IControlSetProvider + { + IControlSet CurrentControlSet { get; } + } - public ControlSetRepository() + [MappedType(BaseType = typeof(IControlSetRepository), IsSingleton = true)] + [MappedType(BaseType = typeof(IControlSetProvider), IsSingleton = true)] + public class ControlSetRepository : IControlSetRepository, IControlSetProvider { - CurrentControlSet = new EmptyControlSet(); + public IControlSet CurrentControlSet { get; set; } + + public ControlSetRepository() + { + CurrentControlSet = new EmptyControlSet(); + } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/IHudControlProvider.cs b/EndlessClient/ControlSets/IHudControlProvider.cs index ff7160750..c6693c135 100644 --- a/EndlessClient/ControlSets/IHudControlProvider.cs +++ b/EndlessClient/ControlSets/IHudControlProvider.cs @@ -6,64 +6,65 @@ using System; using System.Collections.Generic; -namespace EndlessClient.ControlSets; - -public interface IHudControlProvider +namespace EndlessClient.ControlSets { - bool IsInGame { get; } + public interface IHudControlProvider + { + bool IsInGame { get; } - InGameControlSet ControlSet { get; } + InGameControlSet ControlSet { get; } - IReadOnlyList HudPanels { get; } + IReadOnlyList HudPanels { get; } - T GetComponent(HudControlIdentifier identifier) where T : IGameComponent; -} + T GetComponent(HudControlIdentifier identifier) where T : IGameComponent; + } -[MappedType(BaseType = typeof(IHudControlProvider), IsSingleton = true)] -public class HudControlProvider : IHudControlProvider -{ - private readonly IGameStateProvider _gameStateProvider; - private readonly IControlSetProvider _controlSetProvider; + [MappedType(BaseType = typeof(IHudControlProvider), IsSingleton = true)] + public class HudControlProvider : IHudControlProvider + { + private readonly IGameStateProvider _gameStateProvider; + private readonly IControlSetProvider _controlSetProvider; - public bool IsInGame => _gameStateProvider.CurrentState == GameStates.PlayingTheGame && - _controlSetProvider.CurrentControlSet.GameState == GameStates.PlayingTheGame && - _controlSetProvider.CurrentControlSet is InGameControlSet; + public bool IsInGame => _gameStateProvider.CurrentState == GameStates.PlayingTheGame && + _controlSetProvider.CurrentControlSet.GameState == GameStates.PlayingTheGame && + _controlSetProvider.CurrentControlSet is InGameControlSet; - public InGameControlSet ControlSet - { - get + public InGameControlSet ControlSet { - if (!IsInGame) - throw new InvalidOperationException("Not currently in game, in game control set does not exist"); + get + { + if (!IsInGame) + throw new InvalidOperationException("Not currently in game, in game control set does not exist"); - return (InGameControlSet)_controlSetProvider.CurrentControlSet; + return (InGameControlSet)_controlSetProvider.CurrentControlSet; + } } - } - public IReadOnlyList HudPanels => new[] - { - GetComponent(HudControlIdentifier.NewsPanel), - GetComponent(HudControlIdentifier.InventoryPanel), - GetComponent(HudControlIdentifier.ActiveSpellsPanel), - GetComponent(HudControlIdentifier.PassiveSpellsPanel), - GetComponent(HudControlIdentifier.ChatPanel), - GetComponent(HudControlIdentifier.StatsPanel), - GetComponent(HudControlIdentifier.OnlineListPanel), - GetComponent(HudControlIdentifier.PartyPanel), - //macro panel - GetComponent(HudControlIdentifier.SettingsPanel), - GetComponent(HudControlIdentifier.HelpPanel) - }; + public IReadOnlyList HudPanels => new[] + { + GetComponent(HudControlIdentifier.NewsPanel), + GetComponent(HudControlIdentifier.InventoryPanel), + GetComponent(HudControlIdentifier.ActiveSpellsPanel), + GetComponent(HudControlIdentifier.PassiveSpellsPanel), + GetComponent(HudControlIdentifier.ChatPanel), + GetComponent(HudControlIdentifier.StatsPanel), + GetComponent(HudControlIdentifier.OnlineListPanel), + GetComponent(HudControlIdentifier.PartyPanel), + //macro panel + GetComponent(HudControlIdentifier.SettingsPanel), + GetComponent(HudControlIdentifier.HelpPanel) + }; - public HudControlProvider(IGameStateProvider gameStateProvider, - IControlSetProvider controlSetProvider) - { - _gameStateProvider = gameStateProvider; - _controlSetProvider = controlSetProvider; - } + public HudControlProvider(IGameStateProvider gameStateProvider, + IControlSetProvider controlSetProvider) + { + _gameStateProvider = gameStateProvider; + _controlSetProvider = controlSetProvider; + } - public T GetComponent(HudControlIdentifier identifier) where T : IGameComponent - { - return ControlSet.GetHudComponent(identifier); + public T GetComponent(HudControlIdentifier identifier) where T : IGameComponent + { + return ControlSet.GetHudComponent(identifier); + } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/InGameControlSet.cs b/EndlessClient/ControlSets/InGameControlSet.cs index 0a4bcf56e..12bb0dfd6 100644 --- a/EndlessClient/ControlSets/InGameControlSet.cs +++ b/EndlessClient/ControlSets/InGameControlSet.cs @@ -11,62 +11,63 @@ using System.Linq; using XNAControls; -namespace EndlessClient.ControlSets; - -public class InGameControlSet : BackButtonControlSet +namespace EndlessClient.ControlSets { - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IHudControlsFactory _hudControlsFactory; - private readonly IActiveDialogRepository _activeDialogRepository; - private IReadOnlyDictionary _controls; - - public override GameStates GameState => GameStates.PlayingTheGame; - - public InGameControlSet(IMainButtonController mainButtonController, - IEOMessageBoxFactory messageBoxFactory, - IHudControlsFactory hudControlsFactory, - IActiveDialogRepository activeDialogRepository, - IClientWindowSizeRepository clientWindowSizeRepository) - : base(mainButtonController, clientWindowSizeRepository) + public class InGameControlSet : BackButtonControlSet { - _messageBoxFactory = messageBoxFactory; - _hudControlsFactory = hudControlsFactory; - _activeDialogRepository = activeDialogRepository; - _controls = new Dictionary(); - } + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IHudControlsFactory _hudControlsFactory; + private readonly IActiveDialogRepository _activeDialogRepository; + private IReadOnlyDictionary _controls; - public T GetHudComponent(HudControlIdentifier whichControl) - where T : IGameComponent - { - return (T)_controls[whichControl]; - } + public override GameStates GameState => GameStates.PlayingTheGame; - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - _controls = _hudControlsFactory.CreateHud(); - _allComponents.AddRange(_controls.Select(x => x.Value)); + public InGameControlSet(IMainButtonController mainButtonController, + IEOMessageBoxFactory messageBoxFactory, + IHudControlsFactory hudControlsFactory, + IActiveDialogRepository activeDialogRepository, + IClientWindowSizeRepository clientWindowSizeRepository) + : base(mainButtonController, clientWindowSizeRepository) + { + _messageBoxFactory = messageBoxFactory; + _hudControlsFactory = hudControlsFactory; + _activeDialogRepository = activeDialogRepository; + _controls = new Dictionary(); + } - base.InitializeControlsHelper(currentControlSet); - } + public T GetHudComponent(HudControlIdentifier whichControl) + where T : IGameComponent + { + return (T)_controls[whichControl]; + } - protected override async void DoBackButtonClick(object sender, EventArgs e) - { - var messageBox = _messageBoxFactory.CreateMessageBox( - DialogResourceID.EXIT_GAME_ARE_YOU_SURE, - EODialogButtons.OkCancel); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + _controls = _hudControlsFactory.CreateHud(); + _allComponents.AddRange(_controls.Select(x => x.Value)); - var result = await messageBox.ShowDialogAsync(); - if (result == XNADialogResult.OK) - _mainButtonController.GoToInitialStateAndDisconnect(); - } + base.InitializeControlsHelper(currentControlSet); + } - protected override void Dispose(bool disposing) - { - if (disposing) + protected override async void DoBackButtonClick(object sender, EventArgs e) { - _activeDialogRepository.Dispose(); + var messageBox = _messageBoxFactory.CreateMessageBox( + DialogResourceID.EXIT_GAME_ARE_YOU_SURE, + EODialogButtons.OkCancel); + + var result = await messageBox.ShowDialogAsync(); + if (result == XNADialogResult.OK) + _mainButtonController.GoToInitialStateAndDisconnect(); } - base.Dispose(disposing); + protected override void Dispose(bool disposing) + { + if (disposing) + { + _activeDialogRepository.Dispose(); + } + + base.Dispose(disposing); + } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/InitialControlSet.cs b/EndlessClient/ControlSets/InitialControlSet.cs index 92aff0895..11c4d8a31 100644 --- a/EndlessClient/ControlSets/InitialControlSet.cs +++ b/EndlessClient/ControlSets/InitialControlSet.cs @@ -10,165 +10,166 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.ControlSets; - -public class InitialControlSet : BaseControlSet +namespace EndlessClient.ControlSets { - private readonly IConfigurationProvider _configProvider; - private readonly IMainButtonController _mainButtonController; - - private IXNAButton _createAccount, - _login, - _viewCredits, - _exitGame; - private IXNALabel _versionInfo; + public class InitialControlSet : BaseControlSet + { + private readonly IConfigurationProvider _configProvider; + private readonly IMainButtonController _mainButtonController; - protected IXNAPictureBox _personPicture; + private IXNAButton _createAccount, + _login, + _viewCredits, + _exitGame; + private IXNALabel _versionInfo; - private readonly Texture2D[] _personSet1; - private readonly Random _randomGen; + protected IXNAPictureBox _personPicture; - private Task _mainButtonClickTask; + private readonly Texture2D[] _personSet1; + private readonly Random _randomGen; - public override GameStates GameState => GameStates.Initial; + private Task _mainButtonClickTask; - public InitialControlSet(IConfigurationProvider configProvider, - IMainButtonController mainButtonController) - { - _configProvider = configProvider; - _mainButtonController = mainButtonController; - _personSet1 = new Texture2D[4]; - _randomGen = new Random(); - } + public override GameStates GameState => GameStates.Initial; - public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - base.InitializeResources(gfxManager, contentProvider); + public InitialControlSet(IConfigurationProvider configProvider, + IMainButtonController mainButtonController) + { + _configProvider = configProvider; + _mainButtonController = mainButtonController; + _personSet1 = new Texture2D[4]; + _randomGen = new Random(); + } - for (int i = 0; i < _personSet1.Length; ++i) - _personSet1[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 41 + i, true); - } + public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + base.InitializeResources(gfxManager, contentProvider); - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - _createAccount = GetControl(currentControlSet, GameControlIdentifier.InitialCreateAccount, GetMainCreateAccountButton); - _login = GetControl(currentControlSet, GameControlIdentifier.InitialLogin, GetMainLoginButton); - _viewCredits = GetControl(currentControlSet, GameControlIdentifier.InitialViewCredits, GetViewCreditsButton); - _exitGame = GetControl(currentControlSet, GameControlIdentifier.InitialExitGame, GetExitButton); - _versionInfo = GetControl(currentControlSet, GameControlIdentifier.InitialVersionLabel, GetVersionInfoLabel); - _personPicture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay1, GetPersonPicture1); - - _allComponents.Add(_createAccount); - _allComponents.Add(_login); - _allComponents.Add(_viewCredits); - _allComponents.Add(_exitGame); - _allComponents.Add(_versionInfo); - _allComponents.Add(_personPicture); - } + for (int i = 0; i < _personSet1.Length; ++i) + _personSet1[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 41 + i, true); + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) - { - switch (control) + protected override void InitializeControlsHelper(IControlSet currentControlSet) { - case GameControlIdentifier.InitialCreateAccount: return _createAccount; - case GameControlIdentifier.InitialLogin: return _login; - case GameControlIdentifier.InitialViewCredits: return _viewCredits; - case GameControlIdentifier.InitialExitGame: return _exitGame; - case GameControlIdentifier.InitialVersionLabel: return _versionInfo; - case GameControlIdentifier.PersonDisplay1: return _personPicture; - default: return base.FindComponentByControlIdentifier(control); + _createAccount = GetControl(currentControlSet, GameControlIdentifier.InitialCreateAccount, GetMainCreateAccountButton); + _login = GetControl(currentControlSet, GameControlIdentifier.InitialLogin, GetMainLoginButton); + _viewCredits = GetControl(currentControlSet, GameControlIdentifier.InitialViewCredits, GetViewCreditsButton); + _exitGame = GetControl(currentControlSet, GameControlIdentifier.InitialExitGame, GetExitButton); + _versionInfo = GetControl(currentControlSet, GameControlIdentifier.InitialVersionLabel, GetVersionInfoLabel); + _personPicture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay1, GetPersonPicture1); + + _allComponents.Add(_createAccount); + _allComponents.Add(_login); + _allComponents.Add(_viewCredits); + _allComponents.Add(_exitGame); + _allComponents.Add(_versionInfo); + _allComponents.Add(_personPicture); } - } - - private IXNAButton GetMainCreateAccountButton() - { - var button = MainButtonCreationHelper(GameControlIdentifier.InitialCreateAccount); - button.OnClick += (o, e) => AsyncMainButtonClick(_mainButtonController.ClickCreateAccount); - return button; - } - private IXNAButton GetMainLoginButton() - { - var button = MainButtonCreationHelper(GameControlIdentifier.InitialLogin); - button.OnClick += (o, e) => AsyncMainButtonClick(_mainButtonController.ClickLogin); - return button; - } + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) + { + switch (control) + { + case GameControlIdentifier.InitialCreateAccount: return _createAccount; + case GameControlIdentifier.InitialLogin: return _login; + case GameControlIdentifier.InitialViewCredits: return _viewCredits; + case GameControlIdentifier.InitialExitGame: return _exitGame; + case GameControlIdentifier.InitialVersionLabel: return _versionInfo; + case GameControlIdentifier.PersonDisplay1: return _personPicture; + default: return base.FindComponentByControlIdentifier(control); + } + } - private IXNAButton GetViewCreditsButton() - { - var button = MainButtonCreationHelper(GameControlIdentifier.InitialViewCredits); - button.OnClick += (o, e) => _mainButtonController.ClickViewCredits(); - return button; - } + private IXNAButton GetMainCreateAccountButton() + { + var button = MainButtonCreationHelper(GameControlIdentifier.InitialCreateAccount); + button.OnClick += (o, e) => AsyncMainButtonClick(_mainButtonController.ClickCreateAccount); + return button; + } - private IXNAButton GetExitButton() - { - var button = MainButtonCreationHelper(GameControlIdentifier.InitialExitGame); - button.OnClick += (o, e) => _mainButtonController.ClickExit(); - return button; - } + private IXNAButton GetMainLoginButton() + { + var button = MainButtonCreationHelper(GameControlIdentifier.InitialLogin); + button.OnClick += (o, e) => AsyncMainButtonClick(_mainButtonController.ClickLogin); + return button; + } - private void AsyncMainButtonClick(Func clickHandler) - { - if (_mainButtonClickTask == null) + private IXNAButton GetViewCreditsButton() { - _mainButtonClickTask = clickHandler(); - _mainButtonClickTask.ContinueWith(_ => _mainButtonClickTask = null); + var button = MainButtonCreationHelper(GameControlIdentifier.InitialViewCredits); + button.OnClick += (o, e) => _mainButtonController.ClickViewCredits(); + return button; } - } - private IXNAButton MainButtonCreationHelper(GameControlIdentifier whichControl) - { - int i; - switch (whichControl) + private IXNAButton GetExitButton() { - case GameControlIdentifier.InitialCreateAccount: i = 0; break; - case GameControlIdentifier.InitialLogin: i = 1; break; - case GameControlIdentifier.InitialViewCredits: i = 2; break; - case GameControlIdentifier.InitialExitGame: i = 3; break; - default: throw new ArgumentException("Invalid control specified for helper", nameof(whichControl)); + var button = MainButtonCreationHelper(GameControlIdentifier.InitialExitGame); + button.OnClick += (o, e) => _mainButtonController.ClickExit(); + return button; } - var widthFactor = _mainButtonTexture.Width / 2; - var heightFactor = _mainButtonTexture.Height / 4; - var outSource = new Rectangle(0, i * heightFactor, widthFactor, heightFactor); - var overSource = new Rectangle(widthFactor, i * heightFactor, widthFactor, heightFactor); + private void AsyncMainButtonClick(Func clickHandler) + { + if (_mainButtonClickTask == null) + { + _mainButtonClickTask = clickHandler(); + _mainButtonClickTask.ContinueWith(_ => _mainButtonClickTask = null); + } + } - return new XNAButton(_mainButtonTexture, new Vector2(25, 280 + i * 40), outSource, overSource) + private IXNAButton MainButtonCreationHelper(GameControlIdentifier whichControl) { - //DrawOrder = i + 1 - }; - } + int i; + switch (whichControl) + { + case GameControlIdentifier.InitialCreateAccount: i = 0; break; + case GameControlIdentifier.InitialLogin: i = 1; break; + case GameControlIdentifier.InitialViewCredits: i = 2; break; + case GameControlIdentifier.InitialExitGame: i = 3; break; + default: throw new ArgumentException("Invalid control specified for helper", nameof(whichControl)); + } + + var widthFactor = _mainButtonTexture.Width / 2; + var heightFactor = _mainButtonTexture.Height / 4; + var outSource = new Rectangle(0, i * heightFactor, widthFactor, heightFactor); + var overSource = new Rectangle(widthFactor, i * heightFactor, widthFactor, heightFactor); + + return new XNAButton(_mainButtonTexture, new Vector2(25, 280 + i * 40), outSource, overSource) + { + //DrawOrder = i + 1 + }; + } - private IXNALabel GetVersionInfoLabel() - { - return new XNALabel(Constants.FontSize07) + private IXNALabel GetVersionInfoLabel() { - AutoSize = true, - Text = string.Format(Constants.VersionInfoFormat, - _configProvider.VersionMajor, - _configProvider.VersionMinor, - _configProvider.VersionBuild, - _configProvider.Host, - _configProvider.Port), - ForeColor = Color.FromNonPremultiplied(190, 170, 150, 255), - DrawArea = new Rectangle(28, 457, 1, 1) - }; - } + return new XNALabel(Constants.FontSize07) + { + AutoSize = true, + Text = string.Format(Constants.VersionInfoFormat, + _configProvider.VersionMajor, + _configProvider.VersionMinor, + _configProvider.VersionBuild, + _configProvider.Host, + _configProvider.Port), + ForeColor = Color.FromNonPremultiplied(190, 170, 150, 255), + DrawArea = new Rectangle(28, 457, 1, 1) + }; + } - private IXNAPictureBox GetPersonPicture1() - { - var texture = _personSet1[_randomGen.Next(4)]; - return new XNAPictureBox + private IXNAPictureBox GetPersonPicture1() { - Texture = texture, - DrawArea = new Rectangle(229, 70, texture.Width, texture.Height) - }; - } + var texture = _personSet1[_randomGen.Next(4)]; + return new XNAPictureBox + { + Texture = texture, + DrawArea = new Rectangle(229, 70, texture.Width, texture.Height) + }; + } - protected void ExcludePersonPicture1() - { - _personPicture.Dispose(); - _allComponents.Remove(_personPicture); + protected void ExcludePersonPicture1() + { + _personPicture.Dispose(); + _allComponents.Remove(_personPicture); + } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/IntermediateControlSet.cs b/EndlessClient/ControlSets/IntermediateControlSet.cs index 6d581fd9a..63ebe9f95 100644 --- a/EndlessClient/ControlSets/IntermediateControlSet.cs +++ b/EndlessClient/ControlSets/IntermediateControlSet.cs @@ -8,75 +8,76 @@ using System; using XNAControls; -namespace EndlessClient.ControlSets; - -public abstract class IntermediateControlSet : BackButtonControlSet +namespace EndlessClient.ControlSets { - private readonly Texture2D[] _personSet2; - private readonly Random _randomGen; + public abstract class IntermediateControlSet : BackButtonControlSet + { + private readonly Texture2D[] _personSet2; + private readonly Random _randomGen; - private IXNAButton _btnCreate; - private IXNAPictureBox _person2Picture; + private IXNAButton _btnCreate; + private IXNAPictureBox _person2Picture; - protected IntermediateControlSet(IMainButtonController mainButtonController, - IClientWindowSizeRepository clientWindowSizeRepository) - : base(mainButtonController, clientWindowSizeRepository) - { - _personSet2 = new Texture2D[8]; - _randomGen = new Random(); - } + protected IntermediateControlSet(IMainButtonController mainButtonController, + IClientWindowSizeRepository clientWindowSizeRepository) + : base(mainButtonController, clientWindowSizeRepository) + { + _personSet2 = new Texture2D[8]; + _randomGen = new Random(); + } - public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - base.InitializeResources(gfxManager, contentProvider); + public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + base.InitializeResources(gfxManager, contentProvider); - for (int i = 0; i < _personSet2.Length; ++i) - _personSet2[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 61 + i, true); - } + for (int i = 0; i < _personSet2.Length; ++i) + _personSet2[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 61 + i, true); + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - _btnCreate = GetControl(currentControlSet, - GameState == GameStates.LoggedIn ? GameControlIdentifier.CreateCharacterButton : GameControlIdentifier.CreateAccountButton, - GetCreateButton); - _person2Picture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay2, GetPerson2Picture); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + _btnCreate = GetControl(currentControlSet, + GameState == GameStates.LoggedIn ? GameControlIdentifier.CreateCharacterButton : GameControlIdentifier.CreateAccountButton, + GetCreateButton); + _person2Picture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay2, GetPerson2Picture); - _allComponents.Add(_btnCreate); - _allComponents.Add(_person2Picture); + _allComponents.Add(_btnCreate); + _allComponents.Add(_person2Picture); - base.InitializeControlsHelper(currentControlSet); - } + base.InitializeControlsHelper(currentControlSet); + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) - { - switch (control) + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) { - case GameControlIdentifier.CreateAccountButton: - return GameState == GameStates.CreateAccount ? _btnCreate : null; - case GameControlIdentifier.CreateCharacterButton: - return GameState == GameStates.LoggedIn ? _btnCreate : null; - case GameControlIdentifier.PersonDisplay2: return _person2Picture; - default: return base.FindComponentByControlIdentifier(control); + switch (control) + { + case GameControlIdentifier.CreateAccountButton: + return GameState == GameStates.CreateAccount ? _btnCreate : null; + case GameControlIdentifier.CreateCharacterButton: + return GameState == GameStates.LoggedIn ? _btnCreate : null; + case GameControlIdentifier.PersonDisplay2: return _person2Picture; + default: return base.FindComponentByControlIdentifier(control); + } } - } - protected virtual IXNAButton GetCreateButton() - { - var isCreateCharacterButton = GameState == GameStates.LoggedIn; - var button = new XNAButton(_secondaryButtonTexture, - new Vector2(isCreateCharacterButton ? 334 : 359, 417), - new Rectangle(0, 0, 120, 40), - new Rectangle(120, 0, 120, 40)); - return button; - } + protected virtual IXNAButton GetCreateButton() + { + var isCreateCharacterButton = GameState == GameStates.LoggedIn; + var button = new XNAButton(_secondaryButtonTexture, + new Vector2(isCreateCharacterButton ? 334 : 359, 417), + new Rectangle(0, 0, 120, 40), + new Rectangle(120, 0, 120, 40)); + return button; + } - private IXNAPictureBox GetPerson2Picture() - { - var texture = _personSet2[_randomGen.Next(8)]; - return new XNAPictureBox + private IXNAPictureBox GetPerson2Picture() { - Texture = texture, - DrawArea = new Rectangle(43, 140, texture.Width, texture.Height) - }; + var texture = _personSet2[_randomGen.Next(8)]; + return new XNAPictureBox + { + Texture = texture, + DrawArea = new Rectangle(43, 140, texture.Width, texture.Height) + }; + } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/LoggedInControlSet.cs b/EndlessClient/ControlSets/LoggedInControlSet.cs index f37a12550..325b4895b 100644 --- a/EndlessClient/ControlSets/LoggedInControlSet.cs +++ b/EndlessClient/ControlSets/LoggedInControlSet.cs @@ -10,96 +10,97 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.ControlSets; - -public class LoggedInControlSet : IntermediateControlSet +namespace EndlessClient.ControlSets { - private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; - private readonly ICharacterSelectorProvider _characterSelectorProvider; - private readonly ICharacterManagementController _characterManagementController; - private readonly IAccountController _accountController; - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IUserInputRepository _userInputRepository; - private readonly List _characterInfoPanels; + public class LoggedInControlSet : IntermediateControlSet + { + private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; + private readonly ICharacterSelectorProvider _characterSelectorProvider; + private readonly ICharacterManagementController _characterManagementController; + private readonly IAccountController _accountController; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IUserInputRepository _userInputRepository; + private readonly List _characterInfoPanels; - private IXNAButton _changePasswordButton; + private IXNAButton _changePasswordButton; - private Task _loggedInActionTask; + private Task _loggedInActionTask; - public override GameStates GameState => GameStates.LoggedIn; + public override GameStates GameState => GameStates.LoggedIn; - public LoggedInControlSet(IMainButtonController mainButtonController, - ICharacterInfoPanelFactory characterInfoPanelFactory, - ICharacterSelectorProvider characterSelectorProvider, - ICharacterManagementController characterManagementController, - IAccountController accountController, - IEndlessGameProvider endlessGameProvider, - IUserInputRepository userInputRepository, - IClientWindowSizeRepository clientWindowSizeRepository) - : base(mainButtonController, clientWindowSizeRepository) - { - _characterInfoPanelFactory = characterInfoPanelFactory; - _characterSelectorProvider = characterSelectorProvider; - _characterManagementController = characterManagementController; - _accountController = accountController; - _endlessGameProvider = endlessGameProvider; - _userInputRepository = userInputRepository; - _characterInfoPanels = new List(); - } + public LoggedInControlSet(IMainButtonController mainButtonController, + ICharacterInfoPanelFactory characterInfoPanelFactory, + ICharacterSelectorProvider characterSelectorProvider, + ICharacterManagementController characterManagementController, + IAccountController accountController, + IEndlessGameProvider endlessGameProvider, + IUserInputRepository userInputRepository, + IClientWindowSizeRepository clientWindowSizeRepository) + : base(mainButtonController, clientWindowSizeRepository) + { + _characterInfoPanelFactory = characterInfoPanelFactory; + _characterSelectorProvider = characterSelectorProvider; + _characterManagementController = characterManagementController; + _accountController = accountController; + _endlessGameProvider = endlessGameProvider; + _userInputRepository = userInputRepository; + _characterInfoPanels = new List(); + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - base.InitializeControlsHelper(currentControlSet); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + base.InitializeControlsHelper(currentControlSet); - _changePasswordButton = GetControl(currentControlSet, GameControlIdentifier.ChangePasswordButton, GetPasswordButton); - _characterInfoPanels.AddRange(_characterInfoPanelFactory.CreatePanels(_characterSelectorProvider.Characters)); + _changePasswordButton = GetControl(currentControlSet, GameControlIdentifier.ChangePasswordButton, GetPasswordButton); + _characterInfoPanels.AddRange(_characterInfoPanelFactory.CreatePanels(_characterSelectorProvider.Characters)); - _allComponents.Add(new CurrentUserInputTracker(_endlessGameProvider, _userInputRepository)); - _allComponents.Add(new PreviousUserInputTracker(_endlessGameProvider, _userInputRepository)); - _allComponents.Add(_changePasswordButton); - _allComponents.AddRange(_characterInfoPanels); - } + _allComponents.Add(new CurrentUserInputTracker(_endlessGameProvider, _userInputRepository)); + _allComponents.Add(new PreviousUserInputTracker(_endlessGameProvider, _userInputRepository)); + _allComponents.Add(_changePasswordButton); + _allComponents.AddRange(_characterInfoPanels); + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) - { - switch (control) + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) { - case GameControlIdentifier.Character1Panel: return _characterInfoPanels[0]; - case GameControlIdentifier.Character2Panel: return _characterInfoPanels[1]; - case GameControlIdentifier.Character3Panel: return _characterInfoPanels[2]; - case GameControlIdentifier.ChangePasswordButton: return _changePasswordButton; - default: return base.FindComponentByControlIdentifier(control); + switch (control) + { + case GameControlIdentifier.Character1Panel: return _characterInfoPanels[0]; + case GameControlIdentifier.Character2Panel: return _characterInfoPanels[1]; + case GameControlIdentifier.Character3Panel: return _characterInfoPanels[2]; + case GameControlIdentifier.ChangePasswordButton: return _changePasswordButton; + default: return base.FindComponentByControlIdentifier(control); + } } - } - private IXNAButton GetPasswordButton() - { - var button = new XNAButton(_secondaryButtonTexture, - new Vector2(454, 417), - new Rectangle(0, 120, 120, 40), - new Rectangle(120, 120, 120, 40)); - button.OnClick += (o, e) => AsyncButtonAction(_accountController.ChangePassword); - return button; - } + private IXNAButton GetPasswordButton() + { + var button = new XNAButton(_secondaryButtonTexture, + new Vector2(454, 417), + new Rectangle(0, 120, 120, 40), + new Rectangle(120, 120, 120, 40)); + button.OnClick += (o, e) => AsyncButtonAction(_accountController.ChangePassword); + return button; + } - protected override IXNAButton GetCreateButton() - { - var button = base.GetCreateButton(); - button.OnClick += (o, e) => AsyncButtonAction(_characterManagementController.CreateCharacter); - return button; - } + protected override IXNAButton GetCreateButton() + { + var button = base.GetCreateButton(); + button.OnClick += (o, e) => AsyncButtonAction(_characterManagementController.CreateCharacter); + return button; + } - protected override void DoBackButtonClick(object sender, EventArgs e) - { - _mainButtonController.GoToInitialStateAndDisconnect(); - } + protected override void DoBackButtonClick(object sender, EventArgs e) + { + _mainButtonController.GoToInitialStateAndDisconnect(); + } - private void AsyncButtonAction(Func clickHandler) - { - if (_loggedInActionTask == null) + private void AsyncButtonAction(Func clickHandler) { - _loggedInActionTask = clickHandler(); - _loggedInActionTask.ContinueWith(_ => _loggedInActionTask = null); + if (_loggedInActionTask == null) + { + _loggedInActionTask = clickHandler(); + _loggedInActionTask.ContinueWith(_ => _loggedInActionTask = null); + } } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/LoginPromptControlSet.cs b/EndlessClient/ControlSets/LoginPromptControlSet.cs index bb46138ce..2da2d5452 100644 --- a/EndlessClient/ControlSets/LoginPromptControlSet.cs +++ b/EndlessClient/ControlSets/LoginPromptControlSet.cs @@ -13,153 +13,154 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.ControlSets; - -public class LoginPromptControlSet : InitialControlSet +namespace EndlessClient.ControlSets { - private readonly IMainButtonController _mainButtonController; - private readonly ILoginController _loginController; + public class LoginPromptControlSet : InitialControlSet + { + private readonly IMainButtonController _mainButtonController; + private readonly ILoginController _loginController; - private IXNATextBox _tbUsername, _tbPassword; - private XNAButton _btnLogin, _btnCancel; - private IXNAPictureBox _loginPanelBackground; + private IXNATextBox _tbUsername, _tbPassword; + private XNAButton _btnLogin, _btnCancel; + private IXNAPictureBox _loginPanelBackground; - private Texture2D _loginBackgroundTexture; + private Texture2D _loginBackgroundTexture; - private Task _loginTask; + private Task _loginTask; - public override GameStates GameState => GameStates.Login; + public override GameStates GameState => GameStates.Login; - public LoginPromptControlSet(IConfigurationProvider configProvider, - IMainButtonController mainButtonController, - ILoginController loginController) - : base(configProvider, mainButtonController) - { - _mainButtonController = mainButtonController; - _loginController = loginController; - } + public LoginPromptControlSet(IConfigurationProvider configProvider, + IMainButtonController mainButtonController, + ILoginController loginController) + : base(configProvider, mainButtonController) + { + _mainButtonController = mainButtonController; + _loginController = loginController; + } - public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) - { - base.InitializeResources(gfxManager, contentProvider); + public override void InitializeResources(INativeGraphicsManager gfxManager, IContentProvider contentProvider) + { + base.InitializeResources(gfxManager, contentProvider); - _loginBackgroundTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 2); - } + _loginBackgroundTexture = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 2); + } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - base.InitializeControlsHelper(currentControlSet); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + base.InitializeControlsHelper(currentControlSet); - _loginPanelBackground = GetControl(currentControlSet, GameControlIdentifier.LoginPanelBackground, GetLoginPanelBackground); - _tbUsername = GetControl(currentControlSet, GameControlIdentifier.LoginAccountName, GetLoginUserNameTextBox); - _tbPassword = GetControl(currentControlSet, GameControlIdentifier.LoginPassword, GetLoginPasswordTextBox); - _btnLogin = GetControl(currentControlSet, GameControlIdentifier.LoginButton, GetLoginAccountButton); - _btnCancel = GetControl(currentControlSet, GameControlIdentifier.LoginCancel, GetLoginCancelButton); + _loginPanelBackground = GetControl(currentControlSet, GameControlIdentifier.LoginPanelBackground, GetLoginPanelBackground); + _tbUsername = GetControl(currentControlSet, GameControlIdentifier.LoginAccountName, GetLoginUserNameTextBox); + _tbPassword = GetControl(currentControlSet, GameControlIdentifier.LoginPassword, GetLoginPasswordTextBox); + _btnLogin = GetControl(currentControlSet, GameControlIdentifier.LoginButton, GetLoginAccountButton); + _btnCancel = GetControl(currentControlSet, GameControlIdentifier.LoginCancel, GetLoginCancelButton); - _allComponents.Add(_loginPanelBackground); - _allComponents.Add(_tbUsername); - _allComponents.Add(_tbPassword); - _allComponents.Add(_btnLogin); - _allComponents.Add(_btnCancel); + _allComponents.Add(_loginPanelBackground); + _allComponents.Add(_tbUsername); + _allComponents.Add(_tbPassword); + _allComponents.Add(_btnLogin); + _allComponents.Add(_btnCancel); - _tbUsername.Selected = true; - } + _tbUsername.Selected = true; + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) - { - switch (control) + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) { - case GameControlIdentifier.LoginPanelBackground: return _loginPanelBackground; - case GameControlIdentifier.LoginAccountName: return _tbUsername; - case GameControlIdentifier.LoginPassword: return _tbPassword; - case GameControlIdentifier.LoginButton: return _btnLogin; - case GameControlIdentifier.LoginCancel: return _btnCancel; - default: return base.FindComponentByControlIdentifier(control); + switch (control) + { + case GameControlIdentifier.LoginPanelBackground: return _loginPanelBackground; + case GameControlIdentifier.LoginAccountName: return _tbUsername; + case GameControlIdentifier.LoginPassword: return _tbPassword; + case GameControlIdentifier.LoginButton: return _btnLogin; + case GameControlIdentifier.LoginCancel: return _btnCancel; + default: return base.FindComponentByControlIdentifier(control); + } } - } - private IXNAPictureBox GetLoginPanelBackground() - { - return new XNAPictureBox + private IXNAPictureBox GetLoginPanelBackground() { - Texture = _loginBackgroundTexture, - DrawArea = new Rectangle(266, 291, _loginBackgroundTexture.Width, _loginBackgroundTexture.Height), - DrawOrder = _personPicture.DrawOrder + 1 - }; - } + return new XNAPictureBox + { + Texture = _loginBackgroundTexture, + DrawArea = new Rectangle(266, 291, _loginBackgroundTexture.Width, _loginBackgroundTexture.Height), + DrawOrder = _personPicture.DrawOrder + 1 + }; + } - private IXNATextBox GetLoginUserNameTextBox() - { - var textBox = new XNATextBox( - new Rectangle(402, 322, 140, _textBoxBackground.Height), - Constants.FontSize08, - _textBoxBackground, - _textBoxLeft, - _textBoxRight, - _textBoxCursor) + private IXNATextBox GetLoginUserNameTextBox() { - MaxChars = 16, - DefaultText = "", - LeftPadding = 4, - DrawOrder = _personPicture.DrawOrder + 2, - DefaultTextColor = Color.FromNonPremultiplied(80, 80, 80, 0xff), - TextColor = Color.Black, - TabOrder = 1, - }; - textBox.OnEnterPressed += DoLogin; - return textBox; - } + var textBox = new XNATextBox( + new Rectangle(402, 322, 140, _textBoxBackground.Height), + Constants.FontSize08, + _textBoxBackground, + _textBoxLeft, + _textBoxRight, + _textBoxCursor) + { + MaxChars = 16, + DefaultText = "", + LeftPadding = 4, + DrawOrder = _personPicture.DrawOrder + 2, + DefaultTextColor = Color.FromNonPremultiplied(80, 80, 80, 0xff), + TextColor = Color.Black, + TabOrder = 1, + }; + textBox.OnEnterPressed += DoLogin; + return textBox; + } - private IXNATextBox GetLoginPasswordTextBox() - { - var textBox = new XNATextBox( - new Rectangle(402, 358, 140, _textBoxBackground.Height), - Constants.FontSize08, - _textBoxBackground, - _textBoxLeft, - _textBoxRight, - _textBoxCursor) + private IXNATextBox GetLoginPasswordTextBox() { - MaxChars = 12, - PasswordBox = true, - LeftPadding = 4, - DefaultText = "", - DrawOrder = _personPicture.DrawOrder + 2, - DefaultTextColor = Color.FromNonPremultiplied(80, 80, 80, 0xff), - TextColor = Color.Black, - TabOrder = 2, - }; - textBox.OnEnterPressed += DoLogin; - return textBox; - } + var textBox = new XNATextBox( + new Rectangle(402, 358, 140, _textBoxBackground.Height), + Constants.FontSize08, + _textBoxBackground, + _textBoxLeft, + _textBoxRight, + _textBoxCursor) + { + MaxChars = 12, + PasswordBox = true, + LeftPadding = 4, + DefaultText = "", + DrawOrder = _personPicture.DrawOrder + 2, + DefaultTextColor = Color.FromNonPremultiplied(80, 80, 80, 0xff), + TextColor = Color.Black, + TabOrder = 2, + }; + textBox.OnEnterPressed += DoLogin; + return textBox; + } - private XNAButton GetLoginAccountButton() - { - var button = new XNAButton(_smallButtonSheet, new Vector2(361, 389), new Rectangle(0, 0, 91, 29), new Rectangle(91, 0, 91, 29)) + private XNAButton GetLoginAccountButton() { - DrawOrder = _personPicture.DrawOrder + 2 - }; - button.OnClick += DoLogin; - return button; - } + var button = new XNAButton(_smallButtonSheet, new Vector2(361, 389), new Rectangle(0, 0, 91, 29), new Rectangle(91, 0, 91, 29)) + { + DrawOrder = _personPicture.DrawOrder + 2 + }; + button.OnClick += DoLogin; + return button; + } - private void DoLogin(object sender, EventArgs e) - { - if (_loginTask == null) + private void DoLogin(object sender, EventArgs e) { - var loginParameters = new LoginParameters(_tbUsername.Text, _tbPassword.Text); - _loginTask = _loginController.LoginToAccount(loginParameters); - _loginTask.ContinueWith(_ => _loginTask = null); + if (_loginTask == null) + { + var loginParameters = new LoginParameters(_tbUsername.Text, _tbPassword.Text); + _loginTask = _loginController.LoginToAccount(loginParameters); + _loginTask.ContinueWith(_ => _loginTask = null); + } } - } - private XNAButton GetLoginCancelButton() - { - var button = new XNAButton(_smallButtonSheet, new Vector2(453, 389), new Rectangle(0, 29, 91, 29), new Rectangle(91, 29, 91, 29)) + private XNAButton GetLoginCancelButton() { - DrawOrder = _personPicture.DrawOrder + 2 - }; - button.OnClick += (o, e) => _mainButtonController.GoToInitialState(); - return button; + var button = new XNAButton(_smallButtonSheet, new Vector2(453, 389), new Rectangle(0, 29, 91, 29), new Rectangle(91, 29, 91, 29)) + { + DrawOrder = _personPicture.DrawOrder + 2 + }; + button.OnClick += (o, e) => _mainButtonController.GoToInitialState(); + return button; + } } } \ No newline at end of file diff --git a/EndlessClient/ControlSets/ViewCreditsControlSet.cs b/EndlessClient/ControlSets/ViewCreditsControlSet.cs index 7e74e8463..e6b37e55a 100644 --- a/EndlessClient/ControlSets/ViewCreditsControlSet.cs +++ b/EndlessClient/ControlSets/ViewCreditsControlSet.cs @@ -5,43 +5,44 @@ using Microsoft.Xna.Framework; using XNAControls; -namespace EndlessClient.ControlSets; - -public class ViewCreditsControlSet : InitialControlSet +namespace EndlessClient.ControlSets { - private IXNALabel _creditsLabel; + public class ViewCreditsControlSet : InitialControlSet + { + private IXNALabel _creditsLabel; - public override GameStates GameState => GameStates.ViewCredits; + public override GameStates GameState => GameStates.ViewCredits; - public ViewCreditsControlSet(IConfigurationProvider configProvider, - IMainButtonController mainButtonController) - : base(configProvider, mainButtonController) { } + public ViewCreditsControlSet(IConfigurationProvider configProvider, + IMainButtonController mainButtonController) + : base(configProvider, mainButtonController) { } - protected override void InitializeControlsHelper(IControlSet currentControlSet) - { - base.InitializeControlsHelper(currentControlSet); - ExcludePersonPicture1(); + protected override void InitializeControlsHelper(IControlSet currentControlSet) + { + base.InitializeControlsHelper(currentControlSet); + ExcludePersonPicture1(); - _creditsLabel = GetControl(currentControlSet, GameControlIdentifier.CreditsLabel, GetCreditsLabel); - _allComponents.Add(_creditsLabel); - } + _creditsLabel = GetControl(currentControlSet, GameControlIdentifier.CreditsLabel, GetCreditsLabel); + _allComponents.Add(_creditsLabel); + } - public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) - { - switch (control) + public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) { - case GameControlIdentifier.CreditsLabel: return _creditsLabel; - default: return base.FindComponentByControlIdentifier(control); + switch (control) + { + case GameControlIdentifier.CreditsLabel: return _creditsLabel; + default: return base.FindComponentByControlIdentifier(control); + } } - } - private XNALabel GetCreditsLabel() - { - return new XNALabel(Constants.FontSize10) + private XNALabel GetCreditsLabel() { - AutoSize = true, - Text = Constants.CreditsText, - DrawPosition = new Vector2(300, 200) - }; + return new XNALabel(Constants.FontSize10) + { + AutoSize = true, + Text = Constants.CreditsText, + DrawPosition = new Vector2(300, 200) + }; + } } } \ No newline at end of file diff --git a/EndlessClient/Controllers/AccountController.cs b/EndlessClient/Controllers/AccountController.cs index 80d587adf..79394a599 100644 --- a/EndlessClient/Controllers/AccountController.cs +++ b/EndlessClient/Controllers/AccountController.cs @@ -8,113 +8,114 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Controllers; - -[MappedType(BaseType = typeof(IAccountController))] -public class AccountController : IAccountController +namespace EndlessClient.Controllers { - private readonly IAccountDialogDisplayActions _accountDialogDisplayActions; - private readonly IErrorDialogDisplayAction _errorDisplayAction; - private readonly IAccountActions _accountActions; - private readonly IGameStateActions _gameStateActions; - private readonly ISafeNetworkOperationFactory _networkOperationFactory; - - public AccountController(IAccountDialogDisplayActions accountDialogDisplayActions, - IErrorDialogDisplayAction errorDisplayAction, - IAccountActions accountActions, - IGameStateActions gameStateActions, - ISafeNetworkOperationFactory networkOperationFactory) - { - _accountDialogDisplayActions = accountDialogDisplayActions; - _errorDisplayAction = errorDisplayAction; - _accountActions = accountActions; - _gameStateActions = gameStateActions; - _networkOperationFactory = networkOperationFactory; - } - - public async Task CreateAccount(ICreateAccountParameters createAccountParameters) + [MappedType(BaseType = typeof(IAccountController))] + public class AccountController : IAccountController { - var paramsValidationResult = _accountActions.CheckAccountCreateParameters(createAccountParameters); - if (paramsValidationResult.FaultingParameter != WhichParameter.None) + private readonly IAccountDialogDisplayActions _accountDialogDisplayActions; + private readonly IErrorDialogDisplayAction _errorDisplayAction; + private readonly IAccountActions _accountActions; + private readonly IGameStateActions _gameStateActions; + private readonly ISafeNetworkOperationFactory _networkOperationFactory; + + public AccountController(IAccountDialogDisplayActions accountDialogDisplayActions, + IErrorDialogDisplayAction errorDisplayAction, + IAccountActions accountActions, + IGameStateActions gameStateActions, + ISafeNetworkOperationFactory networkOperationFactory) { - _accountDialogDisplayActions.ShowCreateParameterValidationError(paramsValidationResult); - return; + _accountDialogDisplayActions = accountDialogDisplayActions; + _errorDisplayAction = errorDisplayAction; + _accountActions = accountActions; + _gameStateActions = gameStateActions; + _networkOperationFactory = networkOperationFactory; } - var checkNameOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _accountActions.CheckAccountNameWithServer(createAccountParameters.AccountName), - SetInitialStateAndShowError, - SetInitialStateAndShowError); - if (!await checkNameOperation.Invoke().ConfigureAwait(false)) - return; - - var nameResult = checkNameOperation.Result; - if (nameResult < (AccountReply)10) + public async Task CreateAccount(ICreateAccountParameters createAccountParameters) { - _accountDialogDisplayActions.ShowCreateAccountServerError(nameResult); - return; + var paramsValidationResult = _accountActions.CheckAccountCreateParameters(createAccountParameters); + if (paramsValidationResult.FaultingParameter != WhichParameter.None) + { + _accountDialogDisplayActions.ShowCreateParameterValidationError(paramsValidationResult); + return; + } + + var checkNameOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _accountActions.CheckAccountNameWithServer(createAccountParameters.AccountName), + SetInitialStateAndShowError, + SetInitialStateAndShowError); + if (!await checkNameOperation.Invoke().ConfigureAwait(false)) + return; + + var nameResult = checkNameOperation.Result; + if (nameResult < (AccountReply)10) + { + _accountDialogDisplayActions.ShowCreateAccountServerError(nameResult); + return; + } + + var result = await _accountDialogDisplayActions.ShowCreatePendingDialog().ConfigureAwait(false); + if (result == XNADialogResult.Cancel) + return; + + var createAccountOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _accountActions.CreateAccount(createAccountParameters, (int)nameResult), + SetInitialStateAndShowError, + SetInitialStateAndShowError); + if (!await createAccountOperation.Invoke().ConfigureAwait(false)) + return; + + var accountResult = createAccountOperation.Result; + if (accountResult != AccountReply.Created) + { + _accountDialogDisplayActions.ShowCreateAccountServerError(accountResult); + return; + } + + _gameStateActions.ChangeToState(GameStates.Initial); + _accountDialogDisplayActions.ShowSuccessMessage(); } - var result = await _accountDialogDisplayActions.ShowCreatePendingDialog().ConfigureAwait(false); - if (result == XNADialogResult.Cancel) - return; + public async Task ChangePassword() + { + var changePasswordResult = await _accountDialogDisplayActions.ShowChangePasswordDialog().ConfigureAwait(false); + changePasswordResult.MatchSome(changePasswordParameters => + { + var changePasswordOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _accountActions.ChangePassword(changePasswordParameters), + SetInitialStateAndShowError, + SetInitialStateAndShowError); - var createAccountOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _accountActions.CreateAccount(createAccountParameters, (int)nameResult), - SetInitialStateAndShowError, - SetInitialStateAndShowError); - if (!await createAccountOperation.Invoke().ConfigureAwait(false)) - return; + var opTask = changePasswordOperation.Invoke(); + opTask.ContinueWith(t => + { + if (t.Result) + { + var result = changePasswordOperation.Result; + _accountDialogDisplayActions.ShowCreateAccountServerError(result); + } + }); + }); + } - var accountResult = createAccountOperation.Result; - if (accountResult != AccountReply.Created) + private void SetInitialStateAndShowError(NoDataSentException ex) { - _accountDialogDisplayActions.ShowCreateAccountServerError(accountResult); - return; + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDisplayAction.ShowException(ex); } - _gameStateActions.ChangeToState(GameStates.Initial); - _accountDialogDisplayActions.ShowSuccessMessage(); - } - - public async Task ChangePassword() - { - var changePasswordResult = await _accountDialogDisplayActions.ShowChangePasswordDialog().ConfigureAwait(false); - changePasswordResult.MatchSome(changePasswordParameters => - { - var changePasswordOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _accountActions.ChangePassword(changePasswordParameters), - SetInitialStateAndShowError, - SetInitialStateAndShowError); - - var opTask = changePasswordOperation.Invoke(); - opTask.ContinueWith(t => - { - if (t.Result) - { - var result = changePasswordOperation.Result; - _accountDialogDisplayActions.ShowCreateAccountServerError(result); - } - }); - }); + private void SetInitialStateAndShowError(EmptyPacketReceivedException ex) + { + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDisplayAction.ShowException(ex); + } } - private void SetInitialStateAndShowError(NoDataSentException ex) + public interface IAccountController { - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDisplayAction.ShowException(ex); - } + Task CreateAccount(ICreateAccountParameters createAccountParameters); - private void SetInitialStateAndShowError(EmptyPacketReceivedException ex) - { - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDisplayAction.ShowException(ex); + Task ChangePassword(); } -} - -public interface IAccountController -{ - Task CreateAccount(ICreateAccountParameters createAccountParameters); - - Task ChangePassword(); } \ No newline at end of file diff --git a/EndlessClient/Controllers/ArrowKeyController.cs b/EndlessClient/Controllers/ArrowKeyController.cs index 0db96e81b..d42bd8ac6 100644 --- a/EndlessClient/Controllers/ArrowKeyController.cs +++ b/EndlessClient/Controllers/ArrowKeyController.cs @@ -10,142 +10,143 @@ using EOLib.Localization; using Optional; -namespace EndlessClient.Controllers; - -[AutoMappedType] -public class ArrowKeyController : IArrowKeyController +namespace EndlessClient.Controllers { - private readonly IWalkValidationActions _walkValidationActions; - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly ICharacterProvider _characterProvider; - private readonly IUnwalkableTileActions _unwalkableTileActions; - private readonly IUnwalkableTileActionsHandler _unwalkableTileActionsHandler; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IGhostingRepository _ghostingRepository; - private readonly ISfxPlayer _sfxPlayer; - - public ArrowKeyController(IWalkValidationActions walkValidationActions, - ICharacterAnimationActions characterAnimationActions, - ICharacterProvider characterProvider, - IUnwalkableTileActions walkErrorHandler, - IUnwalkableTileActionsHandler unwalkableTileActionsHandler, - IStatusLabelSetter statusLabelSetter, - IGhostingRepository ghostingRepository, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class ArrowKeyController : IArrowKeyController { - _walkValidationActions = walkValidationActions; - _characterAnimationActions = characterAnimationActions; - _characterProvider = characterProvider; - _unwalkableTileActions = walkErrorHandler; - _unwalkableTileActionsHandler = unwalkableTileActionsHandler; - _statusLabelSetter = statusLabelSetter; - _ghostingRepository = ghostingRepository; - _sfxPlayer = sfxPlayer; - } - - public bool MoveLeft() - { - if (!CanWalkAgain()) - return false; - - FaceOrAttemptWalk(EODirection.Left); + private readonly IWalkValidationActions _walkValidationActions; + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly ICharacterProvider _characterProvider; + private readonly IUnwalkableTileActions _unwalkableTileActions; + private readonly IUnwalkableTileActionsHandler _unwalkableTileActionsHandler; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IGhostingRepository _ghostingRepository; + private readonly ISfxPlayer _sfxPlayer; + + public ArrowKeyController(IWalkValidationActions walkValidationActions, + ICharacterAnimationActions characterAnimationActions, + ICharacterProvider characterProvider, + IUnwalkableTileActions walkErrorHandler, + IUnwalkableTileActionsHandler unwalkableTileActionsHandler, + IStatusLabelSetter statusLabelSetter, + IGhostingRepository ghostingRepository, + ISfxPlayer sfxPlayer) + { + _walkValidationActions = walkValidationActions; + _characterAnimationActions = characterAnimationActions; + _characterProvider = characterProvider; + _unwalkableTileActions = walkErrorHandler; + _unwalkableTileActionsHandler = unwalkableTileActionsHandler; + _statusLabelSetter = statusLabelSetter; + _ghostingRepository = ghostingRepository; + _sfxPlayer = sfxPlayer; + } - return true; - } + public bool MoveLeft() + { + if (!CanWalkAgain()) + return false; - public bool MoveRight() - { - if (!CanWalkAgain()) - return false; + FaceOrAttemptWalk(EODirection.Left); - FaceOrAttemptWalk(EODirection.Right); + return true; + } - return true; - } + public bool MoveRight() + { + if (!CanWalkAgain()) + return false; - public bool MoveUp() - { - if (!CanWalkAgain()) - return false; + FaceOrAttemptWalk(EODirection.Right); - FaceOrAttemptWalk(EODirection.Up); + return true; + } - return true; - } + public bool MoveUp() + { + if (!CanWalkAgain()) + return false; - public bool MoveDown() - { - if (!CanWalkAgain()) - return false; + FaceOrAttemptWalk(EODirection.Up); - FaceOrAttemptWalk(EODirection.Down); + return true; + } - return true; - } + public bool MoveDown() + { + if (!CanWalkAgain()) + return false; - public void KeysUp() - { - _ghostingRepository.ResetState(); - } + FaceOrAttemptWalk(EODirection.Down); - private bool CanWalkAgain() - { - return _characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing) || - _characterProvider.MainCharacter.RenderProperties.ActualWalkFrame == CharacterRenderProperties.MAX_NUMBER_OF_WALK_FRAMES - 1; - } + return true; + } - private bool CurrentDirectionIs(EODirection direction) - { - return _characterProvider.MainCharacter.RenderProperties.IsFacing(direction); - } + public void KeysUp() + { + _ghostingRepository.ResetState(); + } - private void FaceOrAttemptWalk(EODirection direction) - { - if (!CurrentDirectionIs(direction) && _characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing)) + private bool CanWalkAgain() { - _characterAnimationActions.Face(direction); + return _characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing) || + _characterProvider.MainCharacter.RenderProperties.ActualWalkFrame == CharacterRenderProperties.MAX_NUMBER_OF_WALK_FRAMES - 1; } - else + + private bool CurrentDirectionIs(EODirection direction) { - _characterAnimationActions.Face(direction); - AttemptToStartWalking(); + return _characterProvider.MainCharacter.RenderProperties.IsFacing(direction); } - } - private void AttemptToStartWalking() - { - var walkValidationResult = _walkValidationActions.CanMoveToDestinationCoordinates(); - if (walkValidationResult == WalkValidationResult.GhostComplete) - _sfxPlayer.PlaySfx(SoundEffectID.GhostPlayer); + private void FaceOrAttemptWalk(EODirection direction) + { + if (!CurrentDirectionIs(direction) && _characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing)) + { + _characterAnimationActions.Face(direction); + } + else + { + _characterAnimationActions.Face(direction); + AttemptToStartWalking(); + } + } - switch (walkValidationResult) + private void AttemptToStartWalking() { - case WalkValidationResult.BlockedByCharacter: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_KEEP_MOVING_THROUGH_PLAYER); - break; - case WalkValidationResult.NotWalkable: - var (unwalkableActions, cellState) = _unwalkableTileActions.GetUnwalkableTileActions(); - _unwalkableTileActionsHandler.HandleUnwalkableTileActions(unwalkableActions, cellState); - break; - case WalkValidationResult.GhostComplete: - _characterAnimationActions.StartWalking(Option.None(), ghosted: true); - break; - case WalkValidationResult.Walkable: - _characterAnimationActions.StartWalking(Option.None()); - break; + var walkValidationResult = _walkValidationActions.CanMoveToDestinationCoordinates(); + if (walkValidationResult == WalkValidationResult.GhostComplete) + _sfxPlayer.PlaySfx(SoundEffectID.GhostPlayer); + + switch (walkValidationResult) + { + case WalkValidationResult.BlockedByCharacter: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_KEEP_MOVING_THROUGH_PLAYER); + break; + case WalkValidationResult.NotWalkable: + var (unwalkableActions, cellState) = _unwalkableTileActions.GetUnwalkableTileActions(); + _unwalkableTileActionsHandler.HandleUnwalkableTileActions(unwalkableActions, cellState); + break; + case WalkValidationResult.GhostComplete: + _characterAnimationActions.StartWalking(Option.None(), ghosted: true); + break; + case WalkValidationResult.Walkable: + _characterAnimationActions.StartWalking(Option.None()); + break; + } } } -} -public interface IArrowKeyController -{ - bool MoveLeft(); + public interface IArrowKeyController + { + bool MoveLeft(); - bool MoveRight(); + bool MoveRight(); - bool MoveUp(); + bool MoveUp(); - bool MoveDown(); + bool MoveDown(); - void KeysUp(); + void KeysUp(); + } } \ No newline at end of file diff --git a/EndlessClient/Controllers/BardController.cs b/EndlessClient/Controllers/BardController.cs index 86936799b..6cf4c2e8e 100644 --- a/EndlessClient/Controllers/BardController.cs +++ b/EndlessClient/Controllers/BardController.cs @@ -4,39 +4,40 @@ using EOLib.Domain.Extensions; using EOLib.Domain.Interact.Jukebox; -namespace EndlessClient.Controllers; - -[AutoMappedType] -public class BardController : IBardController +namespace EndlessClient.Controllers { - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly IJukeboxActions _jukeboxActions; - private readonly ICharacterProvider _characterProvider; - - public BardController(ICharacterAnimationActions characterAnimationActions, - IJukeboxActions jukeboxActions, - ICharacterProvider characterProvider) + [AutoMappedType] + public class BardController : IBardController { - _characterAnimationActions = characterAnimationActions; - _jukeboxActions = jukeboxActions; - _characterProvider = characterProvider; - } + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly IJukeboxActions _jukeboxActions; + private readonly ICharacterProvider _characterProvider; - public void PlayInstrumentNote(int noteIndex) - { - _characterAnimationActions.StartAttacking(noteIndex); - _jukeboxActions.PlayNote(noteIndex); + public BardController(ICharacterAnimationActions characterAnimationActions, + IJukeboxActions jukeboxActions, + ICharacterProvider characterProvider) + { + _characterAnimationActions = characterAnimationActions; + _jukeboxActions = jukeboxActions; + _characterProvider = characterProvider; + } + + public void PlayInstrumentNote(int noteIndex) + { + _characterAnimationActions.StartAttacking(noteIndex); + _jukeboxActions.PlayNote(noteIndex); + } + + private bool CanAttackAgain() + { + var rp = _characterProvider.MainCharacter.RenderProperties; + return rp.IsActing(CharacterActionState.Standing) || + rp.RenderAttackFrame == CharacterRenderProperties.MAX_NUMBER_OF_ATTACK_FRAMES; + } } - private bool CanAttackAgain() + public interface IBardController { - var rp = _characterProvider.MainCharacter.RenderProperties; - return rp.IsActing(CharacterActionState.Standing) || - rp.RenderAttackFrame == CharacterRenderProperties.MAX_NUMBER_OF_ATTACK_FRAMES; + void PlayInstrumentNote(int noteIndex); } -} - -public interface IBardController -{ - void PlayInstrumentNote(int noteIndex); } \ No newline at end of file diff --git a/EndlessClient/Controllers/CharacterManagementController.cs b/EndlessClient/Controllers/CharacterManagementController.cs index ddc076cf1..90eb67e2a 100644 --- a/EndlessClient/Controllers/CharacterManagementController.cs +++ b/EndlessClient/Controllers/CharacterManagementController.cs @@ -12,150 +12,151 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Controllers; - -[MappedType(BaseType = typeof(ICharacterManagementController))] -public class CharacterManagementController : ICharacterManagementController +namespace EndlessClient.Controllers { - private readonly ISafeNetworkOperationFactory _safeNetworkOperationFactory; - private readonly ICharacterManagementActions _characterManagementActions; - private readonly IErrorDialogDisplayAction _errorDialogDisplayAction; - private readonly ICharacterDialogActions _characterDialogActions; - private readonly IBackgroundReceiveActions _backgroundReceiveActions; - private readonly INetworkConnectionActions _networkConnectionActions; - private readonly IGameStateActions _gameStateActions; - private readonly ICharacterSelectorRepository _characterSelectorRepository; - private readonly ISfxPlayer _sfxPlayer; - - public CharacterManagementController(ISafeNetworkOperationFactory safeNetworkOperationFactory, - ICharacterManagementActions characterManagementActions, - IErrorDialogDisplayAction errorDialogDisplayAction, - ICharacterDialogActions characterDialogActions, - IBackgroundReceiveActions backgroundReceiveActions, - INetworkConnectionActions networkConnectionActions, - IGameStateActions gameStateActions, - ICharacterSelectorRepository characterSelectorRepository, - ISfxPlayer sfxPlayer) + [MappedType(BaseType = typeof(ICharacterManagementController))] + public class CharacterManagementController : ICharacterManagementController { - _safeNetworkOperationFactory = safeNetworkOperationFactory; - _characterManagementActions = characterManagementActions; - _errorDialogDisplayAction = errorDialogDisplayAction; - _characterDialogActions = characterDialogActions; - _backgroundReceiveActions = backgroundReceiveActions; - _networkConnectionActions = networkConnectionActions; - _gameStateActions = gameStateActions; - _characterSelectorRepository = characterSelectorRepository; - _sfxPlayer = sfxPlayer; - } + private readonly ISafeNetworkOperationFactory _safeNetworkOperationFactory; + private readonly ICharacterManagementActions _characterManagementActions; + private readonly IErrorDialogDisplayAction _errorDialogDisplayAction; + private readonly ICharacterDialogActions _characterDialogActions; + private readonly IBackgroundReceiveActions _backgroundReceiveActions; + private readonly INetworkConnectionActions _networkConnectionActions; + private readonly IGameStateActions _gameStateActions; + private readonly ICharacterSelectorRepository _characterSelectorRepository; + private readonly ISfxPlayer _sfxPlayer; + + public CharacterManagementController(ISafeNetworkOperationFactory safeNetworkOperationFactory, + ICharacterManagementActions characterManagementActions, + IErrorDialogDisplayAction errorDialogDisplayAction, + ICharacterDialogActions characterDialogActions, + IBackgroundReceiveActions backgroundReceiveActions, + INetworkConnectionActions networkConnectionActions, + IGameStateActions gameStateActions, + ICharacterSelectorRepository characterSelectorRepository, + ISfxPlayer sfxPlayer) + { + _safeNetworkOperationFactory = safeNetworkOperationFactory; + _characterManagementActions = characterManagementActions; + _errorDialogDisplayAction = errorDialogDisplayAction; + _characterDialogActions = characterDialogActions; + _backgroundReceiveActions = backgroundReceiveActions; + _networkConnectionActions = networkConnectionActions; + _gameStateActions = gameStateActions; + _characterSelectorRepository = characterSelectorRepository; + _sfxPlayer = sfxPlayer; + } - public async Task CreateCharacter() - { - var requestCreateOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(_characterManagementActions.RequestCharacterCreation, SendError, RecvError); - if (!await requestCreateOp.Invoke().ConfigureAwait(false)) - return; + public async Task CreateCharacter() + { + var requestCreateOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(_characterManagementActions.RequestCharacterCreation, SendError, RecvError); + if (!await requestCreateOp.Invoke().ConfigureAwait(false)) + return; - var createID = requestCreateOp.Result; + var createID = requestCreateOp.Result; - //todo: make not approved character names cancel the dialog close - var showResult = await _characterDialogActions.ShowCreateCharacterDialog().ConfigureAwait(false); - showResult.MatchSome(parameters => - { - var createOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation( - () => _characterManagementActions.CreateCharacter(parameters, createID), SendError, RecvError); - var opTask = createOp.Invoke(); - opTask.ContinueWith(t => + //todo: make not approved character names cancel the dialog close + var showResult = await _characterDialogActions.ShowCreateCharacterDialog().ConfigureAwait(false); + showResult.MatchSome(parameters => { - if (t.Result) + var createOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation( + () => _characterManagementActions.CreateCharacter(parameters, createID), SendError, RecvError); + var opTask = createOp.Invoke(); + opTask.ContinueWith(t => { - _gameStateActions.RefreshCurrentState(); - _characterDialogActions.ShowCharacterReplyDialog(createOp.Result); - } + if (t.Result) + { + _gameStateActions.RefreshCurrentState(); + _characterDialogActions.ShowCharacterReplyDialog(createOp.Result); + } + }); }); - }); - } - - public async Task DeleteCharacter(Character characterToDelete) - { - void ShowCharacterDeleteWarning(Character c) - { - _characterDialogActions.ShowCharacterDeleteWarning(c.Name); - _characterSelectorRepository.CharacterForDelete = Option.Some(c); } - var warningShown = _characterSelectorRepository.CharacterForDelete.Match( - some: c => + public async Task DeleteCharacter(Character characterToDelete) + { + void ShowCharacterDeleteWarning(Character c) { - if (c != characterToDelete) + _characterDialogActions.ShowCharacterDeleteWarning(c.Name); + _characterSelectorRepository.CharacterForDelete = Option.Some(c); + } + + var warningShown = _characterSelectorRepository.CharacterForDelete.Match( + some: c => + { + if (c != characterToDelete) + { + ShowCharacterDeleteWarning(characterToDelete); + return true; + } + + return false; + }, + none: () => { ShowCharacterDeleteWarning(characterToDelete); return true; - } + }); - return false; - }, - none: () => - { - ShowCharacterDeleteWarning(characterToDelete); - return true; - }); + if (warningShown) + return; - if (warningShown) - return; + var requestDeleteOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(_characterManagementActions.RequestCharacterDelete, SendError, RecvError); + if (!await requestDeleteOp.Invoke().ConfigureAwait(false)) + return; - var requestDeleteOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(_characterManagementActions.RequestCharacterDelete, SendError, RecvError); - if (!await requestDeleteOp.Invoke().ConfigureAwait(false)) - return; + var takeID = requestDeleteOp.Result; - var takeID = requestDeleteOp.Result; + var dialogResult = await _characterDialogActions.ShowConfirmDeleteWarning(characterToDelete.Name).ConfigureAwait(false); + if (dialogResult != XNADialogResult.OK) + return; - var dialogResult = await _characterDialogActions.ShowConfirmDeleteWarning(characterToDelete.Name).ConfigureAwait(false); - if (dialogResult != XNADialogResult.OK) - return; + var deleteOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(() => _characterManagementActions.DeleteCharacter(takeID), SendError, RecvError); + if (!await deleteOp.Invoke().ConfigureAwait(false)) + return; + + _characterSelectorRepository.CharacterForDelete = Option.None(); + if (deleteOp.Result != CharacterReply.Deleted) + { + SetInitialStateAndShowError(); + DisconnectAndStopReceiving(); + return; + } - var deleteOp = _safeNetworkOperationFactory.CreateSafeBlockingOperation(() => _characterManagementActions.DeleteCharacter(takeID), SendError, RecvError); - if (!await deleteOp.Invoke().ConfigureAwait(false)) - return; + _sfxPlayer.PlaySfx(SoundEffectID.DeleteCharacter); + _gameStateActions.RefreshCurrentState(); + } - _characterSelectorRepository.CharacterForDelete = Option.None(); - if (deleteOp.Result != CharacterReply.Deleted) + private void SendError(NoDataSentException ndes) { SetInitialStateAndShowError(); DisconnectAndStopReceiving(); - return; } - _sfxPlayer.PlaySfx(SoundEffectID.DeleteCharacter); - _gameStateActions.RefreshCurrentState(); - } + private void RecvError(EmptyPacketReceivedException epre) + { + SetInitialStateAndShowError(); + DisconnectAndStopReceiving(); + } - private void SendError(NoDataSentException ndes) - { - SetInitialStateAndShowError(); - DisconnectAndStopReceiving(); - } + private void SetInitialStateAndShowError() + { + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDialogDisplayAction.ShowError(ConnectResult.SocketError); + } - private void RecvError(EmptyPacketReceivedException epre) - { - SetInitialStateAndShowError(); - DisconnectAndStopReceiving(); + private void DisconnectAndStopReceiving() + { + _backgroundReceiveActions.CancelBackgroundReceiveLoop(); + _networkConnectionActions.DisconnectFromServer(); + } } - private void SetInitialStateAndShowError() + public interface ICharacterManagementController { - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDialogDisplayAction.ShowError(ConnectResult.SocketError); - } + Task CreateCharacter(); - private void DisconnectAndStopReceiving() - { - _backgroundReceiveActions.CancelBackgroundReceiveLoop(); - _networkConnectionActions.DisconnectFromServer(); + Task DeleteCharacter(Character characterToDelete); } -} - -public interface ICharacterManagementController -{ - Task CreateCharacter(); - - Task DeleteCharacter(Character characterToDelete); } \ No newline at end of file diff --git a/EndlessClient/Controllers/ChatController.cs b/EndlessClient/Controllers/ChatController.cs index f181bd56c..4e84953b2 100644 --- a/EndlessClient/Controllers/ChatController.cs +++ b/EndlessClient/Controllers/ChatController.cs @@ -11,101 +11,102 @@ using EOLib.Localization; using System; -namespace EndlessClient.Controllers; - -[AutoMappedType] -public class ChatController : IChatController +namespace EndlessClient.Controllers { - private readonly IChatTextBoxActions _chatTextBoxActions; - private readonly IChatActions _chatActions; - private readonly IPrivateMessageActions _privateMessageActions; - private readonly IChatBubbleActions _chatBubbleActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IHudControlProvider _hudControlProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IChatTypeCalculator _chatTypeCalculator; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - - public ChatController(IChatTextBoxActions chatTextBoxActions, - IChatActions chatActions, - IPrivateMessageActions privateMessageActions, - IChatBubbleActions chatBubbleActions, - IStatusLabelSetter statusLabelSetter, - IHudControlProvider hudControlProvider, - ISfxPlayer sfxPlayer, - IChatTypeCalculator chatTypeCalculator, - ICurrentMapStateProvider currentMapStateProvider) + [AutoMappedType] + public class ChatController : IChatController { - _chatTextBoxActions = chatTextBoxActions; - _chatActions = chatActions; - _privateMessageActions = privateMessageActions; - _chatBubbleActions = chatBubbleActions; - _statusLabelSetter = statusLabelSetter; - _hudControlProvider = hudControlProvider; - _sfxPlayer = sfxPlayer; - _chatTypeCalculator = chatTypeCalculator; - _currentMapStateProvider = currentMapStateProvider; - } + private readonly IChatTextBoxActions _chatTextBoxActions; + private readonly IChatActions _chatActions; + private readonly IPrivateMessageActions _privateMessageActions; + private readonly IChatBubbleActions _chatBubbleActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IHudControlProvider _hudControlProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IChatTypeCalculator _chatTypeCalculator; + private readonly ICurrentMapStateProvider _currentMapStateProvider; - public void SendChatAndClearTextBox() - { - var localTypedText = ChatTextBox.Text; - var (pmCheckOk, targetCharacter) = _privateMessageActions.GetTargetCharacter(localTypedText); + public ChatController(IChatTextBoxActions chatTextBoxActions, + IChatActions chatActions, + IPrivateMessageActions privateMessageActions, + IChatBubbleActions chatBubbleActions, + IStatusLabelSetter statusLabelSetter, + IHudControlProvider hudControlProvider, + ISfxPlayer sfxPlayer, + IChatTypeCalculator chatTypeCalculator, + ICurrentMapStateProvider currentMapStateProvider) + { + _chatTextBoxActions = chatTextBoxActions; + _chatActions = chatActions; + _privateMessageActions = privateMessageActions; + _chatBubbleActions = chatBubbleActions; + _statusLabelSetter = statusLabelSetter; + _hudControlProvider = hudControlProvider; + _sfxPlayer = sfxPlayer; + _chatTypeCalculator = chatTypeCalculator; + _currentMapStateProvider = currentMapStateProvider; + } - if (pmCheckOk) + public void SendChatAndClearTextBox() { - if (!string.IsNullOrEmpty(targetCharacter)) - { - _sfxPlayer.PlaySfx(SoundEffectID.PrivateMessageSent); - } + var localTypedText = ChatTextBox.Text; + var (pmCheckOk, targetCharacter) = _privateMessageActions.GetTargetCharacter(localTypedText); - var chatType = _chatTypeCalculator.CalculateChatType(localTypedText); - var (result, updatedChat) = _chatActions.SendChatToServer(localTypedText, targetCharacter, chatType); - switch (result) + if (pmCheckOk) { - case ChatResult.Ok: _chatBubbleActions.ShowChatBubbleForMainCharacter(updatedChat, chatType == ChatType.Party); break; - case ChatResult.YourMindPrevents: _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.YOUR_MIND_PREVENTS_YOU_TO_SAY); break; - case ChatResult.Command: - { - var commandText = updatedChat[1..].Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)[0]; - _sfxPlayer.PlaySfx(commandText switch + if (!string.IsNullOrEmpty(targetCharacter)) + { + _sfxPlayer.PlaySfx(SoundEffectID.PrivateMessageSent); + } + + var chatType = _chatTypeCalculator.CalculateChatType(localTypedText); + var (result, updatedChat) = _chatActions.SendChatToServer(localTypedText, targetCharacter, chatType); + switch (result) + { + case ChatResult.Ok: _chatBubbleActions.ShowChatBubbleForMainCharacter(updatedChat, chatType == ChatType.Party); break; + case ChatResult.YourMindPrevents: _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.YOUR_MIND_PREVENTS_YOU_TO_SAY); break; + case ChatResult.Command: { - NoWallCommand.Text or PingCommand.Text => SoundEffectID.ServerCommand, - _ => SoundEffectID.ServerMessage, - }); - } - break; - case ChatResult.JailProtection: _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_USE_GLOBAL); break; - case ChatResult.AdminAnnounce: _sfxPlayer.PlaySfx(SoundEffectID.AdminAnnounceReceived); goto case ChatResult.Ok; - case ChatResult.HideSpeechBubble: break; // no-op - case ChatResult.HideAll: break; // no-op + var commandText = updatedChat[1..].Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)[0]; + _sfxPlayer.PlaySfx(commandText switch + { + NoWallCommand.Text or PingCommand.Text => SoundEffectID.ServerCommand, + _ => SoundEffectID.ServerMessage, + }); + } + break; + case ChatResult.JailProtection: _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_USE_GLOBAL); break; + case ChatResult.AdminAnnounce: _sfxPlayer.PlaySfx(SoundEffectID.AdminAnnounceReceived); goto case ChatResult.Ok; + case ChatResult.HideSpeechBubble: break; // no-op + case ChatResult.HideAll: break; // no-op + } } + + _chatTextBoxActions.ClearChatText(); } - _chatTextBoxActions.ClearChatText(); - } + public void SelectChatTextBox() + { + _chatTextBoxActions.FocusChatTextBox(); + } - public void SelectChatTextBox() - { - _chatTextBoxActions.FocusChatTextBox(); - } + public void ClearAndWarnIfJailAndGlobal() + { + if (!_currentMapStateProvider.IsJail || _chatTypeCalculator.CalculateChatType(ChatTextBox.Text) != ChatType.Global) return; - public void ClearAndWarnIfJailAndGlobal() - { - if (!_currentMapStateProvider.IsJail || _chatTypeCalculator.CalculateChatType(ChatTextBox.Text) != ChatType.Global) return; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_USE_GLOBAL); + _chatTextBoxActions.ClearChatText(); + } - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_USE_GLOBAL); - _chatTextBoxActions.ClearChatText(); + private ChatTextBox ChatTextBox => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); } - private ChatTextBox ChatTextBox => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); -} - -public interface IChatController -{ - void SendChatAndClearTextBox(); + public interface IChatController + { + void SendChatAndClearTextBox(); - void SelectChatTextBox(); + void SelectChatTextBox(); - void ClearAndWarnIfJailAndGlobal(); + void ClearAndWarnIfJailAndGlobal(); + } } \ No newline at end of file diff --git a/EndlessClient/Controllers/ControlKeyController.cs b/EndlessClient/Controllers/ControlKeyController.cs index 9f1ff9bd9..6b8c06ff8 100644 --- a/EndlessClient/Controllers/ControlKeyController.cs +++ b/EndlessClient/Controllers/ControlKeyController.cs @@ -6,91 +6,92 @@ using EOLib.Domain.Extensions; using EOLib.Localization; -namespace EndlessClient.Controllers; - -[MappedType(BaseType = typeof(IControlKeyController))] -public class ControlKeyController : IControlKeyController +namespace EndlessClient.Controllers { - private readonly ICharacterProvider _characterProvider; - private readonly IAttackValidationActions _attackValidationActions; - private readonly ICharacterActions _characterActions; - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ISfxPlayer _sfxPlayer; - - public ControlKeyController(ICharacterProvider characterProvider, - IAttackValidationActions attackValidationActions, - ICharacterActions characterActions, - ICharacterAnimationActions characterAnimationActions, - IStatusLabelSetter statusLabelSetter, - ISfxPlayer sfxPlayer) + [MappedType(BaseType = typeof(IControlKeyController))] + public class ControlKeyController : IControlKeyController { - _characterProvider = characterProvider; - _attackValidationActions = attackValidationActions; - _characterActions = characterActions; - _characterAnimationActions = characterAnimationActions; - _statusLabelSetter = statusLabelSetter; - _sfxPlayer = sfxPlayer; - } + private readonly ICharacterProvider _characterProvider; + private readonly IAttackValidationActions _attackValidationActions; + private readonly ICharacterActions _characterActions; + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ISfxPlayer _sfxPlayer; - public bool Attack() - { - _characterAnimationActions.CancelClickToWalk(); + public ControlKeyController(ICharacterProvider characterProvider, + IAttackValidationActions attackValidationActions, + ICharacterActions characterActions, + ICharacterAnimationActions characterAnimationActions, + IStatusLabelSetter statusLabelSetter, + ISfxPlayer sfxPlayer) + { + _characterProvider = characterProvider; + _attackValidationActions = attackValidationActions; + _characterActions = characterActions; + _characterAnimationActions = characterAnimationActions; + _statusLabelSetter = statusLabelSetter; + _sfxPlayer = sfxPlayer; + } - if (!CanAttackAgain()) - return false; + public bool Attack() + { + _characterAnimationActions.CancelClickToWalk(); - AttemptAttack(); + if (!CanAttackAgain()) + return false; - return true; - } + AttemptAttack(); - private bool CanAttackAgain() - { - var rp = _characterProvider.MainCharacter.RenderProperties; - return rp.IsActing(CharacterActionState.Standing) || - rp.RenderAttackFrame == CharacterRenderProperties.MAX_NUMBER_OF_ATTACK_FRAMES; - } + return true; + } - private void AttemptAttack() - { - var showAnimationAnyway = false; - var validationResult = _attackValidationActions.ValidateCharacterStateBeforeAttacking(); - if (validationResult != AttackValidationError.OK) + private bool CanAttackAgain() { - if (validationResult == AttackValidationError.Overweight) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.STATUS_LABEL_CANNOT_ATTACK_OVERWEIGHT); - else if (validationResult == AttackValidationError.Exhausted) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); - else if (validationResult == AttackValidationError.NotYourBattle) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, - EOResourceID.STATUS_LABEL_UNABLE_TO_ATTACK); - showAnimationAnyway = true; - } - else if (validationResult == AttackValidationError.MissingArrows) + var rp = _characterProvider.MainCharacter.RenderProperties; + return rp.IsActing(CharacterActionState.Standing) || + rp.RenderAttackFrame == CharacterRenderProperties.MAX_NUMBER_OF_ATTACK_FRAMES; + } + + private void AttemptAttack() + { + var showAnimationAnyway = false; + var validationResult = _attackValidationActions.ValidateCharacterStateBeforeAttacking(); + if (validationResult != AttackValidationError.OK) { - _sfxPlayer.PlaySfx(SoundEffectID.NoArrows); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.STATUS_LABEL_YOU_HAVE_NO_ARROWS); + if (validationResult == AttackValidationError.Overweight) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.STATUS_LABEL_CANNOT_ATTACK_OVERWEIGHT); + else if (validationResult == AttackValidationError.Exhausted) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); + else if (validationResult == AttackValidationError.NotYourBattle) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, + EOResourceID.STATUS_LABEL_UNABLE_TO_ATTACK); + showAnimationAnyway = true; + } + else if (validationResult == AttackValidationError.MissingArrows) + { + _sfxPlayer.PlaySfx(SoundEffectID.NoArrows); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.STATUS_LABEL_YOU_HAVE_NO_ARROWS); - _sfxPlayer.PlaySfx(SoundEffectID.NoArrows); + _sfxPlayer.PlaySfx(SoundEffectID.NoArrows); + } } - } - else - showAnimationAnyway = true; + else + showAnimationAnyway = true; - if (showAnimationAnyway) - { - _characterActions.Attack(); - _characterAnimationActions.StartAttacking(); + if (showAnimationAnyway) + { + _characterActions.Attack(); + _characterAnimationActions.StartAttacking(); + } } } -} -public interface IControlKeyController -{ - bool Attack(); + public interface IControlKeyController + { + bool Attack(); + } } \ No newline at end of file diff --git a/EndlessClient/Controllers/FunctionKeyController.cs b/EndlessClient/Controllers/FunctionKeyController.cs index d605efbef..ffc5ed050 100644 --- a/EndlessClient/Controllers/FunctionKeyController.cs +++ b/EndlessClient/Controllers/FunctionKeyController.cs @@ -17,110 +17,111 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Controllers; - -[AutoMappedType] -public class FunctionKeyController : IFunctionKeyController +namespace EndlessClient.Controllers { - private readonly IMapActions _mapActions; - private readonly ICharacterActions _characterActions; - private readonly ISpellSelectActions _spellSelectActions; - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly ISpellCastValidationActions _spellCastValidationActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ICharacterProvider _characterProvider; - private readonly IESFFileProvider _esfFileProvider; - private readonly ISpellSlotDataProvider _spellSlotDataProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly ISfxPlayer _sfxPlayer; - - public FunctionKeyController(IMapActions mapActions, - ICharacterActions characterActions, - ISpellSelectActions spellSelectActions, - ICharacterAnimationActions characterAnimationActions, - ISpellCastValidationActions spellCastValidationActions, - IInGameDialogActions inGameDialogActions, - IStatusLabelSetter statusLabelSetter, - ICharacterProvider characterProvider, - IESFFileProvider esfFileProvider, - ISpellSlotDataProvider spellSlotDataProvider, - IHudControlProvider hudControlProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class FunctionKeyController : IFunctionKeyController { - _mapActions = mapActions; - _characterActions = characterActions; - _spellSelectActions = spellSelectActions; - _characterAnimationActions = characterAnimationActions; - _spellCastValidationActions = spellCastValidationActions; - _inGameDialogActions = inGameDialogActions; - _statusLabelSetter = statusLabelSetter; - _characterProvider = characterProvider; - _esfFileProvider = esfFileProvider; - _spellSlotDataProvider = spellSlotDataProvider; - _hudControlProvider = hudControlProvider; - _sfxPlayer = sfxPlayer; - } + private readonly IMapActions _mapActions; + private readonly ICharacterActions _characterActions; + private readonly ISpellSelectActions _spellSelectActions; + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly ISpellCastValidationActions _spellCastValidationActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ICharacterProvider _characterProvider; + private readonly IESFFileProvider _esfFileProvider; + private readonly ISpellSlotDataProvider _spellSlotDataProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly ISfxPlayer _sfxPlayer; - public bool SelectSpell(int index, bool isAlternate) - { - if (_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing)) + public FunctionKeyController(IMapActions mapActions, + ICharacterActions characterActions, + ISpellSelectActions spellSelectActions, + ICharacterAnimationActions characterAnimationActions, + ISpellCastValidationActions spellCastValidationActions, + IInGameDialogActions inGameDialogActions, + IStatusLabelSetter statusLabelSetter, + ICharacterProvider characterProvider, + IESFFileProvider esfFileProvider, + ISpellSlotDataProvider spellSlotDataProvider, + IHudControlProvider hudControlProvider, + ISfxPlayer sfxPlayer) { - _spellSelectActions.SelectSpellBySlot(index + (isAlternate ? ActiveSpellsPanel.SpellRowLength : 0)); + _mapActions = mapActions; + _characterActions = characterActions; + _spellSelectActions = spellSelectActions; + _characterAnimationActions = characterAnimationActions; + _spellCastValidationActions = spellCastValidationActions; + _inGameDialogActions = inGameDialogActions; + _statusLabelSetter = statusLabelSetter; + _characterProvider = characterProvider; + _esfFileProvider = esfFileProvider; + _spellSlotDataProvider = spellSlotDataProvider; + _hudControlProvider = hudControlProvider; + _sfxPlayer = sfxPlayer; + } - _spellSlotDataProvider.SelectedSpellInfo.MatchSome(x => + public bool SelectSpell(int index, bool isAlternate) + { + if (_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing)) { - var spellData = _esfFileProvider.ESFFile[x.ID]; - if (spellData.Type == SpellType.Bard && _spellCastValidationActions.ValidateBard()) - { - _inGameDialogActions.ShowBardDialog(); - } - else if (spellData.Target == SpellTarget.Self || spellData.Target == SpellTarget.Group) - { - var castResult = _spellCastValidationActions.ValidateSpellCast(x.ID); + _spellSelectActions.SelectSpellBySlot(index + (isAlternate ? ActiveSpellsPanel.SpellRowLength : 0)); - if (castResult == SpellCastValidationResult.ExhaustedNoTp) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_TP); - else if (castResult == SpellCastValidationResult.ExhaustedNoSp) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); - else if (_characterAnimationActions.PrepareMainCharacterSpell(x.ID, _characterProvider.MainCharacter)) - _characterActions.PrepareCastSpell(x.ID); - } - else + _spellSlotDataProvider.SelectedSpellInfo.MatchSome(x => { - _sfxPlayer.PlaySfx(SoundEffectID.SpellActivate); - } - }); + var spellData = _esfFileProvider.ESFFile[x.ID]; + if (spellData.Type == SpellType.Bard && _spellCastValidationActions.ValidateBard()) + { + _inGameDialogActions.ShowBardDialog(); + } + else if (spellData.Target == SpellTarget.Self || spellData.Target == SpellTarget.Group) + { + var castResult = _spellCastValidationActions.ValidateSpellCast(x.ID); - return true; - } + if (castResult == SpellCastValidationResult.ExhaustedNoTp) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_TP); + else if (castResult == SpellCastValidationResult.ExhaustedNoSp) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); + else if (_characterAnimationActions.PrepareMainCharacterSpell(x.ID, _characterProvider.MainCharacter)) + _characterActions.PrepareCastSpell(x.ID); + } + else + { + _sfxPlayer.PlaySfx(SoundEffectID.SpellActivate); + } + }); - return false; - } + return true; + } - public bool Sit() - { - if (_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Walking, CharacterActionState.Attacking, CharacterActionState.SpellCast)) return false; + } - var cursorRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - _characterActions.Sit(cursorRenderer.GridCoordinates); + public bool Sit() + { + if (_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Walking, CharacterActionState.Attacking, CharacterActionState.SpellCast)) + return false; - return true; - } + var cursorRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + _characterActions.Sit(cursorRenderer.GridCoordinates); - public bool RefreshMapState() - { - _mapActions.RequestRefresh(); - return true; + return true; + } + + public bool RefreshMapState() + { + _mapActions.RequestRefresh(); + return true; + } } -} -public interface IFunctionKeyController -{ - bool SelectSpell(int index, bool isAlternate); + public interface IFunctionKeyController + { + bool SelectSpell(int index, bool isAlternate); - bool Sit(); + bool Sit(); - bool RefreshMapState(); + bool RefreshMapState(); + } } \ No newline at end of file diff --git a/EndlessClient/Controllers/InventoryController.cs b/EndlessClient/Controllers/InventoryController.cs index 1e88a5efa..34ccb0ba6 100644 --- a/EndlessClient/Controllers/InventoryController.cs +++ b/EndlessClient/Controllers/InventoryController.cs @@ -24,396 +24,397 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Controllers; - -[AutoMappedType(IsSingleton = true)] -public class InventoryController : IInventoryController +namespace EndlessClient.Controllers { - private readonly IItemActions _itemActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IPaperdollActions _paperdollActions; - private readonly IChestActions _chestActions; - private readonly ILockerActions _lockerActions; - private readonly IBankActions _bankActions; - private readonly ITradeActions _tradeActions; - private readonly IItemEquipValidator _itemEquipValidator; - private readonly IItemDropValidator _itemDropValidator; - private readonly ICharacterProvider _characterProvider; - private readonly IPaperdollProvider _paperdollProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly ITradeProvider _tradeProvider; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IItemTransferDialogFactory _itemTransferDialogFactory; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ISfxPlayer _sfxPlayer; - - private bool _goldWarningShown = false; - - public InventoryController(IItemActions itemActions, - IInGameDialogActions inGameDialogActions, - IPaperdollActions paperdollActions, - IChestActions chestActions, - ILockerActions lockerActions, - IBankActions bankActions, - ITradeActions tradeActions, - IItemEquipValidator itemEquipValidator, - IItemDropValidator itemDropValidator, - ICharacterProvider characterProvider, - IPaperdollProvider paperdollProvider, - IHudControlProvider hudControlProvider, - ICurrentMapProvider currentMapProvider, - IEIFFileProvider eifFileProvider, - IActiveDialogProvider activeDialogProvider, - ITradeProvider tradeProvider, - IStatusLabelSetter statusLabelSetter, - IItemTransferDialogFactory itemTransferDialogFactory, - IEOMessageBoxFactory eoMessageBoxFactory, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - ISfxPlayer sfxPlayer) + [AutoMappedType(IsSingleton = true)] + public class InventoryController : IInventoryController { - _itemActions = itemActions; - _inGameDialogActions = inGameDialogActions; - _paperdollActions = paperdollActions; - _chestActions = chestActions; - _lockerActions = lockerActions; - _bankActions = bankActions; - _tradeActions = tradeActions; - _itemEquipValidator = itemEquipValidator; - _itemDropValidator = itemDropValidator; - _characterProvider = characterProvider; - _paperdollProvider = paperdollProvider; - _hudControlProvider = hudControlProvider; - _currentMapProvider = currentMapProvider; - _eifFileProvider = eifFileProvider; - _activeDialogProvider = activeDialogProvider; - _tradeProvider = tradeProvider; - _statusLabelSetter = statusLabelSetter; - _itemTransferDialogFactory = itemTransferDialogFactory; - _eoMessageBoxFactory = eoMessageBoxFactory; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _sfxPlayer = sfxPlayer; - } + private readonly IItemActions _itemActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IPaperdollActions _paperdollActions; + private readonly IChestActions _chestActions; + private readonly ILockerActions _lockerActions; + private readonly IBankActions _bankActions; + private readonly ITradeActions _tradeActions; + private readonly IItemEquipValidator _itemEquipValidator; + private readonly IItemDropValidator _itemDropValidator; + private readonly ICharacterProvider _characterProvider; + private readonly IPaperdollProvider _paperdollProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly ITradeProvider _tradeProvider; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IItemTransferDialogFactory _itemTransferDialogFactory; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ISfxPlayer _sfxPlayer; + + private bool _goldWarningShown = false; + + public InventoryController(IItemActions itemActions, + IInGameDialogActions inGameDialogActions, + IPaperdollActions paperdollActions, + IChestActions chestActions, + ILockerActions lockerActions, + IBankActions bankActions, + ITradeActions tradeActions, + IItemEquipValidator itemEquipValidator, + IItemDropValidator itemDropValidator, + ICharacterProvider characterProvider, + IPaperdollProvider paperdollProvider, + IHudControlProvider hudControlProvider, + ICurrentMapProvider currentMapProvider, + IEIFFileProvider eifFileProvider, + IActiveDialogProvider activeDialogProvider, + ITradeProvider tradeProvider, + IStatusLabelSetter statusLabelSetter, + IItemTransferDialogFactory itemTransferDialogFactory, + IEOMessageBoxFactory eoMessageBoxFactory, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + ISfxPlayer sfxPlayer) + { + _itemActions = itemActions; + _inGameDialogActions = inGameDialogActions; + _paperdollActions = paperdollActions; + _chestActions = chestActions; + _lockerActions = lockerActions; + _bankActions = bankActions; + _tradeActions = tradeActions; + _itemEquipValidator = itemEquipValidator; + _itemDropValidator = itemDropValidator; + _characterProvider = characterProvider; + _paperdollProvider = paperdollProvider; + _hudControlProvider = hudControlProvider; + _currentMapProvider = currentMapProvider; + _eifFileProvider = eifFileProvider; + _activeDialogProvider = activeDialogProvider; + _tradeProvider = tradeProvider; + _statusLabelSetter = statusLabelSetter; + _itemTransferDialogFactory = itemTransferDialogFactory; + _eoMessageBoxFactory = eoMessageBoxFactory; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _sfxPlayer = sfxPlayer; + } - public void ShowPaperdollDialog() - { - // when called from inventory controller, paperdoll is for the main character - _paperdollActions.RequestPaperdoll(_characterProvider.MainCharacter.ID); - _inGameDialogActions.ShowPaperdollDialog(_characterProvider.MainCharacter, isMainCharacter: true); - } + public void ShowPaperdollDialog() + { + // when called from inventory controller, paperdoll is for the main character + _paperdollActions.RequestPaperdoll(_characterProvider.MainCharacter.ID); + _inGameDialogActions.ShowPaperdollDialog(_characterProvider.MainCharacter, isMainCharacter: true); + } - public void UseItem(EIFRecord record) - { - var useItem = false; + public void UseItem(EIFRecord record) + { + var useItem = false; - var character = _characterProvider.MainCharacter; + var character = _characterProvider.MainCharacter; - switch (record.Type) - { - //usable items - case ItemType.Teleport: - if (!_currentMapProvider.CurrentMap.Properties.CanScroll) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_NOTHING_HAPPENED); + switch (record.Type) + { + //usable items + case ItemType.Teleport: + if (!_currentMapProvider.CurrentMap.Properties.CanScroll) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_NOTHING_HAPPENED); + break; + } + + if (record.ScrollMap == character.MapID && record.ScrollX == character.RenderProperties.MapX && record.ScrollY == character.RenderProperties.MapY) + break; + + useItem = true; break; - } - if (record.ScrollMap == character.MapID && record.ScrollX == character.RenderProperties.MapX && record.ScrollY == character.RenderProperties.MapY) + case ItemType.CureCurse: + var paperdollItems = _paperdollProvider.VisibleCharacterPaperdolls[_characterProvider.MainCharacter.ID].Paperdoll.Values; + if (paperdollItems.Where(id => id > 0).Select(id => _eifFileProvider.EIFFile[id].Special).Any(s => s == ItemSpecial.Cursed)) + { + var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_CURSE_REMOVE_PROMPT, EODialogButtons.OkCancel, EOMessageBoxStyle.SmallDialogSmallHeader); + msgBox.DialogClosing += (o, e) => + { + if (e.Result == XNADialogResult.OK) + { + _itemActions.UseItem(record.ID); + } + }; + msgBox.ShowDialog(); + } break; - useItem = true; - break; + case ItemType.Heal: + case ItemType.HairDye: + case ItemType.Beer: + case ItemType.EffectPotion: + case ItemType.EXPReward: + useItem = true; + break; - case ItemType.CureCurse: - var paperdollItems = _paperdollProvider.VisibleCharacterPaperdolls[_characterProvider.MainCharacter.ID].Paperdoll.Values; - if (paperdollItems.Where(id => id > 0).Select(id => _eifFileProvider.EIFFile[id].Special).Any(s => s == ItemSpecial.Cursed)) + // Not implemented server - side + case ItemType.SkillReward: + case ItemType.StatReward: + break; + } + + if (useItem) + { + _itemActions.UseItem(record.ID); + + if (record.Type == ItemType.Beer) { - var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_CURSE_REMOVE_PROMPT, EODialogButtons.OkCancel, EOMessageBoxStyle.SmallDialogSmallHeader); - msgBox.DialogClosing += (o, e) => - { - if (e.Result == XNADialogResult.OK) - { - _itemActions.UseItem(record.ID); - } - }; - msgBox.ShowDialog(); + // The server does not send back the potency, it is all client-side + _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler) + .SetDrunkTimeout(record.BeerPotency); } - break; - - case ItemType.Heal: - case ItemType.HairDye: - case ItemType.Beer: - case ItemType.EffectPotion: - case ItemType.EXPReward: - useItem = true; - break; - - // Not implemented server - side - case ItemType.SkillReward: - case ItemType.StatReward: - break; + } } - if (useItem) + public void EquipItem(EIFRecord itemData) { - _itemActions.UseItem(record.ID); + var c = _characterProvider.MainCharacter; + var (validationResult, detail, isAlternateEquipLocation) = _itemEquipValidator.ValidateItemEquip(c, itemData); - if (record.Type == ItemType.Beer) + switch (validationResult) { - // The server does not send back the potency, it is all client-side - _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler) - .SetDrunkTimeout(record.BeerPotency); + case ItemEquipResult.NotEquippable: + throw new ArgumentException("Item is not equippable", nameof(itemData)); + case ItemEquipResult.AlreadyEquipped: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_TYPE_ALREADY_EQUIPPED); + break; + case ItemEquipResult.WrongGender: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_DOES_NOT_FIT_GENDER); + break; + case ItemEquipResult.StatRequirementNotMet: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, + EOResourceID.STATUS_LABEL_ITEM_EQUIP_THIS_ITEM_REQUIRES, detail); + break; + case ItemEquipResult.ClassRequirementNotMet: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, + EOResourceID.STATUS_LABEL_ITEM_EQUIP_CAN_ONLY_BE_USED_BY, detail); + break; + case ItemEquipResult.Ok: + _itemActions.EquipItem(itemData.ID, isAlternateEquipLocation); + break; } } - } - public void EquipItem(EIFRecord itemData) - { - var c = _characterProvider.MainCharacter; - var (validationResult, detail, isAlternateEquipLocation) = _itemEquipValidator.ValidateItemEquip(c, itemData); - - switch (validationResult) + public void UnequipItem(EquipLocation equipLocation) { - case ItemEquipResult.NotEquippable: - throw new ArgumentException("Item is not equippable", nameof(itemData)); - case ItemEquipResult.AlreadyEquipped: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_TYPE_ALREADY_EQUIPPED); - break; - case ItemEquipResult.WrongGender: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_DOES_NOT_FIT_GENDER); - break; - case ItemEquipResult.StatRequirementNotMet: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, - EOResourceID.STATUS_LABEL_ITEM_EQUIP_THIS_ITEM_REQUIRES, detail); - break; - case ItemEquipResult.ClassRequirementNotMet: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, - EOResourceID.STATUS_LABEL_ITEM_EQUIP_CAN_ONLY_BE_USED_BY, detail); - break; - case ItemEquipResult.Ok: - _itemActions.EquipItem(itemData.ID, isAlternateEquipLocation); - break; + var locName = Enum.GetName(typeof(EquipLocation), equipLocation); + var equipId = _paperdollProvider.VisibleCharacterPaperdolls[_characterProvider.MainCharacter.ID].Paperdoll[equipLocation]; + _itemActions.UnequipItem(equipId, alternateLocation: locName.Contains('2')); } - } - - public void UnequipItem(EquipLocation equipLocation) - { - var locName = Enum.GetName(typeof(EquipLocation), equipLocation); - var equipId = _paperdollProvider.VisibleCharacterPaperdolls[_characterProvider.MainCharacter.ID].Paperdoll[equipLocation]; - _itemActions.UnequipItem(equipId, alternateLocation: locName.Contains('2')); - } - - public void DropItem(EIFRecord itemData, InventoryItem inventoryItem, MapCoordinate coords) - { - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue) && mapRenderer.MouseOver) - return; - - var rp = _characterProvider.MainCharacter.RenderProperties; - var validationResult = _itemDropValidator.ValidateItemDrop(_characterProvider.MainCharacter, inventoryItem, coords); - if (validationResult == ItemDropResult.Lore) - { - var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM, EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); - msgBox.ShowDialog(); - } - else if (validationResult == ItemDropResult.Jail) - { - var msgBox = _eoMessageBoxFactory.CreateMessageBox( - EOResourceID.JAIL_WARNING_CANNOT_DROP_ITEMS, - EOResourceID.STATUS_LABEL_TYPE_WARNING, - EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); - msgBox.ShowDialog(); - } - else if (validationResult == ItemDropResult.Ok) + public void DropItem(EIFRecord itemData, InventoryItem inventoryItem, MapCoordinate coords) { - DoItemDrop(itemData, inventoryItem, a => _itemActions.DropItem(inventoryItem.ItemID, a, coords)); - } - else if (validationResult == ItemDropResult.TooFar) - { - var localizedMessage = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_DROP_OUT_OF_RANGE); - var chatData = new ChatData(ChatTab.System, "System", localizedMessage, ChatIcon.DotDotDotDot); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_DROP_OUT_OF_RANGE); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } - } + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue) && mapRenderer.MouseOver) + return; - public void DropItemInChest(EIFRecord itemData, InventoryItem inventoryItem) - { - var validationResult = _itemDropValidator.ValidateItemDrop(_characterProvider.MainCharacter, inventoryItem); + var rp = _characterProvider.MainCharacter.RenderProperties; + var validationResult = _itemDropValidator.ValidateItemDrop(_characterProvider.MainCharacter, inventoryItem, coords); - if (validationResult == ItemDropResult.Lore) - { - var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM); - msgBox.ShowDialog(); - } - else - { - DoItemDrop(itemData, inventoryItem, a => _chestActions.AddItemToChest(inventoryItem.WithAmount(a))); + if (validationResult == ItemDropResult.Lore) + { + var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM, EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); + msgBox.ShowDialog(); + } + else if (validationResult == ItemDropResult.Jail) + { + var msgBox = _eoMessageBoxFactory.CreateMessageBox( + EOResourceID.JAIL_WARNING_CANNOT_DROP_ITEMS, + EOResourceID.STATUS_LABEL_TYPE_WARNING, + EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); + msgBox.ShowDialog(); + } + else if (validationResult == ItemDropResult.Ok) + { + DoItemDrop(itemData, inventoryItem, a => _itemActions.DropItem(inventoryItem.ItemID, a, coords)); + } + else if (validationResult == ItemDropResult.TooFar) + { + var localizedMessage = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_DROP_OUT_OF_RANGE); + var chatData = new ChatData(ChatTab.System, "System", localizedMessage, ChatIcon.DotDotDotDot); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_DROP_OUT_OF_RANGE); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } } - } - public void DropItemInLocker(EIFRecord itemData, InventoryItem inventoryItem) - { - if (inventoryItem.ItemID == 1) + public void DropItemInChest(EIFRecord itemData, InventoryItem inventoryItem) { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_DEPOSIT_GOLD_ERROR); - dlg.ShowDialog(); + var validationResult = _itemDropValidator.ValidateItemDrop(_characterProvider.MainCharacter, inventoryItem); + + if (validationResult == ItemDropResult.Lore) + { + var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM); + msgBox.ShowDialog(); + } + else + { + DoItemDrop(itemData, inventoryItem, a => _chestActions.AddItemToChest(inventoryItem.WithAmount(a))); + } } - else + + public void DropItemInLocker(EIFRecord itemData, InventoryItem inventoryItem) { - DoItemDrop(itemData, inventoryItem, a => + if (inventoryItem.ItemID == 1) { - if (_lockerActions.GetNewItemAmount(inventoryItem.ItemID, a) > Constants.LockerMaxSingleItemAmount) - { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_FULL_SINGLE_ITEM_MAX); - dlg.ShowDialog(); - } - else + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_DEPOSIT_GOLD_ERROR); + dlg.ShowDialog(); + } + else + { + DoItemDrop(itemData, inventoryItem, a => { - _lockerActions.AddItemToLocker(inventoryItem.WithAmount(a)); - } - }, - ItemTransferDialog.TransferType.ShopTransfer, - EOResourceID.DIALOG_TRANSFER_TRANSFER); + if (_lockerActions.GetNewItemAmount(inventoryItem.ItemID, a) > Constants.LockerMaxSingleItemAmount) + { + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_FULL_SINGLE_ITEM_MAX); + dlg.ShowDialog(); + } + else + { + _lockerActions.AddItemToLocker(inventoryItem.WithAmount(a)); + } + }, + ItemTransferDialog.TransferType.ShopTransfer, + EOResourceID.DIALOG_TRANSFER_TRANSFER); + } } - } - public void DropItemInBank(EIFRecord itemData, InventoryItem inventoryItem) - { - if (inventoryItem.Amount == 0) + public void DropItemInBank(EIFRecord itemData, InventoryItem inventoryItem) { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); - dlg.ShowDialog(); - } - else - { - DoItemDrop(itemData, - inventoryItem, - a => _bankActions.Deposit(a), - ItemTransferDialog.TransferType.BankTransfer, - EOResourceID.DIALOG_TRANSFER_DEPOSIT); + if (inventoryItem.Amount == 0) + { + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); + dlg.ShowDialog(); + } + else + { + DoItemDrop(itemData, + inventoryItem, + a => _bankActions.Deposit(a), + ItemTransferDialog.TransferType.BankTransfer, + EOResourceID.DIALOG_TRANSFER_DEPOSIT); + } } - } - public void JunkItem(EIFRecord itemData, InventoryItem inventoryItem) - { - if (inventoryItem.Amount > 1) + public void JunkItem(EIFRecord itemData, InventoryItem inventoryItem) { - var transferDialog = _itemTransferDialogFactory.CreateItemTransferDialog( - itemData.Name, - ItemTransferDialog.TransferType.JunkItems, - inventoryItem.Amount, - EOResourceID.DIALOG_TRANSFER_JUNK); - transferDialog.DialogClosing += (sender, e) => + if (inventoryItem.Amount > 1) { - if (e.Result == XNADialogResult.OK) + var transferDialog = _itemTransferDialogFactory.CreateItemTransferDialog( + itemData.Name, + ItemTransferDialog.TransferType.JunkItems, + inventoryItem.Amount, + EOResourceID.DIALOG_TRANSFER_JUNK); + transferDialog.DialogClosing += (sender, e) => { - _itemActions.JunkItem(inventoryItem.ItemID, transferDialog.SelectedAmount); - } - }; - transferDialog.ShowDialog(); - } - else - { - _itemActions.JunkItem(inventoryItem.ItemID, 1); + if (e.Result == XNADialogResult.OK) + { + _itemActions.JunkItem(inventoryItem.ItemID, transferDialog.SelectedAmount); + } + }; + transferDialog.ShowDialog(); + } + else + { + _itemActions.JunkItem(inventoryItem.ItemID, 1); + } } - } - public void TradeItem(EIFRecord itemData, InventoryItem inventoryItem) - { - var mainPlayerAgrees = _characterProvider.MainCharacter.ID == _tradeProvider.PlayerOneOffer.PlayerID - ? _tradeProvider.PlayerOneOffer.Agrees - : _tradeProvider.PlayerTwoOffer.Agrees; + public void TradeItem(EIFRecord itemData, InventoryItem inventoryItem) + { + var mainPlayerAgrees = _characterProvider.MainCharacter.ID == _tradeProvider.PlayerOneOffer.PlayerID + ? _tradeProvider.PlayerOneOffer.Agrees + : _tradeProvider.PlayerTwoOffer.Agrees; - if (mainPlayerAgrees) - return; + if (mainPlayerAgrees) + return; - if (itemData.Special == ItemSpecial.Lore) - { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM); - dlg.ShowDialog(); - } - else - { - DoItemDrop(itemData, inventoryItem, - a => _tradeActions.AddItemToOffer(inventoryItem.ItemID, a), - ItemTransferDialog.TransferType.TradeItems, - EOResourceID.DIALOG_TRANSFER_OFFER); + if (itemData.Special == ItemSpecial.Lore) + { + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_LORE_ITEM); + dlg.ShowDialog(); + } + else + { + DoItemDrop(itemData, inventoryItem, + a => _tradeActions.AddItemToOffer(inventoryItem.ItemID, a), + ItemTransferDialog.TransferType.TradeItems, + EOResourceID.DIALOG_TRANSFER_OFFER); + } } - } - private void DoItemDrop(EIFRecord itemData, InventoryItem inventoryItem, Action dropAction, - ItemTransferDialog.TransferType transferType = ItemTransferDialog.TransferType.DropItems, - EOResourceID message = EOResourceID.DIALOG_TRANSFER_DROP) - { - if (inventoryItem.Amount > 1) + private void DoItemDrop(EIFRecord itemData, InventoryItem inventoryItem, Action dropAction, + ItemTransferDialog.TransferType transferType = ItemTransferDialog.TransferType.DropItems, + EOResourceID message = EOResourceID.DIALOG_TRANSFER_DROP) { - var transferDialog = _itemTransferDialogFactory.CreateItemTransferDialog( - itemData.Name, - transferType, - inventoryItem.Amount, - message); - - transferDialog.DialogClosing += (sender, e) => + if (inventoryItem.Amount > 1) { - if (e.Result == XNADialogResult.OK) - { - var isLargeGoldItemDrop = inventoryItem.ItemID == 1 && inventoryItem.Amount > 10000 && transferType == ItemTransferDialog.TransferType.DropItems; + var transferDialog = _itemTransferDialogFactory.CreateItemTransferDialog( + itemData.Name, + transferType, + inventoryItem.Amount, + message); - if (isLargeGoldItemDrop && !_goldWarningShown) + transferDialog.DialogClosing += (sender, e) => + { + if (e.Result == XNADialogResult.OK) { - var warningMsg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.DROP_MANY_GOLD_ON_GROUND, EODialogButtons.OkCancel); - _sfxPlayer.PlaySfx(SoundEffectID.Login); - warningMsg.DialogClosing += (_, warningArgs) => + var isLargeGoldItemDrop = inventoryItem.ItemID == 1 && inventoryItem.Amount > 10000 && transferType == ItemTransferDialog.TransferType.DropItems; + + if (isLargeGoldItemDrop && !_goldWarningShown) { - if (warningArgs.Result == XNADialogResult.OK) + var warningMsg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.DROP_MANY_GOLD_ON_GROUND, EODialogButtons.OkCancel); + _sfxPlayer.PlaySfx(SoundEffectID.Login); + warningMsg.DialogClosing += (_, warningArgs) => { - _goldWarningShown = true; - } - }; - warningMsg.ShowDialog(); - } - else - { - dropAction(transferDialog.SelectedAmount); + if (warningArgs.Result == XNADialogResult.OK) + { + _goldWarningShown = true; + } + }; + warningMsg.ShowDialog(); + } + else + { + dropAction(transferDialog.SelectedAmount); + } } - } - }; - transferDialog.ShowDialog(); - } - else - { - dropAction(1); + }; + transferDialog.ShowDialog(); + } + else + { + dropAction(1); + } } } -} -public interface IInventoryController -{ - void ShowPaperdollDialog(); + public interface IInventoryController + { + void ShowPaperdollDialog(); - void UseItem(EIFRecord record); + void UseItem(EIFRecord record); - void EquipItem(EIFRecord itemData); + void EquipItem(EIFRecord itemData); - void UnequipItem(EquipLocation equipLocation); + void UnequipItem(EquipLocation equipLocation); - void DropItem(EIFRecord itemData, InventoryItem inventoryItem, MapCoordinate coords); + void DropItem(EIFRecord itemData, InventoryItem inventoryItem, MapCoordinate coords); - void DropItemInChest(EIFRecord itemData, InventoryItem inventoryItem); + void DropItemInChest(EIFRecord itemData, InventoryItem inventoryItem); - void DropItemInLocker(EIFRecord itemData, InventoryItem inventoryItem); + void DropItemInLocker(EIFRecord itemData, InventoryItem inventoryItem); - void DropItemInBank(EIFRecord itemData, InventoryItem inventoryItem); + void DropItemInBank(EIFRecord itemData, InventoryItem inventoryItem); - void JunkItem(EIFRecord itemData, InventoryItem inventoryItem); + void JunkItem(EIFRecord itemData, InventoryItem inventoryItem); - void TradeItem(EIFRecord itemData, InventoryItem inventoryItem); + void TradeItem(EIFRecord itemData, InventoryItem inventoryItem); + } } \ No newline at end of file diff --git a/EndlessClient/Controllers/LoginController.cs b/EndlessClient/Controllers/LoginController.cs index f68a749d2..b8fc7b40f 100644 --- a/EndlessClient/Controllers/LoginController.cs +++ b/EndlessClient/Controllers/LoginController.cs @@ -25,295 +25,296 @@ using System.IO; using System.Threading.Tasks; -namespace EndlessClient.Controllers; - -[AutoMappedType] -public class LoginController : ILoginController +namespace EndlessClient.Controllers { - private readonly ILoginActions _loginActions; - private readonly IMapFileLoadActions _mapFileLoadActions; - private readonly IFileRequestActions _fileRequestActions; - private readonly IGameStateActions _gameStateActions; - private readonly IChatTextBoxActions _chatTextBoxActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IChatRepository _chatRepository; - private readonly INewsProvider _newsProvider; - private readonly IUserInputTimeRepository _userInputTimeRepository; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private readonly IConfigurationProvider _configurationProvider; - private readonly IPlayerInfoRepository _playerInfoRepository; - private readonly IErrorDialogDisplayAction _errorDisplayAction; - private readonly ISafeNetworkOperationFactory _networkOperationFactory; - private readonly IGameLoadingDialogFactory _gameLoadingDialogFactory; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IFirstTimePlayerActions _firstTimePlayerActions; - private readonly IMapChangedActions _mapChangedActions; - - public LoginController(ILoginActions loginActions, - IMapFileLoadActions mapFileLoadActions, - IFileRequestActions fileRequestActions, - IGameStateActions gameStateActions, - IChatTextBoxActions chatTextBoxActions, - IErrorDialogDisplayAction errorDisplayAction, - IFirstTimePlayerActions firstTimePlayerActions, - IMapChangedActions mapChangedActions, - ISafeNetworkOperationFactory networkOperationFactory, - IGameLoadingDialogFactory gameLoadingDialogFactory, - ICurrentMapStateProvider currentMapStateProvider, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - IChatRepository chatRepository, - INewsProvider newsProvider, - IUserInputTimeRepository userInputTimeRepository, - IClientWindowSizeRepository clientWindowSizeRepository, - IConfigurationProvider configurationProvider, - IPlayerInfoRepository playerInfoRepository) - { - _loginActions = loginActions; - _mapFileLoadActions = mapFileLoadActions; - _fileRequestActions = fileRequestActions; - _gameStateActions = gameStateActions; - _chatTextBoxActions = chatTextBoxActions; - _errorDisplayAction = errorDisplayAction; - _firstTimePlayerActions = firstTimePlayerActions; - _mapChangedActions = mapChangedActions; - _networkOperationFactory = networkOperationFactory; - _gameLoadingDialogFactory = gameLoadingDialogFactory; - _currentMapStateProvider = currentMapStateProvider; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _chatRepository = chatRepository; - _newsProvider = newsProvider; - _userInputTimeRepository = userInputTimeRepository; - _clientWindowSizeRepository = clientWindowSizeRepository; - _configurationProvider = configurationProvider; - _playerInfoRepository = playerInfoRepository; - } - - public async Task LoginToAccount(ILoginParameters loginParameters) + [AutoMappedType] + public class LoginController : ILoginController { - if (!_loginActions.LoginParametersAreValid(loginParameters)) - return; - - var loginToServerOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _loginActions.LoginToServer(loginParameters), - SetInitialStateAndShowError, SetInitialStateAndShowError); - - if (!await loginToServerOperation.Invoke().ConfigureAwait(false)) - return; - var reply = loginToServerOperation.Result; - - if (reply == LoginReply.Ok) + private readonly ILoginActions _loginActions; + private readonly IMapFileLoadActions _mapFileLoadActions; + private readonly IFileRequestActions _fileRequestActions; + private readonly IGameStateActions _gameStateActions; + private readonly IChatTextBoxActions _chatTextBoxActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IChatRepository _chatRepository; + private readonly INewsProvider _newsProvider; + private readonly IUserInputTimeRepository _userInputTimeRepository; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IConfigurationProvider _configurationProvider; + private readonly IPlayerInfoRepository _playerInfoRepository; + private readonly IErrorDialogDisplayAction _errorDisplayAction; + private readonly ISafeNetworkOperationFactory _networkOperationFactory; + private readonly IGameLoadingDialogFactory _gameLoadingDialogFactory; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IFirstTimePlayerActions _firstTimePlayerActions; + private readonly IMapChangedActions _mapChangedActions; + + public LoginController(ILoginActions loginActions, + IMapFileLoadActions mapFileLoadActions, + IFileRequestActions fileRequestActions, + IGameStateActions gameStateActions, + IChatTextBoxActions chatTextBoxActions, + IErrorDialogDisplayAction errorDisplayAction, + IFirstTimePlayerActions firstTimePlayerActions, + IMapChangedActions mapChangedActions, + ISafeNetworkOperationFactory networkOperationFactory, + IGameLoadingDialogFactory gameLoadingDialogFactory, + ICurrentMapStateProvider currentMapStateProvider, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + IChatRepository chatRepository, + INewsProvider newsProvider, + IUserInputTimeRepository userInputTimeRepository, + IClientWindowSizeRepository clientWindowSizeRepository, + IConfigurationProvider configurationProvider, + IPlayerInfoRepository playerInfoRepository) { - await DispatcherGameComponent.Invoke(() => _gameStateActions.ChangeToState(GameStates.LoggedIn)); + _loginActions = loginActions; + _mapFileLoadActions = mapFileLoadActions; + _fileRequestActions = fileRequestActions; + _gameStateActions = gameStateActions; + _chatTextBoxActions = chatTextBoxActions; + _errorDisplayAction = errorDisplayAction; + _firstTimePlayerActions = firstTimePlayerActions; + _mapChangedActions = mapChangedActions; + _networkOperationFactory = networkOperationFactory; + _gameLoadingDialogFactory = gameLoadingDialogFactory; + _currentMapStateProvider = currentMapStateProvider; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _chatRepository = chatRepository; + _newsProvider = newsProvider; + _userInputTimeRepository = userInputTimeRepository; + _clientWindowSizeRepository = clientWindowSizeRepository; + _configurationProvider = configurationProvider; + _playerInfoRepository = playerInfoRepository; } - else + + public async Task LoginToAccount(ILoginParameters loginParameters) { - if (reply == LoginReply.WrongUser || reply == LoginReply.WrongUserPassword) - _playerInfoRepository.LoginAttempts++; - else - _playerInfoRepository.LoginAttempts = 3; + if (!_loginActions.LoginParametersAreValid(loginParameters)) + return; - _errorDisplayAction.ShowLoginError(reply); + var loginToServerOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _loginActions.LoginToServer(loginParameters), + SetInitialStateAndShowError, SetInitialStateAndShowError); - if (_playerInfoRepository.LoginAttempts >= 3) + if (!await loginToServerOperation.Invoke().ConfigureAwait(false)) + return; + var reply = loginToServerOperation.Result; + + if (reply == LoginReply.Ok) { - _gameStateActions.ChangeToState(GameStates.Initial); - _playerInfoRepository.LoginAttempts = 0; + await DispatcherGameComponent.Invoke(() => _gameStateActions.ChangeToState(GameStates.LoggedIn)); + } + else + { + if (reply == LoginReply.WrongUser || reply == LoginReply.WrongUserPassword) + _playerInfoRepository.LoginAttempts++; + else + _playerInfoRepository.LoginAttempts = 3; + + _errorDisplayAction.ShowLoginError(reply); + + if (_playerInfoRepository.LoginAttempts >= 3) + { + _gameStateActions.ChangeToState(GameStates.Initial); + _playerInfoRepository.LoginAttempts = 0; + } } - } - } - - public async Task LoginToCharacter(Character character) - { - var requestCharacterLoginOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _loginActions.RequestCharacterLogin(character), - SetInitialStateAndShowError, SetInitialStateAndShowError); - if (!await requestCharacterLoginOperation.Invoke().ConfigureAwait(false)) - return; - - var sessionID = requestCharacterLoginOperation.Result; - - var unableToLoadMap = false; - try - { - _mapFileLoadActions.LoadMapFileByID(_currentMapStateProvider.CurrentMapID); - } - catch (IOException) - { - // Try to load the map now that we know what Map ID we need - // non-fatal exception - unableToLoadMap = true; } - GameLoadingDialog gameLoadingDialog = null; - try + public async Task LoginToCharacter(Character character) { - gameLoadingDialog = _gameLoadingDialogFactory.CreateGameLoadingDialog(); - gameLoadingDialog.ShowDialog(); + var requestCharacterLoginOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _loginActions.RequestCharacterLogin(character), + SetInitialStateAndShowError, SetInitialStateAndShowError); + if (!await requestCharacterLoginOperation.Invoke().ConfigureAwait(false)) + return; - await InitialDelayInReleaseMode().ConfigureAwait(false); + var sessionID = requestCharacterLoginOperation.Result; - if (unableToLoadMap || _fileRequestActions.NeedsFileForLogin(FileType.Emf, _currentMapStateProvider.CurrentMapID)) + var unableToLoadMap = false; + try { - gameLoadingDialog.SetState(GameLoadingDialogState.Map); - if (!await SafeGetFile(() => _fileRequestActions.GetMapFromServer(_currentMapStateProvider.CurrentMapID, sessionID)).ConfigureAwait(false)) - return; - await Task.Delay(1000).ConfigureAwait(false); + _mapFileLoadActions.LoadMapFileByID(_currentMapStateProvider.CurrentMapID); } - - if (_fileRequestActions.NeedsFileForLogin(FileType.Eif)) + catch (IOException) { - gameLoadingDialog.SetState(GameLoadingDialogState.Item); - if (!await SafeGetFile(() => _fileRequestActions.GetItemFileFromServer(sessionID)).ConfigureAwait(false)) - return; - await Task.Delay(1000).ConfigureAwait(false); - } - - if (_fileRequestActions.NeedsFileForLogin(FileType.Enf)) - { - gameLoadingDialog.SetState(GameLoadingDialogState.NPC); - if (!await SafeGetFile(() => _fileRequestActions.GetNPCFileFromServer(sessionID)).ConfigureAwait(false)) - return; - await Task.Delay(1000).ConfigureAwait(false); + // Try to load the map now that we know what Map ID we need + // non-fatal exception + unableToLoadMap = true; } - if (_fileRequestActions.NeedsFileForLogin(FileType.Esf)) + GameLoadingDialog gameLoadingDialog = null; + try { - gameLoadingDialog.SetState(GameLoadingDialogState.Spell); - if (!await SafeGetFile(() => _fileRequestActions.GetSpellFileFromServer(sessionID)).ConfigureAwait(false)) + gameLoadingDialog = _gameLoadingDialogFactory.CreateGameLoadingDialog(); + gameLoadingDialog.ShowDialog(); + + await InitialDelayInReleaseMode().ConfigureAwait(false); + + if (unableToLoadMap || _fileRequestActions.NeedsFileForLogin(FileType.Emf, _currentMapStateProvider.CurrentMapID)) + { + gameLoadingDialog.SetState(GameLoadingDialogState.Map); + if (!await SafeGetFile(() => _fileRequestActions.GetMapFromServer(_currentMapStateProvider.CurrentMapID, sessionID)).ConfigureAwait(false)) + return; + await Task.Delay(1000).ConfigureAwait(false); + } + + if (_fileRequestActions.NeedsFileForLogin(FileType.Eif)) + { + gameLoadingDialog.SetState(GameLoadingDialogState.Item); + if (!await SafeGetFile(() => _fileRequestActions.GetItemFileFromServer(sessionID)).ConfigureAwait(false)) + return; + await Task.Delay(1000).ConfigureAwait(false); + } + + if (_fileRequestActions.NeedsFileForLogin(FileType.Enf)) + { + gameLoadingDialog.SetState(GameLoadingDialogState.NPC); + if (!await SafeGetFile(() => _fileRequestActions.GetNPCFileFromServer(sessionID)).ConfigureAwait(false)) + return; + await Task.Delay(1000).ConfigureAwait(false); + } + + if (_fileRequestActions.NeedsFileForLogin(FileType.Esf)) + { + gameLoadingDialog.SetState(GameLoadingDialogState.Spell); + if (!await SafeGetFile(() => _fileRequestActions.GetSpellFileFromServer(sessionID)).ConfigureAwait(false)) + return; + await Task.Delay(1000).ConfigureAwait(false); + } + + if (_fileRequestActions.NeedsFileForLogin(FileType.Ecf)) + { + gameLoadingDialog.SetState(GameLoadingDialogState.Class); + if (!await SafeGetFile(() => _fileRequestActions.GetClassFileFromServer(sessionID)).ConfigureAwait(false)) + return; + await Task.Delay(1000).ConfigureAwait(false); + } + + gameLoadingDialog.SetState(GameLoadingDialogState.LoadingGame); + + var completeCharacterLoginOperation = _networkOperationFactory.CreateSafeBlockingOperation( + () => _loginActions.CompleteCharacterLogin(sessionID), + SetInitialStateAndShowError, + SetInitialStateAndShowError); + if (!await completeCharacterLoginOperation.Invoke().ConfigureAwait(false)) return; - await Task.Delay(1000).ConfigureAwait(false); - } - if (_fileRequestActions.NeedsFileForLogin(FileType.Ecf)) - { - gameLoadingDialog.SetState(GameLoadingDialogState.Class); - if (!await SafeGetFile(() => _fileRequestActions.GetClassFileFromServer(sessionID)).ConfigureAwait(false)) + if (completeCharacterLoginOperation.Result == WelcomeCode.ServerBusy) + { + // https://discord.com/channels/723989119503696013/787685796055482368/946634672295784509 + // Sausage: 'I have WELCOME_REPLY 3 as returning a "server is busy" message if you send it and then disconnect the client' + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDisplayAction.ShowLoginError(LoginReply.Busy); return; - await Task.Delay(1000).ConfigureAwait(false); - } + } - gameLoadingDialog.SetState(GameLoadingDialogState.LoadingGame); + // TODO: This is a temporary workaround until the bug in AutomaticTypeMapper/Unity is resolved + // https://github.com/ethanmoffat/EndlessClient/issues/151#issuecomment-1079738889 + ClearChat(); + AddDefaultTextToChat(); - var completeCharacterLoginOperation = _networkOperationFactory.CreateSafeBlockingOperation( - () => _loginActions.CompleteCharacterLogin(sessionID), - SetInitialStateAndShowError, - SetInitialStateAndShowError); - if (!await completeCharacterLoginOperation.Invoke().ConfigureAwait(false)) - return; + _userInputTimeRepository.LastInputTime = DateTime.Now; - if (completeCharacterLoginOperation.Result == WelcomeCode.ServerBusy) + await Task.Delay(1000).ConfigureAwait(false); //always wait 1 second + } + finally { - // https://discord.com/channels/723989119503696013/787685796055482368/946634672295784509 - // Sausage: 'I have WELCOME_REPLY 3 as returning a "server is busy" message if you send it and then disconnect the client' - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDisplayAction.ShowLoginError(LoginReply.Busy); - return; + gameLoadingDialog?.CloseDialog(); } - // TODO: This is a temporary workaround until the bug in AutomaticTypeMapper/Unity is resolved - // https://github.com/ethanmoffat/EndlessClient/issues/151#issuecomment-1079738889 - ClearChat(); - AddDefaultTextToChat(); - - _userInputTimeRepository.LastInputTime = DateTime.Now; - - await Task.Delay(1000).ConfigureAwait(false); //always wait 1 second - } - finally - { - gameLoadingDialog?.CloseDialog(); - } - - if (_configurationProvider.InGameWidth != 0 && _configurationProvider.InGameHeight != 0) - { - var layoutConfig = new IniReader(Constants.PanelLayoutFile); - - int width = _configurationProvider.InGameWidth; - int height = _configurationProvider.InGameHeight; - var loaded = layoutConfig.Load() && layoutConfig.GetValue("DISPLAY", "Width", out width) && layoutConfig.GetValue("DISPLAY", "Height", out height); + if (_configurationProvider.InGameWidth != 0 && _configurationProvider.InGameHeight != 0) + { + var layoutConfig = new IniReader(Constants.PanelLayoutFile); + + int width = _configurationProvider.InGameWidth; + int height = _configurationProvider.InGameHeight; + var loaded = layoutConfig.Load() && layoutConfig.GetValue("DISPLAY", "Width", out width) && layoutConfig.GetValue("DISPLAY", "Height", out height); + + await DispatcherGameComponent.Invoke(() => + { + _clientWindowSizeRepository.Width = loaded ? width : _configurationProvider.InGameWidth; + _clientWindowSizeRepository.Height = loaded ? height : _configurationProvider.InGameHeight; + }); + _clientWindowSizeRepository.Resizable = true; + } await DispatcherGameComponent.Invoke(() => { - _clientWindowSizeRepository.Width = loaded ? width : _configurationProvider.InGameWidth; - _clientWindowSizeRepository.Height = loaded ? height : _configurationProvider.InGameHeight; + _gameStateActions.ChangeToState(GameStates.PlayingTheGame); + _chatTextBoxActions.FocusChatTextBox(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.LOADING_GAME_HINT_FIRST); + _firstTimePlayerActions.WarnFirstTimePlayers(); + _mapChangedActions.ActiveCharacterEnterMapForLogin(); }); - _clientWindowSizeRepository.Resizable = true; } - await DispatcherGameComponent.Invoke(() => + private void SetInitialStateAndShowError(NoDataSentException ex) { - _gameStateActions.ChangeToState(GameStates.PlayingTheGame); - _chatTextBoxActions.FocusChatTextBox(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.LOADING_GAME_HINT_FIRST); - _firstTimePlayerActions.WarnFirstTimePlayers(); - _mapChangedActions.ActiveCharacterEnterMapForLogin(); - }); - } - - private void SetInitialStateAndShowError(NoDataSentException ex) - { - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDisplayAction.ShowException(ex); - } + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDisplayAction.ShowException(ex); + } - private void SetInitialStateAndShowError(EmptyPacketReceivedException ex) - { - _gameStateActions.ChangeToState(GameStates.Initial); - _errorDisplayAction.ShowException(ex); - } + private void SetInitialStateAndShowError(EmptyPacketReceivedException ex) + { + _gameStateActions.ChangeToState(GameStates.Initial); + _errorDisplayAction.ShowException(ex); + } - private static Task InitialDelayInReleaseMode() - { + private static Task InitialDelayInReleaseMode() + { #if DEBUG - return Task.Delay(1000); + return Task.Delay(1000); #else - return Task.Delay(5000); + return Task.Delay(5000); #endif - } - - private async Task SafeGetFile(Func operation) - { - var op = _networkOperationFactory.CreateSafeBlockingOperation( - operation, - SetInitialStateAndShowError, - SetInitialStateAndShowError); - return await op.Invoke().ConfigureAwait(false); - } + } - private void ClearChat() - { - foreach (var chat in _chatRepository.AllChat.Values) + private async Task SafeGetFile(Func operation) { - chat.Clear(); + var op = _networkOperationFactory.CreateSafeBlockingOperation( + operation, + SetInitialStateAndShowError, + SetInitialStateAndShowError); + return await op.Invoke().ConfigureAwait(false); } - } - private void AddDefaultTextToChat() - { - var server = _localizedStringFinder.GetString(EOResourceID.STRING_SERVER); - var serverMessage1 = _localizedStringFinder.GetString(EOResourceID.GLOBAL_CHAT_SERVER_MESSAGE_1); - var serverMessage2 = _localizedStringFinder.GetString(EOResourceID.GLOBAL_CHAT_SERVER_MESSAGE_2); - - if (!string.IsNullOrWhiteSpace(_newsProvider.NewsHeader)) + private void ClearChat() { - _chatRepository.AllChat[ChatTab.Local].Add( - new ChatData(ChatTab.Local, server, _newsProvider.NewsHeader, ChatIcon.Note, ChatColor.Server, log: false)); + foreach (var chat in _chatRepository.AllChat.Values) + { + chat.Clear(); + } } - _chatRepository.AllChat[ChatTab.Global].Add( - new ChatData(ChatTab.Global, server, serverMessage1, ChatIcon.Note, ChatColor.Server, log: false)); - _chatRepository.AllChat[ChatTab.Global].Add( - new ChatData(ChatTab.Global, server, serverMessage2, ChatIcon.Note, ChatColor.Server, log: false)); + private void AddDefaultTextToChat() + { + var server = _localizedStringFinder.GetString(EOResourceID.STRING_SERVER); + var serverMessage1 = _localizedStringFinder.GetString(EOResourceID.GLOBAL_CHAT_SERVER_MESSAGE_1); + var serverMessage2 = _localizedStringFinder.GetString(EOResourceID.GLOBAL_CHAT_SERVER_MESSAGE_2); + + if (!string.IsNullOrWhiteSpace(_newsProvider.NewsHeader)) + { + _chatRepository.AllChat[ChatTab.Local].Add( + new ChatData(ChatTab.Local, server, _newsProvider.NewsHeader, ChatIcon.Note, ChatColor.Server, log: false)); + } + + _chatRepository.AllChat[ChatTab.Global].Add( + new ChatData(ChatTab.Global, server, serverMessage1, ChatIcon.Note, ChatColor.Server, log: false)); + _chatRepository.AllChat[ChatTab.Global].Add( + new ChatData(ChatTab.Global, server, serverMessage2, ChatIcon.Note, ChatColor.Server, log: false)); + } } -} -public interface ILoginController -{ - Task LoginToAccount(ILoginParameters loginParameters); + public interface ILoginController + { + Task LoginToAccount(ILoginParameters loginParameters); - Task LoginToCharacter(Character character); + Task LoginToCharacter(Character character); + } } \ No newline at end of file diff --git a/EndlessClient/Controllers/MainButtonController.cs b/EndlessClient/Controllers/MainButtonController.cs index cc4f040d8..4f68aa7ff 100644 --- a/EndlessClient/Controllers/MainButtonController.cs +++ b/EndlessClient/Controllers/MainButtonController.cs @@ -13,167 +13,168 @@ using System.Threading; using System.Threading.Tasks; -namespace EndlessClient.Controllers; - -[AutoMappedType(IsSingleton = true)] -public class MainButtonController : IMainButtonController +namespace EndlessClient.Controllers { - private readonly INetworkConnectionActions _networkConnectionActions; - private readonly IErrorDialogDisplayAction _errorDialogDisplayAction; - private readonly IPacketProcessActions _packetProcessActions; - private readonly IBackgroundReceiveActions _backgroundReceiveActions; - private readonly IGameStateActions _gameStateActions; - private readonly IAccountDialogDisplayActions _accountDialogDisplayActions; - private readonly IResetStateAction _resetStateAction; - private readonly ISafeNetworkOperationFactory _networkOperationFactory; - - private readonly Random _random; - - private int _numberOfConnectionRequests; - - public MainButtonController(INetworkConnectionActions networkConnectionActions, - IErrorDialogDisplayAction errorDialogDisplayAction, - IPacketProcessActions packetProcessActions, - IBackgroundReceiveActions backgroundReceiveActions, - IGameStateActions gameStateActions, - IAccountDialogDisplayActions accountDialogDisplayActions, - IResetStateAction resetStateAction, - ISafeNetworkOperationFactory networkOperationFactory) - { - _networkConnectionActions = networkConnectionActions; - _errorDialogDisplayAction = errorDialogDisplayAction; - _packetProcessActions = packetProcessActions; - _backgroundReceiveActions = backgroundReceiveActions; - _gameStateActions = gameStateActions; - _accountDialogDisplayActions = accountDialogDisplayActions; - _resetStateAction = resetStateAction; - _networkOperationFactory = networkOperationFactory; - - _random = new Random(); - } - - public void GoToInitialState() - { - _gameStateActions.ChangeToState(GameStates.Initial); - } - - public void GoToInitialStateAndDisconnect(bool showLostConnection = false) + [AutoMappedType(IsSingleton = true)] + public class MainButtonController : IMainButtonController { - GoToInitialState(); - StopReceivingAndDisconnect(); - - _resetStateAction.ResetState(); - - if (showLostConnection) - _errorDialogDisplayAction.ShowConnectionLost(false); - } - - public async Task ClickCreateAccount() - { - var result = await StartNetworkConnection().ConfigureAwait(false); - - if (result) + private readonly INetworkConnectionActions _networkConnectionActions; + private readonly IErrorDialogDisplayAction _errorDialogDisplayAction; + private readonly IPacketProcessActions _packetProcessActions; + private readonly IBackgroundReceiveActions _backgroundReceiveActions; + private readonly IGameStateActions _gameStateActions; + private readonly IAccountDialogDisplayActions _accountDialogDisplayActions; + private readonly IResetStateAction _resetStateAction; + private readonly ISafeNetworkOperationFactory _networkOperationFactory; + + private readonly Random _random; + + private int _numberOfConnectionRequests; + + public MainButtonController(INetworkConnectionActions networkConnectionActions, + IErrorDialogDisplayAction errorDialogDisplayAction, + IPacketProcessActions packetProcessActions, + IBackgroundReceiveActions backgroundReceiveActions, + IGameStateActions gameStateActions, + IAccountDialogDisplayActions accountDialogDisplayActions, + IResetStateAction resetStateAction, + ISafeNetworkOperationFactory networkOperationFactory) { - await DispatcherGameComponent.Invoke(() => - { - _gameStateActions.ChangeToState(GameStates.CreateAccount); - _accountDialogDisplayActions.ShowInitialCreateWarningDialog(); - }); + _networkConnectionActions = networkConnectionActions; + _errorDialogDisplayAction = errorDialogDisplayAction; + _packetProcessActions = packetProcessActions; + _backgroundReceiveActions = backgroundReceiveActions; + _gameStateActions = gameStateActions; + _accountDialogDisplayActions = accountDialogDisplayActions; + _resetStateAction = resetStateAction; + _networkOperationFactory = networkOperationFactory; + + _random = new Random(); } - } - - public async Task ClickLogin() - { - var result = await StartNetworkConnection().ConfigureAwait(false); - if (result) + public void GoToInitialState() { - await DispatcherGameComponent.Invoke(() => _gameStateActions.ChangeToState(GameStates.Login)); + _gameStateActions.ChangeToState(GameStates.Initial); } - } - public void ClickViewCredits() - { - _gameStateActions.ChangeToState(GameStates.ViewCredits); - } + public void GoToInitialStateAndDisconnect(bool showLostConnection = false) + { + GoToInitialState(); + StopReceivingAndDisconnect(); - public void ClickExit() - { - StopReceivingAndDisconnect(); - _gameStateActions.ExitGame(); - } + _resetStateAction.ResetState(); - private async Task StartNetworkConnection() - { - if (Interlocked.Increment(ref _numberOfConnectionRequests) != 1) - return false; + if (showLostConnection) + _errorDialogDisplayAction.ShowConnectionLost(false); + } - try + public async Task ClickCreateAccount() { - var connectResult = await _networkConnectionActions.ConnectToServer().ConfigureAwait(false); - if (connectResult == ConnectResult.AlreadyConnected) - return true; + var result = await StartNetworkConnection().ConfigureAwait(false); - if (connectResult != ConnectResult.Success) + if (result) { - _errorDialogDisplayAction.ShowError(connectResult); - return false; + await DispatcherGameComponent.Invoke(() => + { + _gameStateActions.ChangeToState(GameStates.CreateAccount); + _accountDialogDisplayActions.ShowInitialCreateWarningDialog(); + }); } + } - _backgroundReceiveActions.RunBackgroundReceiveLoop(); - - var beginHandshakeOperation = _networkOperationFactory.CreateSafeBlockingOperation( - async () => await _networkConnectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)), - ex => _errorDialogDisplayAction.ShowException(ex), - ex => _errorDialogDisplayAction.ShowException(ex)); + public async Task ClickLogin() + { + var result = await StartNetworkConnection().ConfigureAwait(false); - if (!await beginHandshakeOperation.Invoke().ConfigureAwait(false)) + if (result) { - StopReceivingAndDisconnect(); - return false; + await DispatcherGameComponent.Invoke(() => _gameStateActions.ChangeToState(GameStates.Login)); } + } - var serverPacket = beginHandshakeOperation.Result; + public void ClickViewCredits() + { + _gameStateActions.ChangeToState(GameStates.ViewCredits); + } - if (serverPacket.ReplyCode != InitReply.Ok) - { - _errorDialogDisplayAction.ShowError(serverPacket.ReplyCode, serverPacket.ReplyCodeData); - StopReceivingAndDisconnect(); - return false; - } + public void ClickExit() + { + StopReceivingAndDisconnect(); + _gameStateActions.ExitGame(); + } - var okData = (InitInitServerPacket.ReplyCodeDataOk)serverPacket.ReplyCodeData; - var sequenceStart = InitSequenceStart.FromInitValues(okData.Seq1, okData.Seq2); - _packetProcessActions.SetSequenceStart(sequenceStart); - _packetProcessActions.SetEncodeMultiples(okData.ServerEncryptionMultiple, okData.ClientEncryptionMultiple); + private async Task StartNetworkConnection() + { + if (Interlocked.Increment(ref _numberOfConnectionRequests) != 1) + return false; - _networkConnectionActions.CompleteHandshake(serverPacket); - return true; + try + { + var connectResult = await _networkConnectionActions.ConnectToServer().ConfigureAwait(false); + if (connectResult == ConnectResult.AlreadyConnected) + return true; + + if (connectResult != ConnectResult.Success) + { + _errorDialogDisplayAction.ShowError(connectResult); + return false; + } + + _backgroundReceiveActions.RunBackgroundReceiveLoop(); + + var beginHandshakeOperation = _networkOperationFactory.CreateSafeBlockingOperation( + async () => await _networkConnectionActions.BeginHandshake(_random.Next(Constants.MaxChallenge)), + ex => _errorDialogDisplayAction.ShowException(ex), + ex => _errorDialogDisplayAction.ShowException(ex)); + + if (!await beginHandshakeOperation.Invoke().ConfigureAwait(false)) + { + StopReceivingAndDisconnect(); + return false; + } + + var serverPacket = beginHandshakeOperation.Result; + + if (serverPacket.ReplyCode != InitReply.Ok) + { + _errorDialogDisplayAction.ShowError(serverPacket.ReplyCode, serverPacket.ReplyCodeData); + StopReceivingAndDisconnect(); + return false; + } + + var okData = (InitInitServerPacket.ReplyCodeDataOk)serverPacket.ReplyCodeData; + var sequenceStart = InitSequenceStart.FromInitValues(okData.Seq1, okData.Seq2); + _packetProcessActions.SetSequenceStart(sequenceStart); + _packetProcessActions.SetEncodeMultiples(okData.ServerEncryptionMultiple, okData.ClientEncryptionMultiple); + + _networkConnectionActions.CompleteHandshake(serverPacket); + return true; + } + finally + { + Interlocked.Exchange(ref _numberOfConnectionRequests, 0); + } } - finally + + private void StopReceivingAndDisconnect() { - Interlocked.Exchange(ref _numberOfConnectionRequests, 0); + _backgroundReceiveActions.CancelBackgroundReceiveLoop(); + _networkConnectionActions.DisconnectFromServer(); } } - private void StopReceivingAndDisconnect() + public interface IMainButtonController { - _backgroundReceiveActions.CancelBackgroundReceiveLoop(); - _networkConnectionActions.DisconnectFromServer(); - } -} + void GoToInitialState(); -public interface IMainButtonController -{ - void GoToInitialState(); - - void GoToInitialStateAndDisconnect(bool showLostConnection = false); + void GoToInitialStateAndDisconnect(bool showLostConnection = false); - Task ClickCreateAccount(); + Task ClickCreateAccount(); - Task ClickLogin(); + Task ClickLogin(); - void ClickViewCredits(); + void ClickViewCredits(); - void ClickExit(); + void ClickExit(); + } } \ No newline at end of file diff --git a/EndlessClient/Controllers/MapInteractionController.cs b/EndlessClient/Controllers/MapInteractionController.cs index 82c7ae55d..b64509482 100644 --- a/EndlessClient/Controllers/MapInteractionController.cs +++ b/EndlessClient/Controllers/MapInteractionController.cs @@ -28,290 +28,291 @@ using System; using System.Linq; -namespace EndlessClient.Controllers; - -[AutoMappedType] -public class MapInteractionController : IMapInteractionController +namespace EndlessClient.Controllers { - private readonly IMapActions _mapActions; - private readonly ICharacterActions _characterActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IPaperdollActions _paperdollActions; - private readonly IWalkValidationActions _walkValidationActions; - private readonly IUnwalkableTileActions _unwalkableTileActions; - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly ISpellCastValidationActions _spellCastValidationActions; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IHudControlProvider _hudControlProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly IContextMenuRepository _contextMenuRepository; - private readonly IUserInputTimeRepository _userInputTimeRepository; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IContextMenuRendererFactory _contextMenuRendererFactory; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ISfxPlayer _sfxPlayer; - - public MapInteractionController(IMapActions mapActions, - ICharacterActions characterActions, - IInGameDialogActions inGameDialogActions, - IPaperdollActions paperdollActions, - IWalkValidationActions walkValidationActions, - IUnwalkableTileActions unwalkableTileActions, - ICharacterAnimationActions characterAnimationActions, - ISpellCastValidationActions spellCastValidationActions, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterProvider characterProvider, - IStatusLabelSetter statusLabelSetter, - IInventorySpaceValidator inventorySpaceValidator, - IHudControlProvider hudControlProvider, - ICharacterRendererProvider characterRendererProvider, - IContextMenuRepository contextMenuRepository, - IUserInputTimeRepository userInputTimeRepository, - IEOMessageBoxFactory messageBoxFactory, - IContextMenuRendererFactory contextMenuRendererFactory, - IActiveDialogProvider activeDialogProvider, - ISpellSlotDataRepository spellSlotDataRepository, - ICurrentMapProvider currentMapProvider, - ISfxPlayer sfxPlayer) - { - _mapActions = mapActions; - _characterActions = characterActions; - _inGameDialogActions = inGameDialogActions; - _paperdollActions = paperdollActions; - _walkValidationActions = walkValidationActions; - _unwalkableTileActions = unwalkableTileActions; - _characterAnimationActions = characterAnimationActions; - _spellCastValidationActions = spellCastValidationActions; - _currentMapStateProvider = currentMapStateProvider; - _characterProvider = characterProvider; - _statusLabelSetter = statusLabelSetter; - _inventorySpaceValidator = inventorySpaceValidator; - _hudControlProvider = hudControlProvider; - _characterRendererProvider = characterRendererProvider; - _contextMenuRepository = contextMenuRepository; - _userInputTimeRepository = userInputTimeRepository; - _messageBoxFactory = messageBoxFactory; - _contextMenuRendererFactory = contextMenuRendererFactory; - _activeDialogProvider = activeDialogProvider; - _spellSlotDataRepository = spellSlotDataRepository; - _currentMapProvider = currentMapProvider; - _sfxPlayer = sfxPlayer; - } - - public void LeftClick(IMapCellState cellState) + [AutoMappedType] + public class MapInteractionController : IMapInteractionController { - if (!InventoryPanel.NoItemsDragging() || _activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) - return; + private readonly IMapActions _mapActions; + private readonly ICharacterActions _characterActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IPaperdollActions _paperdollActions; + private readonly IWalkValidationActions _walkValidationActions; + private readonly IUnwalkableTileActions _unwalkableTileActions; + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly ISpellCastValidationActions _spellCastValidationActions; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IHudControlProvider _hudControlProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly IContextMenuRepository _contextMenuRepository; + private readonly IUserInputTimeRepository _userInputTimeRepository; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IContextMenuRendererFactory _contextMenuRendererFactory; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ISfxPlayer _sfxPlayer; - var optionalItem = cellState.Items.FirstOrNone(); - if (optionalItem.HasValue) + public MapInteractionController(IMapActions mapActions, + ICharacterActions characterActions, + IInGameDialogActions inGameDialogActions, + IPaperdollActions paperdollActions, + IWalkValidationActions walkValidationActions, + IUnwalkableTileActions unwalkableTileActions, + ICharacterAnimationActions characterAnimationActions, + ISpellCastValidationActions spellCastValidationActions, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterProvider characterProvider, + IStatusLabelSetter statusLabelSetter, + IInventorySpaceValidator inventorySpaceValidator, + IHudControlProvider hudControlProvider, + ICharacterRendererProvider characterRendererProvider, + IContextMenuRepository contextMenuRepository, + IUserInputTimeRepository userInputTimeRepository, + IEOMessageBoxFactory messageBoxFactory, + IContextMenuRendererFactory contextMenuRendererFactory, + IActiveDialogProvider activeDialogProvider, + ISpellSlotDataRepository spellSlotDataRepository, + ICurrentMapProvider currentMapProvider, + ISfxPlayer sfxPlayer) { - var item = optionalItem.ValueOr(MapItem.None); - if (!_inventorySpaceValidator.ItemFits(item)) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); - else - HandlePickupResult(_mapActions.PickUpItem(item), item); + _mapActions = mapActions; + _characterActions = characterActions; + _inGameDialogActions = inGameDialogActions; + _paperdollActions = paperdollActions; + _walkValidationActions = walkValidationActions; + _unwalkableTileActions = unwalkableTileActions; + _characterAnimationActions = characterAnimationActions; + _spellCastValidationActions = spellCastValidationActions; + _currentMapStateProvider = currentMapStateProvider; + _characterProvider = characterProvider; + _statusLabelSetter = statusLabelSetter; + _inventorySpaceValidator = inventorySpaceValidator; + _hudControlProvider = hudControlProvider; + _characterRendererProvider = characterRendererProvider; + _contextMenuRepository = contextMenuRepository; + _userInputTimeRepository = userInputTimeRepository; + _messageBoxFactory = messageBoxFactory; + _contextMenuRendererFactory = contextMenuRendererFactory; + _activeDialogProvider = activeDialogProvider; + _spellSlotDataRepository = spellSlotDataRepository; + _currentMapProvider = currentMapProvider; + _sfxPlayer = sfxPlayer; } - else if (cellState.Sign.HasValue) - { - var sign = cellState.Sign.ValueOr(Sign.None); - var messageBox = _messageBoxFactory.CreateMessageBox(sign.Message, sign.Title); - messageBox.ShowDialog(); - _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); - } - // vanilla client prioritizes standing first, then board interaction - else if (_characterProvider.MainCharacter.RenderProperties.SitState != SitState.Standing) - { - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - _characterActions.Sit(mapRenderer.GridCoordinates); - } - else if (InteractableTileSpec(cellState.TileSpec) && (cellState.TileSpec.IsBoard() || cellState.TileSpec == TileSpec.Jukebox || CharacterIsCloseEnough(cellState.Coordinate))) + + public void LeftClick(IMapCellState cellState) { - var unwalkableActions = _unwalkableTileActions.GetUnwalkableTileActions(cellState); + if (!InventoryPanel.NoItemsDragging() || _activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) + return; - foreach (var unwalkableAction in unwalkableActions) + var optionalItem = cellState.Items.FirstOrNone(); + if (optionalItem.HasValue) { - if (cellState.TileSpec.IsBoard()) - { - _mapActions.OpenBoard(cellState.TileSpec); - _inGameDialogActions.ShowBoardDialog(); - } - else if (cellState.TileSpec.IsChair()) - { - _characterActions.Sit(cellState.Coordinate, isChair: true); - } + var item = optionalItem.ValueOr(MapItem.None); + if (!_inventorySpaceValidator.ItemFits(item)) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); else + HandlePickupResult(_mapActions.PickUpItem(item), item); + } + else if (cellState.Sign.HasValue) + { + var sign = cellState.Sign.ValueOr(Sign.None); + var messageBox = _messageBoxFactory.CreateMessageBox(sign.Message, sign.Title); + messageBox.ShowDialog(); + _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); + } + // vanilla client prioritizes standing first, then board interaction + else if (_characterProvider.MainCharacter.RenderProperties.SitState != SitState.Standing) + { + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + _characterActions.Sit(mapRenderer.GridCoordinates); + } + else if (InteractableTileSpec(cellState.TileSpec) && (cellState.TileSpec.IsBoard() || cellState.TileSpec == TileSpec.Jukebox || CharacterIsCloseEnough(cellState.Coordinate))) + { + var unwalkableActions = _unwalkableTileActions.GetUnwalkableTileActions(cellState); + + foreach (var unwalkableAction in unwalkableActions) { - switch (cellState.TileSpec) + if (cellState.TileSpec.IsBoard()) + { + _mapActions.OpenBoard(cellState.TileSpec); + _inGameDialogActions.ShowBoardDialog(); + } + else if (cellState.TileSpec.IsChair()) + { + _characterActions.Sit(cellState.Coordinate, isChair: true); + } + else { - case TileSpec.Chest: - if (unwalkableAction == UnwalkableTileAction.Chest) - { - _mapActions.OpenChest(cellState.Coordinate); - _inGameDialogActions.ShowChestDialog(); - } - break; - case TileSpec.BankVault: - if (unwalkableAction == UnwalkableTileAction.Locker) - { - _mapActions.OpenLocker(cellState.Coordinate); - _inGameDialogActions.ShowLockerDialog(); - } - break; - case TileSpec.Jukebox: - if (unwalkableAction == UnwalkableTileAction.Jukebox) - { - _mapActions.OpenJukebox(cellState.Coordinate); - _inGameDialogActions.ShowJukeboxDialog(); - } - break; + switch (cellState.TileSpec) + { + case TileSpec.Chest: + if (unwalkableAction == UnwalkableTileAction.Chest) + { + _mapActions.OpenChest(cellState.Coordinate); + _inGameDialogActions.ShowChestDialog(); + } + break; + case TileSpec.BankVault: + if (unwalkableAction == UnwalkableTileAction.Locker) + { + _mapActions.OpenLocker(cellState.Coordinate); + _inGameDialogActions.ShowLockerDialog(); + } + break; + case TileSpec.Jukebox: + if (unwalkableAction == UnwalkableTileAction.Jukebox) + { + _mapActions.OpenJukebox(cellState.Coordinate); + _inGameDialogActions.ShowJukeboxDialog(); + } + break; + } } } } - } - else if (cellState.InBounds && !cellState.Character.HasValue && !cellState.NPC.HasValue - && _walkValidationActions.IsCellStateWalkable(cellState) == WalkValidationResult.Walkable - && !_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Attacking) - && !_spellSlotDataRepository.SelectedSpellSlot.HasValue) - { - _characterAnimationActions.StartWalking(Option.Some(cellState.Coordinate)); - _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer) - .AnimateMouseClick(); - } + else if (cellState.InBounds && !cellState.Character.HasValue && !cellState.NPC.HasValue + && _walkValidationActions.IsCellStateWalkable(cellState) == WalkValidationResult.Walkable + && !_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Attacking) + && !_spellSlotDataRepository.SelectedSpellSlot.HasValue) + { + _characterAnimationActions.StartWalking(Option.Some(cellState.Coordinate)); + _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer) + .AnimateMouseClick(); + } - cellState.Warp.MatchSome(w => - { - w.SomeWhen(d => d.DoorType != DoorSpec.NoDoor) - .MatchSome(d => - { - if (_unwalkableTileActions.GetUnwalkableTileActions(cellState).Any(x => x == UnwalkableTileAction.Door)) + cellState.Warp.MatchSome(w => + { + w.SomeWhen(d => d.DoorType != DoorSpec.NoDoor) + .MatchSome(d => { - _mapActions.OpenDoor(d); - } - }); - }); + if (_unwalkableTileActions.GetUnwalkableTileActions(cellState).Any(x => x == UnwalkableTileAction.Door)) + { + _mapActions.OpenDoor(d); + } + }); + }); - _spellSlotDataRepository.SelectedSpellSlot = Option.None(); - - _userInputTimeRepository.LastInputTime = DateTime.Now; - } - - public bool LeftClick(ISpellTargetable target) - { - _userInputTimeRepository.LastInputTime = DateTime.Now; + _spellSlotDataRepository.SelectedSpellSlot = Option.None(); - if (!_spellSlotDataRepository.SpellIsPrepared) - return false; + _userInputTimeRepository.LastInputTime = DateTime.Now; + } - _spellSlotDataRepository.SelectedSpellInfo.MatchSome(si => + public bool LeftClick(ISpellTargetable target) { - var result = _spellCastValidationActions.ValidateSpellCast(si.ID, target); - if (result == SpellCastValidationResult.Ok && _characterAnimationActions.PrepareMainCharacterSpell(si.ID, target)) - _characterActions.PrepareCastSpell(si.ID); - else if (result == SpellCastValidationResult.CannotAttackNPC) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.YOU_CANNOT_ATTACK_THIS_NPC); - else if (result == SpellCastValidationResult.ExhaustedNoTp) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_TP); - else if (result == SpellCastValidationResult.ExhaustedNoSp) - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); - }); + _userInputTimeRepository.LastInputTime = DateTime.Now; - _spellSlotDataRepository.SpellIsPrepared = false; - _spellSlotDataRepository.SelectedSpellSlot = Option.None(); + if (!_spellSlotDataRepository.SpellIsPrepared) + return false; - return true; - } + _spellSlotDataRepository.SelectedSpellInfo.MatchSome(si => + { + var result = _spellCastValidationActions.ValidateSpellCast(si.ID, target); + if (result == SpellCastValidationResult.Ok && _characterAnimationActions.PrepareMainCharacterSpell(si.ID, target)) + _characterActions.PrepareCastSpell(si.ID); + else if (result == SpellCastValidationResult.CannotAttackNPC) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.YOU_CANNOT_ATTACK_THIS_NPC); + else if (result == SpellCastValidationResult.ExhaustedNoTp) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_TP); + else if (result == SpellCastValidationResult.ExhaustedNoSp) + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ATTACK_YOU_ARE_EXHAUSTED_SP); + }); - public void RightClick(ISpellTargetable target) - { - if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) - return; + _spellSlotDataRepository.SpellIsPrepared = false; + _spellSlotDataRepository.SelectedSpellSlot = Option.None(); - if (target == _characterProvider.MainCharacter) - { - _paperdollActions.RequestPaperdoll(_characterProvider.MainCharacter.ID); - _inGameDialogActions.ShowPaperdollDialog(_characterProvider.MainCharacter, isMainCharacter: true); - _userInputTimeRepository.LastInputTime = DateTime.Now; + return true; } - else if (target is Character character && _characterRendererProvider.CharacterRenderers.ContainsKey(character.ID)) + + public void RightClick(ISpellTargetable target) { - _contextMenuRepository.ContextMenu = _contextMenuRepository.ContextMenu.Match( - some: cmr => - { - cmr.Dispose(); - return Option.Some(_contextMenuRendererFactory.CreateContextMenuRenderer(_characterRendererProvider.CharacterRenderers[character.ID])); - }, - none: () => Option.Some(_contextMenuRendererFactory.CreateContextMenuRenderer(_characterRendererProvider.CharacterRenderers[character.ID]))); - _contextMenuRepository.ContextMenu.MatchSome(r => r.Initialize()); + if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) + return; + + if (target == _characterProvider.MainCharacter) + { + _paperdollActions.RequestPaperdoll(_characterProvider.MainCharacter.ID); + _inGameDialogActions.ShowPaperdollDialog(_characterProvider.MainCharacter, isMainCharacter: true); + _userInputTimeRepository.LastInputTime = DateTime.Now; + } + else if (target is Character character && _characterRendererProvider.CharacterRenderers.ContainsKey(character.ID)) + { + _contextMenuRepository.ContextMenu = _contextMenuRepository.ContextMenu.Match( + some: cmr => + { + cmr.Dispose(); + return Option.Some(_contextMenuRendererFactory.CreateContextMenuRenderer(_characterRendererProvider.CharacterRenderers[character.ID])); + }, + none: () => Option.Some(_contextMenuRendererFactory.CreateContextMenuRenderer(_characterRendererProvider.CharacterRenderers[character.ID]))); + _contextMenuRepository.ContextMenu.MatchSome(r => r.Initialize()); + } } - } - private bool IsSteppingStone(CharacterRenderProperties renderProps) - { - return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump - || _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump; - } + private bool IsSteppingStone(CharacterRenderProperties renderProps) + { + return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump + || _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump; + } - private void HandlePickupResult(ItemPickupResult pickupResult, MapItem item) - { - switch (pickupResult) + private void HandlePickupResult(ItemPickupResult pickupResult, MapItem item) { - case ItemPickupResult.DropProtection: - var message = EOResourceID.STATUS_LABEL_ITEM_PICKUP_PROTECTED; - var extra = string.Empty; + switch (pickupResult) + { + case ItemPickupResult.DropProtection: + var message = EOResourceID.STATUS_LABEL_ITEM_PICKUP_PROTECTED; + var extra = string.Empty; - item.OwningPlayerID.MatchSome(playerId => - { - message = EOResourceID.STATUS_LABEL_ITEM_PICKUP_PROTECTED_BY; - if (_currentMapStateProvider.Characters.TryGetValue(playerId, out var character)) + item.OwningPlayerID.MatchSome(playerId => { - extra = $" {character.Name}"; - } - }); + message = EOResourceID.STATUS_LABEL_ITEM_PICKUP_PROTECTED_BY; + if (_currentMapStateProvider.Characters.TryGetValue(playerId, out var character)) + { + extra = $" {character.Name}"; + } + }); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, message, extra); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, message, extra); - break; - case ItemPickupResult.TooHeavy: - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT); - break; - case ItemPickupResult.TooFar: - case ItemPickupResult.Ok: break; - default: throw new ArgumentOutOfRangeException(nameof(pickupResult), pickupResult, null); + break; + case ItemPickupResult.TooHeavy: + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT); + break; + case ItemPickupResult.TooFar: + case ItemPickupResult.Ok: break; + default: throw new ArgumentOutOfRangeException(nameof(pickupResult), pickupResult, null); + } } - } - private InventoryPanel InventoryPanel => _hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); + private InventoryPanel InventoryPanel => _hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); - private static bool InteractableTileSpec(TileSpec tileSpec) - { - return tileSpec.IsBoard() || tileSpec.IsChair() - || tileSpec == TileSpec.Chest - || tileSpec == TileSpec.BankVault - || tileSpec == TileSpec.Jukebox; - } + private static bool InteractableTileSpec(TileSpec tileSpec) + { + return tileSpec.IsBoard() || tileSpec.IsChair() + || tileSpec == TileSpec.Chest + || tileSpec == TileSpec.BankVault + || tileSpec == TileSpec.Jukebox; + } - private bool CharacterIsCloseEnough(MapCoordinate coordinate) - { - var x = _characterProvider.MainCharacter.RenderProperties.MapX; - var y = _characterProvider.MainCharacter.RenderProperties.MapY; + private bool CharacterIsCloseEnough(MapCoordinate coordinate) + { + var x = _characterProvider.MainCharacter.RenderProperties.MapX; + var y = _characterProvider.MainCharacter.RenderProperties.MapY; - var withinOneUnit = Math.Max(Math.Abs(x - coordinate.X), Math.Abs(y - coordinate.Y)) <= 1; - var sameXOrY = x == coordinate.X || y == coordinate.Y; - return withinOneUnit && sameXOrY; + var withinOneUnit = Math.Max(Math.Abs(x - coordinate.X), Math.Abs(y - coordinate.Y)) <= 1; + var sameXOrY = x == coordinate.X || y == coordinate.Y; + return withinOneUnit && sameXOrY; + } } -} -public interface IMapInteractionController -{ - void LeftClick(IMapCellState cellState); + public interface IMapInteractionController + { + void LeftClick(IMapCellState cellState); - bool LeftClick(ISpellTargetable target); + bool LeftClick(ISpellTargetable target); - void RightClick(ISpellTargetable target); + void RightClick(ISpellTargetable target); + } } \ No newline at end of file diff --git a/EndlessClient/Controllers/NPCInteractionController.cs b/EndlessClient/Controllers/NPCInteractionController.cs index 4760bb05a..f031b3596 100644 --- a/EndlessClient/Controllers/NPCInteractionController.cs +++ b/EndlessClient/Controllers/NPCInteractionController.cs @@ -9,75 +9,76 @@ using EOLib.Localization; using System.Linq; -namespace EndlessClient.Controllers; - -[AutoMappedType] -public class NPCInteractionController : INPCInteractionController +namespace EndlessClient.Controllers { - private readonly IMapNPCActions _mapNpcActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IENFFileProvider _enfFileProvider; - private readonly IActiveDialogProvider _activeDialogProvider; - - public NPCInteractionController(IMapNPCActions mapNpcActions, - IInGameDialogActions inGameDialogActions, - IStatusLabelSetter statusLabelSetter, - IENFFileProvider enfFileProvider, - IActiveDialogProvider activeDialogProvider) + [AutoMappedType] + public class NPCInteractionController : INPCInteractionController { - _mapNpcActions = mapNpcActions; - _inGameDialogActions = inGameDialogActions; - _statusLabelSetter = statusLabelSetter; - _enfFileProvider = enfFileProvider; - _activeDialogProvider = activeDialogProvider; - } + private readonly IMapNPCActions _mapNpcActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IENFFileProvider _enfFileProvider; + private readonly IActiveDialogProvider _activeDialogProvider; - public void ShowNPCDialog(NPC npc) - { - if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) - return; + public NPCInteractionController(IMapNPCActions mapNpcActions, + IInGameDialogActions inGameDialogActions, + IStatusLabelSetter statusLabelSetter, + IENFFileProvider enfFileProvider, + IActiveDialogProvider activeDialogProvider) + { + _mapNpcActions = mapNpcActions; + _inGameDialogActions = inGameDialogActions; + _statusLabelSetter = statusLabelSetter; + _enfFileProvider = enfFileProvider; + _activeDialogProvider = activeDialogProvider; + } - var data = _enfFileProvider.ENFFile[npc.ID]; + public void ShowNPCDialog(NPC npc) + { + if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) + return; - // there is no "NPC" text in the localized files - _statusLabelSetter.SetStatusLabel($"[ NPC ] {data.Name}"); + var data = _enfFileProvider.ENFFile[npc.ID]; - switch (data.Type) - { - case EOLib.IO.NPCType.Shop: - _mapNpcActions.RequestShop(npc); - break; - case EOLib.IO.NPCType.Quest: - _mapNpcActions.RequestQuest(npc); - break; - case EOLib.IO.NPCType.Bank: - _mapNpcActions.RequestBank(npc); - // note: the npc action types rely on a server response to show the dialog because they are driven - // by config data on the server. Bank account dialog does not have this restriction; - // interaction with the NPC should *always* show the dialog - _inGameDialogActions.ShowBankAccountDialog(); - break; - case EOLib.IO.NPCType.Skills: - _mapNpcActions.RequestSkillmaster(npc); - break; - case EOLib.IO.NPCType.Inn: - _mapNpcActions.RequestInnkeeper(npc); - break; - case EOLib.IO.NPCType.Law: - _mapNpcActions.RequestLaw(npc); - break; - case EOLib.IO.NPCType.Priest: - _mapNpcActions.RequestPriest(npc); - break; - case EOLib.IO.NPCType.Barber: - _mapNpcActions.RequestBarber(npc); - break; + // there is no "NPC" text in the localized files + _statusLabelSetter.SetStatusLabel($"[ NPC ] {data.Name}"); + + switch (data.Type) + { + case EOLib.IO.NPCType.Shop: + _mapNpcActions.RequestShop(npc); + break; + case EOLib.IO.NPCType.Quest: + _mapNpcActions.RequestQuest(npc); + break; + case EOLib.IO.NPCType.Bank: + _mapNpcActions.RequestBank(npc); + // note: the npc action types rely on a server response to show the dialog because they are driven + // by config data on the server. Bank account dialog does not have this restriction; + // interaction with the NPC should *always* show the dialog + _inGameDialogActions.ShowBankAccountDialog(); + break; + case EOLib.IO.NPCType.Skills: + _mapNpcActions.RequestSkillmaster(npc); + break; + case EOLib.IO.NPCType.Inn: + _mapNpcActions.RequestInnkeeper(npc); + break; + case EOLib.IO.NPCType.Law: + _mapNpcActions.RequestLaw(npc); + break; + case EOLib.IO.NPCType.Priest: + _mapNpcActions.RequestPriest(npc); + break; + case EOLib.IO.NPCType.Barber: + _mapNpcActions.RequestBarber(npc); + break; + } } } -} -public interface INPCInteractionController -{ - void ShowNPCDialog(NPC npc); + public interface INPCInteractionController + { + void ShowNPCDialog(NPC npc); + } } \ No newline at end of file diff --git a/EndlessClient/Controllers/NumPadController.cs b/EndlessClient/Controllers/NumPadController.cs index 892f861d1..5661d14a2 100644 --- a/EndlessClient/Controllers/NumPadController.cs +++ b/EndlessClient/Controllers/NumPadController.cs @@ -3,35 +3,36 @@ using EOLib.Domain.Character; using EOLib.Domain.Extensions; -namespace EndlessClient.Controllers; - -[AutoMappedType] -public class NumPadController : INumPadController +namespace EndlessClient.Controllers { - private readonly ICharacterActions _characterActions; - private readonly ICharacterAnimationActions _characterAnimationActions; - private readonly ICharacterProvider _characterProvider; - - public NumPadController(ICharacterActions characterActions, - ICharacterAnimationActions characterAnimationActions, - ICharacterProvider characterProvider) + [AutoMappedType] + public class NumPadController : INumPadController { - _characterActions = characterActions; - _characterAnimationActions = characterAnimationActions; - _characterProvider = characterProvider; - } + private readonly ICharacterActions _characterActions; + private readonly ICharacterAnimationActions _characterAnimationActions; + private readonly ICharacterProvider _characterProvider; - public void Emote(Emote whichEmote) - { - if (!_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing, CharacterActionState.Sitting)) - return; + public NumPadController(ICharacterActions characterActions, + ICharacterAnimationActions characterAnimationActions, + ICharacterProvider characterProvider) + { + _characterActions = characterActions; + _characterAnimationActions = characterAnimationActions; + _characterProvider = characterProvider; + } - _characterActions.Emote(whichEmote); - _characterAnimationActions.Emote(whichEmote); + public void Emote(Emote whichEmote) + { + if (!_characterProvider.MainCharacter.RenderProperties.IsActing(CharacterActionState.Standing, CharacterActionState.Sitting)) + return; + + _characterActions.Emote(whichEmote); + _characterAnimationActions.Emote(whichEmote); + } } -} -public interface INumPadController -{ - void Emote(Emote whichEmote); + public interface INumPadController + { + void Emote(Emote whichEmote); + } } \ No newline at end of file diff --git a/EndlessClient/Controllers/TrainingController.cs b/EndlessClient/Controllers/TrainingController.cs index 22d460607..4968f9f29 100644 --- a/EndlessClient/Controllers/TrainingController.cs +++ b/EndlessClient/Controllers/TrainingController.cs @@ -2,54 +2,55 @@ using EndlessClient.Audio; using EOLib.Domain.Character; -namespace EndlessClient.Controllers; - -[MappedType(BaseType = typeof(ITrainingController))] -public class TrainingController : ITrainingController +namespace EndlessClient.Controllers { - private readonly ITrainingActions _trainingActions; - private readonly ISfxPlayer _sfxPlayer; - - public TrainingController(ITrainingActions trainingActions, - ISfxPlayer sfxPlayer) + [MappedType(BaseType = typeof(ITrainingController))] + public class TrainingController : ITrainingController { - _trainingActions = trainingActions; - _sfxPlayer = sfxPlayer; - } + private readonly ITrainingActions _trainingActions; + private readonly ISfxPlayer _sfxPlayer; - public void AddStatPoint(CharacterStat whichStat) - { - if (InvalidStat(whichStat)) - return; + public TrainingController(ITrainingActions trainingActions, + ISfxPlayer sfxPlayer) + { + _trainingActions = trainingActions; + _sfxPlayer = sfxPlayer; + } - _trainingActions.LevelUpStat(whichStat); - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - } + public void AddStatPoint(CharacterStat whichStat) + { + if (InvalidStat(whichStat)) + return; - public void AddSkillPoint(int spellId) - { - _trainingActions.LevelUpSkill(spellId); - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - } + _trainingActions.LevelUpStat(whichStat); + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + } - private static bool InvalidStat(CharacterStat whichStat) - { - switch (whichStat) + public void AddSkillPoint(int spellId) { - case CharacterStat.Strength: - case CharacterStat.Intelligence: - case CharacterStat.Wisdom: - case CharacterStat.Agility: - case CharacterStat.Constitution: - case CharacterStat.Charisma: return false; - default: return true; + _trainingActions.LevelUpSkill(spellId); + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + } + + private static bool InvalidStat(CharacterStat whichStat) + { + switch (whichStat) + { + case CharacterStat.Strength: + case CharacterStat.Intelligence: + case CharacterStat.Wisdom: + case CharacterStat.Agility: + case CharacterStat.Constitution: + case CharacterStat.Charisma: return false; + default: return true; + } } } -} -public interface ITrainingController -{ - void AddStatPoint(CharacterStat whichStat); + public interface ITrainingController + { + void AddStatPoint(CharacterStat whichStat); - void AddSkillPoint(int spellId); + void AddSkillPoint(int spellId); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs b/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs index 013ed696f..6a7fa651b 100644 --- a/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs +++ b/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs @@ -8,84 +8,85 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Dialogs.Actions; - -[AutoMappedType] -public class AccountDialogDisplayActions : IAccountDialogDisplayActions +namespace EndlessClient.Dialogs.Actions { - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ICreateAccountWarningDialogFactory _createAccountWarningDialogFactory; - private readonly ICreateAccountProgressDialogFactory _createAccountProgressDialogFactory; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IChangePasswordDialogFactory _changePasswordDialogFactory; - - public AccountDialogDisplayActions(ILocalizedStringFinder localizedStringFinder, - ICreateAccountWarningDialogFactory createAccountWarningDialogFactory, - ICreateAccountProgressDialogFactory createAccountProgressDialogFactory, - IEOMessageBoxFactory eoMessageBoxFactory, - IChangePasswordDialogFactory changePasswordDialogFactory) + [AutoMappedType] + public class AccountDialogDisplayActions : IAccountDialogDisplayActions { - _localizedStringFinder = localizedStringFinder; - _createAccountWarningDialogFactory = createAccountWarningDialogFactory; - _createAccountProgressDialogFactory = createAccountProgressDialogFactory; - _eoMessageBoxFactory = eoMessageBoxFactory; - _changePasswordDialogFactory = changePasswordDialogFactory; - } + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ICreateAccountWarningDialogFactory _createAccountWarningDialogFactory; + private readonly ICreateAccountProgressDialogFactory _createAccountProgressDialogFactory; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IChangePasswordDialogFactory _changePasswordDialogFactory; - public void ShowInitialCreateWarningDialog() - { - var message = - $"{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_1)}\n\n{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_2)}\n\n{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_3)}"; + public AccountDialogDisplayActions(ILocalizedStringFinder localizedStringFinder, + ICreateAccountWarningDialogFactory createAccountWarningDialogFactory, + ICreateAccountProgressDialogFactory createAccountProgressDialogFactory, + IEOMessageBoxFactory eoMessageBoxFactory, + IChangePasswordDialogFactory changePasswordDialogFactory) + { + _localizedStringFinder = localizedStringFinder; + _createAccountWarningDialogFactory = createAccountWarningDialogFactory; + _createAccountProgressDialogFactory = createAccountProgressDialogFactory; + _eoMessageBoxFactory = eoMessageBoxFactory; + _changePasswordDialogFactory = changePasswordDialogFactory; + } - var dialog = _createAccountWarningDialogFactory.ShowCreateAccountWarningDialog(message); - dialog.ShowDialog(); - } + public void ShowInitialCreateWarningDialog() + { + var message = + $"{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_1)}\n\n{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_2)}\n\n{_localizedStringFinder.GetString(EOResourceID.ACCOUNT_CREATE_WARNING_DIALOG_3)}"; - public Task ShowCreatePendingDialog() - { - var progress = _createAccountProgressDialogFactory.BuildCreateAccountProgressDialog(); - return progress.ShowDialogAsync(); - } + var dialog = _createAccountWarningDialogFactory.ShowCreateAccountWarningDialog(message); + dialog.ShowDialog(); + } - public Task> ShowChangePasswordDialog() - { - var changePassword = _changePasswordDialogFactory.BuildChangePasswordDialog(); - return changePassword.ShowDialogAsync() - .ContinueWith(showDialogTask => showDialogTask.Result.SomeWhen(x => x == XNADialogResult.OK).Map(x => changePassword.Result)); - } + public Task ShowCreatePendingDialog() + { + var progress = _createAccountProgressDialogFactory.BuildCreateAccountProgressDialog(); + return progress.ShowDialogAsync(); + } - public void ShowCreateParameterValidationError(CreateAccountParameterResult validationResult) - { - var messageBox = _eoMessageBoxFactory.CreateMessageBox( - validationResult.ErrorString, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + public Task> ShowChangePasswordDialog() + { + var changePassword = _changePasswordDialogFactory.BuildChangePasswordDialog(); + return changePassword.ShowDialogAsync() + .ContinueWith(showDialogTask => showDialogTask.Result.SomeWhen(x => x == XNADialogResult.OK).Map(x => changePassword.Result)); + } - public void ShowCreateAccountServerError(AccountReply serverError) - { - DialogResourceID message; - switch (serverError) + public void ShowCreateParameterValidationError(CreateAccountParameterResult validationResult) { - case AccountReply.Exists: message = DialogResourceID.ACCOUNT_CREATE_NAME_EXISTS; break; - case AccountReply.NotApproved: message = DialogResourceID.ACCOUNT_CREATE_NAME_NOT_APPROVED; break; - case AccountReply.Created: message = DialogResourceID.ACCOUNT_CREATE_SUCCESS_WELCOME; break; - case AccountReply.ChangeFailed: message = DialogResourceID.CHANGE_PASSWORD_MISMATCH; break; - case AccountReply.Changed: message = DialogResourceID.CHANGE_PASSWORD_SUCCESS; break; - case AccountReply.RequestDenied: message = DialogResourceID.LOGIN_SERVER_COULD_NOT_PROCESS; break; - default: throw new ArgumentOutOfRangeException(nameof(serverError), serverError, null); + var messageBox = _eoMessageBoxFactory.CreateMessageBox( + validationResult.ErrorString, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); } - var messageBox = _eoMessageBoxFactory.CreateMessageBox( - message, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + public void ShowCreateAccountServerError(AccountReply serverError) + { + DialogResourceID message; + switch (serverError) + { + case AccountReply.Exists: message = DialogResourceID.ACCOUNT_CREATE_NAME_EXISTS; break; + case AccountReply.NotApproved: message = DialogResourceID.ACCOUNT_CREATE_NAME_NOT_APPROVED; break; + case AccountReply.Created: message = DialogResourceID.ACCOUNT_CREATE_SUCCESS_WELCOME; break; + case AccountReply.ChangeFailed: message = DialogResourceID.CHANGE_PASSWORD_MISMATCH; break; + case AccountReply.Changed: message = DialogResourceID.CHANGE_PASSWORD_SUCCESS; break; + case AccountReply.RequestDenied: message = DialogResourceID.LOGIN_SERVER_COULD_NOT_PROCESS; break; + default: throw new ArgumentOutOfRangeException(nameof(serverError), serverError, null); + } - public void ShowSuccessMessage() - { - ShowCreateAccountServerError(AccountReply.Created); + var messageBox = _eoMessageBoxFactory.CreateMessageBox( + message, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } + + public void ShowSuccessMessage() + { + ShowCreateAccountServerError(AccountReply.Created); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs b/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs index b7af0fd41..ee99390e4 100644 --- a/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs @@ -8,74 +8,75 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Dialogs.Actions; - -[AutoMappedType] -public class CharacterDialogActions : ICharacterDialogActions +namespace EndlessClient.Dialogs.Actions { - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ICreateCharacterDialogFactory _createCharacterDialogFactory; - - public CharacterDialogActions(IEOMessageBoxFactory messageBoxFactory, - ICreateCharacterDialogFactory createCharacterDialogFactory) + [AutoMappedType] + public class CharacterDialogActions : ICharacterDialogActions { - _messageBoxFactory = messageBoxFactory; - _createCharacterDialogFactory = createCharacterDialogFactory; - } + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ICreateCharacterDialogFactory _createCharacterDialogFactory; - public Task> ShowCreateCharacterDialog() - { - var dialog = _createCharacterDialogFactory.BuildCreateCharacterDialog(); - return dialog.ShowDialogAsync() - .ContinueWith(dialogTask => - dialogTask.Result.SomeWhen(x => x == XNADialogResult.OK) - .Map(x => new CharacterCreateParameters(dialog.Name, dialog.Gender, dialog.HairStyle, dialog.HairColor, dialog.Race))); - } + public CharacterDialogActions(IEOMessageBoxFactory messageBoxFactory, + ICreateCharacterDialogFactory createCharacterDialogFactory) + { + _messageBoxFactory = messageBoxFactory; + _createCharacterDialogFactory = createCharacterDialogFactory; + } - public void ShowCharacterReplyDialog(CharacterReply response) - { - DialogResourceID message; - switch (response) + public Task> ShowCreateCharacterDialog() { - case CharacterReply.Exists: message = DialogResourceID.CHARACTER_CREATE_NAME_EXISTS; break; - case CharacterReply.Full: message = DialogResourceID.CHARACTER_CREATE_TOO_MANY_CHARS; break; - case CharacterReply.NotApproved: message = DialogResourceID.CHARACTER_CREATE_NAME_NOT_APPROVED; break; - case CharacterReply.Ok: message = DialogResourceID.CHARACTER_CREATE_SUCCESS; break; - default: throw new ArgumentOutOfRangeException(nameof(response), response, null); + var dialog = _createCharacterDialogFactory.BuildCreateCharacterDialog(); + return dialog.ShowDialogAsync() + .ContinueWith(dialogTask => + dialogTask.Result.SomeWhen(x => x == XNADialogResult.OK) + .Map(x => new CharacterCreateParameters(dialog.Name, dialog.Gender, dialog.HairStyle, dialog.HairColor, dialog.Race))); } - var messageBox = _messageBoxFactory.CreateMessageBox(message, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + public void ShowCharacterReplyDialog(CharacterReply response) + { + DialogResourceID message; + switch (response) + { + case CharacterReply.Exists: message = DialogResourceID.CHARACTER_CREATE_NAME_EXISTS; break; + case CharacterReply.Full: message = DialogResourceID.CHARACTER_CREATE_TOO_MANY_CHARS; break; + case CharacterReply.NotApproved: message = DialogResourceID.CHARACTER_CREATE_NAME_NOT_APPROVED; break; + case CharacterReply.Ok: message = DialogResourceID.CHARACTER_CREATE_SUCCESS; break; + default: throw new ArgumentOutOfRangeException(nameof(response), response, null); + } - public void ShowCharacterDeleteWarning(string characterName) - { - var messageBox = _messageBoxFactory.CreateMessageBox( - $"Character \'{characterName}\' ", - DialogResourceID.CHARACTER_DELETE_FIRST_CHECK); - messageBox.ShowDialog(); - } + var messageBox = _messageBoxFactory.CreateMessageBox(message, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - public Task ShowConfirmDeleteWarning(string characterName) - { - var messageBox = _messageBoxFactory.CreateMessageBox( - $"Character \'{characterName}\' ", - DialogResourceID.CHARACTER_DELETE_CONFIRM, - EODialogButtons.OkCancel, - EOMessageBoxStyle.SmallDialogLargeHeader); + public void ShowCharacterDeleteWarning(string characterName) + { + var messageBox = _messageBoxFactory.CreateMessageBox( + $"Character \'{characterName}\' ", + DialogResourceID.CHARACTER_DELETE_FIRST_CHECK); + messageBox.ShowDialog(); + } - return messageBox.ShowDialogAsync(); - } + public Task ShowConfirmDeleteWarning(string characterName) + { + var messageBox = _messageBoxFactory.CreateMessageBox( + $"Character \'{characterName}\' ", + DialogResourceID.CHARACTER_DELETE_CONFIRM, + EODialogButtons.OkCancel, + EOMessageBoxStyle.SmallDialogLargeHeader); - public void ShowCharacterDeleteError() - { - var messageBox = _messageBoxFactory.CreateMessageBox( - "The server did not respond properly for deleting the character. Try again.", - "Server error", - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); + return messageBox.ShowDialogAsync(); + } + + public void ShowCharacterDeleteError() + { + var messageBox = _messageBoxFactory.CreateMessageBox( + "The server did not respond properly for deleting the character. Try again.", + "Server error", + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs b/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs index 734900dd2..430d84281 100644 --- a/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs +++ b/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs @@ -9,165 +9,166 @@ using System.Net.Sockets; using System.Runtime.InteropServices; -namespace EndlessClient.Dialogs.Actions; - -[AutoMappedType] -public class ErrorDialogDisplayAction : IErrorDialogDisplayAction +namespace EndlessClient.Dialogs.Actions { - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ISfxPlayer _sfxPlayer; - - public ErrorDialogDisplayAction(IEOMessageBoxFactory messageBoxFactory, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class ErrorDialogDisplayAction : IErrorDialogDisplayAction { - _messageBoxFactory = messageBoxFactory; - _sfxPlayer = sfxPlayer; - } + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ISfxPlayer _sfxPlayer; - public void ShowError(ConnectResult connectResult) - { - switch (connectResult) + public ErrorDialogDisplayAction(IEOMessageBoxFactory messageBoxFactory, + ISfxPlayer sfxPlayer) { - case ConnectResult.Timeout: - case ConnectResult.InvalidEndpoint: - case ConnectResult.InvalidSocket: - case ConnectResult.SocketError: - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } - break; - default: - { - var errorCode = (int)connectResult; - var ex = new SocketException(errorCode); + _messageBoxFactory = messageBoxFactory; + _sfxPlayer = sfxPlayer; + } - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + public void ShowError(ConnectResult connectResult) + { + switch (connectResult) + { + case ConnectResult.Timeout: + case ConnectResult.InvalidEndpoint: + case ConnectResult.InvalidSocket: + case ConnectResult.SocketError: + { + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } + break; + default: { - if (Enum.TryParse(errorCode.ToString(), out var socketError)) + var errorCode = (int)connectResult; + var ex = new SocketException(errorCode); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - switch (socketError) + if (Enum.TryParse(errorCode.ToString(), out var socketError)) { - case SocketError.HostUnreachable: - case SocketError.HostNotFound: - case SocketError.HostDown: - var hostDownMessageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - hostDownMessageBox.ShowDialog(); - return; + switch (socketError) + { + case SocketError.HostUnreachable: + case SocketError.HostNotFound: + case SocketError.HostDown: + var hostDownMessageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + hostDownMessageBox.ShowDialog(); + return; - // For some reason, this socket error code does not exist in the SocketError enum, but does occurr when the host is unreachable. - default: - if (errorCode == 10063) - goto case SocketError.HostDown; - break; + // For some reason, this socket error code does not exist in the SocketError enum, but does occurr when the host is unreachable. + default: + if (errorCode == 10063) + goto case SocketError.HostDown; + break; + } } } - } - var messageBox = _messageBoxFactory.CreateMessageBox( - $"Error code from socket: {ex.SocketErrorCode}", - "Internal Error"); - messageBox.ShowDialog(); - } - break; + var messageBox = _messageBoxFactory.CreateMessageBox( + $"Error code from socket: {ex.SocketErrorCode}", + "Internal Error"); + messageBox.ShowDialog(); + } + break; + } } - } - public void ShowError(InitReply replyCode, InitInitServerPacket.IReplyCodeData initializationData) - { - switch (replyCode) + public void ShowError(InitReply replyCode, InitInitServerPacket.IReplyCodeData initializationData) { - case InitReply.OutOfDate: - { - var data = (InitInitServerPacket.ReplyCodeDataOutOfDate)initializationData; - var extra = $" {data.Version.Major:D3}.{data.Version.Minor:D3}.{data.Version.Patch:D3}"; - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_CLIENT_OUT_OF_DATE, - extra, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } - break; - case InitReply.Banned: - { - var data = (InitInitServerPacket.ReplyCodeDataBanned)initializationData; - if (data.BanType == InitBanType.Permanent) - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_IP_BAN_PERM, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } - else if (data.BanType == InitBanType.Temporary || data.BanType == 0) + switch (replyCode) + { + case InitReply.OutOfDate: { - var banMinutesRemaining = data.BanTypeData is InitInitServerPacket.ReplyCodeDataBanned.BanTypeData0 dataZero - ? dataZero.MinutesRemaining - : data.BanTypeData is InitInitServerPacket.ReplyCodeDataBanned.BanTypeDataTemporary dataTemp - ? dataTemp.MinutesRemaining - : throw new ArgumentException(); - var extra = $" {banMinutesRemaining} minutes."; - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_IP_BAN_TEMP, + var data = (InitInitServerPacket.ReplyCodeDataOutOfDate)initializationData; + var extra = $" {data.Version.Major:D3}.{data.Version.Minor:D3}.{data.Version.Patch:D3}"; + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_CLIENT_OUT_OF_DATE, extra, EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogLargeHeader); messageBox.ShowDialog(); } + break; + case InitReply.Banned: + { + var data = (InitInitServerPacket.ReplyCodeDataBanned)initializationData; + if (data.BanType == InitBanType.Permanent) + { + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_IP_BAN_PERM, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } + else if (data.BanType == InitBanType.Temporary || data.BanType == 0) + { + var banMinutesRemaining = data.BanTypeData is InitInitServerPacket.ReplyCodeDataBanned.BanTypeData0 dataZero + ? dataZero.MinutesRemaining + : data.BanTypeData is InitInitServerPacket.ReplyCodeDataBanned.BanTypeDataTemporary dataTemp + ? dataTemp.MinutesRemaining + : throw new ArgumentException(); + var extra = $" {banMinutesRemaining} minutes."; + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_IP_BAN_TEMP, + extra, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - _sfxPlayer.PlaySfx(SoundEffectID.Banned); - } - break; - case 0: - ShowError(ConnectResult.SocketError); - break; - default: throw new ArgumentOutOfRangeException(); + _sfxPlayer.PlaySfx(SoundEffectID.Banned); + } + break; + case 0: + ShowError(ConnectResult.SocketError); + break; + default: throw new ArgumentOutOfRangeException(); + } } - } - public void ShowException(NoDataSentException ex) - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, - "\n\"" + ex.Message + "\"", - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + public void ShowException(NoDataSentException ex) + { + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, + "\n\"" + ex.Message + "\"", + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - public void ShowException(EmptyPacketReceivedException ex) - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, - "\n\"" + ex.Message + "\"", - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + public void ShowException(EmptyPacketReceivedException ex) + { + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CONNECTION_SERVER_NOT_FOUND, + "\n\"" + ex.Message + "\"", + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - public void ShowLoginError(LoginReply loginError) - { - var message = loginError switch + public void ShowLoginError(LoginReply loginError) { - LoginReply.WrongUser => DialogResourceID.LOGIN_ACCOUNT_NAME_NOT_FOUND, - LoginReply.WrongUserPassword => DialogResourceID.LOGIN_ACCOUNT_NAME_OR_PASSWORD_NOT_FOUND, - LoginReply.Banned => DialogResourceID.LOGIN_BANNED_FROM_SERVER, - LoginReply.LoggedIn => DialogResourceID.LOGIN_ACCOUNT_ALREADY_LOGGED_ON, - LoginReply.Busy => DialogResourceID.CONNECTION_SERVER_IS_FULL, - _ => DialogResourceID.LOGIN_SERVER_COULD_NOT_PROCESS, - }; - var messageBox = _messageBoxFactory.CreateMessageBox(message, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } + var message = loginError switch + { + LoginReply.WrongUser => DialogResourceID.LOGIN_ACCOUNT_NAME_NOT_FOUND, + LoginReply.WrongUserPassword => DialogResourceID.LOGIN_ACCOUNT_NAME_OR_PASSWORD_NOT_FOUND, + LoginReply.Banned => DialogResourceID.LOGIN_BANNED_FROM_SERVER, + LoginReply.LoggedIn => DialogResourceID.LOGIN_ACCOUNT_ALREADY_LOGGED_ON, + LoginReply.Busy => DialogResourceID.CONNECTION_SERVER_IS_FULL, + _ => DialogResourceID.LOGIN_SERVER_COULD_NOT_PROCESS, + }; + var messageBox = _messageBoxFactory.CreateMessageBox(message, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } - public void ShowConnectionLost(bool isInGame) - { - var resource = isInGame ? DialogResourceID.CONNECTION_LOST_IN_GAME : DialogResourceID.CONNECTION_LOST_CONNECTION; - var style = isInGame ? EOMessageBoxStyle.SmallDialogSmallHeader : EOMessageBoxStyle.SmallDialogLargeHeader; + public void ShowConnectionLost(bool isInGame) + { + var resource = isInGame ? DialogResourceID.CONNECTION_LOST_IN_GAME : DialogResourceID.CONNECTION_LOST_CONNECTION; + var style = isInGame ? EOMessageBoxStyle.SmallDialogSmallHeader : EOMessageBoxStyle.SmallDialogLargeHeader; - var messageBox = _messageBoxFactory.CreateMessageBox(resource, style: style); - messageBox.ShowDialog(); + var messageBox = _messageBoxFactory.CreateMessageBox(resource, style: style); + messageBox.ShowDialog(); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs b/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs index a04d491e8..162da9453 100644 --- a/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs +++ b/EndlessClient/Dialogs/Actions/FirstTimePlayerActions.cs @@ -3,32 +3,33 @@ using EOLib.Domain.Login; using EOLib.Localization; -namespace EndlessClient.Dialogs.Actions; - -[MappedType(BaseType = typeof(IFirstTimePlayerActions))] -public class FirstTimePlayerActions : IFirstTimePlayerActions +namespace EndlessClient.Dialogs.Actions { - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - - public FirstTimePlayerActions(IPlayerInfoProvider playerInfoProvider, - IEOMessageBoxFactory messageBoxFactory) + [MappedType(BaseType = typeof(IFirstTimePlayerActions))] + public class FirstTimePlayerActions : IFirstTimePlayerActions { - _playerInfoProvider = playerInfoProvider; - _messageBoxFactory = messageBoxFactory; - } + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; - public void WarnFirstTimePlayers() - { - if (_playerInfoProvider.IsFirstTimePlayer) + public FirstTimePlayerActions(IPlayerInfoProvider playerInfoProvider, + IEOMessageBoxFactory messageBoxFactory) + { + _playerInfoProvider = playerInfoProvider; + _messageBoxFactory = messageBoxFactory; + } + + public void WarnFirstTimePlayers() { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_FIRST_TIME_PLAYERS); - messageBox.ShowDialog(); + if (_playerInfoProvider.IsFirstTimePlayer) + { + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_FIRST_TIME_PLAYERS); + messageBox.ShowDialog(); + } } } -} -public interface IFirstTimePlayerActions -{ - void WarnFirstTimePlayers(); + public interface IFirstTimePlayerActions + { + void WarnFirstTimePlayers(); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/HelpActions.cs b/EndlessClient/Dialogs/Actions/HelpActions.cs index 9e5ebe628..ee018a1d0 100644 --- a/EndlessClient/Dialogs/Actions/HelpActions.cs +++ b/EndlessClient/Dialogs/Actions/HelpActions.cs @@ -6,103 +6,104 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs.Actions; - -[AutoMappedType] -public class HelpActions : IHelpActions +namespace EndlessClient.Dialogs.Actions { - private readonly IReportActions _reportActions; - private readonly ITextMultiInputDialogFactory _textMultiInputDialogFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly ISfxPlayer _sfxPlayer; - - public HelpActions(IReportActions reportActions, - ITextMultiInputDialogFactory textMultiInputDialogFactory, - ITextInputDialogFactory textInputDialogFactory, - IEOMessageBoxFactory eoMessageBoxFactory, - ISfxPlayer sfxPlayer) - { - _reportActions = reportActions; - _textMultiInputDialogFactory = textMultiInputDialogFactory; - _textInputDialogFactory = textInputDialogFactory; - _eoMessageBoxFactory = eoMessageBoxFactory; - _sfxPlayer = sfxPlayer; - } - - public void ResetPassword() + [AutoMappedType] + public class HelpActions : IHelpActions { - // no - } - - public void ReportSomeone() - { - const string Title = "Report Player"; - const string Prompt = "Who do you want to report, and why?"; + private readonly IReportActions _reportActions; + private readonly ITextMultiInputDialogFactory _textMultiInputDialogFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly ISfxPlayer _sfxPlayer; + + public HelpActions(IReportActions reportActions, + ITextMultiInputDialogFactory textMultiInputDialogFactory, + ITextInputDialogFactory textInputDialogFactory, + IEOMessageBoxFactory eoMessageBoxFactory, + ISfxPlayer sfxPlayer) + { + _reportActions = reportActions; + _textMultiInputDialogFactory = textMultiInputDialogFactory; + _textInputDialogFactory = textInputDialogFactory; + _eoMessageBoxFactory = eoMessageBoxFactory; + _sfxPlayer = sfxPlayer; + } + + public void ResetPassword() + { + // no + } - var dlg = _textMultiInputDialogFactory.Create(Title, Prompt, TextMultiInputDialog.DialogSize.Two, - new TextMultiInputDialog.InputInfo { Label = "Name", MaxChars = 16 }, - new TextMultiInputDialog.InputInfo { Label = "Reason", MaxChars = 48 }); - dlg.DialogClosing += (_, e) => + public void ReportSomeone() { - if (e.Result == XNADialogResult.OK) + const string Title = "Report Player"; + const string Prompt = "Who do you want to report, and why?"; + + var dlg = _textMultiInputDialogFactory.Create(Title, Prompt, TextMultiInputDialog.DialogSize.Two, + new TextMultiInputDialog.InputInfo { Label = "Name", MaxChars = 16 }, + new TextMultiInputDialog.InputInfo { Label = "Reason", MaxChars = 48 }); + dlg.DialogClosing += (_, e) => { - if (dlg.Responses[0].Length > 0 && dlg.Responses[1].Length > 0) + if (e.Result == XNADialogResult.OK) { - _reportActions.ReportPlayer(dlg.Responses[0], dlg.Responses[1]); - _sfxPlayer.PlaySfx(SoundEffectID.AdminRequestSent); + if (dlg.Responses[0].Length > 0 && dlg.Responses[1].Length > 0) + { + _reportActions.ReportPlayer(dlg.Responses[0], dlg.Responses[1]); + _sfxPlayer.PlaySfx(SoundEffectID.AdminRequestSent); + } + + var dlg2 = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.HELP_REQUEST_RECEIVED); + dlg2.ShowDialog(); } + }; - var dlg2 = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.HELP_REQUEST_RECEIVED); - dlg2.ShowDialog(); - } - }; - - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.ShowDialog(); - } - - public void SpeakToAdmin() - { - const string Prompt = "Please enter your question, and we will try to get back to you."; + dlg.ShowDialog(); + } - var dlg = _textInputDialogFactory.Create(Prompt, maxInputChars: 48); - dlg.DialogClosing += (_, e) => + public void SpeakToAdmin() { - if (e.Result == XNADialogResult.OK) + const string Prompt = "Please enter your question, and we will try to get back to you."; + + var dlg = _textInputDialogFactory.Create(Prompt, maxInputChars: 48); + dlg.DialogClosing += (_, e) => { - if (dlg.ResponseText.Length > 0) + if (e.Result == XNADialogResult.OK) { - _reportActions.SpeakToAdmin(dlg.ResponseText); - _sfxPlayer.PlaySfx(SoundEffectID.AdminRequestSent); + if (dlg.ResponseText.Length > 0) + { + _reportActions.SpeakToAdmin(dlg.ResponseText); + _sfxPlayer.PlaySfx(SoundEffectID.AdminRequestSent); + } + + var dlg2 = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.HELP_REQUEST_RECEIVED); + dlg2.ShowDialog(); } + }; - var dlg2 = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.HELP_REQUEST_RECEIVED); - dlg2.ShowDialog(); - } - }; - - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.ShowDialog(); - } + dlg.ShowDialog(); + } - // copied from InGameDialogActions - private void UseDefaultDialogSounds(BaseEODialog dialog) - { - dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + // copied from InGameDialogActions + private void UseDefaultDialogSounds(BaseEODialog dialog) + { + dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - foreach (var textbox in dialog.ChildControls.OfType()) - textbox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); + foreach (var textbox in dialog.ChildControls.OfType()) + textbox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); + } } -} -public interface IHelpActions -{ - void ResetPassword(); + public interface IHelpActions + { + void ResetPassword(); - void ReportSomeone(); + void ReportSomeone(); - void SpeakToAdmin(); + void SpeakToAdmin(); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs b/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs index 7bd133ffa..b394df971 100644 --- a/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs +++ b/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs @@ -4,19 +4,20 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Dialogs.Actions; - -public interface IAccountDialogDisplayActions +namespace EndlessClient.Dialogs.Actions { - void ShowInitialCreateWarningDialog(); + public interface IAccountDialogDisplayActions + { + void ShowInitialCreateWarningDialog(); - Task ShowCreatePendingDialog(); + Task ShowCreatePendingDialog(); - Task> ShowChangePasswordDialog(); + Task> ShowChangePasswordDialog(); - void ShowCreateParameterValidationError(CreateAccountParameterResult validationResult); + void ShowCreateParameterValidationError(CreateAccountParameterResult validationResult); - void ShowCreateAccountServerError(AccountReply serverError); + void ShowCreateAccountServerError(AccountReply serverError); - void ShowSuccessMessage(); + void ShowSuccessMessage(); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs b/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs index b24d3d932..c681896cc 100644 --- a/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs @@ -4,17 +4,18 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.Dialogs.Actions; - -public interface ICharacterDialogActions +namespace EndlessClient.Dialogs.Actions { - Task> ShowCreateCharacterDialog(); + public interface ICharacterDialogActions + { + Task> ShowCreateCharacterDialog(); - void ShowCharacterReplyDialog(CharacterReply response); + void ShowCharacterReplyDialog(CharacterReply response); - void ShowCharacterDeleteWarning(string characterName); + void ShowCharacterDeleteWarning(string characterName); - Task ShowConfirmDeleteWarning(string characterName); + Task ShowConfirmDeleteWarning(string characterName); - void ShowCharacterDeleteError(); + void ShowCharacterDeleteError(); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs b/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs index 6464954ce..49707b8a1 100644 --- a/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs +++ b/EndlessClient/Dialogs/Actions/IErrorDialogDisplayAction.cs @@ -2,19 +2,20 @@ using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -namespace EndlessClient.Dialogs.Actions; - -public interface IErrorDialogDisplayAction +namespace EndlessClient.Dialogs.Actions { - void ShowError(ConnectResult connectResult); + public interface IErrorDialogDisplayAction + { + void ShowError(ConnectResult connectResult); - void ShowError(InitReply replyCode, InitInitServerPacket.IReplyCodeData initializationData); + void ShowError(InitReply replyCode, InitInitServerPacket.IReplyCodeData initializationData); - void ShowException(NoDataSentException ex); + void ShowException(NoDataSentException ex); - void ShowException(EmptyPacketReceivedException ex); + void ShowException(EmptyPacketReceivedException ex); - void ShowLoginError(LoginReply loginError); + void ShowLoginError(LoginReply loginError); - void ShowConnectionLost(bool isIngame); + void ShowConnectionLost(bool isIngame); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/InGameDialogActions.cs b/EndlessClient/Dialogs/Actions/InGameDialogActions.cs index ce85874f8..58562eea9 100644 --- a/EndlessClient/Dialogs/Actions/InGameDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/InGameDialogActions.cs @@ -13,534 +13,535 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs.Actions; - -[AutoMappedType] -public class InGameDialogActions : IInGameDialogActions +namespace EndlessClient.Dialogs.Actions { - private readonly IFriendIgnoreListDialogFactory _friendIgnoreListDialogFactory; - private readonly IPaperdollDialogFactory _paperdollDialogFactory; - private readonly IBookDialogFactory _bookDialogFactory; - private readonly ISessionExpDialogFactory _sessionExpDialogFactory; - private readonly IQuestStatusDialogFactory _questStatusDialogFactory; - private readonly IActiveDialogRepository _activeDialogRepository; - private readonly IShopDataRepository _shopDataRepository; - private readonly IQuestDataRepository _questDataRepository; - private readonly ISkillDataRepository _skillDataRepository; - private readonly IChestDialogFactory _chestDialogFactory; - private readonly ILockerDialogFactory _lockerDialogFactory; - private readonly IBankAccountDialogFactory _bankAccountDialogFactory; - private readonly ISkillmasterDialogFactory _skillmasterDialogFactory; - private readonly IBardDialogFactory _bardDialogFactory; - private readonly IScrollingListDialogFactory _scrollingListDialogFactory; - private readonly ITradeDialogFactory _tradeDialogFactory; - private readonly IBoardDialogFactory _boardDialogFactory; - private readonly IJukeboxDialogFactory _jukeboxDialogFactory; - private readonly IInnkeeperDialogFactory _innkeeperDialogFactory; - private readonly ILawDialogFactory _lawDialogFactory; - private readonly IHelpDialogFactory _helpDialogFactory; - private readonly ISfxPlayer _sfxPlayer; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IShopDialogFactory _shopDialogFactory; - private readonly IQuestDialogFactory _questDialogFactory; - private readonly IBarberDialogFactory _barberDialogFactory; - - public InGameDialogActions(IFriendIgnoreListDialogFactory friendIgnoreListDialogFactory, - IPaperdollDialogFactory paperdollDialogFactory, - IBookDialogFactory bookDialogFactory, - ISessionExpDialogFactory sessionExpDialogFactory, - IQuestStatusDialogFactory questStatusDialogFactory, - IShopDialogFactory shopDialogFactory, - IQuestDialogFactory questDialogFactory, - IActiveDialogRepository activeDialogRepository, - IShopDataRepository shopDataRepository, - IQuestDataRepository questDataRepository, - ISkillDataRepository skillDataRepository, - IChestDialogFactory chestDialogFactory, - ILockerDialogFactory lockerDialogFactory, - IBankAccountDialogFactory bankAccountDialogFactory, - ISkillmasterDialogFactory skillmasterDialogFactory, - IBardDialogFactory bardDialogFactory, - IScrollingListDialogFactory scrollingListDialogFactory, - ITradeDialogFactory tradeDialogFactory, - IBoardDialogFactory boardDialogFactory, - IJukeboxDialogFactory jukeboxDialogFactory, - IInnkeeperDialogFactory innkeeperDialogFactory, - ILawDialogFactory lawDialogFactory, - IHelpDialogFactory helpDialogFactory, - ISfxPlayer sfxPlayer, - IStatusLabelSetter statusLabelSetter, - IBarberDialogFactory barberDialogFactory) + [AutoMappedType] + public class InGameDialogActions : IInGameDialogActions { - _friendIgnoreListDialogFactory = friendIgnoreListDialogFactory; - _paperdollDialogFactory = paperdollDialogFactory; - _bookDialogFactory = bookDialogFactory; - _sessionExpDialogFactory = sessionExpDialogFactory; - _questStatusDialogFactory = questStatusDialogFactory; - _activeDialogRepository = activeDialogRepository; - _shopDataRepository = shopDataRepository; - _questDataRepository = questDataRepository; - _skillDataRepository = skillDataRepository; - _chestDialogFactory = chestDialogFactory; - _lockerDialogFactory = lockerDialogFactory; - _bankAccountDialogFactory = bankAccountDialogFactory; - _skillmasterDialogFactory = skillmasterDialogFactory; - _bardDialogFactory = bardDialogFactory; - _scrollingListDialogFactory = scrollingListDialogFactory; - _tradeDialogFactory = tradeDialogFactory; - _boardDialogFactory = boardDialogFactory; - _jukeboxDialogFactory = jukeboxDialogFactory; - _innkeeperDialogFactory = innkeeperDialogFactory; - _lawDialogFactory = lawDialogFactory; - _helpDialogFactory = helpDialogFactory; - _sfxPlayer = sfxPlayer; - _statusLabelSetter = statusLabelSetter; - _shopDialogFactory = shopDialogFactory; - _questDialogFactory = questDialogFactory; - _barberDialogFactory = barberDialogFactory; - } - - public void ShowFriendListDialog() - { - _activeDialogRepository.FriendIgnoreDialog.MatchNone(() => + private readonly IFriendIgnoreListDialogFactory _friendIgnoreListDialogFactory; + private readonly IPaperdollDialogFactory _paperdollDialogFactory; + private readonly IBookDialogFactory _bookDialogFactory; + private readonly ISessionExpDialogFactory _sessionExpDialogFactory; + private readonly IQuestStatusDialogFactory _questStatusDialogFactory; + private readonly IActiveDialogRepository _activeDialogRepository; + private readonly IShopDataRepository _shopDataRepository; + private readonly IQuestDataRepository _questDataRepository; + private readonly ISkillDataRepository _skillDataRepository; + private readonly IChestDialogFactory _chestDialogFactory; + private readonly ILockerDialogFactory _lockerDialogFactory; + private readonly IBankAccountDialogFactory _bankAccountDialogFactory; + private readonly ISkillmasterDialogFactory _skillmasterDialogFactory; + private readonly IBardDialogFactory _bardDialogFactory; + private readonly IScrollingListDialogFactory _scrollingListDialogFactory; + private readonly ITradeDialogFactory _tradeDialogFactory; + private readonly IBoardDialogFactory _boardDialogFactory; + private readonly IJukeboxDialogFactory _jukeboxDialogFactory; + private readonly IInnkeeperDialogFactory _innkeeperDialogFactory; + private readonly ILawDialogFactory _lawDialogFactory; + private readonly IHelpDialogFactory _helpDialogFactory; + private readonly ISfxPlayer _sfxPlayer; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IShopDialogFactory _shopDialogFactory; + private readonly IQuestDialogFactory _questDialogFactory; + private readonly IBarberDialogFactory _barberDialogFactory; + + public InGameDialogActions(IFriendIgnoreListDialogFactory friendIgnoreListDialogFactory, + IPaperdollDialogFactory paperdollDialogFactory, + IBookDialogFactory bookDialogFactory, + ISessionExpDialogFactory sessionExpDialogFactory, + IQuestStatusDialogFactory questStatusDialogFactory, + IShopDialogFactory shopDialogFactory, + IQuestDialogFactory questDialogFactory, + IActiveDialogRepository activeDialogRepository, + IShopDataRepository shopDataRepository, + IQuestDataRepository questDataRepository, + ISkillDataRepository skillDataRepository, + IChestDialogFactory chestDialogFactory, + ILockerDialogFactory lockerDialogFactory, + IBankAccountDialogFactory bankAccountDialogFactory, + ISkillmasterDialogFactory skillmasterDialogFactory, + IBardDialogFactory bardDialogFactory, + IScrollingListDialogFactory scrollingListDialogFactory, + ITradeDialogFactory tradeDialogFactory, + IBoardDialogFactory boardDialogFactory, + IJukeboxDialogFactory jukeboxDialogFactory, + IInnkeeperDialogFactory innkeeperDialogFactory, + ILawDialogFactory lawDialogFactory, + IHelpDialogFactory helpDialogFactory, + ISfxPlayer sfxPlayer, + IStatusLabelSetter statusLabelSetter, + IBarberDialogFactory barberDialogFactory) { - var dlg = _friendIgnoreListDialogFactory.Create(isFriendList: true); - dlg.DialogClosed += (_, _) => _activeDialogRepository.FriendIgnoreDialog = Option.None(); - _activeDialogRepository.FriendIgnoreDialog = Option.Some(dlg); - - UseDefaultDialogSounds(dlg); - - dlg.Show(); - }); - } - - public void ShowIgnoreListDialog() - { - _activeDialogRepository.FriendIgnoreDialog.MatchNone(() => + _friendIgnoreListDialogFactory = friendIgnoreListDialogFactory; + _paperdollDialogFactory = paperdollDialogFactory; + _bookDialogFactory = bookDialogFactory; + _sessionExpDialogFactory = sessionExpDialogFactory; + _questStatusDialogFactory = questStatusDialogFactory; + _activeDialogRepository = activeDialogRepository; + _shopDataRepository = shopDataRepository; + _questDataRepository = questDataRepository; + _skillDataRepository = skillDataRepository; + _chestDialogFactory = chestDialogFactory; + _lockerDialogFactory = lockerDialogFactory; + _bankAccountDialogFactory = bankAccountDialogFactory; + _skillmasterDialogFactory = skillmasterDialogFactory; + _bardDialogFactory = bardDialogFactory; + _scrollingListDialogFactory = scrollingListDialogFactory; + _tradeDialogFactory = tradeDialogFactory; + _boardDialogFactory = boardDialogFactory; + _jukeboxDialogFactory = jukeboxDialogFactory; + _innkeeperDialogFactory = innkeeperDialogFactory; + _lawDialogFactory = lawDialogFactory; + _helpDialogFactory = helpDialogFactory; + _sfxPlayer = sfxPlayer; + _statusLabelSetter = statusLabelSetter; + _shopDialogFactory = shopDialogFactory; + _questDialogFactory = questDialogFactory; + _barberDialogFactory = barberDialogFactory; + } + + public void ShowFriendListDialog() { - var dlg = _friendIgnoreListDialogFactory.Create(isFriendList: false); - dlg.DialogClosed += (_, _) => _activeDialogRepository.FriendIgnoreDialog = Option.None(); - _activeDialogRepository.FriendIgnoreDialog = Option.Some(dlg); + _activeDialogRepository.FriendIgnoreDialog.MatchNone(() => + { + var dlg = _friendIgnoreListDialogFactory.Create(isFriendList: true); + dlg.DialogClosed += (_, _) => _activeDialogRepository.FriendIgnoreDialog = Option.None(); + _activeDialogRepository.FriendIgnoreDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowSessionExpDialog() - { - _activeDialogRepository.SessionExpDialog.MatchNone(() => + public void ShowIgnoreListDialog() { - var dlg = _sessionExpDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.SessionExpDialog = Option.None(); - _activeDialogRepository.SessionExpDialog = Option.Some(dlg); + _activeDialogRepository.FriendIgnoreDialog.MatchNone(() => + { + var dlg = _friendIgnoreListDialogFactory.Create(isFriendList: false); + dlg.DialogClosed += (_, _) => _activeDialogRepository.FriendIgnoreDialog = Option.None(); + _activeDialogRepository.FriendIgnoreDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowQuestStatusDialog() - { - _activeDialogRepository.QuestStatusDialog.MatchNone(() => + public void ShowSessionExpDialog() { - var dlg = _questStatusDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.QuestStatusDialog = Option.None(); - _activeDialogRepository.QuestStatusDialog = Option.Some(dlg); + _activeDialogRepository.SessionExpDialog.MatchNone(() => + { + var dlg = _sessionExpDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.SessionExpDialog = Option.None(); + _activeDialogRepository.SessionExpDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowPaperdollDialog(Character character, bool isMainCharacter) - { - _activeDialogRepository.PaperdollDialog.MatchNone(() => + public void ShowQuestStatusDialog() { - var dlg = _paperdollDialogFactory.Create(character, isMainCharacter); - dlg.DialogClosed += (_, _) => _activeDialogRepository.PaperdollDialog = Option.None(); - _activeDialogRepository.PaperdollDialog = Option.Some(dlg); + _activeDialogRepository.QuestStatusDialog.MatchNone(() => + { + var dlg = _questStatusDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.QuestStatusDialog = Option.None(); + _activeDialogRepository.QuestStatusDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowBookDialog(Character character, bool isMainCharacter) - { - _activeDialogRepository.BookDialog.MatchNone(() => + public void ShowPaperdollDialog(Character character, bool isMainCharacter) { - var dlg = _bookDialogFactory.Create(character, isMainCharacter); - dlg.DialogClosed += (_, _) => _activeDialogRepository.BookDialog = Option.None(); - _activeDialogRepository.BookDialog = Option.Some(dlg); + _activeDialogRepository.PaperdollDialog.MatchNone(() => + { + var dlg = _paperdollDialogFactory.Create(character, isMainCharacter); + dlg.DialogClosed += (_, _) => _activeDialogRepository.PaperdollDialog = Option.None(); + _activeDialogRepository.PaperdollDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowShopDialog() - { - _activeDialogRepository.ShopDialog.MatchNone(() => + public void ShowBookDialog(Character character, bool isMainCharacter) { - var dlg = _shopDialogFactory.Create(); - dlg.DialogClosed += (_, _) => + _activeDialogRepository.BookDialog.MatchNone(() => { - _activeDialogRepository.ShopDialog = Option.None(); - _shopDataRepository.ResetState(); - }; - _activeDialogRepository.ShopDialog = Option.Some(dlg); + var dlg = _bookDialogFactory.Create(character, isMainCharacter); + dlg.DialogClosed += (_, _) => _activeDialogRepository.BookDialog = Option.None(); + _activeDialogRepository.BookDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowQuestDialog() - { - _activeDialogRepository.QuestDialog.MatchNone(() => + public void ShowShopDialog() { - var dlg = _questDialogFactory.Create(); - dlg.DialogClosed += (_, _) => + _activeDialogRepository.ShopDialog.MatchNone(() => { - _activeDialogRepository.QuestDialog = Option.None(); - _questDataRepository.ResetState(); - }; - _activeDialogRepository.QuestDialog = Option.Some(dlg); + var dlg = _shopDialogFactory.Create(); + dlg.DialogClosed += (_, _) => + { + _activeDialogRepository.ShopDialog = Option.None(); + _shopDataRepository.ResetState(); + }; + _activeDialogRepository.ShopDialog = Option.Some(dlg); - UseQuestDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowChestDialog() - { - _activeDialogRepository.ChestDialog.MatchNone(() => + public void ShowQuestDialog() { - var dlg = _chestDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.ChestDialog = Option.None(); - _activeDialogRepository.ChestDialog = Option.Some(dlg); + _activeDialogRepository.QuestDialog.MatchNone(() => + { + var dlg = _questDialogFactory.Create(); + dlg.DialogClosed += (_, _) => + { + _activeDialogRepository.QuestDialog = Option.None(); + _questDataRepository.ResetState(); + }; + _activeDialogRepository.QuestDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); - _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); + UseQuestDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowLockerDialog() - { - _activeDialogRepository.LockerDialog.MatchNone(() => + public void ShowChestDialog() { - var dlg = _lockerDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.LockerDialog = Option.None(); - _activeDialogRepository.LockerDialog = Option.Some(dlg); + _activeDialogRepository.ChestDialog.MatchNone(() => + { + var dlg = _chestDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.ChestDialog = Option.None(); + _activeDialogRepository.ChestDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); - _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); + UseDefaultDialogSounds(dlg); + _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowBankAccountDialog() - { - _activeDialogRepository.BankAccountDialog.MatchNone(() => + public void ShowLockerDialog() { - var dlg = _bankAccountDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.BankAccountDialog = Option.None(); - _activeDialogRepository.BankAccountDialog = Option.Some(dlg); + _activeDialogRepository.LockerDialog.MatchNone(() => + { + var dlg = _lockerDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.LockerDialog = Option.None(); + _activeDialogRepository.LockerDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); + _sfxPlayer.PlaySfx(SoundEffectID.ChestOpen); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowSkillmasterDialog() - { - var dlg = _skillmasterDialogFactory.Create(); - dlg.DialogClosed += (_, _) => + public void ShowBankAccountDialog() { - _activeDialogRepository.SkillmasterDialog = Option.None(); - _skillDataRepository.ResetState(); - }; - _activeDialogRepository.SkillmasterDialog = Option.Some(dlg); + _activeDialogRepository.BankAccountDialog.MatchNone(() => + { + var dlg = _bankAccountDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.BankAccountDialog = Option.None(); + _activeDialogRepository.BankAccountDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - } + dlg.Show(); + }); + } - public void ShowBardDialog() - { - _activeDialogRepository.BardDialog.MatchNone(() => + public void ShowSkillmasterDialog() { - var dlg = _bardDialogFactory.Create(); + var dlg = _skillmasterDialogFactory.Create(); dlg.DialogClosed += (_, _) => { - _activeDialogRepository.BardDialog = Option.None(); + _activeDialogRepository.SkillmasterDialog = Option.None(); + _skillDataRepository.ResetState(); }; - _activeDialogRepository.BardDialog = Option.Some(dlg); + _activeDialogRepository.SkillmasterDialog = Option.Some(dlg); UseDefaultDialogSounds(dlg); dlg.Show(); - }); - } + } - public void ShowMessageDialog(string title, IReadOnlyList messages) - { - _activeDialogRepository.MessageDialog.MatchNone(() => + public void ShowBardDialog() { - var dlg = _scrollingListDialogFactory.Create(DialogType.Message); - dlg.DialogClosed += (_, _) => _activeDialogRepository.MessageDialog = Option.None(); + _activeDialogRepository.BardDialog.MatchNone(() => + { + var dlg = _bardDialogFactory.Create(); + dlg.DialogClosed += (_, _) => + { + _activeDialogRepository.BardDialog = Option.None(); + }; + _activeDialogRepository.BardDialog = Option.Some(dlg); - dlg.ListItemType = ListDialogItem.ListItemStyle.Small; - dlg.Buttons = ScrollingListDialogButtons.Cancel; - dlg.Title = title; + UseDefaultDialogSounds(dlg); - var _68spaces = new string(Enumerable.Repeat(' ', 68).ToArray()); - var items = messages - // BU hack - assume that 68 spaces or more indicates an extra line break - .Select(x => x.Replace(_68spaces, " \n")) - // BU hack - assume that 3 spaces or more indicates extra padding and should split the message into multiple lines - .SelectMany(x => x.Split(" ", StringSplitOptions.RemoveEmptyEntries)) - .Select(x => new ListDialogItem(dlg, ListDialogItem.ListItemStyle.Small) { PrimaryText = x == "\n" ? string.Empty : x.Trim() }).ToList(); + dlg.Show(); + }); + } - dlg.SetItemList(items); + public void ShowMessageDialog(string title, IReadOnlyList messages) + { + _activeDialogRepository.MessageDialog.MatchNone(() => + { + var dlg = _scrollingListDialogFactory.Create(DialogType.Message); + dlg.DialogClosed += (_, _) => _activeDialogRepository.MessageDialog = Option.None(); - _activeDialogRepository.MessageDialog = Option.Some(dlg); + dlg.ListItemType = ListDialogItem.ListItemStyle.Small; + dlg.Buttons = ScrollingListDialogButtons.Cancel; + dlg.Title = title; - UseDefaultDialogSounds(dlg); + var _68spaces = new string(Enumerable.Repeat(' ', 68).ToArray()); + var items = messages + // BU hack - assume that 68 spaces or more indicates an extra line break + .Select(x => x.Replace(_68spaces, " \n")) + // BU hack - assume that 3 spaces or more indicates extra padding and should split the message into multiple lines + .SelectMany(x => x.Split(" ", StringSplitOptions.RemoveEmptyEntries)) + .Select(x => new ListDialogItem(dlg, ListDialogItem.ListItemStyle.Small) { PrimaryText = x == "\n" ? string.Empty : x.Trim() }).ToList(); - dlg.Show(); - }); - } + dlg.SetItemList(items); - public void ShowKeyValueMessageDialog(string title, IReadOnlyList<(string, string)> messages) - { - _activeDialogRepository.MessageDialog.MatchNone(() => + _activeDialogRepository.MessageDialog = Option.Some(dlg); + + UseDefaultDialogSounds(dlg); + + dlg.Show(); + }); + } + + public void ShowKeyValueMessageDialog(string title, IReadOnlyList<(string, string)> messages) { - var dlg = _scrollingListDialogFactory.Create(DialogType.Message); - dlg.DialogClosed += (_, _) => _activeDialogRepository.MessageDialog = Option.None(); + _activeDialogRepository.MessageDialog.MatchNone(() => + { + var dlg = _scrollingListDialogFactory.Create(DialogType.Message); + dlg.DialogClosed += (_, _) => _activeDialogRepository.MessageDialog = Option.None(); - dlg.ListItemType = ListDialogItem.ListItemStyle.SmallKeyValue; - dlg.Buttons = ScrollingListDialogButtons.Cancel; - dlg.Title = title; + dlg.ListItemType = ListDialogItem.ListItemStyle.SmallKeyValue; + dlg.Buttons = ScrollingListDialogButtons.Cancel; + dlg.Title = title; - var _68spaces = new string(Enumerable.Repeat(' ', 68).ToArray()); - var items = messages - .Select(x => - new ListDialogItem(dlg, ListDialogItem.ListItemStyle.SmallKeyValue) - { - PrimaryText = x.Item1, - SubText = x.Item2, - }) - .ToList(); + var _68spaces = new string(Enumerable.Repeat(' ', 68).ToArray()); + var items = messages + .Select(x => + new ListDialogItem(dlg, ListDialogItem.ListItemStyle.SmallKeyValue) + { + PrimaryText = x.Item1, + SubText = x.Item2, + }) + .ToList(); - dlg.SetItemList(items); + dlg.SetItemList(items); - _activeDialogRepository.MessageDialog = Option.Some(dlg); + _activeDialogRepository.MessageDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void ShowTradeDialog() - { - _activeDialogRepository.TradeDialog.MatchNone(() => + public void ShowTradeDialog() { - var dlg = _tradeDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.TradeDialog = Option.None(); - _activeDialogRepository.TradeDialog = Option.Some(dlg); + _activeDialogRepository.TradeDialog.MatchNone(() => + { + var dlg = _tradeDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.TradeDialog = Option.None(); + _activeDialogRepository.TradeDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - public void CloseTradeDialog() - { - _activeDialogRepository.TradeDialog.MatchSome(dlg => dlg.Close()); - } + public void CloseTradeDialog() + { + _activeDialogRepository.TradeDialog.MatchSome(dlg => dlg.Close()); + } - public void ShowBoardDialog() - { - _activeDialogRepository.BoardDialog.MatchNone(() => + public void ShowBoardDialog() { - var dlg = _boardDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.BoardDialog = Option.None(); - _activeDialogRepository.BoardDialog = Option.Some(dlg); + _activeDialogRepository.BoardDialog.MatchNone(() => + { + var dlg = _boardDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.BoardDialog = Option.None(); + _activeDialogRepository.BoardDialog = Option.Some(dlg); - dlg.Show(); + dlg.Show(); - UseDefaultDialogSounds(dlg); - }); + UseDefaultDialogSounds(dlg); + }); - // the vanilla client shows the status label any time the server sends the BOARD_OPEN packet - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.BOARD_TOWN_BOARD_NOW_VIEWED); - } + // the vanilla client shows the status label any time the server sends the BOARD_OPEN packet + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.BOARD_TOWN_BOARD_NOW_VIEWED); + } - public void ShowJukeboxDialog() - { - _activeDialogRepository.JukeboxDialog.MatchNone(() => + public void ShowJukeboxDialog() { - var dlg = _jukeboxDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.JukeboxDialog = Option.None(); - _activeDialogRepository.JukeboxDialog = Option.Some(dlg); + _activeDialogRepository.JukeboxDialog.MatchNone(() => + { + var dlg = _jukeboxDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.JukeboxDialog = Option.None(); + _activeDialogRepository.JukeboxDialog = Option.Some(dlg); - dlg.Show(); + dlg.Show(); - UseDefaultDialogSounds(dlg); - }); + UseDefaultDialogSounds(dlg); + }); - // the vanilla client shows the status label any time the server sends the BOARD_OPEN packet - // the vanilla client uses [Action] for Board and [Information] for Jukebox, for some reason - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.JUKEBOX_NOW_VIEWED); - } + // the vanilla client shows the status label any time the server sends the BOARD_OPEN packet + // the vanilla client uses [Action] for Board and [Information] for Jukebox, for some reason + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.JUKEBOX_NOW_VIEWED); + } - public void ShowInnkeeperDialog() - { - _activeDialogRepository.InnkeeperDialog.MatchNone(() => + public void ShowInnkeeperDialog() { - var dlg = _innkeeperDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.InnkeeperDialog = Option.None(); - _activeDialogRepository.InnkeeperDialog = Option.Some(dlg); + _activeDialogRepository.InnkeeperDialog.MatchNone(() => + { + var dlg = _innkeeperDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.InnkeeperDialog = Option.None(); + _activeDialogRepository.InnkeeperDialog = Option.Some(dlg); - dlg.Show(); + dlg.Show(); - UseDefaultDialogSounds(dlg); - }); - } + UseDefaultDialogSounds(dlg); + }); + } - public void ShowLawDialog() - { - _activeDialogRepository.LawDialog.MatchNone(() => + public void ShowLawDialog() { - var dlg = _lawDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.LawDialog = Option.None(); - _activeDialogRepository.LawDialog = Option.Some(dlg); + _activeDialogRepository.LawDialog.MatchNone(() => + { + var dlg = _lawDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.LawDialog = Option.None(); + _activeDialogRepository.LawDialog = Option.Some(dlg); - dlg.Show(); + dlg.Show(); - UseDefaultDialogSounds(dlg); - }); - } + UseDefaultDialogSounds(dlg); + }); + } - public void ShowHelpDialog() - { - _activeDialogRepository.HelpDialog.MatchNone(() => + public void ShowHelpDialog() { - var dlg = _helpDialogFactory.Create(); - dlg.DialogClosed += (_, _) => _activeDialogRepository.HelpDialog = Option.None(); - _activeDialogRepository.HelpDialog = Option.Some(dlg); + _activeDialogRepository.HelpDialog.MatchNone(() => + { + var dlg = _helpDialogFactory.Create(); + dlg.DialogClosed += (_, _) => _activeDialogRepository.HelpDialog = Option.None(); + _activeDialogRepository.HelpDialog = Option.Some(dlg); - dlg.Show(); + dlg.Show(); - UseDefaultDialogSounds(dlg); - }); - } + UseDefaultDialogSounds(dlg); + }); + } - public void ShowBarberDialog() - { - _activeDialogRepository.BarberDialog.MatchNone(() => + public void ShowBarberDialog() { - var dlg = _barberDialogFactory.Create(); - dlg.DialogClosed += (_, _) => + _activeDialogRepository.BarberDialog.MatchNone(() => { - _activeDialogRepository.BarberDialog = Option.None(); - }; - _activeDialogRepository.BarberDialog = Option.Some(dlg); + var dlg = _barberDialogFactory.Create(); + dlg.DialogClosed += (_, _) => + { + _activeDialogRepository.BarberDialog = Option.None(); + }; + _activeDialogRepository.BarberDialog = Option.Some(dlg); - UseDefaultDialogSounds(dlg); + UseDefaultDialogSounds(dlg); - dlg.Show(); - }); - } + dlg.Show(); + }); + } - private void UseDefaultDialogSounds(ScrollingListDialog dialog) - { - UseDefaultDialogSounds((BaseEODialog)dialog); + private void UseDefaultDialogSounds(ScrollingListDialog dialog) + { + UseDefaultDialogSounds((BaseEODialog)dialog); - foreach (var button in dialog.ChildControls.OfType()) - button.OnClick += Handler; + foreach (var button in dialog.ChildControls.OfType()) + button.OnClick += Handler; - void Handler(object sender, EventArgs e) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - } + void Handler(object sender, EventArgs e) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + } - private void UseDefaultDialogSounds(BaseEODialog dialog) - { - dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + private void UseDefaultDialogSounds(BaseEODialog dialog) + { + dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - foreach (var textbox in dialog.ChildControls.OfType()) - textbox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); - } + foreach (var textbox in dialog.ChildControls.OfType()) + textbox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); + } - private void UseQuestDialogSounds(QuestDialog dialog) - { - dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - dialog.BackAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); - dialog.NextAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); - dialog.LinkClickAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + private void UseQuestDialogSounds(QuestDialog dialog) + { + dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + dialog.BackAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); + dialog.NextAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.TextBoxFocus); + dialog.LinkClickAction += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + } } -} -public interface IInGameDialogActions -{ - void ShowFriendListDialog(); + public interface IInGameDialogActions + { + void ShowFriendListDialog(); - void ShowIgnoreListDialog(); + void ShowIgnoreListDialog(); - void ShowSessionExpDialog(); + void ShowSessionExpDialog(); - void ShowQuestStatusDialog(); + void ShowQuestStatusDialog(); - void ShowPaperdollDialog(Character character, bool isMainCharacter); + void ShowPaperdollDialog(Character character, bool isMainCharacter); - void ShowBookDialog(Character character, bool isMainCharacter); + void ShowBookDialog(Character character, bool isMainCharacter); - void ShowShopDialog(); + void ShowShopDialog(); - void ShowQuestDialog(); + void ShowQuestDialog(); - void ShowChestDialog(); + void ShowChestDialog(); - void ShowLockerDialog(); + void ShowLockerDialog(); - void ShowBankAccountDialog(); + void ShowBankAccountDialog(); - void ShowSkillmasterDialog(); + void ShowSkillmasterDialog(); - void ShowBardDialog(); + void ShowBardDialog(); - void ShowMessageDialog(string title, IReadOnlyList messages); + void ShowMessageDialog(string title, IReadOnlyList messages); - void ShowKeyValueMessageDialog(string title, IReadOnlyList<(string, string)> messages); + void ShowKeyValueMessageDialog(string title, IReadOnlyList<(string, string)> messages); - void ShowTradeDialog(); + void ShowTradeDialog(); - void CloseTradeDialog(); + void CloseTradeDialog(); - void ShowBoardDialog(); + void ShowBoardDialog(); - void ShowJukeboxDialog(); + void ShowJukeboxDialog(); - void ShowInnkeeperDialog(); + void ShowInnkeeperDialog(); - void ShowLawDialog(); + void ShowLawDialog(); - void ShowHelpDialog(); + void ShowHelpDialog(); - void ShowBarberDialog(); + void ShowBarberDialog(); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs b/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs index ef34befce..d6ebec130 100644 --- a/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs +++ b/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs @@ -13,220 +13,221 @@ using XNAControls; -namespace EndlessClient.Dialogs.Actions; - -[AutoMappedType] -public class NPCInteractionActions : INPCInteractionNotifier +namespace EndlessClient.Dialogs.Actions { - private readonly IInGameDialogActions _inGameDialogActions; - private readonly ICitizenActions _citizenActions; - private readonly IPriestActions _priestActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IPubFileProvider _pubFileProvider; - private readonly ISfxPlayer _sfxPlayer; - - public NPCInteractionActions(IInGameDialogActions inGameDialogActions, - ICitizenActions citizenActions, - IPriestActions priestActions, - IEOMessageBoxFactory messageBoxFactory, - ITextInputDialogFactory textInputDialogFactory, - ILocalizedStringFinder localizedStringFinder, - IPubFileProvider pubFileProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class NPCInteractionActions : INPCInteractionNotifier { - _inGameDialogActions = inGameDialogActions; - _citizenActions = citizenActions; - _priestActions = priestActions; - _messageBoxFactory = messageBoxFactory; - _textInputDialogFactory = textInputDialogFactory; - _localizedStringFinder = localizedStringFinder; - _pubFileProvider = pubFileProvider; - _sfxPlayer = sfxPlayer; - } + private readonly IInGameDialogActions _inGameDialogActions; + private readonly ICitizenActions _citizenActions; + private readonly IPriestActions _priestActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IPubFileProvider _pubFileProvider; + private readonly ISfxPlayer _sfxPlayer; + + public NPCInteractionActions(IInGameDialogActions inGameDialogActions, + ICitizenActions citizenActions, + IPriestActions priestActions, + IEOMessageBoxFactory messageBoxFactory, + ITextInputDialogFactory textInputDialogFactory, + ILocalizedStringFinder localizedStringFinder, + IPubFileProvider pubFileProvider, + ISfxPlayer sfxPlayer) + { + _inGameDialogActions = inGameDialogActions; + _citizenActions = citizenActions; + _priestActions = priestActions; + _messageBoxFactory = messageBoxFactory; + _textInputDialogFactory = textInputDialogFactory; + _localizedStringFinder = localizedStringFinder; + _pubFileProvider = pubFileProvider; + _sfxPlayer = sfxPlayer; + } - public void NotifyInteractionFromNPC(NPCType npcType) - { - // originally, these methods were called directly from NPCInteractionController - // however, this resulted in empty responses (e.g. no shop or quest) showing an empty dialog - // instead, wait for the response packet to notify this class and then show the dialog - // once data has been received from the server - switch (npcType) + public void NotifyInteractionFromNPC(NPCType npcType) { - case NPCType.Shop: _inGameDialogActions.ShowShopDialog(); break; - case NPCType.Quest: _inGameDialogActions.ShowQuestDialog(); break; - case NPCType.Skills: _inGameDialogActions.ShowSkillmasterDialog(); break; - case NPCType.Inn: _inGameDialogActions.ShowInnkeeperDialog(); break; - case NPCType.Law: _inGameDialogActions.ShowLawDialog(); break; - case NPCType.Barber: _inGameDialogActions.ShowBarberDialog(); break; - case NPCType.Priest: ShowPriestDialog(); break; + // originally, these methods were called directly from NPCInteractionController + // however, this resulted in empty responses (e.g. no shop or quest) showing an empty dialog + // instead, wait for the response packet to notify this class and then show the dialog + // once data has been received from the server + switch (npcType) + { + case NPCType.Shop: _inGameDialogActions.ShowShopDialog(); break; + case NPCType.Quest: _inGameDialogActions.ShowQuestDialog(); break; + case NPCType.Skills: _inGameDialogActions.ShowSkillmasterDialog(); break; + case NPCType.Inn: _inGameDialogActions.ShowInnkeeperDialog(); break; + case NPCType.Law: _inGameDialogActions.ShowLawDialog(); break; + case NPCType.Barber: _inGameDialogActions.ShowBarberDialog(); break; + case NPCType.Priest: ShowPriestDialog(); break; + } } - } - public void NotifySkillLearnSuccess(int spellId, int characterGold) - { - _sfxPlayer.PlaySfx(SoundEffectID.LearnNewSpell); - } + public void NotifySkillLearnSuccess(int spellId, int characterGold) + { + _sfxPlayer.PlaySfx(SoundEffectID.LearnNewSpell); + } - public void NotifySkillLearnFail(SkillmasterReply skillmasterReply, int classId) - { - switch (skillmasterReply) + public void NotifySkillLearnFail(SkillmasterReply skillmasterReply, int classId) { - //not sure if this will ever actually be sent because client validates data before trying to learn a skill - case SkillmasterReply.ErrorWrongClass: - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_WRONG_CLASS, $" {_pubFileProvider.ECFFile[classId].Name}!"); - dlg.ShowDialog(); - } - break; - case SkillmasterReply.ErrorRemoveItems: - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_CLEAR_PAPERDOLL); - dlg.ShowDialog(); - } - break; + switch (skillmasterReply) + { + //not sure if this will ever actually be sent because client validates data before trying to learn a skill + case SkillmasterReply.ErrorWrongClass: + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_WRONG_CLASS, $" {_pubFileProvider.ECFFile[classId].Name}!"); + dlg.ShowDialog(); + } + break; + case SkillmasterReply.ErrorRemoveItems: + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_CLEAR_PAPERDOLL); + dlg.ShowDialog(); + } + break; + } } - } - public void NotifySkillForget() - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_FORGET_SUCCESS); - dlg.ShowDialog(); - } + public void NotifySkillForget() + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_FORGET_SUCCESS); + dlg.ShowDialog(); + } - public void NotifyStatReset() - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_COMPLETE); - dlg.ShowDialog(); + public void NotifyStatReset() + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_COMPLETE); + dlg.ShowDialog(); - _sfxPlayer.PlaySfx(SoundEffectID.LearnNewSpell); - } + _sfxPlayer.PlaySfx(SoundEffectID.LearnNewSpell); + } - public void NotifyCitizenUnsubscribe(InnUnsubscribeReply reply) - { - var message = EOResourceID.INN_YOU_ARE_NOT_A_CITIZEN + (int)reply; - var dlg = _messageBoxFactory.CreateMessageBox(message, EOResourceID.INN_REGISTRATION_SERVICE); - dlg.ShowDialog(); - } + public void NotifyCitizenUnsubscribe(InnUnsubscribeReply reply) + { + var message = EOResourceID.INN_YOU_ARE_NOT_A_CITIZEN + (int)reply; + var dlg = _messageBoxFactory.CreateMessageBox(message, EOResourceID.INN_REGISTRATION_SERVICE); + dlg.ShowDialog(); + } - public void NotifyCitizenSignUp(int questionsWrong) - { - if (questionsWrong == 0) + public void NotifyCitizenSignUp(int questionsWrong) { - _sfxPlayer.PlaySfx(SoundEffectID.InnSignUp); + if (questionsWrong == 0) + { + _sfxPlayer.PlaySfx(SoundEffectID.InnSignUp); - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.INN_BECOME_CITIZEN_CONGRATULATIONS, EOResourceID.INN_REGISTRATION_SERVICE); - dlg.ShowDialog(); + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.INN_BECOME_CITIZEN_CONGRATULATIONS, EOResourceID.INN_REGISTRATION_SERVICE); + dlg.ShowDialog(); + } + else + { + var dlg = _messageBoxFactory.CreateMessageBox( + $"{questionsWrong} {_localizedStringFinder.GetString(EOResourceID.INN_YOUR_ANSWERS_WERE_INCORRECT)}", + _localizedStringFinder.GetString(EOResourceID.INN_REGISTRATION_SERVICE)); + dlg.ShowDialog(); + } } - else + + public void NotifyCitizenRequestSleep(int sleepCost) { - var dlg = _messageBoxFactory.CreateMessageBox( - $"{questionsWrong} {_localizedStringFinder.GetString(EOResourceID.INN_YOUR_ANSWERS_WERE_INCORRECT)}", - _localizedStringFinder.GetString(EOResourceID.INN_REGISTRATION_SERVICE)); + var message = $"{_localizedStringFinder.GetString(EOResourceID.INN_A_GOOD_NIGHT_REST_WILL_COST_YOU)} {sleepCost} Gold"; + + var dlg = _messageBoxFactory.CreateMessageBox(message, _localizedStringFinder.GetString(EOResourceID.INN_SLEEP), EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + { + _citizenActions.ConfirmSleep(); + } + }; + dlg.ShowDialog(); } - } - - public void NotifyCitizenRequestSleep(int sleepCost) - { - var message = $"{_localizedStringFinder.GetString(EOResourceID.INN_A_GOOD_NIGHT_REST_WILL_COST_YOU)} {sleepCost} Gold"; - var dlg = _messageBoxFactory.CreateMessageBox(message, _localizedStringFinder.GetString(EOResourceID.INN_SLEEP), EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => + public void NotifyPriestReply(PriestReply reply) { - if (e.Result == XNADialogResult.OK) + var message = reply switch { - _citizenActions.ConfirmSleep(); - } - }; + PriestReply.NotDressed => DialogResourceID.WEDDING_NEED_PROPER_CLOTHES, + PriestReply.LowLevel => DialogResourceID.WEDDING_NEED_HIGHER_LEVEL, + PriestReply.PartnerNotPresent => DialogResourceID.WEDDING_PARTNER_IS_MISSING, + PriestReply.PartnerNotDressed => DialogResourceID.WEDDING_PARTNER_NEED_CLOTHES, + PriestReply.Busy => DialogResourceID.WEDDING_PRIEST_IS_BUSY, + PriestReply.DoYou => DialogResourceID.WEDDING_DO_YOU_ACCEPT, + PriestReply.PartnerAlreadyMarried => DialogResourceID.WEDDING_PARTNER_ALREADY_MARRIED, + PriestReply.NoPermission => DialogResourceID.WEDDING_NO_PERMISSION_TO_COMPLETE, + _ => throw new ArgumentOutOfRangeException(nameof(reply)) + }; - dlg.ShowDialog(); - } + var dlg = _messageBoxFactory.CreateMessageBox(message, whichButtons: reply == PriestReply.DoYou ? EODialogButtons.OkCancel : EODialogButtons.Ok); + if (reply == PriestReply.DoYou) + { + dlg.DialogClosing += (_, e) => + { + if (e.Result != XNADialogResult.OK) + return; - public void NotifyPriestReply(PriestReply reply) - { - var message = reply switch - { - PriestReply.NotDressed => DialogResourceID.WEDDING_NEED_PROPER_CLOTHES, - PriestReply.LowLevel => DialogResourceID.WEDDING_NEED_HIGHER_LEVEL, - PriestReply.PartnerNotPresent => DialogResourceID.WEDDING_PARTNER_IS_MISSING, - PriestReply.PartnerNotDressed => DialogResourceID.WEDDING_PARTNER_NEED_CLOTHES, - PriestReply.Busy => DialogResourceID.WEDDING_PRIEST_IS_BUSY, - PriestReply.DoYou => DialogResourceID.WEDDING_DO_YOU_ACCEPT, - PriestReply.PartnerAlreadyMarried => DialogResourceID.WEDDING_PARTNER_ALREADY_MARRIED, - PriestReply.NoPermission => DialogResourceID.WEDDING_NO_PERMISSION_TO_COMPLETE, - _ => throw new ArgumentOutOfRangeException(nameof(reply)) - }; - - var dlg = _messageBoxFactory.CreateMessageBox(message, whichButtons: reply == PriestReply.DoYou ? EODialogButtons.OkCancel : EODialogButtons.Ok); - if (reply == PriestReply.DoYou) + _priestActions.ConfirmMarriage(); + }; + } + dlg.ShowDialog(); + } + + public void NotifyPriestRequest(string partnerName) { + // The dialog title "Ceremony Notice" is not paired with the message, which is in EOResourceID and not a proper dialog text (????) + var ceremonyNoticeCaption = _localizedStringFinder.GetString(DialogResourceID.WEDDING_NEED_PROPER_CLOTHES); + var ceremonyNoticeMessage = $"{char.ToUpper(partnerName[0]) + partnerName[1..]} {_localizedStringFinder.GetString(EOResourceID.WEDDING_IS_ASKING_YOU_TO_MARRY)}"; + + var dlg = _messageBoxFactory.CreateMessageBox(ceremonyNoticeMessage, ceremonyNoticeCaption, EODialogButtons.OkCancel); dlg.DialogClosing += (_, e) => { if (e.Result != XNADialogResult.OK) return; - _priestActions.ConfirmMarriage(); + _priestActions.AcceptRequest(); }; + dlg.ShowDialog(); } - dlg.ShowDialog(); - } - - public void NotifyPriestRequest(string partnerName) - { - // The dialog title "Ceremony Notice" is not paired with the message, which is in EOResourceID and not a proper dialog text (????) - var ceremonyNoticeCaption = _localizedStringFinder.GetString(DialogResourceID.WEDDING_NEED_PROPER_CLOTHES); - var ceremonyNoticeMessage = $"{char.ToUpper(partnerName[0]) + partnerName[1..]} {_localizedStringFinder.GetString(EOResourceID.WEDDING_IS_ASKING_YOU_TO_MARRY)}"; - var dlg = _messageBoxFactory.CreateMessageBox(ceremonyNoticeMessage, ceremonyNoticeCaption, EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => + public void NotifyMarriageReply(MarriageReply reply) { - if (e.Result != XNADialogResult.OK) - return; - - _priestActions.AcceptRequest(); - }; - dlg.ShowDialog(); - } + var message = reply switch + { + MarriageReply.AlreadyMarried => DialogResourceID.WEDDING_YOU_ALREADY_MARRIED, + MarriageReply.NotMarried => DialogResourceID.WEDDING_CANNOT_DIVORCE_NO_PARTNER, + MarriageReply.Success => DialogResourceID.WEDDING_REGISTRATION_COMPLETE, + MarriageReply.NotEnoughGold => DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, + MarriageReply.WrongName => DialogResourceID.WEDDING_PARTNER_NOT_MATCH, + MarriageReply.ServiceBusy => DialogResourceID.WEDDING_REGISTRATION_TOO_BUSY, + MarriageReply.DivorceNotification => DialogResourceID.WEDDING_DIVORCE_NO_MORE_PARTNER, + _ => throw new ArgumentOutOfRangeException(nameof(reply)) + }; - public void NotifyMarriageReply(MarriageReply reply) - { - var message = reply switch - { - MarriageReply.AlreadyMarried => DialogResourceID.WEDDING_YOU_ALREADY_MARRIED, - MarriageReply.NotMarried => DialogResourceID.WEDDING_CANNOT_DIVORCE_NO_PARTNER, - MarriageReply.Success => DialogResourceID.WEDDING_REGISTRATION_COMPLETE, - MarriageReply.NotEnoughGold => DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, - MarriageReply.WrongName => DialogResourceID.WEDDING_PARTNER_NOT_MATCH, - MarriageReply.ServiceBusy => DialogResourceID.WEDDING_REGISTRATION_TOO_BUSY, - MarriageReply.DivorceNotification => DialogResourceID.WEDDING_DIVORCE_NO_MORE_PARTNER, - _ => throw new ArgumentOutOfRangeException(nameof(reply)) - }; - - var dlg = _messageBoxFactory.CreateMessageBox(message, reply == MarriageReply.NotEnoughGold ? $" {_pubFileProvider.EIFFile[1].Name}" : string.Empty); - dlg.ShowDialog(); - } + var dlg = _messageBoxFactory.CreateMessageBox(message, reply == MarriageReply.NotEnoughGold ? $" {_pubFileProvider.EIFFile[1].Name}" : string.Empty); + dlg.ShowDialog(); + } - private void ShowPriestDialog() - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WEDDING_PRIEST_CAN_PERFORM, EODialogButtons.OkCancel, EOMessageBoxStyle.LargeDialogSmallHeader); - dlg.DialogClosing += (_, e1) => + private void ShowPriestDialog() { - if (e1.Result != XNADialogResult.OK) - return; - - var inputDlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PLEASE_ENTER_NAME)); - inputDlg.DialogClosing += (_, e2) => + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WEDDING_PRIEST_CAN_PERFORM, EODialogButtons.OkCancel, EOMessageBoxStyle.LargeDialogSmallHeader); + dlg.DialogClosing += (_, e1) => { - if (e2.Result != XNADialogResult.OK) + if (e1.Result != XNADialogResult.OK) return; - _priestActions.RequestMarriage(inputDlg.ResponseText); - }; + var inputDlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PLEASE_ENTER_NAME)); + inputDlg.DialogClosing += (_, e2) => + { + if (e2.Result != XNADialogResult.OK) + return; + + _priestActions.RequestMarriage(inputDlg.ResponseText); + }; - inputDlg.ShowDialog(); - }; - dlg.ShowDialog(); + inputDlg.ShowDialog(); + }; + dlg.ShowDialog(); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/PartyDialogActions.cs b/EndlessClient/Dialogs/Actions/PartyDialogActions.cs index c752de038..5c911ccf6 100644 --- a/EndlessClient/Dialogs/Actions/PartyDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/PartyDialogActions.cs @@ -10,76 +10,77 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using XNAControls; -namespace EndlessClient.Dialogs.Actions; - -[AutoMappedType] -public class PartyDialogActions : IPartyEventNotifier +namespace EndlessClient.Dialogs.Actions { - private readonly IPartyActions _partyActions; - private readonly ISfxPlayer _sfxPlayer; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IChatRepository _chatRepository; - private readonly IConfigurationProvider _configurationProvider; - - public PartyDialogActions(IPartyActions partyActions, - ISfxPlayer sfxPlayer, - IEOMessageBoxFactory messageBoxFactory, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - IChatRepository chatRepository, - IConfigurationProvider configurationProvider) + [AutoMappedType] + public class PartyDialogActions : IPartyEventNotifier { - _partyActions = partyActions; - _sfxPlayer = sfxPlayer; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _chatRepository = chatRepository; - _configurationProvider = configurationProvider; - } + private readonly IPartyActions _partyActions; + private readonly ISfxPlayer _sfxPlayer; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IChatRepository _chatRepository; + private readonly IConfigurationProvider _configurationProvider; - public void NotifyPartyRequest(PartyRequestType type, int playerId, string name) - { - if (!_configurationProvider.Interaction) - return; + public PartyDialogActions(IPartyActions partyActions, + ISfxPlayer sfxPlayer, + IEOMessageBoxFactory messageBoxFactory, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + IChatRepository chatRepository, + IConfigurationProvider configurationProvider) + { + _partyActions = partyActions; + _sfxPlayer = sfxPlayer; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _chatRepository = chatRepository; + _configurationProvider = configurationProvider; + } - var dlg = _messageBoxFactory.CreateMessageBox( - $"{char.ToUpper(name[0])}{name[1..]} ", - type == PartyRequestType.Join - ? DialogResourceID.PARTY_GROUP_REQUEST_TO_JOIN - : DialogResourceID.PARTY_GROUP_SEND_INVITATION, - EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => + public void NotifyPartyRequest(PartyRequestType type, int playerId, string name) { - if (e.Result == XNADialogResult.OK) + if (!_configurationProvider.Interaction) + return; + + var dlg = _messageBoxFactory.CreateMessageBox( + $"{char.ToUpper(name[0])}{name[1..]} ", + type == PartyRequestType.Join + ? DialogResourceID.PARTY_GROUP_REQUEST_TO_JOIN + : DialogResourceID.PARTY_GROUP_SEND_INVITATION, + EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => { - _partyActions.AcceptParty(type, playerId); - } - }; - dlg.ShowDialog(); - } + if (e.Result == XNADialogResult.OK) + { + _partyActions.AcceptParty(type, playerId); + } + }; + dlg.ShowDialog(); + } - public void NotifyPartyJoined() - { - _sfxPlayer.PlaySfx(SoundEffectID.JoinParty); + public void NotifyPartyJoined() + { + _sfxPlayer.PlaySfx(SoundEffectID.JoinParty); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_PARTY_YOU_JOINED); - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_YOU_JOINED), ChatIcon.PlayerParty, ChatColor.PM)); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_PARTY_YOU_JOINED); + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_YOU_JOINED), ChatIcon.PlayerParty, ChatColor.PM)); + } - public void NotifyPartyMemberAdd(string name) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, name, EOResourceID.STATUS_LABEL_PARTY_JOINED_YOUR); - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_JOINED_YOUR), ChatIcon.PlayerParty, ChatColor.PM)); - } + public void NotifyPartyMemberAdd(string name) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, name, EOResourceID.STATUS_LABEL_PARTY_JOINED_YOUR); + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_JOINED_YOUR), ChatIcon.PlayerParty, ChatColor.PM)); + } - public void NotifyPartyMemberRemove(string name) - { - _sfxPlayer.PlaySfx(SoundEffectID.MemberLeftParty); + public void NotifyPartyMemberRemove(string name) + { + _sfxPlayer.PlaySfx(SoundEffectID.MemberLeftParty); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, name, EOResourceID.STATUS_LABEL_PARTY_LEFT_YOUR); - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_LEFT_YOUR), ChatIcon.PlayerPartyDark, ChatColor.PM)); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, name, EOResourceID.STATUS_LABEL_PARTY_LEFT_YOUR); + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_PARTY_LEFT_YOUR), ChatIcon.PlayerPartyDark, ChatColor.PM)); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Actions/TradeDialogActions.cs b/EndlessClient/Dialogs/Actions/TradeDialogActions.cs index b770f3eb4..c1be94edf 100644 --- a/EndlessClient/Dialogs/Actions/TradeDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/TradeDialogActions.cs @@ -8,80 +8,81 @@ using EOLib.Localization; using XNAControls; -namespace EndlessClient.Dialogs.Actions; - -[AutoMappedType] -public class TradeDialogActions : ITradeEventNotifier +namespace EndlessClient.Dialogs.Actions { - private readonly ITradeActions _tradeActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ITradeProvider _tradeProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IConfigurationProvider _configurationProvider; - - public TradeDialogActions(ITradeActions tradeActions, - IInGameDialogActions inGameDialogActions, - IEOMessageBoxFactory messageBoxFactory, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - ITradeProvider tradeProvider, - ICharacterProvider characterProvider, - IConfigurationProvider configurationProvider) + [AutoMappedType] + public class TradeDialogActions : ITradeEventNotifier { - _tradeActions = tradeActions; - _inGameDialogActions = inGameDialogActions; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _tradeProvider = tradeProvider; - _characterProvider = characterProvider; - _configurationProvider = configurationProvider; - } + private readonly ITradeActions _tradeActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ITradeProvider _tradeProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IConfigurationProvider _configurationProvider; - public void NotifyTradeRequest(int playerId, string name) - { - if (!_configurationProvider.Interaction) - return; - - var dlg = _messageBoxFactory.CreateMessageBox(char.ToUpper(name[0]) + name[1..] + " ", DialogResourceID.TRADE_REQUEST, EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => + public TradeDialogActions(ITradeActions tradeActions, + IInGameDialogActions inGameDialogActions, + IEOMessageBoxFactory messageBoxFactory, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + ITradeProvider tradeProvider, + ICharacterProvider characterProvider, + IConfigurationProvider configurationProvider) { - if (e.Result == XNADialogResult.OK) - { - _tradeActions.AcceptTradeRequest(playerId); - } - }; - - dlg.ShowDialog(); - } + _tradeActions = tradeActions; + _inGameDialogActions = inGameDialogActions; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _tradeProvider = tradeProvider; + _characterProvider = characterProvider; + _configurationProvider = configurationProvider; + } - public void NotifyTradeAccepted() - { - _inGameDialogActions.ShowTradeDialog(); + public void NotifyTradeRequest(int playerId, string name) + { + if (!_configurationProvider.Interaction) + return; - var otherName = _tradeProvider.PlayerOneOffer.PlayerID == _characterProvider.MainCharacter.ID - ? _tradeProvider.PlayerOneOffer.PlayerName - : _tradeProvider.PlayerTwoOffer.PlayerName; - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - EOResourceID.STATUS_LABEL_TRADE_YOU_ARE_TRADING_WITH, - $"{otherName} {_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_DRAG_AND_DROP_ITEMS)}"); - } + var dlg = _messageBoxFactory.CreateMessageBox(char.ToUpper(name[0]) + name[1..] + " ", DialogResourceID.TRADE_REQUEST, EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + { + _tradeActions.AcceptTradeRequest(playerId); + } + }; - public void NotifyTradeClose(bool cancel) - { - _inGameDialogActions.CloseTradeDialog(); + dlg.ShowDialog(); + } - if (cancel) + public void NotifyTradeAccepted() { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_TRADE_ABORTED); + _inGameDialogActions.ShowTradeDialog(); + + var otherName = _tradeProvider.PlayerOneOffer.PlayerID == _characterProvider.MainCharacter.ID + ? _tradeProvider.PlayerOneOffer.PlayerName + : _tradeProvider.PlayerTwoOffer.PlayerName; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + EOResourceID.STATUS_LABEL_TRADE_YOU_ARE_TRADING_WITH, + $"{otherName} {_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_DRAG_AND_DROP_ITEMS)}"); } - else + + public void NotifyTradeClose(bool cancel) { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_SUCCESS); - dlg.ShowDialog(); + _inGameDialogActions.CloseTradeDialog(); + + if (cancel) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_TRADE_ABORTED); + } + else + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_SUCCESS); + dlg.ShowDialog(); + } } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ActiveDialogRepository.cs b/EndlessClient/Dialogs/ActiveDialogRepository.cs index 34ec910fd..b8932eee4 100644 --- a/EndlessClient/Dialogs/ActiveDialogRepository.cs +++ b/EndlessClient/Dialogs/ActiveDialogRepository.cs @@ -5,212 +5,213 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs; - -public interface IActiveDialogProvider : IDisposable +namespace EndlessClient.Dialogs { - Option FriendIgnoreDialog { get; } + public interface IActiveDialogProvider : IDisposable + { + Option FriendIgnoreDialog { get; } - Option SessionExpDialog { get; } + Option SessionExpDialog { get; } - Option QuestStatusDialog { get; } + Option QuestStatusDialog { get; } - Option PaperdollDialog { get; } + Option PaperdollDialog { get; } - Option BookDialog { get; } + Option BookDialog { get; } - Option ShopDialog { get; } + Option ShopDialog { get; } - Option QuestDialog { get; } + Option QuestDialog { get; } - Option ChestDialog { get; } + Option ChestDialog { get; } - Option LockerDialog { get; } + Option LockerDialog { get; } - Option BankAccountDialog { get; } + Option BankAccountDialog { get; } - Option SkillmasterDialog { get; } + Option SkillmasterDialog { get; } - Option BardDialog { get; } + Option BardDialog { get; } - Option MessageDialog { get; } + Option MessageDialog { get; } - Option TradeDialog { get; } + Option TradeDialog { get; } - Option MessageBox { get; } + Option MessageBox { get; } - Option BoardDialog { get; } + Option BoardDialog { get; } - Option JukeboxDialog { get; } + Option JukeboxDialog { get; } - Option InnkeeperDialog { get; } + Option InnkeeperDialog { get; } - Option LawDialog { get; } + Option LawDialog { get; } - Option BarberDialog { get; } + Option BarberDialog { get; } - Option HelpDialog { get; } + Option HelpDialog { get; } - IReadOnlyList> ActiveDialogs { get; } -} + IReadOnlyList> ActiveDialogs { get; } + } -public interface IActiveDialogRepository : IDisposable -{ - Option FriendIgnoreDialog { get; set; } + public interface IActiveDialogRepository : IDisposable + { + Option FriendIgnoreDialog { get; set; } - Option SessionExpDialog { get; set; } + Option SessionExpDialog { get; set; } - Option QuestStatusDialog { get; set; } + Option QuestStatusDialog { get; set; } - Option PaperdollDialog { get; set; } + Option PaperdollDialog { get; set; } - Option BookDialog { get; set; } + Option BookDialog { get; set; } - Option ShopDialog { get; set; } + Option ShopDialog { get; set; } - Option QuestDialog { get; set; } + Option QuestDialog { get; set; } - Option ChestDialog { get; set; } + Option ChestDialog { get; set; } - Option LockerDialog { get; set; } + Option LockerDialog { get; set; } - Option BankAccountDialog { get; set; } + Option BankAccountDialog { get; set; } - Option SkillmasterDialog { get; set; } + Option SkillmasterDialog { get; set; } - Option BardDialog { get; set; } + Option BardDialog { get; set; } - Option MessageDialog { get; set; } + Option MessageDialog { get; set; } - Option TradeDialog { get; set; } + Option TradeDialog { get; set; } - Option MessageBox { get; set; } + Option MessageBox { get; set; } - Option BoardDialog { get; set; } + Option BoardDialog { get; set; } - Option JukeboxDialog { get; set; } + Option JukeboxDialog { get; set; } - Option InnkeeperDialog { get; set; } + Option InnkeeperDialog { get; set; } - Option LawDialog { get; set; } + Option LawDialog { get; set; } - Option BarberDialog { get; set; } + Option BarberDialog { get; set; } - Option HelpDialog { get; set; } + Option HelpDialog { get; set; } - IReadOnlyList> ActiveDialogs { get; } -} + IReadOnlyList> ActiveDialogs { get; } + } -[AutoMappedType(IsSingleton = true)] -public class ActiveDialogRepository : IActiveDialogRepository, IActiveDialogProvider -{ - public Option FriendIgnoreDialog { get; set; } + [AutoMappedType(IsSingleton = true)] + public class ActiveDialogRepository : IActiveDialogRepository, IActiveDialogProvider + { + public Option FriendIgnoreDialog { get; set; } - public Option SessionExpDialog { get; set; } + public Option SessionExpDialog { get; set; } - public Option QuestStatusDialog { get; set; } + public Option QuestStatusDialog { get; set; } - public Option PaperdollDialog { get; set; } + public Option PaperdollDialog { get; set; } - public Option BookDialog { get; set; } + public Option BookDialog { get; set; } - public Option ShopDialog { get; set; } + public Option ShopDialog { get; set; } - public Option QuestDialog { get; set; } + public Option QuestDialog { get; set; } - public Option ChestDialog { get; set; } + public Option ChestDialog { get; set; } - public Option LockerDialog { get; set; } + public Option LockerDialog { get; set; } - public Option BankAccountDialog { get; set; } + public Option BankAccountDialog { get; set; } - public Option SkillmasterDialog { get; set; } + public Option SkillmasterDialog { get; set; } - public Option BardDialog { get; set; } + public Option BardDialog { get; set; } - public Option MessageDialog { get; set; } + public Option MessageDialog { get; set; } - public Option TradeDialog { get; set; } + public Option TradeDialog { get; set; } - public Option MessageBox { get; set; } + public Option MessageBox { get; set; } - public Option BoardDialog { get; set; } + public Option BoardDialog { get; set; } - public Option JukeboxDialog { get; set; } + public Option JukeboxDialog { get; set; } - public Option InnkeeperDialog { get; set; } + public Option InnkeeperDialog { get; set; } - public Option LawDialog { get; set; } + public Option LawDialog { get; set; } - public Option BarberDialog { get; set; } + public Option BarberDialog { get; set; } - public Option HelpDialog { get; set; } + public Option HelpDialog { get; set; } - IReadOnlyList> ActiveDialogs - { - get + IReadOnlyList> ActiveDialogs { - return new Option[] + get { - FriendIgnoreDialog.Map(Map), - SessionExpDialog.Map(Map), - QuestStatusDialog.Map(Map), - PaperdollDialog.Map(Map), - BookDialog.Map(Map), - ShopDialog.Map(Map), - QuestDialog.Map(Map), - ChestDialog.Map(Map), - LockerDialog.Map(Map), - BankAccountDialog.Map(Map), - SkillmasterDialog.Map(Map), - BardDialog.Map(Map), - MessageDialog.Map(Map), - TradeDialog.Map(Map), - MessageBox.Map(Map), - BoardDialog.Map(Map), - JukeboxDialog.Map(Map), - InnkeeperDialog.Map(Map), - LawDialog.Map(Map), - BarberDialog.Map(Map), - HelpDialog.Map(Map), - }.ToList(); - - static IXNADialog Map(object d) - { - return (IXNADialog)d; + return new Option[] + { + FriendIgnoreDialog.Map(Map), + SessionExpDialog.Map(Map), + QuestStatusDialog.Map(Map), + PaperdollDialog.Map(Map), + BookDialog.Map(Map), + ShopDialog.Map(Map), + QuestDialog.Map(Map), + ChestDialog.Map(Map), + LockerDialog.Map(Map), + BankAccountDialog.Map(Map), + SkillmasterDialog.Map(Map), + BardDialog.Map(Map), + MessageDialog.Map(Map), + TradeDialog.Map(Map), + MessageBox.Map(Map), + BoardDialog.Map(Map), + JukeboxDialog.Map(Map), + InnkeeperDialog.Map(Map), + LawDialog.Map(Map), + BarberDialog.Map(Map), + HelpDialog.Map(Map), + }.ToList(); + + static IXNADialog Map(object d) + { + return (IXNADialog)d; + } } } - } - IReadOnlyList> IActiveDialogRepository.ActiveDialogs => ActiveDialogs; + IReadOnlyList> IActiveDialogRepository.ActiveDialogs => ActiveDialogs; - IReadOnlyList> IActiveDialogProvider.ActiveDialogs => ActiveDialogs; + IReadOnlyList> IActiveDialogProvider.ActiveDialogs => ActiveDialogs; - public void Dispose() - { - foreach (var dlg in ActiveDialogs) - dlg.MatchSome(d => d.Dispose()); - - FriendIgnoreDialog = Option.None(); - SessionExpDialog = Option.None(); - QuestStatusDialog = Option.None(); - PaperdollDialog = Option.None(); - BookDialog = Option.None(); - ShopDialog = Option.None(); - QuestDialog = Option.None(); - ChestDialog = Option.None(); - LockerDialog = Option.None(); - BankAccountDialog = Option.None(); - SkillmasterDialog = Option.None(); - BardDialog = Option.None(); - MessageDialog = Option.None(); - TradeDialog = Option.None(); - MessageBox = Option.None(); - BoardDialog = Option.None(); - JukeboxDialog = Option.None(); - InnkeeperDialog = Option.None(); - LawDialog = Option.None(); - BarberDialog = Option.None(); - HelpDialog = Option.None(); + public void Dispose() + { + foreach (var dlg in ActiveDialogs) + dlg.MatchSome(d => d.Dispose()); + + FriendIgnoreDialog = Option.None(); + SessionExpDialog = Option.None(); + QuestStatusDialog = Option.None(); + PaperdollDialog = Option.None(); + BookDialog = Option.None(); + ShopDialog = Option.None(); + QuestDialog = Option.None(); + ChestDialog = Option.None(); + LockerDialog = Option.None(); + BankAccountDialog = Option.None(); + SkillmasterDialog = Option.None(); + BardDialog = Option.None(); + MessageDialog = Option.None(); + TradeDialog = Option.None(); + MessageBox = Option.None(); + BoardDialog = Option.None(); + JukeboxDialog = Option.None(); + InnkeeperDialog = Option.None(); + LawDialog = Option.None(); + BarberDialog = Option.None(); + HelpDialog = Option.None(); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BankAccountDialog.cs b/EndlessClient/Dialogs/BankAccountDialog.cs index 5771830f5..f6d9f22bc 100644 --- a/EndlessClient/Dialogs/BankAccountDialog.cs +++ b/EndlessClient/Dialogs/BankAccountDialog.cs @@ -16,234 +16,235 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public class BankAccountDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private readonly IBankActions _bankActions; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IItemTransferDialogFactory _itemTransferDialogFactory; - private readonly IBankDataProvider _bankDataProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly InventoryPanel _inventoryPanel; - - private int _cachedValue; - private Option _cachedUpgrades; - - public BankAccountDialog(INativeGraphicsManager nativeGraphicsManager, - IBankActions bankActions, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - IItemTransferDialogFactory itemTransferDialogFactory, - IHudControlProvider hudControlProvider, - IBankDataProvider bankDataProvider, - ICharacterInventoryProvider characterInventoryProvider, - IEIFFileProvider eifFileProvider) - : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.BankAccountDialog) + public class BankAccountDialog : ScrollingListDialog { - _bankActions = bankActions; - _localizedStringFinder = localizedStringFinder; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _itemTransferDialogFactory = itemTransferDialogFactory; - _bankDataProvider = bankDataProvider; - _characterInventoryProvider = characterInventoryProvider; - _eifFileProvider = eifFileProvider; - _inventoryPanel = hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); - - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.Cancel; - - _titleText.Text = "0"; - _titleText.TextAlign = LabelAlignment.MiddleRight; - _titleText.AutoSize = false; - - var currencyName = _eifFileProvider.EIFFile[1].Name; - - var depositItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_DEPOSIT), - SubText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TRANSFER)} {currencyName} {_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TO_ACCOUNT)}", - IconGraphic = dialogIconService.IconSheet, - IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankDeposit), - OffsetY = 55, - ShowIconBackGround = false, - }; - depositItem.LeftClick += Deposit; - depositItem.RightClick += Deposit; - - var withdrawItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_WITHDRAW), - SubText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TRANSFER)} {currencyName} {_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_FROM_ACCOUNT)}", - IconGraphic = dialogIconService.IconSheet, - IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankWithdraw), - OffsetY = 55, - ShowIconBackGround = false, - }; - withdrawItem.LeftClick += Withdraw; - withdrawItem.RightClick += Withdraw; - - var upgradeItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) + private readonly IBankActions _bankActions; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IItemTransferDialogFactory _itemTransferDialogFactory; + private readonly IBankDataProvider _bankDataProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly InventoryPanel _inventoryPanel; + + private int _cachedValue; + private Option _cachedUpgrades; + + public BankAccountDialog(INativeGraphicsManager nativeGraphicsManager, + IBankActions bankActions, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + IItemTransferDialogFactory itemTransferDialogFactory, + IHudControlProvider hudControlProvider, + IBankDataProvider bankDataProvider, + ICharacterInventoryProvider characterInventoryProvider, + IEIFFileProvider eifFileProvider) + : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.BankAccountDialog) { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_LOCKER_UPGRADE), - SubText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_MORE_SPACE), - IconGraphic = dialogIconService.IconSheet, - IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankLockerUpgrade), - OffsetY = 55, - ShowIconBackGround = false, - }; - upgradeItem.LeftClick += Upgrade; - upgradeItem.RightClick += Upgrade; - - AddItemToList(depositItem, sortList: false); - AddItemToList(withdrawItem, sortList: false); - AddItemToList(upgradeItem, sortList: false); - - DrawPosition += new Vector2(0, 50); - } + _bankActions = bankActions; + _localizedStringFinder = localizedStringFinder; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _itemTransferDialogFactory = itemTransferDialogFactory; + _bankDataProvider = bankDataProvider; + _characterInventoryProvider = characterInventoryProvider; + _eifFileProvider = eifFileProvider; + _inventoryPanel = hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); + + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.Cancel; + + _titleText.Text = "0"; + _titleText.TextAlign = LabelAlignment.MiddleRight; + _titleText.AutoSize = false; + + var currencyName = _eifFileProvider.EIFFile[1].Name; + + var depositItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_DEPOSIT), + SubText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TRANSFER)} {currencyName} {_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TO_ACCOUNT)}", + IconGraphic = dialogIconService.IconSheet, + IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankDeposit), + OffsetY = 55, + ShowIconBackGround = false, + }; + depositItem.LeftClick += Deposit; + depositItem.RightClick += Deposit; - protected override void OnUpdateControl(GameTime gameTime) - { - if (_bankDataProvider.AccountValue != _cachedValue) - { - _cachedValue = _bankDataProvider.AccountValue; - Title = $"{_bankDataProvider.AccountValue}"; - } + var withdrawItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_WITHDRAW), + SubText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_TRANSFER)} {currencyName} {_localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_FROM_ACCOUNT)}", + IconGraphic = dialogIconService.IconSheet, + IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankWithdraw), + OffsetY = 55, + ShowIconBackGround = false, + }; + withdrawItem.LeftClick += Withdraw; + withdrawItem.RightClick += Withdraw; - _cachedUpgrades.Match( - some: c => + var upgradeItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) { - _bankDataProvider.LockerUpgrades.MatchSome( - upgrades => - { - if (upgrades != c) - { - _cachedUpgrades = _bankDataProvider.LockerUpgrades; - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_LOCKER_SPACE_INCREASED); - } - }); - }, - none: () => _cachedUpgrades = _bankDataProvider.LockerUpgrades); + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_LOCKER_UPGRADE), + SubText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BANK_MORE_SPACE), + IconGraphic = dialogIconService.IconSheet, + IconGraphicSource = dialogIconService.GetDialogIconSource(DialogIcon.BankLockerUpgrade), + OffsetY = 55, + ShowIconBackGround = false, + }; + upgradeItem.LeftClick += Upgrade; + upgradeItem.RightClick += Upgrade; - base.OnUpdateControl(gameTime); - } + AddItemToList(depositItem, sortList: false); + AddItemToList(withdrawItem, sortList: false); + AddItemToList(upgradeItem, sortList: false); - private void Deposit(object sender, EventArgs e) - { - if (!_inventoryPanel.NoItemsDragging()) - return; + DrawPosition += new Vector2(0, 50); + } - _characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1) - .Match( - some: characterGold => - { - if (characterGold.Amount == 0) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); - dlg.ShowDialog(); + protected override void OnUpdateControl(GameTime gameTime) + { + if (_bankDataProvider.AccountValue != _cachedValue) + { + _cachedValue = _bankDataProvider.AccountValue; + Title = $"{_bankDataProvider.AccountValue}"; + } - // todo: show the dialog message as a warning in the status label - } - else if (characterGold.Amount == 1) - { - _bankActions.Deposit(1); - } - else if (characterGold.Amount > 1) - { - var dlg = _itemTransferDialogFactory.CreateItemTransferDialog(_eifFileProvider.EIFFile[1].Name, ItemTransferDialog.TransferType.BankTransfer, characterGold.Amount, EOResourceID.DIALOG_TRANSFER_DEPOSIT); - dlg.DialogClosing += (_, e) => + _cachedUpgrades.Match( + some: c => + { + _bankDataProvider.LockerUpgrades.MatchSome( + upgrades => { - if (e.Result == XNADialogResult.OK) - _bankActions.Deposit(dlg.SelectedAmount); - }; - dlg.ShowDialog(); - } + if (upgrades != c) + { + _cachedUpgrades = _bankDataProvider.LockerUpgrades; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_LOCKER_SPACE_INCREASED); + } + }); }, - none: () => - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); - dlg.ShowDialog(); + none: () => _cachedUpgrades = _bankDataProvider.LockerUpgrades); - // todo: show the dialog message as a warning in the status label - }); - } - - private void Withdraw(object sender, EventArgs e) - { - if (!_inventoryPanel.NoItemsDragging()) - return; - - if (_bankDataProvider.AccountValue == 0) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_WITHDRAW); - dlg.ShowDialog(); - - // todo: show the dialog message as a warning in the status label - } - else if (_bankDataProvider.AccountValue == 1) - { - _bankActions.Withdraw(1); - } - else if (_bankDataProvider.AccountValue > 1) - { - var dlg = _itemTransferDialogFactory.CreateItemTransferDialog(_eifFileProvider.EIFFile[1].Name, ItemTransferDialog.TransferType.BankTransfer, _bankDataProvider.AccountValue, EOResourceID.DIALOG_TRANSFER_WITHDRAW); - dlg.DialogClosing += (_, e) => - { - if (e.Result == XNADialogResult.OK) - _bankActions.Withdraw(dlg.SelectedAmount); - }; - dlg.ShowDialog(); + base.OnUpdateControl(gameTime); } - } - - private void Upgrade(object sender, EventArgs e) - { - if (!_inventoryPanel.NoItemsDragging()) - return; - _bankDataProvider.LockerUpgrades.MatchSome(lockerUpgrades => + private void Deposit(object sender, EventArgs e) { - if (lockerUpgrades == Constants.MaxLockerUpgrades) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_UPGRADE_IMPOSSIBLE); - dlg.ShowDialog(); + if (!_inventoryPanel.NoItemsDragging()) return; - } - - int requiredGold = (lockerUpgrades + 1) * 1000; _characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1) .Match( - some: charaterGold => + some: characterGold => { - if (charaterGold.Amount < requiredGold) + if (characterGold.Amount == 0) { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); dlg.ShowDialog(); + + // todo: show the dialog message as a warning in the status label } - else + else if (characterGold.Amount == 1) { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_UPGRADE_UNIT, $"{requiredGold} {_eifFileProvider.EIFFile[1].Name}?", EODialogButtons.OkCancel); + _bankActions.Deposit(1); + } + else if (characterGold.Amount > 1) + { + var dlg = _itemTransferDialogFactory.CreateItemTransferDialog(_eifFileProvider.EIFFile[1].Name, ItemTransferDialog.TransferType.BankTransfer, characterGold.Amount, EOResourceID.DIALOG_TRANSFER_DEPOSIT); dlg.DialogClosing += (_, e) => { if (e.Result == XNADialogResult.OK) - _bankActions.BuyStorageUpgrade(); + _bankActions.Deposit(dlg.SelectedAmount); }; dlg.ShowDialog(); } }, - () => + none: () => { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_DEPOSIT); dlg.ShowDialog(); + + // todo: show the dialog message as a warning in the status label }); - }); + } + + private void Withdraw(object sender, EventArgs e) + { + if (!_inventoryPanel.NoItemsDragging()) + return; + + if (_bankDataProvider.AccountValue == 0) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.BANK_ACCOUNT_UNABLE_TO_WITHDRAW); + dlg.ShowDialog(); + + // todo: show the dialog message as a warning in the status label + } + else if (_bankDataProvider.AccountValue == 1) + { + _bankActions.Withdraw(1); + } + else if (_bankDataProvider.AccountValue > 1) + { + var dlg = _itemTransferDialogFactory.CreateItemTransferDialog(_eifFileProvider.EIFFile[1].Name, ItemTransferDialog.TransferType.BankTransfer, _bankDataProvider.AccountValue, EOResourceID.DIALOG_TRANSFER_WITHDRAW); + dlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + _bankActions.Withdraw(dlg.SelectedAmount); + }; + dlg.ShowDialog(); + } + } + + private void Upgrade(object sender, EventArgs e) + { + if (!_inventoryPanel.NoItemsDragging()) + return; + + _bankDataProvider.LockerUpgrades.MatchSome(lockerUpgrades => + { + if (lockerUpgrades == Constants.MaxLockerUpgrades) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_UPGRADE_IMPOSSIBLE); + dlg.ShowDialog(); + return; + } + + int requiredGold = (lockerUpgrades + 1) * 1000; + + _characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1) + .Match( + some: charaterGold => + { + if (charaterGold.Amount < requiredGold) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); + dlg.ShowDialog(); + } + else + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.LOCKER_UPGRADE_UNIT, $"{requiredGold} {_eifFileProvider.EIFFile[1].Name}?", EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + _bankActions.BuyStorageUpgrade(); + }; + dlg.ShowDialog(); + } + }, + () => + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); + dlg.ShowDialog(); + }); + }); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BarberDialog.cs b/EndlessClient/Dialogs/BarberDialog.cs index b829e2078..f730de83f 100644 --- a/EndlessClient/Dialogs/BarberDialog.cs +++ b/EndlessClient/Dialogs/BarberDialog.cs @@ -13,184 +13,185 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public class BarberDialog : BaseEODialog +namespace EndlessClient.Dialogs { - private const int AdjustedWidth = 175; - private const int AdjustedHighlightXOffset = 3; - private readonly string[] _hairColorNames = { "brown", "green", "pink", "red", "blonde", "blue", "purple", "luna", "white", "black" }; - private readonly CreateCharacterControl _characterControl; - private readonly ICharacterRepository _characterRepository; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IBarberActions _barberActions; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ISfxPlayer _sfxPlayer; - - private CharacterRenderProperties RenderProperties => _characterControl.RenderProperties; - private ListDialogItem _changeHairItem, _changeHairColor, _changeBuyHairStyleOrColor; - - public BarberDialog(INativeGraphicsManager nativeGraphicsManager, - ICharacterRendererFactory rendererFactory, - IEODialogButtonService dialogButtonService, - ICharacterRepository characterLvRepository, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IBarberActions barberActions, - ICharacterInventoryProvider characterInventoryProvider, - IEOMessageBoxFactory messageBoxFactory, - IEIFFileProvider eifFileProvider, - ISfxPlayer sfxPlayer) - : base(nativeGraphicsManager, isInGame: true) + public class BarberDialog : BaseEODialog { - _characterRepository = characterLvRepository; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _barberActions = barberActions; - _characterInventoryProvider = characterInventoryProvider; - _messageBoxFactory = messageBoxFactory; - _eifFileProvider = eifFileProvider; - _sfxPlayer = sfxPlayer; - - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 56); - - var mainCharacterRenderProperties = _characterRepository.MainCharacter.RenderProperties; - _characterControl = new CreateCharacterControl(mainCharacterRenderProperties, rendererFactory) + private const int AdjustedWidth = 175; + private const int AdjustedHighlightXOffset = 3; + private readonly string[] _hairColorNames = { "brown", "green", "pink", "red", "blonde", "blue", "purple", "luna", "white", "black" }; + private readonly CreateCharacterControl _characterControl; + private readonly ICharacterRepository _characterRepository; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IBarberActions _barberActions; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ISfxPlayer _sfxPlayer; + + private CharacterRenderProperties RenderProperties => _characterControl.RenderProperties; + private ListDialogItem _changeHairItem, _changeHairColor, _changeBuyHairStyleOrColor; + + public BarberDialog(INativeGraphicsManager nativeGraphicsManager, + ICharacterRendererFactory rendererFactory, + IEODialogButtonService dialogButtonService, + ICharacterRepository characterLvRepository, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IBarberActions barberActions, + ICharacterInventoryProvider characterInventoryProvider, + IEOMessageBoxFactory messageBoxFactory, + IEIFFileProvider eifFileProvider, + ISfxPlayer sfxPlayer) + : base(nativeGraphicsManager, isInGame: true) { - DrawPosition = new Vector2(210, 19), - }; - - InitializeCharacterControl(); - InitializeDialogItems(dialogButtonService); - CenterInGameView(); - } - - private void InitializeCharacterControl() - { - _characterControl.SetParentControl(this); - } + _characterRepository = characterLvRepository; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _barberActions = barberActions; + _characterInventoryProvider = characterInventoryProvider; + _messageBoxFactory = messageBoxFactory; + _eifFileProvider = eifFileProvider; + _sfxPlayer = sfxPlayer; + + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 56); + + var mainCharacterRenderProperties = _characterRepository.MainCharacter.RenderProperties; + _characterControl = new CreateCharacterControl(mainCharacterRenderProperties, rendererFactory) + { + DrawPosition = new Vector2(210, 19), + }; - private void InitializeDialogItems(IEODialogButtonService dialogButtonService) - { - var cancel = CreateButton(dialogButtonService, new Vector2(215, 151), SmallButton.Cancel); - cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); + InitializeCharacterControl(); + InitializeDialogItems(dialogButtonService); + CenterInGameView(); + } - _changeHairItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + private void InitializeCharacterControl() { - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberHairModel), - ShowIconBackGround = false, - OffsetX = AdjustedHighlightXOffset, - }; - _changeHairItem.DrawArea = _changeHairItem.DrawArea.WithSize(AdjustedWidth, _changeHairItem.DrawArea.Size.Y); - _changeHairItem.LeftClick += ChangeHairStyle_Click; - - _changeHairColor = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberChangeHairColor), - ShowIconBackGround = false, - OffsetX = AdjustedHighlightXOffset, - }; - _changeHairColor.DrawArea = _changeHairColor.DrawArea.WithSize(AdjustedWidth, _changeHairColor.DrawArea.Size.Y); - _changeHairColor.LeftClick += ChangeHairColor_Click; - - _changeBuyHairStyleOrColor = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) + _characterControl.SetParentControl(this); + } + + private void InitializeDialogItems(IEODialogButtonService dialogButtonService) { - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberOk), - ShowIconBackGround = false, - OffsetX = AdjustedHighlightXOffset, - }; - _changeBuyHairStyleOrColor.DrawArea = _changeBuyHairStyleOrColor.DrawArea.WithSize(AdjustedWidth, _changeBuyHairStyleOrColor.DrawArea.Size.Y); - _changeBuyHairStyleOrColor.LeftClick += BuyHair_Click; - } + var cancel = CreateButton(dialogButtonService, new Vector2(215, 151), SmallButton.Cancel); + cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); - public override void Initialize() - { - base.Initialize(); - _characterControl.Initialize(); - UpdateListItems(_characterRepository.MainCharacter.RenderProperties); - } + _changeHairItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + { + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberHairModel), + ShowIconBackGround = false, + OffsetX = AdjustedHighlightXOffset, + }; + _changeHairItem.DrawArea = _changeHairItem.DrawArea.WithSize(AdjustedWidth, _changeHairItem.DrawArea.Size.Y); + _changeHairItem.LeftClick += ChangeHairStyle_Click; - private void UpdateListItems(CharacterRenderProperties currentProperties) - { - _changeHairItem.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_CHANGE_MODAL); - _changeHairItem.SubText = GetCurrentHairStyleText(currentProperties.HairStyle); + _changeHairColor = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberChangeHairColor), + ShowIconBackGround = false, + OffsetX = AdjustedHighlightXOffset, + }; + _changeHairColor.DrawArea = _changeHairColor.DrawArea.WithSize(AdjustedWidth, _changeHairColor.DrawArea.Size.Y); + _changeHairColor.LeftClick += ChangeHairColor_Click; - _changeHairColor.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_CHANGE_HAIR_COLOR); - _changeHairColor.SubText = GetCurrentHairColorText(currentProperties.HairColor); + _changeBuyHairStyleOrColor = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) + { + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.BarberOk), + ShowIconBackGround = false, + OffsetX = AdjustedHighlightXOffset, + }; + _changeBuyHairStyleOrColor.DrawArea = _changeBuyHairStyleOrColor.DrawArea.WithSize(AdjustedWidth, _changeBuyHairStyleOrColor.DrawArea.Size.Y); + _changeBuyHairStyleOrColor.LeftClick += BuyHair_Click; + } - _changeBuyHairStyleOrColor.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_BUY_HAIRSTYLE); - _changeBuyHairStyleOrColor.SubText = GetCostText(); - } + public override void Initialize() + { + base.Initialize(); + _characterControl.Initialize(); + UpdateListItems(_characterRepository.MainCharacter.RenderProperties); + } - private string GetCurrentHairStyleText(int hairStyle) => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {hairStyle}"; - private string GetCurrentHairColorText(int hairColor) => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {_hairColorNames[hairColor % _hairColorNames.Length]}"; - private string GetCostText() => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {CalculateCost()} gold"; + private void UpdateListItems(CharacterRenderProperties currentProperties) + { + _changeHairItem.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_CHANGE_MODAL); + _changeHairItem.SubText = GetCurrentHairStyleText(currentProperties.HairStyle); - private int CalculateCost() - { - var level = (int)_characterRepository.MainCharacter.Stats[CharacterStat.Level]; - return 200 + Math.Max(level - 1, 0) * 200; - } + _changeHairColor.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_CHANGE_HAIR_COLOR); + _changeHairColor.SubText = GetCurrentHairColorText(currentProperties.HairColor); - private void ChangeHairStyle_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) - { - _characterControl.NextHairStyle(); - _changeHairItem.SubText = GetCurrentHairStyleText(_characterControl.RenderProperties.HairStyle); - } + _changeBuyHairStyleOrColor.PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_BUY_HAIRSTYLE); + _changeBuyHairStyleOrColor.SubText = GetCostText(); + } - private void ChangeHairColor_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) - { - _characterControl.NextHairColor(); - _changeHairColor.SubText = GetCurrentHairColorText(_characterControl.RenderProperties.HairColor); - } + private string GetCurrentHairStyleText(int hairStyle) => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {hairStyle}"; + private string GetCurrentHairColorText(int hairColor) => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {_hairColorNames[hairColor % _hairColorNames.Length]}"; + private string GetCostText() => $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT)}: {CalculateCost()} gold"; - private void BuyHair_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) - { - int hairStyle = _characterControl.RenderProperties.HairStyle; - int hairColor = _characterControl.RenderProperties.HairColor; + private int CalculateCost() + { + var level = (int)_characterRepository.MainCharacter.Stats[CharacterStat.Level]; + return 200 + Math.Max(level - 1, 0) * 200; + } + + private void ChangeHairStyle_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) + { + _characterControl.NextHairStyle(); + _changeHairItem.SubText = GetCurrentHairStyleText(_characterControl.RenderProperties.HairStyle); + } - int totalCost = CalculateCost(); - int currentGold = _characterInventoryProvider.ItemInventory.SingleOrNone(i => i.ItemID == 1) - .Map(i => i.Amount) - .ValueOr(0); + private void ChangeHairColor_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) + { + _characterControl.NextHairColor(); + _changeHairColor.SubText = GetCurrentHairColorText(_characterControl.RenderProperties.HairColor); + } - if (currentGold >= totalCost) + private void BuyHair_Click(object sender, MonoGame.Extended.Input.InputListeners.MouseEventArgs e) { - var message = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_DO_YOU_WANT_TO_BUY_A_NEW_HAIRSTYLE)}, {totalCost} {_eifFileProvider.EIFFile[1].Name}"; - var title = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_BUY_HAIRSTYLE); - var msgBox = _messageBoxFactory.CreateMessageBox(message, title, EODialogButtons.OkCancel); + int hairStyle = _characterControl.RenderProperties.HairStyle; + int hairColor = _characterControl.RenderProperties.HairColor; - msgBox.DialogClosing += (_, e) => + int totalCost = CalculateCost(); + int currentGold = _characterInventoryProvider.ItemInventory.SingleOrNone(i => i.ItemID == 1) + .Map(i => i.Amount) + .ValueOr(0); + + if (currentGold >= totalCost) { - if (e.Result == XNADialogResult.OK) - { - _barberActions.Purchase(hairStyle, hairColor); - _sfxPlayer.PlaySfx(SoundEffectID.BuySell); - } - }; + var message = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_DO_YOU_WANT_TO_BUY_A_NEW_HAIRSTYLE)}, {totalCost} {_eifFileProvider.EIFFile[1].Name}"; + var title = _localizedStringFinder.GetString(EOResourceID.DIALOG_BARBER_BUY_HAIRSTYLE); + var msgBox = _messageBoxFactory.CreateMessageBox(message, title, EODialogButtons.OkCancel); - msgBox.ShowDialog(); + msgBox.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + { + _barberActions.Purchase(hairStyle, hairColor); + _sfxPlayer.PlaySfx(SoundEffectID.BuySell); + } + }; + + msgBox.ShowDialog(); + } + else + { + var msgBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); + msgBox.ShowDialog(); + } } - else + + private XNAButton CreateButton(IEODialogButtonService dialogButtonService, Vector2 position, SmallButton buttonType) { - var msgBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, $" {_eifFileProvider.EIFFile[1].Name}"); - msgBox.ShowDialog(); + var button = new XNAButton(dialogButtonService.SmallButtonSheet, position, + dialogButtonService.GetSmallDialogButtonOutSource(buttonType), + dialogButtonService.GetSmallDialogButtonOverSource(buttonType)); + button.Initialize(); + button.SetParentControl(this); + return button; } } - - private XNAButton CreateButton(IEODialogButtonService dialogButtonService, Vector2 position, SmallButton buttonType) - { - var button = new XNAButton(dialogButtonService.SmallButtonSheet, position, - dialogButtonService.GetSmallDialogButtonOutSource(buttonType), - dialogButtonService.GetSmallDialogButtonOverSource(buttonType)); - button.Initialize(); - button.SetParentControl(this); - return button; - } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BardDialog.cs b/EndlessClient/Dialogs/BardDialog.cs index 3382b6446..b2ba3498d 100644 --- a/EndlessClient/Dialogs/BardDialog.cs +++ b/EndlessClient/Dialogs/BardDialog.cs @@ -9,102 +9,103 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public class BardDialog : BaseEODialog +namespace EndlessClient.Dialogs { - private readonly IBardController _bardController; - private readonly Texture2D _noteHighlight; - private readonly Rectangle _noteRectangleArea; - - private Vector2 _highlightDrawPosition; - private Option _highlightSource; - - private ulong _currentTick; - - public BardDialog(INativeGraphicsManager nativeGraphicsManager, - IBardController bardController, - IEODialogButtonService dialogButtonService) - : base(nativeGraphicsManager, isInGame: true) + public class BardDialog : BaseEODialog { - _bardController = bardController; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 65); - _noteHighlight = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 66); - _noteRectangleArea = new Rectangle(15, 15, 240, 60); + private readonly IBardController _bardController; + private readonly Texture2D _noteHighlight; + private readonly Rectangle _noteRectangleArea; - var cancel = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(92, 83), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - cancel.Initialize(); - cancel.SetParentControl(this); - cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); + private Vector2 _highlightDrawPosition; + private Option _highlightSource; - CenterInGameView(); + private ulong _currentTick; - OnMouseOver += HandleMouseOver; - } + public BardDialog(INativeGraphicsManager nativeGraphicsManager, + IBardController bardController, + IEODialogButtonService dialogButtonService) + : base(nativeGraphicsManager, isInGame: true) + { + _bardController = bardController; + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 65); + _noteHighlight = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 66); + _noteRectangleArea = new Rectangle(15, 15, 240, 60); - protected override void OnUpdateControl(GameTime gameTime) - { - _currentTick++; + var cancel = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(92, 83), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + cancel.Initialize(); + cancel.SetParentControl(this); + cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); - base.OnUpdateControl(gameTime); - } + CenterInGameView(); - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + OnMouseOver += HandleMouseOver; + } - _highlightSource.MatchSome(src => + protected override void OnUpdateControl(GameTime gameTime) { - _spriteBatch.Begin(); - _spriteBatch.Draw(_noteHighlight, _highlightDrawPosition, src, Color.White); - _spriteBatch.End(); - }); - } + _currentTick++; - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (eventArgs.Button == MouseButton.Left && _currentTick > 8) + base.OnUpdateControl(gameTime); + } + + protected override void OnDrawControl(GameTime gameTime) { - _highlightSource.MatchSome(highlightSource => + base.OnDrawControl(gameTime); + + _highlightSource.MatchSome(src => { - var highlightDrawPosition = highlightSource.Location.ToVector2(); - var noteIndex = (int)Math.Floor(highlightDrawPosition.X / 20 + (12 * (highlightDrawPosition.Y / 20))); - _bardController.PlayInstrumentNote(noteIndex); - _currentTick = 0; + _spriteBatch.Begin(); + _spriteBatch.Draw(_noteHighlight, _highlightDrawPosition, src, Color.White); + _spriteBatch.End(); }); } - return true; - } - - private void HandleMouseOver(object sender, MouseStateExtended eventArgs) - { - var relativeMousePosition = eventArgs.Position - DrawAreaWithParentOffset.Location; - - if (_noteRectangleArea.Contains(relativeMousePosition)) + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) { - var relativePosition = relativeMousePosition - _noteRectangleArea.Location; - var highlightDrawPosition = new Vector2( - relativePosition.X - (relativePosition.X % 20), - relativePosition.Y - (relativePosition.Y % 20)); - _highlightDrawPosition = highlightDrawPosition + DrawPositionWithParentOffset + _noteRectangleArea.Location.ToVector2(); - _highlightSource = Option.Some(new Rectangle(highlightDrawPosition.ToPoint(), new Point(20, 20))); + if (eventArgs.Button == MouseButton.Left && _currentTick > 8) + { + _highlightSource.MatchSome(highlightSource => + { + var highlightDrawPosition = highlightSource.Location.ToVector2(); + var noteIndex = (int)Math.Floor(highlightDrawPosition.X / 20 + (12 * (highlightDrawPosition.Y / 20))); + _bardController.PlayInstrumentNote(noteIndex); + _currentTick = 0; + }); + } + + return true; } - else + + private void HandleMouseOver(object sender, MouseStateExtended eventArgs) { - _highlightSource = Option.None(); + var relativeMousePosition = eventArgs.Position - DrawAreaWithParentOffset.Location; + + if (_noteRectangleArea.Contains(relativeMousePosition)) + { + var relativePosition = relativeMousePosition - _noteRectangleArea.Location; + var highlightDrawPosition = new Vector2( + relativePosition.X - (relativePosition.X % 20), + relativePosition.Y - (relativePosition.Y % 20)); + _highlightDrawPosition = highlightDrawPosition + DrawPositionWithParentOffset + _noteRectangleArea.Location.ToVector2(); + _highlightSource = Option.Some(new Rectangle(highlightDrawPosition.ToPoint(), new Point(20, 20))); + } + else + { + _highlightSource = Option.None(); + } } - } - protected override void Dispose(bool disposing) - { - if (disposing) + protected override void Dispose(bool disposing) { - OnMouseOver -= HandleMouseOver; - } + if (disposing) + { + OnMouseOver -= HandleMouseOver; + } - base.Dispose(disposing); + base.Dispose(disposing); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BaseEODialog.cs b/EndlessClient/Dialogs/BaseEODialog.cs index 50fa1fb71..52d39c3d8 100644 --- a/EndlessClient/Dialogs/BaseEODialog.cs +++ b/EndlessClient/Dialogs/BaseEODialog.cs @@ -4,37 +4,38 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public abstract class BaseEODialog : XNADialog +namespace EndlessClient.Dialogs { - private readonly Func _isInGame; - - public INativeGraphicsManager GraphicsManager { get; } - - protected BaseEODialog(INativeGraphicsManager graphicsManager, - IGameStateProvider gameStateProvider) - { - GraphicsManager = graphicsManager; - _isInGame = () => gameStateProvider.CurrentState == GameStates.PlayingTheGame; - } - - protected BaseEODialog(INativeGraphicsManager graphicsManager, bool isInGame) - { - GraphicsManager = graphicsManager; - _isInGame = () => isInGame; - } - - public override void CenterInGameView() - { - base.CenterInGameView(); - - if (_isInGame() && !Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, (330 - DrawArea.Height) / 2f); - } - - public void Close() + public abstract class BaseEODialog : XNADialog { - Close(XNADialogResult.NO_BUTTON_PRESSED); + private readonly Func _isInGame; + + public INativeGraphicsManager GraphicsManager { get; } + + protected BaseEODialog(INativeGraphicsManager graphicsManager, + IGameStateProvider gameStateProvider) + { + GraphicsManager = graphicsManager; + _isInGame = () => gameStateProvider.CurrentState == GameStates.PlayingTheGame; + } + + protected BaseEODialog(INativeGraphicsManager graphicsManager, bool isInGame) + { + GraphicsManager = graphicsManager; + _isInGame = () => isInGame; + } + + public override void CenterInGameView() + { + base.CenterInGameView(); + + if (_isInGame() && !Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, (330 - DrawArea.Height) / 2f); + } + + public void Close() + { + Close(XNADialogResult.NO_BUTTON_PRESSED); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BoardDialog.cs b/EndlessClient/Dialogs/BoardDialog.cs index f2a1f0c98..e648db10b 100644 --- a/EndlessClient/Dialogs/BoardDialog.cs +++ b/EndlessClient/Dialogs/BoardDialog.cs @@ -19,296 +19,297 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs; - -public class BoardDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private enum BoardDialogState + public class BoardDialog : ScrollingListDialog { - ViewList, - ViewPost, - CreatePost, - } - - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IBoardActions _boardActions; - private readonly IBoardRepository _boardRepository; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IHudControlProvider _hudControlProvider; - - private readonly XNATextBox _subject, _message; - - private BoardDialogState _state; - private HashSet _cachedPostInfo; - - public BoardDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IEOMessageBoxFactory eoMessageBoxFactory, - IBoardActions boardActions, - IBoardRepository boardRepository, - IPlayerInfoProvider playerInfoProvider, - ICharacterProvider characterProvider, - IContentProvider contentProvider, - IHudControlProvider hudControlProvider) - : base(nativeGraphicsManager, dialogButtonService, DialogType.Board) - { - _localizedStringFinder = localizedStringFinder; - _eoMessageBoxFactory = eoMessageBoxFactory; - _boardActions = boardActions; - _boardRepository = boardRepository; - _playerInfoProvider = playerInfoProvider; - _characterProvider = characterProvider; - _hudControlProvider = hudControlProvider; - ListItemType = ListDialogItem.ListItemStyle.Small; - Title = _localizedStringFinder.GetString(EOResourceID.BOARD_TOWN_BOARD); - _state = BoardDialogState.ViewList; - _cachedPostInfo = new HashSet(); - - _subject = new XNATextBox(new Rectangle(150, 44, 315, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) + private enum BoardDialogState { - TextAlignment = LabelAlignment.MiddleLeft, - TextColor = ColorConstants.LightGrayText, - Visible = false, - MaxWidth = 310 - }; - _subject.SetScrollWheelHandler(_scrollBar); - _subject.SetParentControl(this); - - _message = new XNATextBox(new Rectangle(18, 80, 430, 168), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) + ViewList, + ViewPost, + CreatePost, + } + + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IBoardActions _boardActions; + private readonly IBoardRepository _boardRepository; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IHudControlProvider _hudControlProvider; + + private readonly XNATextBox _subject, _message; + + private BoardDialogState _state; + private HashSet _cachedPostInfo; + + public BoardDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IEOMessageBoxFactory eoMessageBoxFactory, + IBoardActions boardActions, + IBoardRepository boardRepository, + IPlayerInfoProvider playerInfoProvider, + ICharacterProvider characterProvider, + IContentProvider contentProvider, + IHudControlProvider hudControlProvider) + : base(nativeGraphicsManager, dialogButtonService, DialogType.Board) { - TextAlignment = LabelAlignment.TopLeft, - TextColor = ColorConstants.LightGrayText, - Visible = false, - MaxWidth = 412, - - Multiline = true, - ScrollHandler = _scrollBar, - RowSpacing = 16, - }; - _message.SetScrollWheelHandler(_scrollBar); - _message.SetParentControl(this); - - _add.OnClick += AddButton_Click; - _delete.OnClick += DeleteButton_Click; - } + _localizedStringFinder = localizedStringFinder; + _eoMessageBoxFactory = eoMessageBoxFactory; + _boardActions = boardActions; + _boardRepository = boardRepository; + _playerInfoProvider = playerInfoProvider; + _characterProvider = characterProvider; + _hudControlProvider = hudControlProvider; + ListItemType = ListDialogItem.ListItemStyle.Small; + Title = _localizedStringFinder.GetString(EOResourceID.BOARD_TOWN_BOARD); + _state = BoardDialogState.ViewList; + _cachedPostInfo = new HashSet(); + + _subject = new XNATextBox(new Rectangle(150, 44, 315, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) + { + TextAlignment = LabelAlignment.MiddleLeft, + TextColor = ColorConstants.LightGrayText, + Visible = false, + MaxWidth = 310 + }; + _subject.SetScrollWheelHandler(_scrollBar); + _subject.SetParentControl(this); + + _message = new XNATextBox(new Rectangle(18, 80, 430, 168), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) + { + TextAlignment = LabelAlignment.TopLeft, + TextColor = ColorConstants.LightGrayText, + Visible = false, + MaxWidth = 412, + + Multiline = true, + ScrollHandler = _scrollBar, + RowSpacing = 16, + }; + _message.SetScrollWheelHandler(_scrollBar); + _message.SetParentControl(this); + + _add.OnClick += AddButton_Click; + _delete.OnClick += DeleteButton_Click; + } - public override void Initialize() - { - _subject.Initialize(); - _message.Initialize(); + public override void Initialize() + { + _subject.Initialize(); + _message.Initialize(); - base.Initialize(); - } + base.Initialize(); + } - protected override void OnUpdateControl(GameTime gameTime) - { - switch (_state) + protected override void OnUpdateControl(GameTime gameTime) { - case BoardDialogState.ViewList: - if (!_cachedPostInfo.SetEquals(_boardRepository.Posts)) - { - ClearItemList(); + switch (_state) + { + case BoardDialogState.ViewList: + if (!_cachedPostInfo.SetEquals(_boardRepository.Posts)) + { + ClearItemList(); - _cachedPostInfo = new HashSet(_boardRepository.Posts); + _cachedPostInfo = new HashSet(_boardRepository.Posts); - var index = 0; - foreach (var post in _cachedPostInfo) - { - var childItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) + var index = 0; + foreach (var post in _cachedPostInfo) { - PrimaryText = char.ToUpper(post.Author[0]) + post.Author[1..], - SubText = post.Subject, - Data = post.PostId, - Visible = true, - UnderlineLinks = false, - ShowSubtext = true, - OffsetX = 2, - OffsetY = 48, - }; - - childItem.DrawArea = new Rectangle(childItem.DrawArea.Location, new Point(427, 16)); - childItem.SetPrimaryClickAction(ChildItem_Click); - childItem.SetScrollWheelHandler(this); - - AddItemToList(childItem, sortList: false); + var childItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) + { + PrimaryText = char.ToUpper(post.Author[0]) + post.Author[1..], + SubText = post.Subject, + Data = post.PostId, + Visible = true, + UnderlineLinks = false, + ShowSubtext = true, + OffsetX = 2, + OffsetY = 48, + }; + + childItem.DrawArea = new Rectangle(childItem.DrawArea.Location, new Point(427, 16)); + childItem.SetPrimaryClickAction(ChildItem_Click); + childItem.SetScrollWheelHandler(this); + + AddItemToList(childItem, sortList: false); + } + + _scrollBar.ScrollToTop(); } - _scrollBar.ScrollToTop(); - } + break; + case BoardDialogState.ViewPost: + if (_boardRepository.ActivePostMessage.Map(msg => msg != _message.Text).ValueOr(false)) + { + _boardRepository.ActivePostMessage.MatchSome(msg => _message.Text = msg); + _scrollBar.ScrollToTop(); + } + break; + } - break; - case BoardDialogState.ViewPost: - if (_boardRepository.ActivePostMessage.Map(msg => msg != _message.Text).ValueOr(false)) - { - _boardRepository.ActivePostMessage.MatchSome(msg => _message.Text = msg); - _scrollBar.ScrollToTop(); - } - break; + base.OnUpdateControl(gameTime); } - base.OnUpdateControl(gameTime); - } - - private void SetState(BoardDialogState state, int postId = -1) - { - // todo: - // 1. backspace on scrolled newline is broken - // 2. need 10 rows per message for parity (increase space between rows) - - if (state == _state) - return; - - _state = state; + private void SetState(BoardDialogState state, int postId = -1) + { + // todo: + // 1. backspace on scrolled newline is broken + // 2. need 10 rows per message for parity (increase space between rows) - _titleText.DrawArea = _state == BoardDialogState.ViewList - ? GetTitleDrawArea(DialogType) - : GetTitleDrawArea(DialogType).WithPosition(new Vector2(150, _titleText.DrawArea.Y)); + if (state == _state) + return; - BackgroundTextureSource = _state == BoardDialogState.ViewList - ? GetBackgroundSourceRectangle(BackgroundTexture, DialogType) - : GetBackgroundSourceRectangle(BackgroundTexture, DialogType).Value.WithPosition(new Vector2(0, BackgroundTexture.Height / 2)); + _state = state; - _scrollBar.LinesToRender = _state == BoardDialogState.ViewList - ? 12 - : 10; + _titleText.DrawArea = _state == BoardDialogState.ViewList + ? GetTitleDrawArea(DialogType) + : GetTitleDrawArea(DialogType).WithPosition(new Vector2(150, _titleText.DrawArea.Y)); - switch (_state) - { - case BoardDialogState.ViewList: - _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Selected = true; + BackgroundTextureSource = _state == BoardDialogState.ViewList + ? GetBackgroundSourceRectangle(BackgroundTexture, DialogType) + : GetBackgroundSourceRectangle(BackgroundTexture, DialogType).Value.WithPosition(new Vector2(0, BackgroundTexture.Height / 2)); - Buttons = ScrollingListDialogButtons.AddCancel; - Title = _localizedStringFinder.GetString(EOResourceID.BOARD_TOWN_BOARD); - _subject.Visible = _message.Visible = false; - _subject.Selected = _message.Selected = false; + _scrollBar.LinesToRender = _state == BoardDialogState.ViewList + ? 12 + : 10; - _scrollBar.DrawArea = new Rectangle( - _scrollBar.DrawArea.X, 44, - _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType)); + switch (_state) + { + case BoardDialogState.ViewList: + _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Selected = true; - break; + Buttons = ScrollingListDialogButtons.AddCancel; + Title = _localizedStringFinder.GetString(EOResourceID.BOARD_TOWN_BOARD); + _subject.Visible = _message.Visible = false; + _subject.Selected = _message.Selected = false; - case BoardDialogState.CreatePost: - Buttons = ScrollingListDialogButtons.OkCancel; - Title = _localizedStringFinder.GetString(EOResourceID.BOARD_POSTING_NEW_MESSAGE); + _scrollBar.DrawArea = new Rectangle( + _scrollBar.DrawArea.X, 44, + _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType)); - _subject.Text = _message.Text = string.Empty; - _subject.Visible = _message.Visible = true; - _subject.Enabled = _message.Enabled = true; + break; - _subject.TabOrder = 0; - _message.TabOrder = 1; + case BoardDialogState.CreatePost: + Buttons = ScrollingListDialogButtons.OkCancel; + Title = _localizedStringFinder.GetString(EOResourceID.BOARD_POSTING_NEW_MESSAGE); - _subject.Selected = true; + _subject.Text = _message.Text = string.Empty; + _subject.Visible = _message.Visible = true; + _subject.Enabled = _message.Enabled = true; - _scrollBar.DrawArea = new Rectangle( - _scrollBar.DrawArea.X, 74, - _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType) - 30); + _subject.TabOrder = 0; + _message.TabOrder = 1; - ClearItemList(); - _cachedPostInfo.Clear(); - break; + _subject.Selected = true; - case BoardDialogState.ViewPost: - var author = _boardRepository.ActivePost.Map(x => x.Author).ValueOr(string.Empty); - var matchesAuthor = author.IndexOf(_characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase) >= 0; - if (_playerInfoProvider.PlayerHasAdminCharacter || matchesAuthor) - Buttons = ScrollingListDialogButtons.DeleteCancel; - else - Buttons = ScrollingListDialogButtons.OffsetCancel; + _scrollBar.DrawArea = new Rectangle( + _scrollBar.DrawArea.X, 74, + _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType) - 30); - _boardRepository.Posts.SingleOrNone(x => x.PostId == postId) - .MatchSome(post => - { - Title = post.Author; - _subject.Text = post.Subject; - }); + ClearItemList(); + _cachedPostInfo.Clear(); + break; + + case BoardDialogState.ViewPost: + var author = _boardRepository.ActivePost.Map(x => x.Author).ValueOr(string.Empty); + var matchesAuthor = author.IndexOf(_characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase) >= 0; + if (_playerInfoProvider.PlayerHasAdminCharacter || matchesAuthor) + Buttons = ScrollingListDialogButtons.DeleteCancel; + else + Buttons = ScrollingListDialogButtons.OffsetCancel; + + _boardRepository.Posts.SingleOrNone(x => x.PostId == postId) + .MatchSome(post => + { + Title = post.Author; + _subject.Text = post.Subject; + }); - _subject.Visible = true; - _message.Text = _localizedStringFinder.GetString(EOResourceID.BOARD_LOADING_MESSAGE); - _message.Visible = true; + _subject.Visible = true; + _message.Text = _localizedStringFinder.GetString(EOResourceID.BOARD_LOADING_MESSAGE); + _message.Visible = true; - _subject.Enabled = _message.Enabled = false; + _subject.Enabled = _message.Enabled = false; - _scrollBar.DrawArea = new Rectangle( - _scrollBar.DrawArea.X, 74, - _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType) - 30); + _scrollBar.DrawArea = new Rectangle( + _scrollBar.DrawArea.X, 74, + _scrollBar.DrawArea.Width, GetScrollBarHeight(DialogType) - 30); - ClearItemList(); - _cachedPostInfo.Clear(); - break; + ClearItemList(); + _cachedPostInfo.Clear(); + break; + } } - } - private void AddButton_Click(object sender, EventArgs e) - { - var numPostsByThisPlayer = _boardRepository.Posts.Count(x => string.Equals(x.Author, _characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase)); - if (numPostsByThisPlayer > 2) + private void AddButton_Click(object sender, EventArgs e) { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_TOO_MANY_MESSAGES); - dlg.ShowDialog(); - } - else - { - SetState(BoardDialogState.CreatePost); + var numPostsByThisPlayer = _boardRepository.Posts.Count(x => string.Equals(x.Author, _characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase)); + if (numPostsByThisPlayer > 2) + { + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_TOO_MANY_MESSAGES); + dlg.ShowDialog(); + } + else + { + SetState(BoardDialogState.CreatePost); + } } - } - - private void DeleteButton_Click(object sender, MouseEventArgs e) - { - _boardRepository.ActivePost.MatchSome(x => _boardActions.DeletePost(x.PostId)); - SetState(BoardDialogState.ViewList); - } - protected override void CloseButton_Click(object sender, MouseEventArgs e) - { - if (sender == _cancel && _state == BoardDialogState.ViewList) + private void DeleteButton_Click(object sender, MouseEventArgs e) { - Close(XNADialogResult.Cancel); + _boardRepository.ActivePost.MatchSome(x => _boardActions.DeletePost(x.PostId)); + SetState(BoardDialogState.ViewList); } - else + + protected override void CloseButton_Click(object sender, MouseEventArgs e) { - if (sender == _ok && _state == BoardDialogState.CreatePost) + if (sender == _cancel && _state == BoardDialogState.ViewList) { - if (string.IsNullOrEmpty(_message.Text)) - { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_NO_MESSAGE); - dlg.ShowDialog(); - return; - } - else if (string.IsNullOrEmpty(_subject.Text)) + Close(XNADialogResult.Cancel); + } + else + { + if (sender == _ok && _state == BoardDialogState.CreatePost) { - var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_NO_SUBJECT); - dlg.ShowDialog(); - return; - } + if (string.IsNullOrEmpty(_message.Text)) + { + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_NO_MESSAGE); + dlg.ShowDialog(); + return; + } + else if (string.IsNullOrEmpty(_subject.Text)) + { + var dlg = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.BOARD_ERROR_NO_SUBJECT); + dlg.ShowDialog(); + return; + } - _boardActions.AddPost(_subject.Text, _message.Text); - } + _boardActions.AddPost(_subject.Text, _message.Text); + } - _boardRepository.ActivePost = Option.None(); + _boardRepository.ActivePost = Option.None(); - SetState(BoardDialogState.ViewList); + SetState(BoardDialogState.ViewList); + } } - } - private void ChildItem_Click(object sender, MouseEventArgs e) - { - var postId = sender is ListDialogItem itemSender - ? (int)itemSender.Data - : sender is IXNAHyperLink linkSender - ? (int)((ListDialogItem)linkSender.ImmediateParent).Data - : -1; - - if (postId >= 0) + private void ChildItem_Click(object sender, MouseEventArgs e) { - _boardRepository.ActivePost = _boardRepository.Posts.SingleOrNone(x => x.PostId == postId); + var postId = sender is ListDialogItem itemSender + ? (int)itemSender.Data + : sender is IXNAHyperLink linkSender + ? (int)((ListDialogItem)linkSender.ImmediateParent).Data + : -1; + + if (postId >= 0) + { + _boardRepository.ActivePost = _boardRepository.Posts.SingleOrNone(x => x.PostId == postId); - SetState(BoardDialogState.ViewPost, postId); - _boardActions.ViewPost(postId); + SetState(BoardDialogState.ViewPost, postId); + _boardActions.ViewPost(postId); + } } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/BookDialog.cs b/EndlessClient/Dialogs/BookDialog.cs index cef4932c7..fef42d67f 100644 --- a/EndlessClient/Dialogs/BookDialog.cs +++ b/EndlessClient/Dialogs/BookDialog.cs @@ -10,120 +10,121 @@ using XNAControls; using static EndlessClient.Dialogs.QuestStatusListDialogItem; -namespace EndlessClient.Dialogs; - -public class BookDialog : PlayerInfoDialog +namespace EndlessClient.Dialogs { - private readonly IPaperdollProvider _paperdollProvider; - - private readonly List _childItems; - private ScrollBar _scrollBar; - - private int _lastScrollOffset; - - public BookDialog(INativeGraphicsManager graphicsManager, - IEODialogButtonService eoDialogButtonService, - IPubFileProvider pubFileProvider, - IPaperdollProvider paperdollProvider, - Character character, - bool isMainCharacter) - : base(graphicsManager, eoDialogButtonService, pubFileProvider, paperdollProvider, character, isMainCharacter) + public class BookDialog : PlayerInfoDialog { - _paperdollProvider = paperdollProvider; + private readonly IPaperdollProvider _paperdollProvider; + + private readonly List _childItems; + private ScrollBar _scrollBar; - _childItems = new List(); + private int _lastScrollOffset; - var backgroundTexture = graphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); - _scrollBar = new ScrollBar(new Vector2(188, 34), backgroundTexture, new Rectangle(303, 2, 20, 237), ScrollBarColors.DarkOnDark, graphicsManager) + public BookDialog(INativeGraphicsManager graphicsManager, + IEODialogButtonService eoDialogButtonService, + IPubFileProvider pubFileProvider, + IPaperdollProvider paperdollProvider, + Character character, + bool isMainCharacter) + : base(graphicsManager, eoDialogButtonService, pubFileProvider, paperdollProvider, character, isMainCharacter) { - LinesToRender = 14 - }; - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); + _paperdollProvider = paperdollProvider; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 69); + _childItems = new List(); - CenterInGameView(); + var backgroundTexture = graphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); + _scrollBar = new ScrollBar(new Vector2(188, 34), backgroundTexture, new Rectangle(303, 2, 20, 237), ScrollBarColors.DarkOnDark, graphicsManager) + { + LinesToRender = 14 + }; + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); - if (!Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, 15); - } + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 69); - public override void Initialize() - { - _scrollBar.Initialize(); + CenterInGameView(); - base.Initialize(); - } + if (!Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, 15); + } - protected override void OnUnconditionalUpdateControl(GameTime gameTime) - { - if (_childItems.Count > _scrollBar.LinesToRender && _lastScrollOffset != _scrollBar.ScrollOffset) + public override void Initialize() { - _lastScrollOffset = _scrollBar.ScrollOffset; + _scrollBar.Initialize(); - for (int i = 0; i < _childItems.Count; i++) - { - _childItems[i].DrawPosition = new Vector2(_childItems[i].DrawPosition.X, 42 + (i - _lastScrollOffset) * 16); - _childItems[i].Visible = (i - _lastScrollOffset) >= 0 && (i - _lastScrollOffset) < _scrollBar.LinesToRender; - } + base.Initialize(); } - base.OnUnconditionalUpdateControl(gameTime); - } - - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + protected override void OnUnconditionalUpdateControl(GameTime gameTime) + { + if (_childItems.Count > _scrollBar.LinesToRender && _lastScrollOffset != _scrollBar.ScrollOffset) + { + _lastScrollOffset = _scrollBar.ScrollOffset; - var iconTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); + for (int i = 0; i < _childItems.Count; i++) + { + _childItems[i].DrawPosition = new Vector2(_childItems[i].DrawPosition.X, 42 + (i - _lastScrollOffset) * 16); + _childItems[i].Visible = (i - _lastScrollOffset) >= 0 && (i - _lastScrollOffset) < _scrollBar.LinesToRender; + } + } - _spriteBatch.Begin(); + base.OnUnconditionalUpdateControl(gameTime); + } - for (int i = 0; i < Math.Min(_childItems.Count, _scrollBar.LinesToRender); i++) + protected override void OnDrawControl(GameTime gameTime) { - _spriteBatch.Draw(iconTexture, DrawPositionWithParentOffset + new Vector2(26, 41 + i * 16), GetIconSourceRectangle(QuestStatusIcon.None2), Color.White); - } + base.OnDrawControl(gameTime); - _spriteBatch.End(); - } + var iconTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); - protected override void UpdateDisplayedData(PaperdollData paperdollData) - { - base.UpdateDisplayedData(paperdollData); + _spriteBatch.Begin(); - foreach (var item in _childItems) - item.Dispose(); + for (int i = 0; i < Math.Min(_childItems.Count, _scrollBar.LinesToRender); i++) + { + _spriteBatch.Draw(iconTexture, DrawPositionWithParentOffset + new Vector2(26, 41 + i * 16), GetIconSourceRectangle(QuestStatusIcon.None2), Color.White); + } - _childItems.Clear(); + _spriteBatch.End(); + } - for (int i = 0; i < paperdollData.QuestNames.Count; i++) + protected override void UpdateDisplayedData(PaperdollData paperdollData) { - var quest = paperdollData.QuestNames[i]; + base.UpdateDisplayedData(paperdollData); - var nextLabel = new XNALabel(Constants.FontSize08pt5) + foreach (var item in _childItems) + item.Dispose(); + + _childItems.Clear(); + + for (int i = 0; i < paperdollData.QuestNames.Count; i++) { - Text = quest, - ForeColor = ColorConstants.LightGrayText, - AutoSize = true, - DrawPosition = new Vector2(50, 42 + i * 16), - Visible = i < _scrollBar.LinesToRender - }; - nextLabel.SetScrollWheelHandler(_scrollBar); - nextLabel.ResizeBasedOnText(); - nextLabel.SetParentControl(this); - nextLabel.Initialize(); + var quest = paperdollData.QuestNames[i]; + + var nextLabel = new XNALabel(Constants.FontSize08pt5) + { + Text = quest, + ForeColor = ColorConstants.LightGrayText, + AutoSize = true, + DrawPosition = new Vector2(50, 42 + i * 16), + Visible = i < _scrollBar.LinesToRender + }; + nextLabel.SetScrollWheelHandler(_scrollBar); + nextLabel.ResizeBasedOnText(); + nextLabel.SetParentControl(this); + nextLabel.Initialize(); + + _childItems.Add(nextLabel); + } - _childItems.Add(nextLabel); + _scrollBar.ScrollToTop(); + _scrollBar.UpdateDimensions(paperdollData.QuestNames.Count); } - _scrollBar.ScrollToTop(); - _scrollBar.UpdateDimensions(paperdollData.QuestNames.Count); - } - - // copied from QuestStatusListDialogItem - private static Rectangle GetIconSourceRectangle(QuestStatusIcon index) - { - return new Rectangle((int)index * 15, 0, 15, 15); + // copied from QuestStatusListDialogItem + private static Rectangle GetIconSourceRectangle(QuestStatusIcon index) + { + return new Rectangle((int)index * 15, 0, 15, 15); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ChangePasswordDialog.cs b/EndlessClient/Dialogs/ChangePasswordDialog.cs index dd53ec096..37089edbe 100644 --- a/EndlessClient/Dialogs/ChangePasswordDialog.cs +++ b/EndlessClient/Dialogs/ChangePasswordDialog.cs @@ -14,129 +14,130 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs; - -public class ChangePasswordDialog : BaseEODialog +namespace EndlessClient.Dialogs { - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - private readonly IXNATextBox[] _inputBoxes; - private readonly IXNAButton _ok, _cancel; - - private string Username => _inputBoxes[0].Text; - private string OldPassword => _inputBoxes[1].Text; - private string NewPassword => _inputBoxes[2].Text; - private string ConfirmPassword => _inputBoxes[3].Text; - - public IChangePasswordParameters Result => new ChangePasswordParameters(Username, OldPassword, NewPassword); - - public ChangePasswordDialog(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IContentProvider contentProvider, - IEOMessageBoxFactory eoMessageBoxFactory, - IPlayerInfoProvider playerInfoProvider, - IEODialogButtonService dialogButtonService, - IXnaControlSoundMapper xnaControlSoundMapper) - : base(nativeGraphicsManager, gameStateProvider) + public class ChangePasswordDialog : BaseEODialog { - _eoMessageBoxFactory = eoMessageBoxFactory; - _playerInfoProvider = playerInfoProvider; - _xnaControlSoundMapper = xnaControlSoundMapper; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; + private readonly IXNATextBox[] _inputBoxes; + private readonly IXNAButton _ok, _cancel; + + private string Username => _inputBoxes[0].Text; + private string OldPassword => _inputBoxes[1].Text; + private string NewPassword => _inputBoxes[2].Text; + private string ConfirmPassword => _inputBoxes[3].Text; + + public IChangePasswordParameters Result => new ChangePasswordParameters(Username, OldPassword, NewPassword); + + public ChangePasswordDialog(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IContentProvider contentProvider, + IEOMessageBoxFactory eoMessageBoxFactory, + IPlayerInfoProvider playerInfoProvider, + IEODialogButtonService dialogButtonService, + IXnaControlSoundMapper xnaControlSoundMapper) + : base(nativeGraphicsManager, gameStateProvider) + { + _eoMessageBoxFactory = eoMessageBoxFactory; + _playerInfoProvider = playerInfoProvider; + _xnaControlSoundMapper = xnaControlSoundMapper; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 21); + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 21); - var cursorTexture = contentProvider.Textures[ContentProvider.Cursor]; + var cursorTexture = contentProvider.Textures[ContentProvider.Cursor]; - _inputBoxes = new IXNATextBox[4]; - for (int i = 0; i < _inputBoxes.Length; ++i) - { - var tb = new XNATextBox(new Rectangle(198, 60 + i * 30, 137, 19), Constants.FontSize08, caretTexture: cursorTexture) + _inputBoxes = new IXNATextBox[4]; + for (int i = 0; i < _inputBoxes.Length; ++i) { - LeftPadding = 5, - DefaultText = " ", - MaxChars = i == 0 ? 16 : 12, - PasswordBox = i > 1, - TextColor = ColorConstants.LightBeigeText, - TabOrder = i + 1, - }; - _inputBoxes[i] = tb; + var tb = new XNATextBox(new Rectangle(198, 60 + i * 30, 137, 19), Constants.FontSize08, caretTexture: cursorTexture) + { + LeftPadding = 5, + DefaultText = " ", + MaxChars = i == 0 ? 16 : 12, + PasswordBox = i > 1, + TextColor = ColorConstants.LightBeigeText, + TabOrder = i + 1, + }; + _inputBoxes[i] = tb; + } + + _inputBoxes[0].Selected = true; + + _ok = new XNAButton( + dialogButtonService.SmallButtonSheet, + new Vector2(157, 195), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + _ok.OnClick += OnButtonPressed; + + _cancel = new XNAButton( + dialogButtonService.SmallButtonSheet, + new Vector2(250, 195), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); + + CenterInGameView(); } - _inputBoxes[0].Selected = true; - - _ok = new XNAButton( - dialogButtonService.SmallButtonSheet, - new Vector2(157, 195), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - _ok.OnClick += OnButtonPressed; - - _cancel = new XNAButton( - dialogButtonService.SmallButtonSheet, - new Vector2(250, 195), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); - - CenterInGameView(); - } - - public override void Initialize() - { - foreach (var tb in _inputBoxes) + public override void Initialize() { - tb.Initialize(); - tb.SetParentControl(this); - _xnaControlSoundMapper.BindSoundToControl(tb); - } + foreach (var tb in _inputBoxes) + { + tb.Initialize(); + tb.SetParentControl(this); + _xnaControlSoundMapper.BindSoundToControl(tb); + } - _ok.Initialize(); - _ok.SetParentControl(this); - _xnaControlSoundMapper.BindSoundToControl(_ok, Option.Some(Audio.SoundEffectID.DialogButtonClick)); + _ok.Initialize(); + _ok.SetParentControl(this); + _xnaControlSoundMapper.BindSoundToControl(_ok, Option.Some(Audio.SoundEffectID.DialogButtonClick)); - _cancel.Initialize(); - _cancel.SetParentControl(this); - _xnaControlSoundMapper.BindSoundToControl(_cancel, Option.Some(Audio.SoundEffectID.DialogButtonClick)); + _cancel.Initialize(); + _cancel.SetParentControl(this); + _xnaControlSoundMapper.BindSoundToControl(_cancel, Option.Some(Audio.SoundEffectID.DialogButtonClick)); - base.Initialize(); - } - - private void OnButtonPressed(object sender, EventArgs e) - { - if (_inputBoxes.Any(tb => string.IsNullOrWhiteSpace(tb.Text))) - { - return; + base.Initialize(); } - if (Username != _playerInfoProvider.LoggedInAccountName) + private void OnButtonPressed(object sender, EventArgs e) { - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHANGE_PASSWORD_MISMATCH); - messageBox.ShowDialog(); - return; - } + if (_inputBoxes.Any(tb => string.IsNullOrWhiteSpace(tb.Text))) + { + return; + } - if (OldPassword != _playerInfoProvider.PlayerPassword) - { - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHANGE_PASSWORD_MISMATCH); - messageBox.ShowDialog(); - return; - } + if (Username != _playerInfoProvider.LoggedInAccountName) + { + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHANGE_PASSWORD_MISMATCH); + messageBox.ShowDialog(); + return; + } - if (NewPassword != ConfirmPassword) - { - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ACCOUNT_CREATE_PASSWORD_MISMATCH); - messageBox.ShowDialog(); - return; - } + if (OldPassword != _playerInfoProvider.PlayerPassword) + { + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHANGE_PASSWORD_MISMATCH); + messageBox.ShowDialog(); + return; + } - if (NewPassword.Length < 6) - { - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ACCOUNT_CREATE_PASSWORD_TOO_SHORT); - messageBox.ShowDialog(); - return; - } + if (NewPassword != ConfirmPassword) + { + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ACCOUNT_CREATE_PASSWORD_MISMATCH); + messageBox.ShowDialog(); + return; + } - Close(XNADialogResult.OK); + if (NewPassword.Length < 6) + { + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ACCOUNT_CREATE_PASSWORD_TOO_SHORT); + messageBox.ShowDialog(); + return; + } + + Close(XNADialogResult.OK); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ChestDialog.cs b/EndlessClient/Dialogs/ChestDialog.cs index 3db9fd8e3..7cd10cab2 100644 --- a/EndlessClient/Dialogs/ChestDialog.cs +++ b/EndlessClient/Dialogs/ChestDialog.cs @@ -17,106 +17,107 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Dialogs; - -public class ChestDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private readonly IChestActions _chestActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - private readonly IChestDataProvider _chestDataProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICharacterProvider _characterProvider; - - private HashSet _cachedItems; - - public ChestDialog(INativeGraphicsManager nativeGraphicsManager, - IChestActions chestActions, - IEOMessageBoxFactory messageBoxFactory, - IEODialogButtonService dialogButtonService, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - IInventorySpaceValidator inventorySpaceValidator, - IMapItemGraphicProvider mapItemGraphicProvider, - IChestDataProvider chestDataProvider, - IEIFFileProvider eifFileProvider, - ICharacterProvider characterProvider) - : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.Chest) + public class ChestDialog : ScrollingListDialog { - _chestActions = chestActions; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _inventorySpaceValidator = inventorySpaceValidator; - _mapItemGraphicProvider = mapItemGraphicProvider; - _chestDataProvider = chestDataProvider; - _eifFileProvider = eifFileProvider; - _characterProvider = characterProvider; + private readonly IChestActions _chestActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IMapItemGraphicProvider _mapItemGraphicProvider; + private readonly IChestDataProvider _chestDataProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICharacterProvider _characterProvider; - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.Cancel; - - _cachedItems = new HashSet(); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - EOResourceID.STATUS_LABEL_CHEST_YOU_OPENED, - " " + _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_DRAG_AND_DROP_ITEMS)); - } + private HashSet _cachedItems; - protected override void OnUpdateControl(GameTime gameTime) - { - if (!_cachedItems.SetEquals(_chestDataProvider.Items)) + public ChestDialog(INativeGraphicsManager nativeGraphicsManager, + IChestActions chestActions, + IEOMessageBoxFactory messageBoxFactory, + IEODialogButtonService dialogButtonService, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + IInventorySpaceValidator inventorySpaceValidator, + IMapItemGraphicProvider mapItemGraphicProvider, + IChestDataProvider chestDataProvider, + IEIFFileProvider eifFileProvider, + ICharacterProvider characterProvider) + : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.Chest) { - _cachedItems = _chestDataProvider.Items.ToHashSet(); - RefreshItemList(); - } + _chestActions = chestActions; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _inventorySpaceValidator = inventorySpaceValidator; + _mapItemGraphicProvider = mapItemGraphicProvider; + _chestDataProvider = chestDataProvider; + _eifFileProvider = eifFileProvider; + _characterProvider = characterProvider; - base.OnUpdateControl(gameTime); - } + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.Cancel; - private void RefreshItemList() - { - ClearItemList(); + _cachedItems = new HashSet(); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + EOResourceID.STATUS_LABEL_CHEST_YOU_OPENED, + " " + _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_DRAG_AND_DROP_ITEMS)); + } - foreach (var item in _cachedItems) + protected override void OnUpdateControl(GameTime gameTime) { - var itemData = _eifFileProvider.EIFFile[item.ItemID]; - string subText = - $"x {item.Amount} " + - $"{(itemData.Type == ItemType.Armor ? "(" + _localizedStringFinder.GetString(EOResourceID.FEMALE - itemData.Gender) + ")" : "")}"; - var nextItem = new ListDialogItem(this, ListItemType) + if (!_cachedItems.SetEquals(_chestDataProvider.Items)) { - PrimaryText = itemData.Name, - SubText = subText, - IconGraphic = _mapItemGraphicProvider.GetItemGraphic(item.ItemID, item.Amount), - ShowIconBackGround = true, - }; - nextItem.RightClick += (_, _) => TakeItem(item, itemData); + _cachedItems = _chestDataProvider.Items.ToHashSet(); + RefreshItemList(); + } - AddItemToList(nextItem, sortList: false); + base.OnUpdateControl(gameTime); } - } - private void TakeItem(ChestItem item, EIFRecord itemData) - { - if (!_inventorySpaceValidator.ItemFits(item.ItemID)) + private void RefreshItemList() { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); + ClearItemList(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); - } - else if (itemData.Weight * item.Amount + _characterProvider.MainCharacter.Stats[CharacterStat.Weight] > _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]) - { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); + foreach (var item in _cachedItems) + { + var itemData = _eifFileProvider.EIFFile[item.ItemID]; + string subText = + $"x {item.Amount} " + + $"{(itemData.Type == ItemType.Armor ? "(" + _localizedStringFinder.GetString(EOResourceID.FEMALE - itemData.Gender) + ")" : "")}"; + var nextItem = new ListDialogItem(this, ListItemType) + { + PrimaryText = itemData.Name, + SubText = subText, + IconGraphic = _mapItemGraphicProvider.GetItemGraphic(item.ItemID, item.Amount), + ShowIconBackGround = true, + }; + nextItem.RightClick += (_, _) => TakeItem(item, itemData); + + AddItemToList(nextItem, sortList: false); + } } - else + + private void TakeItem(ChestItem item, EIFRecord itemData) { - _chestActions.TakeItemFromChest(item.ItemID); + if (!_inventorySpaceValidator.ItemFits(item.ItemID)) + { + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); + } + else if (itemData.Weight * item.Amount + _characterProvider.MainCharacter.Stats[CharacterStat.Weight] > _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]) + { + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + } + else + { + _chestActions.TakeItemFromChest(item.ItemID); + } } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/CreateCharacterDialog.cs b/EndlessClient/Dialogs/CreateCharacterDialog.cs index f104246c6..3a46497ff 100644 --- a/EndlessClient/Dialogs/CreateCharacterDialog.cs +++ b/EndlessClient/Dialogs/CreateCharacterDialog.cs @@ -14,178 +14,179 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public class CreateCharacterDialog : BaseEODialog +namespace EndlessClient.Dialogs { - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - private readonly IXNATextBox _inputBox; - private readonly IXNAButton[] _arrowButtons = new IXNAButton[4]; - - private readonly IXNAButton _ok, _cancel; - - private readonly CreateCharacterControl _characterControl; - - private readonly Rectangle[] _srcRectangles = new Rectangle[4]; - private readonly Texture2D _charCreateSheet; - - public string Name => _inputBox.Text.Trim(); - - private CharacterRenderProperties RenderProperties => _characterControl.RenderProperties; - public int Gender => RenderProperties.Gender; - public int HairStyle => RenderProperties.HairStyle; - public int HairColor => RenderProperties.HairColor; - public int Race => RenderProperties.Race; - - public CreateCharacterDialog( - INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - ICharacterRendererFactory rendererFactory, - IContentProvider contentProvider, - IEOMessageBoxFactory messageBoxFactory, - IEODialogButtonService eoDialogButtonService, - IXnaControlSoundMapper xnaControlSoundMapper) - : base(nativeGraphicsManager, gameStateProvider) + public class CreateCharacterDialog : BaseEODialog { - _messageBoxFactory = messageBoxFactory; - _xnaControlSoundMapper = xnaControlSoundMapper; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 20); - - _charCreateSheet = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 22); - - var cursorTexture = contentProvider.Textures[ContentProvider.Cursor]; - _inputBox = new XNATextBox(new Rectangle(80, 57, 138, 19), Constants.FontSize08, caretTexture: cursorTexture) - { - LeftPadding = 5, - DefaultText = " ", - Text = " ", - MaxChars = 12, - Selected = true, - TextColor = ColorConstants.LightBeigeText, - Visible = true - }; - _inputBox.SetParentControl(this); - _inputBox.Selected = true; - - for (int i = 0; i < _arrowButtons.Length; ++i) + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; + private readonly IXNATextBox _inputBox; + private readonly IXNAButton[] _arrowButtons = new IXNAButton[4]; + + private readonly IXNAButton _ok, _cancel; + + private readonly CreateCharacterControl _characterControl; + + private readonly Rectangle[] _srcRectangles = new Rectangle[4]; + private readonly Texture2D _charCreateSheet; + + public string Name => _inputBox.Text.Trim(); + + private CharacterRenderProperties RenderProperties => _characterControl.RenderProperties; + public int Gender => RenderProperties.Gender; + public int HairStyle => RenderProperties.HairStyle; + public int HairColor => RenderProperties.HairColor; + public int Race => RenderProperties.Race; + + public CreateCharacterDialog( + INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + ICharacterRendererFactory rendererFactory, + IContentProvider contentProvider, + IEOMessageBoxFactory messageBoxFactory, + IEODialogButtonService eoDialogButtonService, + IXnaControlSoundMapper xnaControlSoundMapper) + : base(nativeGraphicsManager, gameStateProvider) { - var btn = new XNAButton(_charCreateSheet, - new Vector2(196, 85 + i * 26), - new Rectangle(185, 38, 19, 19), - new Rectangle(206, 38, 19, 19)); - btn.OnClick += ArrowButtonClick; - btn.SetParentControl(this); - _arrowButtons[i] = btn; + _messageBoxFactory = messageBoxFactory; + _xnaControlSoundMapper = xnaControlSoundMapper; + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 20); + + _charCreateSheet = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 22); + + var cursorTexture = contentProvider.Textures[ContentProvider.Cursor]; + _inputBox = new XNATextBox(new Rectangle(80, 57, 138, 19), Constants.FontSize08, caretTexture: cursorTexture) + { + LeftPadding = 5, + DefaultText = " ", + Text = " ", + MaxChars = 12, + Selected = true, + TextColor = ColorConstants.LightBeigeText, + Visible = true + }; + _inputBox.SetParentControl(this); + _inputBox.Selected = true; + + for (int i = 0; i < _arrowButtons.Length; ++i) + { + var btn = new XNAButton(_charCreateSheet, + new Vector2(196, 85 + i * 26), + new Rectangle(185, 38, 19, 19), + new Rectangle(206, 38, 19, 19)); + btn.OnClick += ArrowButtonClick; + btn.SetParentControl(this); + _arrowButtons[i] = btn; + } + + _characterControl = new CreateCharacterControl(rendererFactory) + { + DrawPosition = new Vector2(235, 58) + }; + _characterControl.SetParentControl(this); + + _srcRectangles[0] = new Rectangle(0, 38, 23, 19); + _srcRectangles[1] = new Rectangle(0, 19, 23, 19); + _srcRectangles[2] = new Rectangle(0, 0, 23, 19); + _srcRectangles[3] = new Rectangle(46, 38, 23, 19); + + _ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(157, 195), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + _ok.OnClick += (s, e) => ClickOk(); + _ok.SetParentControl(this); + + _cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(250, 195), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); + _cancel.SetParentControl(this); + + CenterInGameView(); } - _characterControl = new CreateCharacterControl(rendererFactory) + public override void Initialize() { - DrawPosition = new Vector2(235, 58) - }; - _characterControl.SetParentControl(this); - - _srcRectangles[0] = new Rectangle(0, 38, 23, 19); - _srcRectangles[1] = new Rectangle(0, 19, 23, 19); - _srcRectangles[2] = new Rectangle(0, 0, 23, 19); - _srcRectangles[3] = new Rectangle(46, 38, 23, 19); - - _ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(157, 195), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - _ok.OnClick += (s, e) => ClickOk(); - _ok.SetParentControl(this); - - _cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(250, 195), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); - _cancel.SetParentControl(this); - - CenterInGameView(); - } + _characterControl.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_characterControl); - public override void Initialize() - { - _characterControl.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_characterControl); + _inputBox.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_inputBox); - _inputBox.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_inputBox); + foreach (var button in _arrowButtons) + { + button.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(button, Option.Some(Audio.SoundEffectID.TextBoxFocus)); + } - foreach (var button in _arrowButtons) - { - button.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(button, Option.Some(Audio.SoundEffectID.TextBoxFocus)); - } + _ok.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_ok, Option.Some(Audio.SoundEffectID.DialogButtonClick)); - _ok.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_ok, Option.Some(Audio.SoundEffectID.DialogButtonClick)); + _cancel.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_cancel, Option.Some(Audio.SoundEffectID.DialogButtonClick)); - _cancel.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_cancel, Option.Some(Audio.SoundEffectID.DialogButtonClick)); + base.Initialize(); + } - base.Initialize(); - } + protected override void OnDrawControl(GameTime gt) + { + base.OnDrawControl(gt); - protected override void OnDrawControl(GameTime gt) - { - base.OnDrawControl(gt); + _spriteBatch.Begin(); - _spriteBatch.Begin(); + for (int i = 0; i < 4; ++i) + { + _spriteBatch.Draw(_charCreateSheet, + new Vector2(170 + DrawPositionWithParentOffset.X, + 84 + i * 27 + DrawPositionWithParentOffset.Y), + _srcRectangles[i], Color.White); + } - for (int i = 0; i < 4; ++i) - { - _spriteBatch.Draw(_charCreateSheet, - new Vector2(170 + DrawPositionWithParentOffset.X, - 84 + i * 27 + DrawPositionWithParentOffset.Y), - _srcRectangles[i], Color.White); + _spriteBatch.End(); } - _spriteBatch.End(); - } - - private void ArrowButtonClick(object sender, EventArgs e) - { - if (sender == _arrowButtons[0]) - { - _characterControl.NextGender(); - _srcRectangles[0] = new Rectangle(0 + 23 * RenderProperties.Gender, 38, 23, 19); - } - else if (sender == _arrowButtons[1]) + private void ArrowButtonClick(object sender, EventArgs e) { - _characterControl.NextHairStyle(); - if (RenderProperties.HairStyle == 0) //skip bald + if (sender == _arrowButtons[0]) + { + _characterControl.NextGender(); + _srcRectangles[0] = new Rectangle(0 + 23 * RenderProperties.Gender, 38, 23, 19); + } + else if (sender == _arrowButtons[1]) + { _characterControl.NextHairStyle(); - - _srcRectangles[1] = new Rectangle(0 + 23 * (RenderProperties.HairStyle - 1), 19, 23, 19); - } - else if (sender == _arrowButtons[2]) - { - _characterControl.NextHairColor(); - _srcRectangles[2] = new Rectangle(0 + 23 * RenderProperties.HairColor, 0, 23, 19); + if (RenderProperties.HairStyle == 0) //skip bald + _characterControl.NextHairStyle(); + + _srcRectangles[1] = new Rectangle(0 + 23 * (RenderProperties.HairStyle - 1), 19, 23, 19); + } + else if (sender == _arrowButtons[2]) + { + _characterControl.NextHairColor(); + _srcRectangles[2] = new Rectangle(0 + 23 * RenderProperties.HairColor, 0, 23, 19); + } + else if (sender == _arrowButtons[3]) + { + _characterControl.NextRace(); + _srcRectangles[3] = new Rectangle(46 + 23 * RenderProperties.Race, 38, 23, 19); + } } - else if (sender == _arrowButtons[3]) - { - _characterControl.NextRace(); - _srcRectangles[3] = new Rectangle(46 + 23 * RenderProperties.Race, 38, 23, 19); - } - } - private void ClickOk() - { - if (_inputBox.Text.Length < 4) - { - var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CHARACTER_CREATE_NAME_TOO_SHORT, - EODialogButtons.Ok, - EOMessageBoxStyle.SmallDialogLargeHeader); - messageBox.ShowDialog(); - } - else + private void ClickOk() { - Close(XNADialogResult.OK); + if (_inputBox.Text.Length < 4) + { + var messageBox = _messageBoxFactory.CreateMessageBox(DialogResourceID.CHARACTER_CREATE_NAME_TOO_SHORT, + EODialogButtons.Ok, + EOMessageBoxStyle.SmallDialogLargeHeader); + messageBox.ShowDialog(); + } + else + { + Close(XNADialogResult.OK); + } } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/EODialogButton.cs b/EndlessClient/Dialogs/EODialogButton.cs index c55232e46..e065433f5 100644 --- a/EndlessClient/Dialogs/EODialogButton.cs +++ b/EndlessClient/Dialogs/EODialogButton.cs @@ -1,8 +1,9 @@ -namespace EndlessClient.Dialogs; - -public enum EODialogButtons +namespace EndlessClient.Dialogs { - Ok, - Cancel, - OkCancel, + public enum EODialogButtons + { + Ok, + Cancel, + OkCancel, + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/EOMessageBox.cs b/EndlessClient/Dialogs/EOMessageBox.cs index aa1084ee6..a5889e812 100644 --- a/EndlessClient/Dialogs/EOMessageBox.cs +++ b/EndlessClient/Dialogs/EOMessageBox.cs @@ -6,123 +6,124 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public enum EOMessageBoxStyle -{ - SmallDialogLargeHeader, - SmallDialogSmallHeader, - LargeDialogSmallHeader -} - -public class EOMessageBox : BaseEODialog +namespace EndlessClient.Dialogs { - private readonly IXNALabel _messageLabel, _captionLabel; - private readonly IXNAButton _ok, _cancel; - - public EOMessageBox(INativeGraphicsManager graphicsManager, - IGameStateProvider gameStateProvider, - IEODialogButtonService eoDialogButtonService, - string message, - string caption = "", - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader, - EODialogButtons whichButtons = EODialogButtons.Ok) - : base(graphicsManager, gameStateProvider) + public enum EOMessageBoxStyle { - var useSmallHeader = style != EOMessageBoxStyle.SmallDialogLargeHeader; + SmallDialogLargeHeader, + SmallDialogSmallHeader, + LargeDialogSmallHeader + } - int graphic; - switch (style) + public class EOMessageBox : BaseEODialog + { + private readonly IXNALabel _messageLabel, _captionLabel; + private readonly IXNAButton _ok, _cancel; + + public EOMessageBox(INativeGraphicsManager graphicsManager, + IGameStateProvider gameStateProvider, + IEODialogButtonService eoDialogButtonService, + string message, + string caption = "", + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader, + EODialogButtons whichButtons = EODialogButtons.Ok) + : base(graphicsManager, gameStateProvider) { - case EOMessageBoxStyle.SmallDialogLargeHeader: graphic = 18; break; - case EOMessageBoxStyle.SmallDialogSmallHeader: graphic = 23; break; - case EOMessageBoxStyle.LargeDialogSmallHeader: graphic = 25; break; - default: throw new ArgumentOutOfRangeException(nameof(style), "Unrecognized dialog style!"); - } + var useSmallHeader = style != EOMessageBoxStyle.SmallDialogLargeHeader; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, graphic); + int graphic; + switch (style) + { + case EOMessageBoxStyle.SmallDialogLargeHeader: graphic = 18; break; + case EOMessageBoxStyle.SmallDialogSmallHeader: graphic = 23; break; + case EOMessageBoxStyle.LargeDialogSmallHeader: graphic = 25; break; + default: throw new ArgumentOutOfRangeException(nameof(style), "Unrecognized dialog style!"); + } - _messageLabel = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - ForeColor = ColorConstants.LightGrayDialogMessage, - Text = message, - TextWidth = 254, - DrawPosition = new Vector2(19, useSmallHeader ? 40 : 62), - WrapBehavior = WrapBehavior.WrapToNewLine, - }; + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, graphic); - _messageLabel.SetParentControl(this); + _messageLabel = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + ForeColor = ColorConstants.LightGrayDialogMessage, + Text = message, + TextWidth = 254, + DrawPosition = new Vector2(19, useSmallHeader ? 40 : 62), + WrapBehavior = WrapBehavior.WrapToNewLine, + }; - _captionLabel = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - ForeColor = ColorConstants.LightYellowText, - Text = caption, - TextWidth = 254, - DrawPosition = useSmallHeader ? new Vector2(18, 12) : new Vector2(60, 27) - }; - _captionLabel.SetParentControl(this); - - var smallButtonSheet = eoDialogButtonService.SmallButtonSheet; - var okOut = eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok); - var okOver = eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok); - var cancelOut = eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel); - var cancelOver = eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel); - - switch (whichButtons) - { - case EODialogButtons.Ok: - _ok = new XNAButton(smallButtonSheet, new Vector2(181, 113), okOut, okOver); - _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); - _ok.SetParentControl(this); - break; - case EODialogButtons.Cancel: - _cancel = new XNAButton(smallButtonSheet, new Vector2(181, 113), cancelOut, cancelOver); - _cancel.OnClick += (sender, e) => Close(XNADialogResult.Cancel); - _cancel.SetParentControl(this); - break; - case EODialogButtons.OkCancel: - //implement this more fully when it is needed - //update draw location of ok button to be on left? - _ok = new XNAButton(smallButtonSheet, new Vector2(89, 113), okOut, okOver); - _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); - _ok.SetParentControl(this); - - _cancel = new XNAButton(smallButtonSheet, new Vector2(181, 113), cancelOut, cancelOver); - _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); - _cancel.SetParentControl(this); - break; - } + _messageLabel.SetParentControl(this); - if (useSmallHeader) - { - if (_ok != null) + _captionLabel = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + ForeColor = ColorConstants.LightYellowText, + Text = caption, + TextWidth = 254, + DrawPosition = useSmallHeader ? new Vector2(18, 12) : new Vector2(60, 27) + }; + _captionLabel.SetParentControl(this); + + var smallButtonSheet = eoDialogButtonService.SmallButtonSheet; + var okOut = eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok); + var okOver = eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok); + var cancelOut = eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel); + var cancelOver = eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel); + + switch (whichButtons) { - _ok.DrawPosition = new Vector2(_ok.DrawPosition.X, - style == EOMessageBoxStyle.SmallDialogSmallHeader ? 82 : 148); + case EODialogButtons.Ok: + _ok = new XNAButton(smallButtonSheet, new Vector2(181, 113), okOut, okOver); + _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); + _ok.SetParentControl(this); + break; + case EODialogButtons.Cancel: + _cancel = new XNAButton(smallButtonSheet, new Vector2(181, 113), cancelOut, cancelOver); + _cancel.OnClick += (sender, e) => Close(XNADialogResult.Cancel); + _cancel.SetParentControl(this); + break; + case EODialogButtons.OkCancel: + //implement this more fully when it is needed + //update draw location of ok button to be on left? + _ok = new XNAButton(smallButtonSheet, new Vector2(89, 113), okOut, okOver); + _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); + _ok.SetParentControl(this); + + _cancel = new XNAButton(smallButtonSheet, new Vector2(181, 113), cancelOut, cancelOver); + _cancel.OnClick += (s, e) => Close(XNADialogResult.Cancel); + _cancel.SetParentControl(this); + break; } - if (_cancel != null) + if (useSmallHeader) { - _cancel.DrawPosition = new Vector2(_cancel.DrawPosition.X, - style == EOMessageBoxStyle.SmallDialogSmallHeader ? 82 : 148); + if (_ok != null) + { + _ok.DrawPosition = new Vector2(_ok.DrawPosition.X, + style == EOMessageBoxStyle.SmallDialogSmallHeader ? 82 : 148); + } + + if (_cancel != null) + { + _cancel.DrawPosition = new Vector2(_cancel.DrawPosition.X, + style == EOMessageBoxStyle.SmallDialogSmallHeader ? 82 : 148); + } } - } - CenterInGameView(); - } + CenterInGameView(); + } - public override void Initialize() - { - _messageLabel.Initialize(); - _captionLabel.Initialize(); + public override void Initialize() + { + _messageLabel.Initialize(); + _captionLabel.Initialize(); - if (_ok != null) - _ok.Initialize(); - if (_cancel != null) - _cancel.Initialize(); + if (_ok != null) + _ok.Initialize(); + if (_cancel != null) + _cancel.Initialize(); - base.Initialize(); + base.Initialize(); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs b/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs index 54603a0a5..fe2f63539 100644 --- a/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs +++ b/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs @@ -2,30 +2,31 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.Dialogs.Extensions; - -public static class EquipLocationExtensions +namespace EndlessClient.Dialogs.Extensions { - public static Rectangle GetEquipLocationRectangle(this EquipLocation loc) + public static class EquipLocationExtensions { - switch (loc) + public static Rectangle GetEquipLocationRectangle(this EquipLocation loc) { - case EquipLocation.Boots: return new Rectangle(87, 220, 56, 54); - case EquipLocation.Accessory: return new Rectangle(55, 250, 23, 23); - case EquipLocation.Gloves: return new Rectangle(22, 188, 56, 54); - case EquipLocation.Belt: return new Rectangle(87, 188, 56, 23); - case EquipLocation.Armor: return new Rectangle(86, 82, 56, 98); - case EquipLocation.Necklace: return new Rectangle(152, 51, 56, 23); - case EquipLocation.Hat: return new Rectangle(87, 21, 56, 54); - case EquipLocation.Shield: return new Rectangle(152, 82, 56, 98); - case EquipLocation.Weapon: return new Rectangle(22, 82, 56, 98); - case EquipLocation.Ring1: return new Rectangle(152, 190, 23, 23); - case EquipLocation.Ring2: return new Rectangle(185, 190, 23, 23); - case EquipLocation.Armlet1: return new Rectangle(152, 220, 23, 23); - case EquipLocation.Armlet2: return new Rectangle(185, 220, 23, 23); - case EquipLocation.Bracer1: return new Rectangle(152, 250, 23, 23); - case EquipLocation.Bracer2: return new Rectangle(185, 250, 23, 23); - default: throw new ArgumentOutOfRangeException(nameof(loc), "That is not a valid equipment location"); + switch (loc) + { + case EquipLocation.Boots: return new Rectangle(87, 220, 56, 54); + case EquipLocation.Accessory: return new Rectangle(55, 250, 23, 23); + case EquipLocation.Gloves: return new Rectangle(22, 188, 56, 54); + case EquipLocation.Belt: return new Rectangle(87, 188, 56, 23); + case EquipLocation.Armor: return new Rectangle(86, 82, 56, 98); + case EquipLocation.Necklace: return new Rectangle(152, 51, 56, 23); + case EquipLocation.Hat: return new Rectangle(87, 21, 56, 54); + case EquipLocation.Shield: return new Rectangle(152, 82, 56, 98); + case EquipLocation.Weapon: return new Rectangle(22, 82, 56, 98); + case EquipLocation.Ring1: return new Rectangle(152, 190, 23, 23); + case EquipLocation.Ring2: return new Rectangle(185, 190, 23, 23); + case EquipLocation.Armlet1: return new Rectangle(152, 220, 23, 23); + case EquipLocation.Armlet2: return new Rectangle(185, 220, 23, 23); + case EquipLocation.Bracer1: return new Rectangle(152, 250, 23, 23); + case EquipLocation.Bracer2: return new Rectangle(185, 250, 23, 23); + default: throw new ArgumentOutOfRangeException(nameof(loc), "That is not a valid equipment location"); + } } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs b/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs index 7dc3a0077..ca9207f4d 100644 --- a/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BankAccountDialogFactory.cs @@ -8,69 +8,70 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class BankAccountDialogFactory : IBankAccountDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IBankActions _bankActions; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IItemTransferDialogFactory _itemTransferDialogFactory; - private readonly IHudControlProvider _hudControlProvider; - private readonly IBankDataProvider _bankDataProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEIFFileProvider _eifFileProvider; - - public BankAccountDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IBankActions bankActions, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - IItemTransferDialogFactory itemTransferDialogFactory, - IHudControlProvider hudControlProvider, - IBankDataProvider bankDataProvider, - ICharacterInventoryProvider characterInventoryProvider, - IEIFFileProvider eifFileProvider) + [AutoMappedType] + public class BankAccountDialogFactory : IBankAccountDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _bankActions = bankActions; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _itemTransferDialogFactory = itemTransferDialogFactory; - _hudControlProvider = hudControlProvider; - _bankDataProvider = bankDataProvider; - _characterInventoryProvider = characterInventoryProvider; - _eifFileProvider = eifFileProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IBankActions _bankActions; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IItemTransferDialogFactory _itemTransferDialogFactory; + private readonly IHudControlProvider _hudControlProvider; + private readonly IBankDataProvider _bankDataProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEIFFileProvider _eifFileProvider; + + public BankAccountDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IBankActions bankActions, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + IItemTransferDialogFactory itemTransferDialogFactory, + IHudControlProvider hudControlProvider, + IBankDataProvider bankDataProvider, + ICharacterInventoryProvider characterInventoryProvider, + IEIFFileProvider eifFileProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _bankActions = bankActions; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _itemTransferDialogFactory = itemTransferDialogFactory; + _hudControlProvider = hudControlProvider; + _bankDataProvider = bankDataProvider; + _characterInventoryProvider = characterInventoryProvider; + _eifFileProvider = eifFileProvider; + } + + public BankAccountDialog Create() + { + return new BankAccountDialog(_nativeGraphicsManager, + _bankActions, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _statusLabelSetter, + _messageBoxFactory, + _itemTransferDialogFactory, + _hudControlProvider, + _bankDataProvider, + _characterInventoryProvider, + _eifFileProvider); + } } - public BankAccountDialog Create() + public interface IBankAccountDialogFactory { - return new BankAccountDialog(_nativeGraphicsManager, - _bankActions, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _statusLabelSetter, - _messageBoxFactory, - _itemTransferDialogFactory, - _hudControlProvider, - _bankDataProvider, - _characterInventoryProvider, - _eifFileProvider); + BankAccountDialog Create(); } -} - -public interface IBankAccountDialogFactory -{ - BankAccountDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs b/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs index 9bfe5832f..ec9055cb3 100644 --- a/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs @@ -13,65 +13,66 @@ using EOLib.Localization; using System.Collections.Generic; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class BarberDialogFactory : IBarberDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly IEODialogButtonService _dialogButtonService; - private readonly ICharacterRepository _characterRepository; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IBarberActions _barberActions; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ISfxPlayer _sfxPlayer; - - public BarberDialogFactory(INativeGraphicsManager nativeGraphicsManager, - ICharacterRendererFactory characterRendererFactory, - IEODialogButtonService dialogButtonService, - ICharacterRepository characterRepository, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IBarberActions barberActions, - ICharacterInventoryProvider characterInventoryProvider, - IEOMessageBoxFactory messageBoxFactory, - IEIFFileProvider eifFileProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class BarberDialogFactory : IBarberDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _characterRendererFactory = characterRendererFactory; - _dialogButtonService = dialogButtonService; - _characterRepository = characterRepository; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _barberActions = barberActions; - _characterInventoryProvider = characterInventoryProvider; - _messageBoxFactory = messageBoxFactory; - _eifFileProvider = eifFileProvider; - _sfxPlayer = sfxPlayer; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly IEODialogButtonService _dialogButtonService; + private readonly ICharacterRepository _characterRepository; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IBarberActions _barberActions; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ISfxPlayer _sfxPlayer; + + public BarberDialogFactory(INativeGraphicsManager nativeGraphicsManager, + ICharacterRendererFactory characterRendererFactory, + IEODialogButtonService dialogButtonService, + ICharacterRepository characterRepository, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IBarberActions barberActions, + ICharacterInventoryProvider characterInventoryProvider, + IEOMessageBoxFactory messageBoxFactory, + IEIFFileProvider eifFileProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _characterRendererFactory = characterRendererFactory; + _dialogButtonService = dialogButtonService; + _characterRepository = characterRepository; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _barberActions = barberActions; + _characterInventoryProvider = characterInventoryProvider; + _messageBoxFactory = messageBoxFactory; + _eifFileProvider = eifFileProvider; + _sfxPlayer = sfxPlayer; + } + + public BarberDialog Create() + { + return new BarberDialog(_nativeGraphicsManager, + _characterRendererFactory, + _dialogButtonService, + _characterRepository, + _dialogIconService, + _localizedStringFinder, + _barberActions, + _characterInventoryProvider, + _messageBoxFactory, + _eifFileProvider, + _sfxPlayer); + } } - public BarberDialog Create() + public interface IBarberDialogFactory { - return new BarberDialog(_nativeGraphicsManager, - _characterRendererFactory, - _dialogButtonService, - _characterRepository, - _dialogIconService, - _localizedStringFinder, - _barberActions, - _characterInventoryProvider, - _messageBoxFactory, - _eifFileProvider, - _sfxPlayer); + BarberDialog Create(); } -} - -public interface IBarberDialogFactory -{ - BarberDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BardDialogFactory.cs b/EndlessClient/Dialogs/Factories/BardDialogFactory.cs index ba1f94286..9be90b362 100644 --- a/EndlessClient/Dialogs/Factories/BardDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BardDialogFactory.cs @@ -3,33 +3,34 @@ using EndlessClient.Dialogs.Services; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class BardDialogFactory : IBardDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IBardController _bardController; - private readonly IEODialogButtonService _dialogButtonService; - - public BardDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IBardController bardController, - IEODialogButtonService dialogButtonService) + [AutoMappedType] + public class BardDialogFactory : IBardDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _bardController = bardController; - _dialogButtonService = dialogButtonService; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IBardController _bardController; + private readonly IEODialogButtonService _dialogButtonService; + + public BardDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IBardController bardController, + IEODialogButtonService dialogButtonService) + { + _nativeGraphicsManager = nativeGraphicsManager; + _bardController = bardController; + _dialogButtonService = dialogButtonService; + } + + public BardDialog Create() + { + return new BardDialog(_nativeGraphicsManager, + _bardController, + _dialogButtonService); + } } - public BardDialog Create() + public interface IBardDialogFactory { - return new BardDialog(_nativeGraphicsManager, - _bardController, - _dialogButtonService); + BardDialog Create(); } -} - -public interface IBardDialogFactory -{ - BardDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs b/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs index a0f1fb2dd..167d2cbd5 100644 --- a/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BoardDialogFactory.cs @@ -8,61 +8,62 @@ using EOLib.Graphics; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class BoardDialogFactory : IBoardDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IBoardActions _boardActions; - private readonly IBoardRepository _boardRepository; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IContentProvider _contentProvider; - private readonly IHudControlProvider _hudControlProvider; - - public BoardDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService eoDialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IEOMessageBoxFactory eoMessageBoxFactory, - IBoardActions boardActions, - IBoardRepository boardRepository, - IPlayerInfoProvider playerInfoProvider, - ICharacterProvider characterProvider, - IContentProvider contentProvider, - IHudControlProvider hudControlProvider) + [AutoMappedType] + public class BoardDialogFactory : IBoardDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _eoDialogButtonService = eoDialogButtonService; - _localizedStringFinder = localizedStringFinder; - _eoMessageBoxFactory = eoMessageBoxFactory; - _boardActions = boardActions; - _boardRepository = boardRepository; - _playerInfoProvider = playerInfoProvider; - _characterProvider = characterProvider; - _contentProvider = contentProvider; - _hudControlProvider = hudControlProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IBoardActions _boardActions; + private readonly IBoardRepository _boardRepository; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IContentProvider _contentProvider; + private readonly IHudControlProvider _hudControlProvider; + + public BoardDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService eoDialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IEOMessageBoxFactory eoMessageBoxFactory, + IBoardActions boardActions, + IBoardRepository boardRepository, + IPlayerInfoProvider playerInfoProvider, + ICharacterProvider characterProvider, + IContentProvider contentProvider, + IHudControlProvider hudControlProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _eoDialogButtonService = eoDialogButtonService; + _localizedStringFinder = localizedStringFinder; + _eoMessageBoxFactory = eoMessageBoxFactory; + _boardActions = boardActions; + _boardRepository = boardRepository; + _playerInfoProvider = playerInfoProvider; + _characterProvider = characterProvider; + _contentProvider = contentProvider; + _hudControlProvider = hudControlProvider; + } + + public BoardDialog Create() + { + return new BoardDialog(_nativeGraphicsManager, + _eoDialogButtonService, + _localizedStringFinder, + _eoMessageBoxFactory, + _boardActions, + _boardRepository, + _playerInfoProvider, + _characterProvider, + _contentProvider, + _hudControlProvider); + } } - public BoardDialog Create() + public interface IBoardDialogFactory { - return new BoardDialog(_nativeGraphicsManager, - _eoDialogButtonService, - _localizedStringFinder, - _eoMessageBoxFactory, - _boardActions, - _boardRepository, - _playerInfoProvider, - _characterProvider, - _contentProvider, - _hudControlProvider); + BoardDialog Create(); } -} - -public interface IBoardDialogFactory -{ - BoardDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/BookDialogFactory.cs b/EndlessClient/Dialogs/Factories/BookDialogFactory.cs index 3ee54fd75..0ab0c369f 100644 --- a/EndlessClient/Dialogs/Factories/BookDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BookDialogFactory.cs @@ -4,40 +4,41 @@ using EOLib.Graphics; using EOLib.IO.Repositories; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class BookDialogFactory : IBookDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IPubFileProvider _pubFileProvider; - private readonly IPaperdollProvider _paperdollProvider; - - public BookDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService eoDialogButtonService, - IPubFileProvider pubFileProvider, - IPaperdollProvider paperdollProvider) + [AutoMappedType] + public class BookDialogFactory : IBookDialogFactory { + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IPubFileProvider _pubFileProvider; + private readonly IPaperdollProvider _paperdollProvider; + + public BookDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService eoDialogButtonService, + IPubFileProvider pubFileProvider, + IPaperdollProvider paperdollProvider) + { - _nativeGraphicsManager = nativeGraphicsManager; - _eoDialogButtonService = eoDialogButtonService; - _pubFileProvider = pubFileProvider; - _paperdollProvider = paperdollProvider; + _nativeGraphicsManager = nativeGraphicsManager; + _eoDialogButtonService = eoDialogButtonService; + _pubFileProvider = pubFileProvider; + _paperdollProvider = paperdollProvider; + } + + public BookDialog Create(Character character, bool isMainCharacter) + { + return new BookDialog(_nativeGraphicsManager, + _eoDialogButtonService, + _pubFileProvider, + _paperdollProvider, + character, + isMainCharacter); + } } - public BookDialog Create(Character character, bool isMainCharacter) + public interface IBookDialogFactory { - return new BookDialog(_nativeGraphicsManager, - _eoDialogButtonService, - _pubFileProvider, - _paperdollProvider, - character, - isMainCharacter); + BookDialog Create(Character character, bool isMainCharacter); } -} - -public interface IBookDialogFactory -{ - BookDialog Create(Character character, bool isMainCharacter); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ChangePasswordDialogFactory.cs b/EndlessClient/Dialogs/Factories/ChangePasswordDialogFactory.cs index 947a92090..c6069b765 100644 --- a/EndlessClient/Dialogs/Factories/ChangePasswordDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ChangePasswordDialogFactory.cs @@ -7,44 +7,45 @@ using EOLib.Domain.Login; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories; - -[MappedType(BaseType = typeof(IChangePasswordDialogFactory))] -public class ChangePasswordDialogFactory : IChangePasswordDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGameStateProvider _gameStateProvider; - private readonly IContentProvider _contentProvider; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - - public ChangePasswordDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IContentProvider contentProvider, - IEOMessageBoxFactory eoMessageBoxFactory, - IPlayerInfoProvider playerInfoProvider, - IEODialogButtonService eoDialogButtonService, - IXnaControlSoundMapper xnaControlSoundMapper) + [MappedType(BaseType = typeof(IChangePasswordDialogFactory))] + public class ChangePasswordDialogFactory : IChangePasswordDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _gameStateProvider = gameStateProvider; - _contentProvider = contentProvider; - _eoMessageBoxFactory = eoMessageBoxFactory; - _playerInfoProvider = playerInfoProvider; - _eoDialogButtonService = eoDialogButtonService; - _xnaControlSoundMapper = xnaControlSoundMapper; - } + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGameStateProvider _gameStateProvider; + private readonly IContentProvider _contentProvider; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - public ChangePasswordDialog BuildChangePasswordDialog() - { - return new ChangePasswordDialog(_nativeGraphicsManager, - _gameStateProvider, - _contentProvider, - _eoMessageBoxFactory, - _playerInfoProvider, - _eoDialogButtonService, - _xnaControlSoundMapper); + public ChangePasswordDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IContentProvider contentProvider, + IEOMessageBoxFactory eoMessageBoxFactory, + IPlayerInfoProvider playerInfoProvider, + IEODialogButtonService eoDialogButtonService, + IXnaControlSoundMapper xnaControlSoundMapper) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gameStateProvider = gameStateProvider; + _contentProvider = contentProvider; + _eoMessageBoxFactory = eoMessageBoxFactory; + _playerInfoProvider = playerInfoProvider; + _eoDialogButtonService = eoDialogButtonService; + _xnaControlSoundMapper = xnaControlSoundMapper; + } + + public ChangePasswordDialog BuildChangePasswordDialog() + { + return new ChangePasswordDialog(_nativeGraphicsManager, + _gameStateProvider, + _contentProvider, + _eoMessageBoxFactory, + _playerInfoProvider, + _eoDialogButtonService, + _xnaControlSoundMapper); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs b/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs index db4022776..7326a6b18 100644 --- a/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ChestDialogFactory.cs @@ -10,65 +10,66 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class ChestDialogFactory : IChestDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChestActions _chestActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - private readonly IChestDataProvider _chestDataProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICharacterProvider _characterProvider; - - public ChestDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IChestActions chestActions, - IEOMessageBoxFactory messageBoxFactory, - IEODialogButtonService dialogButtonService, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - IInventorySpaceValidator inventorySpaceValidator, - IMapItemGraphicProvider mapItemGraphicProvider, - IChestDataProvider chestDataProvider, - IEIFFileProvider eifFileProvider, - ICharacterProvider characterProvider) + [AutoMappedType] + public class ChestDialogFactory : IChestDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _chestActions = chestActions; - _messageBoxFactory = messageBoxFactory; - _dialogButtonService = dialogButtonService; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _inventorySpaceValidator = inventorySpaceValidator; - _mapItemGraphicProvider = mapItemGraphicProvider; - _chestDataProvider = chestDataProvider; - _eifFileProvider = eifFileProvider; - _characterProvider = characterProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChestActions _chestActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IMapItemGraphicProvider _mapItemGraphicProvider; + private readonly IChestDataProvider _chestDataProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICharacterProvider _characterProvider; + + public ChestDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IChestActions chestActions, + IEOMessageBoxFactory messageBoxFactory, + IEODialogButtonService dialogButtonService, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + IInventorySpaceValidator inventorySpaceValidator, + IMapItemGraphicProvider mapItemGraphicProvider, + IChestDataProvider chestDataProvider, + IEIFFileProvider eifFileProvider, + ICharacterProvider characterProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _chestActions = chestActions; + _messageBoxFactory = messageBoxFactory; + _dialogButtonService = dialogButtonService; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _inventorySpaceValidator = inventorySpaceValidator; + _mapItemGraphicProvider = mapItemGraphicProvider; + _chestDataProvider = chestDataProvider; + _eifFileProvider = eifFileProvider; + _characterProvider = characterProvider; + } + + public ChestDialog Create() + { + return new ChestDialog(_nativeGraphicsManager, + _chestActions, + _messageBoxFactory, + _dialogButtonService, + _statusLabelSetter, + _localizedStringFinder, + _inventorySpaceValidator, + _mapItemGraphicProvider, + _chestDataProvider, + _eifFileProvider, + _characterProvider); + } } - public ChestDialog Create() + public interface IChestDialogFactory { - return new ChestDialog(_nativeGraphicsManager, - _chestActions, - _messageBoxFactory, - _dialogButtonService, - _statusLabelSetter, - _localizedStringFinder, - _inventorySpaceValidator, - _mapItemGraphicProvider, - _chestDataProvider, - _eifFileProvider, - _characterProvider); + ChestDialog Create(); } -} - -public interface IChestDialogFactory -{ - ChestDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/CreateAccountProgressDialogFactory.cs b/EndlessClient/Dialogs/Factories/CreateAccountProgressDialogFactory.cs index 9b5dc4f8a..5bd8e664e 100644 --- a/EndlessClient/Dialogs/Factories/CreateAccountProgressDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/CreateAccountProgressDialogFactory.cs @@ -6,44 +6,45 @@ using EOLib.Localization; using XNAControls; -namespace EndlessClient.Dialogs.Factories; - -[MappedType(BaseType = typeof(ICreateAccountProgressDialogFactory))] -public class CreateAccountProgressDialogFactory : ICreateAccountProgressDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGameStateProvider _gameStateProvider; - private readonly IConfigurationProvider _configProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEODialogButtonService _eoDialogButtonService; - - public CreateAccountProgressDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IConfigurationProvider configProvider, - ILocalizedStringFinder localizedStringFinder, - IEODialogButtonService eoDialogButtonService) + [MappedType(BaseType = typeof(ICreateAccountProgressDialogFactory))] + public class CreateAccountProgressDialogFactory : ICreateAccountProgressDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _gameStateProvider = gameStateProvider; - _configProvider = configProvider; - _localizedStringFinder = localizedStringFinder; - _eoDialogButtonService = eoDialogButtonService; - } + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGameStateProvider _gameStateProvider; + private readonly IConfigurationProvider _configProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEODialogButtonService _eoDialogButtonService; - public IXNADialog BuildCreateAccountProgressDialog() - { - var message = _localizedStringFinder.GetString(DialogResourceID.ACCOUNT_CREATE_ACCEPTED + 1); - var caption = _localizedStringFinder.GetString(DialogResourceID.ACCOUNT_CREATE_ACCEPTED); + public CreateAccountProgressDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IConfigurationProvider configProvider, + ILocalizedStringFinder localizedStringFinder, + IEODialogButtonService eoDialogButtonService) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gameStateProvider = gameStateProvider; + _configProvider = configProvider; + _localizedStringFinder = localizedStringFinder; + _eoDialogButtonService = eoDialogButtonService; + } - return new ProgressDialog(_nativeGraphicsManager, - _gameStateProvider, - _configProvider, - _eoDialogButtonService, - message, caption); + public IXNADialog BuildCreateAccountProgressDialog() + { + var message = _localizedStringFinder.GetString(DialogResourceID.ACCOUNT_CREATE_ACCEPTED + 1); + var caption = _localizedStringFinder.GetString(DialogResourceID.ACCOUNT_CREATE_ACCEPTED); + + return new ProgressDialog(_nativeGraphicsManager, + _gameStateProvider, + _configProvider, + _eoDialogButtonService, + message, caption); + } } -} -public interface ICreateAccountProgressDialogFactory -{ - IXNADialog BuildCreateAccountProgressDialog(); + public interface ICreateAccountProgressDialogFactory + { + IXNADialog BuildCreateAccountProgressDialog(); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs b/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs index f3536b098..4342a1a98 100644 --- a/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/CreateAccountWarningDialogFactory.cs @@ -6,44 +6,45 @@ using EOLib.Graphics; using XNAControls; -namespace EndlessClient.Dialogs.Factories; - -[MappedType(BaseType = typeof(ICreateAccountWarningDialogFactory))] -public class CreateAccountWarningDialogFactory : ICreateAccountWarningDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IContentProvider _contentProvider; - private readonly IGameStateProvider _gameStateProvider; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly ISfxPlayer _sfxPlayer; - - public CreateAccountWarningDialogFactory( - INativeGraphicsManager nativeGraphicsManager, - IContentProvider contentProvider, - IGameStateProvider gameStateProvider, - IEODialogButtonService eoDialogButtonService, - ISfxPlayer sfxPlayer) + [MappedType(BaseType = typeof(ICreateAccountWarningDialogFactory))] + public class CreateAccountWarningDialogFactory : ICreateAccountWarningDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _contentProvider = contentProvider; - _gameStateProvider = gameStateProvider; - _eoDialogButtonService = eoDialogButtonService; - _sfxPlayer = sfxPlayer; - } + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IContentProvider _contentProvider; + private readonly IGameStateProvider _gameStateProvider; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly ISfxPlayer _sfxPlayer; - public IXNADialog ShowCreateAccountWarningDialog(string warningMessage) - { - var dialog = new ScrollingMessageDialog(_nativeGraphicsManager, _contentProvider, _gameStateProvider, _eoDialogButtonService) + public CreateAccountWarningDialogFactory( + INativeGraphicsManager nativeGraphicsManager, + IContentProvider contentProvider, + IGameStateProvider gameStateProvider, + IEODialogButtonService eoDialogButtonService, + ISfxPlayer sfxPlayer) { - MessageText = warningMessage - }; - dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + _nativeGraphicsManager = nativeGraphicsManager; + _contentProvider = contentProvider; + _gameStateProvider = gameStateProvider; + _eoDialogButtonService = eoDialogButtonService; + _sfxPlayer = sfxPlayer; + } - return dialog; + public IXNADialog ShowCreateAccountWarningDialog(string warningMessage) + { + var dialog = new ScrollingMessageDialog(_nativeGraphicsManager, _contentProvider, _gameStateProvider, _eoDialogButtonService) + { + MessageText = warningMessage + }; + dialog.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + + return dialog; + } } -} -public interface ICreateAccountWarningDialogFactory -{ - IXNADialog ShowCreateAccountWarningDialog(string warningMessage); + public interface ICreateAccountWarningDialogFactory + { + IXNADialog ShowCreateAccountWarningDialog(string warningMessage); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/CreateCharacterDialogFactory.cs b/EndlessClient/Dialogs/Factories/CreateCharacterDialogFactory.cs index 3e7327374..4e772a8be 100644 --- a/EndlessClient/Dialogs/Factories/CreateCharacterDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/CreateCharacterDialogFactory.cs @@ -7,49 +7,50 @@ using EndlessClient.UIControls; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories; - -[MappedType(BaseType = typeof(ICreateCharacterDialogFactory))] -public class CreateCharacterDialogFactory : ICreateCharacterDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGameStateProvider _gameStateProvider; - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly IContentProvider _contentProvider; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - - public CreateCharacterDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - ICharacterRendererFactory characterRendererFactory, - IContentProvider contentProvider, - IEOMessageBoxFactory eoMessageBoxFactory, - IEODialogButtonService dialogButtonService, - IXnaControlSoundMapper xnaControlSoundMapper) + [MappedType(BaseType = typeof(ICreateCharacterDialogFactory))] + public class CreateCharacterDialogFactory : ICreateCharacterDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _gameStateProvider = gameStateProvider; - _characterRendererFactory = characterRendererFactory; - _contentProvider = contentProvider; - _eoMessageBoxFactory = eoMessageBoxFactory; - _dialogButtonService = dialogButtonService; - _xnaControlSoundMapper = xnaControlSoundMapper; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGameStateProvider _gameStateProvider; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly IContentProvider _contentProvider; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; + + public CreateCharacterDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + ICharacterRendererFactory characterRendererFactory, + IContentProvider contentProvider, + IEOMessageBoxFactory eoMessageBoxFactory, + IEODialogButtonService dialogButtonService, + IXnaControlSoundMapper xnaControlSoundMapper) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gameStateProvider = gameStateProvider; + _characterRendererFactory = characterRendererFactory; + _contentProvider = contentProvider; + _eoMessageBoxFactory = eoMessageBoxFactory; + _dialogButtonService = dialogButtonService; + _xnaControlSoundMapper = xnaControlSoundMapper; + } + + public CreateCharacterDialog BuildCreateCharacterDialog() + { + return new CreateCharacterDialog(_nativeGraphicsManager, + _gameStateProvider, + _characterRendererFactory, + _contentProvider, + _eoMessageBoxFactory, + _dialogButtonService, + _xnaControlSoundMapper); + } } - public CreateCharacterDialog BuildCreateCharacterDialog() + public interface ICreateCharacterDialogFactory { - return new CreateCharacterDialog(_nativeGraphicsManager, - _gameStateProvider, - _characterRendererFactory, - _contentProvider, - _eoMessageBoxFactory, - _dialogButtonService, - _xnaControlSoundMapper); + CreateCharacterDialog BuildCreateCharacterDialog(); } -} - -public interface ICreateCharacterDialogFactory -{ - CreateCharacterDialog BuildCreateCharacterDialog(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/EOMessageBoxFactory.cs b/EndlessClient/Dialogs/Factories/EOMessageBoxFactory.cs index d18710c3b..c62eae05f 100644 --- a/EndlessClient/Dialogs/Factories/EOMessageBoxFactory.cs +++ b/EndlessClient/Dialogs/Factories/EOMessageBoxFactory.cs @@ -7,95 +7,96 @@ using Optional; using XNAControls; -namespace EndlessClient.Dialogs.Factories; - -[MappedType(BaseType = typeof(IEOMessageBoxFactory))] -public class EOMessageBoxFactory : IEOMessageBoxFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGameStateProvider _gameStateProvider; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IActiveDialogRepository _activeDialogRepository; - private readonly ISfxPlayer _sfxPlayer; - - public EOMessageBoxFactory(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IEODialogButtonService eoDialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IActiveDialogRepository activeDialogRepository, - ISfxPlayer sfxPlayer) + [MappedType(BaseType = typeof(IEOMessageBoxFactory))] + public class EOMessageBoxFactory : IEOMessageBoxFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _gameStateProvider = gameStateProvider; - _eoDialogButtonService = eoDialogButtonService; - _localizedStringFinder = localizedStringFinder; - _activeDialogRepository = activeDialogRepository; - _sfxPlayer = sfxPlayer; - } + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGameStateProvider _gameStateProvider; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IActiveDialogRepository _activeDialogRepository; + private readonly ISfxPlayer _sfxPlayer; - public IXNADialog CreateMessageBox(string message, - string caption = "", - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) - { + public EOMessageBoxFactory(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IEODialogButtonService eoDialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IActiveDialogRepository activeDialogRepository, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gameStateProvider = gameStateProvider; + _eoDialogButtonService = eoDialogButtonService; + _localizedStringFinder = localizedStringFinder; + _activeDialogRepository = activeDialogRepository; + _sfxPlayer = sfxPlayer; + } - var messageBox = new EOMessageBox(_nativeGraphicsManager, - _gameStateProvider, - _eoDialogButtonService, - message, - caption, - style, - whichButtons); - messageBox.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - messageBox.DialogClosed += (_, _) => _activeDialogRepository.MessageBox = Option.None(); + public IXNADialog CreateMessageBox(string message, + string caption = "", + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) + { - _activeDialogRepository.MessageBox = Option.Some(messageBox); + var messageBox = new EOMessageBox(_nativeGraphicsManager, + _gameStateProvider, + _eoDialogButtonService, + message, + caption, + style, + whichButtons); + messageBox.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + messageBox.DialogClosed += (_, _) => _activeDialogRepository.MessageBox = Option.None(); - return messageBox; - } + _activeDialogRepository.MessageBox = Option.Some(messageBox); - public IXNADialog CreateMessageBox(DialogResourceID resource, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) - { - return CreateMessageBox(_localizedStringFinder.GetString(resource + 1), - _localizedStringFinder.GetString(resource), - whichButtons, - style); - } + return messageBox; + } - public IXNADialog CreateMessageBox(string prependData, - DialogResourceID resource, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) - { - var message = prependData + _localizedStringFinder.GetString(resource + 1); - return CreateMessageBox(message, - _localizedStringFinder.GetString(resource), - whichButtons, - style); - } + public IXNADialog CreateMessageBox(DialogResourceID resource, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) + { + return CreateMessageBox(_localizedStringFinder.GetString(resource + 1), + _localizedStringFinder.GetString(resource), + whichButtons, + style); + } - public IXNADialog CreateMessageBox(DialogResourceID resource, - string extraData, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) - { - var message = _localizedStringFinder.GetString(resource + 1) + extraData; - return CreateMessageBox(message, - _localizedStringFinder.GetString(resource), - whichButtons, - style); - } + public IXNADialog CreateMessageBox(string prependData, + DialogResourceID resource, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) + { + var message = prependData + _localizedStringFinder.GetString(resource + 1); + return CreateMessageBox(message, + _localizedStringFinder.GetString(resource), + whichButtons, + style); + } - public IXNADialog CreateMessageBox(EOResourceID message, - EOResourceID caption, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) - { - var messageText = _localizedStringFinder.GetString(message); - var captionText = _localizedStringFinder.GetString(caption); - return CreateMessageBox(messageText, captionText, whichButtons, style); + public IXNADialog CreateMessageBox(DialogResourceID resource, + string extraData, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) + { + var message = _localizedStringFinder.GetString(resource + 1) + extraData; + return CreateMessageBox(message, + _localizedStringFinder.GetString(resource), + whichButtons, + style); + } + + public IXNADialog CreateMessageBox(EOResourceID message, + EOResourceID caption, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader) + { + var messageText = _localizedStringFinder.GetString(message); + var captionText = _localizedStringFinder.GetString(caption); + return CreateMessageBox(messageText, captionText, whichButtons, style); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs b/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs index bd0ad4374..d46c7c18a 100644 --- a/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs @@ -14,126 +14,127 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class FriendIgnoreListDialogFactory : IFriendIgnoreListDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ICharacterProvider _characterProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly IOnlinePlayerProvider _onlinePlayerProvider; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IFriendIgnoreListService _friendIgnoreListService; - - public FriendIgnoreListDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - ICharacterProvider characterProvider, - IHudControlProvider hudControlProvider, - IOnlinePlayerProvider onlinePlayerProvider, - ITextInputDialogFactory textInputDialogFactory, - IEOMessageBoxFactory eoMessageBoxFactory, - IFriendIgnoreListService friendIgnoreListService) - { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _localizedStringFinder = localizedStringFinder; - _characterProvider = characterProvider; - _hudControlProvider = hudControlProvider; - _onlinePlayerProvider = onlinePlayerProvider; - _textInputDialogFactory = textInputDialogFactory; - _eoMessageBoxFactory = eoMessageBoxFactory; - _friendIgnoreListService = friendIgnoreListService; - } - - public FriendIgnoreListDialog Create(bool isFriendList) + [AutoMappedType] + public class FriendIgnoreListDialogFactory : IFriendIgnoreListDialogFactory { - var textFileLines = _friendIgnoreListService.LoadList(isFriendList ? Constants.FriendListFile : Constants.IgnoreListFile); - - var dialog = new FriendIgnoreListDialog(_nativeGraphicsManager, _dialogButtonService, _onlinePlayerProvider) + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ICharacterProvider _characterProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly IOnlinePlayerProvider _onlinePlayerProvider; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IFriendIgnoreListService _friendIgnoreListService; + + public FriendIgnoreListDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + ICharacterProvider characterProvider, + IHudControlProvider hudControlProvider, + IOnlinePlayerProvider onlinePlayerProvider, + ITextInputDialogFactory textInputDialogFactory, + IEOMessageBoxFactory eoMessageBoxFactory, + IFriendIgnoreListService friendIgnoreListService) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _localizedStringFinder = localizedStringFinder; + _characterProvider = characterProvider; + _hudControlProvider = hudControlProvider; + _onlinePlayerProvider = onlinePlayerProvider; + _textInputDialogFactory = textInputDialogFactory; + _eoMessageBoxFactory = eoMessageBoxFactory; + _friendIgnoreListService = friendIgnoreListService; + } + + public FriendIgnoreListDialog Create(bool isFriendList) { - Buttons = ScrollingListDialogButtons.AddCancel, - ListItemType = ListDialogItem.ListItemStyle.Small, - }; + var textFileLines = _friendIgnoreListService.LoadList(isFriendList ? Constants.FriendListFile : Constants.IgnoreListFile); - var listItems = textFileLines.Select(x => new ListDialogItem(dialog, ListDialogItem.ListItemStyle.Small) { PrimaryText = x }).ToList(); - foreach (var item in listItems) - SetClickEventHandlers(item, dialog, isFriendList); - dialog.SetItemList(listItems); + var dialog = new FriendIgnoreListDialog(_nativeGraphicsManager, _dialogButtonService, _onlinePlayerProvider) + { + Buttons = ScrollingListDialogButtons.AddCancel, + ListItemType = ListDialogItem.ListItemStyle.Small, + }; - dialog.Title = GetDialogTitle(dialog, isFriendList); + var listItems = textFileLines.Select(x => new ListDialogItem(dialog, ListDialogItem.ListItemStyle.Small) { PrimaryText = x }).ToList(); + foreach (var item in listItems) + SetClickEventHandlers(item, dialog, isFriendList); + dialog.SetItemList(listItems); - dialog.AddAction += (_, _) => InvokeAdd(isFriendList, dialog); - dialog.DialogClosing += (_, _) => - { - if (isFriendList) - _friendIgnoreListService.SaveFriends(Constants.FriendListFile, dialog.NamesList); - else - _friendIgnoreListService.SaveIgnored(Constants.IgnoreListFile, dialog.NamesList); - }; + dialog.Title = GetDialogTitle(dialog, isFriendList); - return dialog; - } + dialog.AddAction += (_, _) => InvokeAdd(isFriendList, dialog); + dialog.DialogClosing += (_, _) => + { + if (isFriendList) + _friendIgnoreListService.SaveFriends(Constants.FriendListFile, dialog.NamesList); + else + _friendIgnoreListService.SaveIgnored(Constants.IgnoreListFile, dialog.NamesList); + }; - private void InvokeAdd(bool isFriendList, ScrollingListDialog parentDialog) - { - string prompt = _localizedStringFinder.GetString(isFriendList ? EOResourceID.DIALOG_WHO_TO_MAKE_FRIEND : EOResourceID.DIALOG_WHO_TO_MAKE_IGNORE); - var inputDialog = _textInputDialogFactory.Create(prompt); + return dialog; + } - inputDialog.DialogClosing += (_, e) => + private void InvokeAdd(bool isFriendList, ScrollingListDialog parentDialog) { - if (e.Result == XNADialogResult.Cancel) - return; + string prompt = _localizedStringFinder.GetString(isFriendList ? EOResourceID.DIALOG_WHO_TO_MAKE_FRIEND : EOResourceID.DIALOG_WHO_TO_MAKE_IGNORE); + var inputDialog = _textInputDialogFactory.Create(prompt); - if (inputDialog.ResponseText.Length < 4) + inputDialog.DialogClosing += (_, e) => { - e.Cancel = true; - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHARACTER_CREATE_NAME_TOO_SHORT); - messageBox.ShowDialog(); - return; - } - - if (parentDialog.NamesList.Any(name => string.Equals(name, inputDialog.ResponseText, StringComparison.InvariantCultureIgnoreCase))) + if (e.Result == XNADialogResult.Cancel) + return; + + if (inputDialog.ResponseText.Length < 4) + { + e.Cancel = true; + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.CHARACTER_CREATE_NAME_TOO_SHORT); + messageBox.ShowDialog(); + return; + } + + if (parentDialog.NamesList.Any(name => string.Equals(name, inputDialog.ResponseText, StringComparison.InvariantCultureIgnoreCase))) + { + e.Cancel = true; + var messageBox = _eoMessageBoxFactory.CreateMessageBox("You are already friends with that person!", "Invalid entry!", EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); + messageBox.ShowDialog(); + return; + } + + var charName = char.ToUpper(inputDialog.ResponseText[0]) + inputDialog.ResponseText.Substring(1); + var newItem = new ListDialogItem(parentDialog, ListDialogItem.ListItemStyle.Small) { PrimaryText = charName }; + SetClickEventHandlers(newItem, parentDialog, isFriendList); + + parentDialog.AddItemToList(newItem, sortList: true); + parentDialog.Title = GetDialogTitle(parentDialog, isFriendList); + }; + + inputDialog.ShowDialog(); + } + + private void SetClickEventHandlers(ListDialogItem item, ScrollingListDialog dialog, bool isFriendList) + { + item.LeftClick += (o, e) => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{item.PrimaryText} "; + item.RightClick += (o, e) => { - e.Cancel = true; - var messageBox = _eoMessageBoxFactory.CreateMessageBox("You are already friends with that person!", "Invalid entry!", EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); - messageBox.ShowDialog(); - return; - } + dialog.RemoveFromList(item); + dialog.Title = GetDialogTitle(dialog, isFriendList); + }; + } - var charName = char.ToUpper(inputDialog.ResponseText[0]) + inputDialog.ResponseText.Substring(1); - var newItem = new ListDialogItem(parentDialog, ListDialogItem.ListItemStyle.Small) { PrimaryText = charName }; - SetClickEventHandlers(newItem, parentDialog, isFriendList); - - parentDialog.AddItemToList(newItem, sortList: true); - parentDialog.Title = GetDialogTitle(parentDialog, isFriendList); - }; - - inputDialog.ShowDialog(); - } - - private void SetClickEventHandlers(ListDialogItem item, ScrollingListDialog dialog, bool isFriendList) - { - item.LeftClick += (o, e) => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{item.PrimaryText} "; - item.RightClick += (o, e) => + private string GetDialogTitle(ScrollingListDialog dialog, bool isFriendList) { - dialog.RemoveFromList(item); - dialog.Title = GetDialogTitle(dialog, isFriendList); - }; + var friendOrIgnoreStr = _localizedStringFinder.GetString(isFriendList ? EOResourceID.STATUS_LABEL_FRIEND_LIST : EOResourceID.STATUS_LABEL_IGNORE_LIST); + return $"{_characterProvider.MainCharacter.Name}'s {friendOrIgnoreStr} [{dialog.NamesList.Count}]"; + } } - private string GetDialogTitle(ScrollingListDialog dialog, bool isFriendList) + public interface IFriendIgnoreListDialogFactory { - var friendOrIgnoreStr = _localizedStringFinder.GetString(isFriendList ? EOResourceID.STATUS_LABEL_FRIEND_LIST : EOResourceID.STATUS_LABEL_IGNORE_LIST); - return $"{_characterProvider.MainCharacter.Name}'s {friendOrIgnoreStr} [{dialog.NamesList.Count}]"; + FriendIgnoreListDialog Create(bool isFriendList); } -} - -public interface IFriendIgnoreListDialogFactory -{ - FriendIgnoreListDialog Create(bool isFriendList); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/GameLoadingDialogFactory.cs b/EndlessClient/Dialogs/Factories/GameLoadingDialogFactory.cs index 5414b575a..55123086b 100644 --- a/EndlessClient/Dialogs/Factories/GameLoadingDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/GameLoadingDialogFactory.cs @@ -4,37 +4,38 @@ using EOLib.Graphics; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[MappedType(BaseType = typeof(IGameLoadingDialogFactory))] -public class GameLoadingDialogFactory : IGameLoadingDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGameStateProvider _gameStateProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - - public GameLoadingDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - ILocalizedStringFinder localizedStringFinder) + [MappedType(BaseType = typeof(IGameLoadingDialogFactory))] + public class GameLoadingDialogFactory : IGameLoadingDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _gameStateProvider = gameStateProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - _localizedStringFinder = localizedStringFinder; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGameStateProvider _gameStateProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + + public GameLoadingDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + ILocalizedStringFinder localizedStringFinder) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gameStateProvider = gameStateProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + _localizedStringFinder = localizedStringFinder; + } + + public GameLoadingDialog CreateGameLoadingDialog() + { + return new GameLoadingDialog(_nativeGraphicsManager, + _gameStateProvider, + _clientWindowSizeProvider, + _localizedStringFinder); + } } - public GameLoadingDialog CreateGameLoadingDialog() + public interface IGameLoadingDialogFactory { - return new GameLoadingDialog(_nativeGraphicsManager, - _gameStateProvider, - _clientWindowSizeProvider, - _localizedStringFinder); + GameLoadingDialog CreateGameLoadingDialog(); } -} - -public interface IGameLoadingDialogFactory -{ - GameLoadingDialog CreateGameLoadingDialog(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs b/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs index 740fccd25..5560d1b46 100644 --- a/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs @@ -8,73 +8,74 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType(IsSingleton = true)] -public class HelpDialogFactory : IHelpDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IContentProvider _contentProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IHelpActions _helpActions; - - public HelpDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IContentProvider contentProvider, - ILocalizedStringFinder localizedStringFinder, - IHelpActions helpActions) + [AutoMappedType(IsSingleton = true)] + public class HelpDialogFactory : IHelpDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _contentProvider = contentProvider; - _localizedStringFinder = localizedStringFinder; - _helpActions = helpActions; - } + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IContentProvider _contentProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IHelpActions _helpActions; - public ScrollingListDialog Create() - { - var dlg = new ScrollingListDialog(_nativeGraphicsManager, _dialogButtonService, DialogType.Help) + public HelpDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IContentProvider contentProvider, + ILocalizedStringFinder localizedStringFinder, + IHelpActions helpActions) { - Title = _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP), - Buttons = ScrollingListDialogButtons.Cancel, - ListItemType = ListDialogItem.ListItemStyle.Small, - }; + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _contentProvider = contentProvider; + _localizedStringFinder = localizedStringFinder; + _helpActions = helpActions; + } - dlg.AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize08pt5], - insertLineBreaks: false, - linkClickActions: GetActions(), - messages: GetMessages()); + public ScrollingListDialog Create() + { + var dlg = new ScrollingListDialog(_nativeGraphicsManager, _dialogButtonService, DialogType.Help) + { + Title = _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP), + Buttons = ScrollingListDialogButtons.Cancel, + ListItemType = ListDialogItem.ListItemStyle.Small, + }; - return dlg; - } + dlg.AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize08pt5], + insertLineBreaks: false, + linkClickActions: GetActions(), + messages: GetMessages()); - private string[] GetMessages() - { - return new[] + return dlg; + } + + private string[] GetMessages() { - _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_SUMMARY_1), - string.Empty, - _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_SUMMARY_2), - string.Empty, - _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_RESET_PASSWORD), - _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_REPORT_SOMEONE), - _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_SPEAK_TO_ADMIN), - }; - } + return new[] + { + _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_SUMMARY_1), + string.Empty, + _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_SUMMARY_2), + string.Empty, + _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_RESET_PASSWORD), + _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_REPORT_SOMEONE), + _localizedStringFinder.GetString(EOResourceID.ENDLESS_HELP_LINK_SPEAK_TO_ADMIN), + }; + } - private List GetActions() - { - return new List + private List GetActions() { - _helpActions.ResetPassword, - _helpActions.ReportSomeone, - _helpActions.SpeakToAdmin, - }; + return new List + { + _helpActions.ResetPassword, + _helpActions.ReportSomeone, + _helpActions.SpeakToAdmin, + }; + } } -} -public interface IHelpDialogFactory -{ - ScrollingListDialog Create(); + public interface IHelpDialogFactory + { + ScrollingListDialog Create(); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs b/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs index 48d76e9d4..80054bf4e 100644 --- a/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/IChangePasswordDialogFactory.cs @@ -1,6 +1,7 @@ -namespace EndlessClient.Dialogs.Factories; - -public interface IChangePasswordDialogFactory +namespace EndlessClient.Dialogs.Factories { - ChangePasswordDialog BuildChangePasswordDialog(); + public interface IChangePasswordDialogFactory + { + ChangePasswordDialog BuildChangePasswordDialog(); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs b/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs index afbc638cc..aa345a1e1 100644 --- a/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs +++ b/EndlessClient/Dialogs/Factories/IEOMessageBoxFactory.cs @@ -1,31 +1,32 @@ using EOLib.Localization; using XNAControls; -namespace EndlessClient.Dialogs.Factories; - -public interface IEOMessageBoxFactory +namespace EndlessClient.Dialogs.Factories { - IXNADialog CreateMessageBox(string message, - string caption = "", - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); + public interface IEOMessageBoxFactory + { + IXNADialog CreateMessageBox(string message, + string caption = "", + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); - IXNADialog CreateMessageBox(DialogResourceID resource, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); + IXNADialog CreateMessageBox(DialogResourceID resource, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); - IXNADialog CreateMessageBox(string prependData, - DialogResourceID resource, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); + IXNADialog CreateMessageBox(string prependData, + DialogResourceID resource, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); - IXNADialog CreateMessageBox(DialogResourceID resource, - string extraData, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); + IXNADialog CreateMessageBox(DialogResourceID resource, + string extraData, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); - IXNADialog CreateMessageBox(EOResourceID message, - EOResourceID caption, - EODialogButtons whichButtons = EODialogButtons.Ok, - EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); + IXNADialog CreateMessageBox(EOResourceID message, + EOResourceID caption, + EODialogButtons whichButtons = EODialogButtons.Ok, + EOMessageBoxStyle style = EOMessageBoxStyle.SmallDialogSmallHeader); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs b/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs index 684328b8e..15a389ce4 100644 --- a/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/InnkeeperDialogFactory.cs @@ -6,61 +6,62 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class InnkeeperDialogFactory : IInnkeeperDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ICitizenActions _citizenActions; - private readonly IContentProvider _contentProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly ICitizenDataProvider _citizenDataProvider; - - public InnkeeperDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IEOMessageBoxFactory messageBoxFactory, - ITextInputDialogFactory textInputDialogFactory, - ICitizenActions citizenActions, - IContentProvider contentProvider, - IENFFileProvider enfFileProvider, - ICitizenDataProvider citizenDataProvider) + [AutoMappedType] + public class InnkeeperDialogFactory : IInnkeeperDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _messageBoxFactory = messageBoxFactory; - _textInputDialogFactory = textInputDialogFactory; - _citizenActions = citizenActions; - _contentProvider = contentProvider; - _enfFileProvider = enfFileProvider; - _citizenDataProvider = citizenDataProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ICitizenActions _citizenActions; + private readonly IContentProvider _contentProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly ICitizenDataProvider _citizenDataProvider; + + public InnkeeperDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IEOMessageBoxFactory messageBoxFactory, + ITextInputDialogFactory textInputDialogFactory, + ICitizenActions citizenActions, + IContentProvider contentProvider, + IENFFileProvider enfFileProvider, + ICitizenDataProvider citizenDataProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _messageBoxFactory = messageBoxFactory; + _textInputDialogFactory = textInputDialogFactory; + _citizenActions = citizenActions; + _contentProvider = contentProvider; + _enfFileProvider = enfFileProvider; + _citizenDataProvider = citizenDataProvider; + } + + public InnkeeperDialog Create() + { + return new InnkeeperDialog(_nativeGraphicsManager, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _messageBoxFactory, + _textInputDialogFactory, + _citizenActions, + _contentProvider, + _enfFileProvider, + _citizenDataProvider); + } } - public InnkeeperDialog Create() + public interface IInnkeeperDialogFactory { - return new InnkeeperDialog(_nativeGraphicsManager, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _messageBoxFactory, - _textInputDialogFactory, - _citizenActions, - _contentProvider, - _enfFileProvider, - _citizenDataProvider); + InnkeeperDialog Create(); } -} - -public interface IInnkeeperDialogFactory -{ - InnkeeperDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ItemTransferDialogFactory.cs b/EndlessClient/Dialogs/Factories/ItemTransferDialogFactory.cs index 17058494e..80c328881 100644 --- a/EndlessClient/Dialogs/Factories/ItemTransferDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ItemTransferDialogFactory.cs @@ -7,57 +7,58 @@ using EOLib.Localization; using XNAControls; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class ItemTransferDialogFactory : IItemTransferDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatTextBoxActions _chatTextBoxActions; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IContentProvider _contentProvider; - private readonly ISfxPlayer _sfxPlayer; - - public ItemTransferDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IContentProvider contentProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class ItemTransferDialogFactory : IItemTransferDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _chatTextBoxActions = chatTextBoxActions; - _eoDialogButtonService = eoDialogButtonService; - _localizedStringFinder = localizedStringFinder; - _contentProvider = contentProvider; - _sfxPlayer = sfxPlayer; - } + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatTextBoxActions _chatTextBoxActions; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IContentProvider _contentProvider; + private readonly ISfxPlayer _sfxPlayer; - public ItemTransferDialog CreateItemTransferDialog(string itemName, ItemTransferDialog.TransferType transferType, int totalAmount, EOResourceID message) - { - var dlg = new ItemTransferDialog(_nativeGraphicsManager, - _chatTextBoxActions, - _eoDialogButtonService, - _localizedStringFinder, - _contentProvider, - itemName, - transferType, - totalAmount, - message); + public ItemTransferDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IContentProvider contentProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _chatTextBoxActions = chatTextBoxActions; + _eoDialogButtonService = eoDialogButtonService; + _localizedStringFinder = localizedStringFinder; + _contentProvider = contentProvider; + _sfxPlayer = sfxPlayer; + } - dlg.DialogClosing += (sender, args) => + public ItemTransferDialog CreateItemTransferDialog(string itemName, ItemTransferDialog.TransferType transferType, int totalAmount, EOResourceID message) { - if (args.Result == XNADialogResult.Cancel) + var dlg = new ItemTransferDialog(_nativeGraphicsManager, + _chatTextBoxActions, + _eoDialogButtonService, + _localizedStringFinder, + _contentProvider, + itemName, + transferType, + totalAmount, + message); + + dlg.DialogClosing += (sender, args) => { - _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - } - }; - return dlg; + if (args.Result == XNADialogResult.Cancel) + { + _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + } + }; + return dlg; + } } -} -public interface IItemTransferDialogFactory -{ - ItemTransferDialog CreateItemTransferDialog(string itemName, ItemTransferDialog.TransferType transferType, int totalAmount, EOResourceID message); + public interface IItemTransferDialogFactory + { + ItemTransferDialog CreateItemTransferDialog(string itemName, ItemTransferDialog.TransferType transferType, int totalAmount, EOResourceID message); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs b/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs index 9d8476163..926646a63 100644 --- a/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/JukeboxDialogFactory.cs @@ -6,61 +6,62 @@ using EOLib.Graphics; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class JukeboxDialogFactory : IJukeboxDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IDataFileProvider _dataFileProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IJukeboxActions _jukeboxActions; - private readonly IJukeboxRepository _jukeboxRepository; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly ISfxPlayer _sfxPlayer; - - public JukeboxDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IDataFileProvider dataFileProvider, - IEOMessageBoxFactory messageBoxFactory, - IJukeboxActions jukeboxActions, - IJukeboxRepository jukeboxRepository, - ICharacterInventoryProvider characterInventoryProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class JukeboxDialogFactory : IJukeboxDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _dataFileProvider = dataFileProvider; - _messageBoxFactory = messageBoxFactory; - _jukeboxActions = jukeboxActions; - _jukeboxRepository = jukeboxRepository; - _characterInventoryProvider = characterInventoryProvider; - _sfxPlayer = sfxPlayer; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IDataFileProvider _dataFileProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IJukeboxActions _jukeboxActions; + private readonly IJukeboxRepository _jukeboxRepository; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly ISfxPlayer _sfxPlayer; + + public JukeboxDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IDataFileProvider dataFileProvider, + IEOMessageBoxFactory messageBoxFactory, + IJukeboxActions jukeboxActions, + IJukeboxRepository jukeboxRepository, + ICharacterInventoryProvider characterInventoryProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _dataFileProvider = dataFileProvider; + _messageBoxFactory = messageBoxFactory; + _jukeboxActions = jukeboxActions; + _jukeboxRepository = jukeboxRepository; + _characterInventoryProvider = characterInventoryProvider; + _sfxPlayer = sfxPlayer; + } + + public JukeboxDialog Create() + { + return new JukeboxDialog(_nativeGraphicsManager, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _dataFileProvider, + _messageBoxFactory, + _jukeboxActions, + _jukeboxRepository, + _characterInventoryProvider, + _sfxPlayer); + } } - public JukeboxDialog Create() + public interface IJukeboxDialogFactory { - return new JukeboxDialog(_nativeGraphicsManager, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _dataFileProvider, - _messageBoxFactory, - _jukeboxActions, - _jukeboxRepository, - _characterInventoryProvider, - _sfxPlayer); + JukeboxDialog Create(); } -} - -public interface IJukeboxDialogFactory -{ - JukeboxDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/LawDialogFactory.cs b/EndlessClient/Dialogs/Factories/LawDialogFactory.cs index e2ccca349..0a9538435 100644 --- a/EndlessClient/Dialogs/Factories/LawDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/LawDialogFactory.cs @@ -7,57 +7,58 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class LawDialogFactory : ILawDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ILawActions _lawActions; - private readonly IContentProvider _contentProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IENFFileProvider _enfFileProvider; - - public LawDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - ITextInputDialogFactory textInputDialogFactory, - ILawActions lawActions, - IContentProvider contentProvider, - ICurrentMapStateProvider currentMapStateProvider, - IENFFileProvider enfFileProvider) + [AutoMappedType] + public class LawDialogFactory : ILawDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _textInputDialogFactory = textInputDialogFactory; - _lawActions = lawActions; - _contentProvider = contentProvider; - _currentMapStateProvider = currentMapStateProvider; - _enfFileProvider = enfFileProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ILawActions _lawActions; + private readonly IContentProvider _contentProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IENFFileProvider _enfFileProvider; + + public LawDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + ITextInputDialogFactory textInputDialogFactory, + ILawActions lawActions, + IContentProvider contentProvider, + ICurrentMapStateProvider currentMapStateProvider, + IENFFileProvider enfFileProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _textInputDialogFactory = textInputDialogFactory; + _lawActions = lawActions; + _contentProvider = contentProvider; + _currentMapStateProvider = currentMapStateProvider; + _enfFileProvider = enfFileProvider; + } + + public LawDialog Create() + { + return new LawDialog(_nativeGraphicsManager, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _textInputDialogFactory, + _lawActions, + _contentProvider, + _currentMapStateProvider, + _enfFileProvider); + } } - public LawDialog Create() + public interface ILawDialogFactory { - return new LawDialog(_nativeGraphicsManager, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _textInputDialogFactory, - _lawActions, - _contentProvider, - _currentMapStateProvider, - _enfFileProvider); + LawDialog Create(); } -} - -public interface ILawDialogFactory -{ - LawDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs b/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs index 499aff5ba..fc9065bee 100644 --- a/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/LockerDialogFactory.cs @@ -9,65 +9,66 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class LockerDialogFactory : ILockerDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ILockerActions _lockerActions; - private readonly IEODialogButtonService _dialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ICharacterProvider _characterProvider; - private readonly ILockerDataProvider _lockerDataProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly IEIFFileProvider _eifFileProvider; - - public LockerDialogFactory(INativeGraphicsManager nativeGraphicsManager, - ILockerActions lockerActions, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IInventorySpaceValidator inventorySpaceValidator, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - ICharacterProvider characterProvider, - ILockerDataProvider lockerDataProvider, - IHudControlProvider hudControlProvider, - IEIFFileProvider eifFileProvider) + [AutoMappedType] + public class LockerDialogFactory : ILockerDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _lockerActions = lockerActions; - _dialogButtonService = dialogButtonService; - _localizedStringFinder = localizedStringFinder; - _inventorySpaceValidator = inventorySpaceValidator; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _characterProvider = characterProvider; - _lockerDataProvider = lockerDataProvider; - _hudControlProvider = hudControlProvider; - _eifFileProvider = eifFileProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ILockerActions _lockerActions; + private readonly IEODialogButtonService _dialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ICharacterProvider _characterProvider; + private readonly ILockerDataProvider _lockerDataProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly IEIFFileProvider _eifFileProvider; + + public LockerDialogFactory(INativeGraphicsManager nativeGraphicsManager, + ILockerActions lockerActions, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IInventorySpaceValidator inventorySpaceValidator, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + ICharacterProvider characterProvider, + ILockerDataProvider lockerDataProvider, + IHudControlProvider hudControlProvider, + IEIFFileProvider eifFileProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _lockerActions = lockerActions; + _dialogButtonService = dialogButtonService; + _localizedStringFinder = localizedStringFinder; + _inventorySpaceValidator = inventorySpaceValidator; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _characterProvider = characterProvider; + _lockerDataProvider = lockerDataProvider; + _hudControlProvider = hudControlProvider; + _eifFileProvider = eifFileProvider; + } + + public LockerDialog Create() + { + return new LockerDialog(_nativeGraphicsManager, + _lockerActions, + _dialogButtonService, + _localizedStringFinder, + _inventorySpaceValidator, + _statusLabelSetter, + _messageBoxFactory, + _characterProvider, + _lockerDataProvider, + _hudControlProvider, + _eifFileProvider); + } } - public LockerDialog Create() + public interface ILockerDialogFactory { - return new LockerDialog(_nativeGraphicsManager, - _lockerActions, - _dialogButtonService, - _localizedStringFinder, - _inventorySpaceValidator, - _statusLabelSetter, - _messageBoxFactory, - _characterProvider, - _lockerDataProvider, - _hudControlProvider, - _eifFileProvider); + LockerDialog Create(); } -} - -public interface ILockerDialogFactory -{ - LockerDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs b/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs index 7fa760f19..b1ec454e0 100644 --- a/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/PaperdollDialogFactory.cs @@ -9,68 +9,69 @@ using EOLib.Graphics; using EOLib.IO.Repositories; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType(IsSingleton = true)] -public class PaperdollDialogFactory : IPaperdollDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ISfxPlayer _sfxPlayer; - private readonly IPaperdollProvider _paperdollProvider; - private readonly IPubFileProvider _pubFileProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly INativeGraphicsManager _nativeGraphicsManager; - private IInventoryController _inventoryController; - - public PaperdollDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IPaperdollProvider paperdollProvider, - IPubFileProvider pubFileProvider, - IHudControlProvider hudControlProvider, - IEODialogButtonService eoDialogButtonService, - IInventorySpaceValidator inventorySpaceValidator, - IEOMessageBoxFactory eoMessageBoxFactory, - IStatusLabelSetter statusLabelSetter, - ISfxPlayer sfxPlayer) + [AutoMappedType(IsSingleton = true)] + public class PaperdollDialogFactory : IPaperdollDialogFactory { - _paperdollProvider = paperdollProvider; - _pubFileProvider = pubFileProvider; - _hudControlProvider = hudControlProvider; - _nativeGraphicsManager = nativeGraphicsManager; - _eoDialogButtonService = eoDialogButtonService; - _inventorySpaceValidator = inventorySpaceValidator; - _eoMessageBoxFactory = eoMessageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _sfxPlayer = sfxPlayer; - } + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ISfxPlayer _sfxPlayer; + private readonly IPaperdollProvider _paperdollProvider; + private readonly IPubFileProvider _pubFileProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private IInventoryController _inventoryController; - public PaperdollDialog Create(Character character, bool isMainCharacter) - { - return new PaperdollDialog(_nativeGraphicsManager, - _inventoryController, - _paperdollProvider, - _pubFileProvider, - _hudControlProvider, - _eoDialogButtonService, - _inventorySpaceValidator, - _eoMessageBoxFactory, - _statusLabelSetter, - _sfxPlayer, - character, - isMainCharacter); - } + public PaperdollDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IPaperdollProvider paperdollProvider, + IPubFileProvider pubFileProvider, + IHudControlProvider hudControlProvider, + IEODialogButtonService eoDialogButtonService, + IInventorySpaceValidator inventorySpaceValidator, + IEOMessageBoxFactory eoMessageBoxFactory, + IStatusLabelSetter statusLabelSetter, + ISfxPlayer sfxPlayer) + { + _paperdollProvider = paperdollProvider; + _pubFileProvider = pubFileProvider; + _hudControlProvider = hudControlProvider; + _nativeGraphicsManager = nativeGraphicsManager; + _eoDialogButtonService = eoDialogButtonService; + _inventorySpaceValidator = inventorySpaceValidator; + _eoMessageBoxFactory = eoMessageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _sfxPlayer = sfxPlayer; + } - public void InjectInventoryController(IInventoryController inventoryController) - { - _inventoryController = inventoryController; + public PaperdollDialog Create(Character character, bool isMainCharacter) + { + return new PaperdollDialog(_nativeGraphicsManager, + _inventoryController, + _paperdollProvider, + _pubFileProvider, + _hudControlProvider, + _eoDialogButtonService, + _inventorySpaceValidator, + _eoMessageBoxFactory, + _statusLabelSetter, + _sfxPlayer, + character, + isMainCharacter); + } + + public void InjectInventoryController(IInventoryController inventoryController) + { + _inventoryController = inventoryController; + } } -} -public interface IPaperdollDialogFactory -{ - PaperdollDialog Create(Character character, bool isMainCharacter); + public interface IPaperdollDialogFactory + { + PaperdollDialog Create(Character character, bool isMainCharacter); - void InjectInventoryController(IInventoryController inventoryController); + void InjectInventoryController(IInventoryController inventoryController); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs b/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs index f29f7c6f5..73b9e7d77 100644 --- a/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/QuestDialogFactory.cs @@ -5,45 +5,46 @@ using EOLib.Graphics; using EOLib.IO.Repositories; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class QuestDialogFactory : IQuestDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IQuestActions _questActions; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IQuestDataProvider _questDataProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly IContentProvider _contentProvider; - - public QuestDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IQuestActions questActions, - IEODialogButtonService dialogButtonService, - IQuestDataProvider questDataProvider, - IENFFileProvider enfFileProvider, - IContentProvider contentProvider) + [AutoMappedType] + public class QuestDialogFactory : IQuestDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _questActions = questActions; - _dialogButtonService = dialogButtonService; - _questDataProvider = questDataProvider; - _enfFileProvider = enfFileProvider; - _contentProvider = contentProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IQuestActions _questActions; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IQuestDataProvider _questDataProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly IContentProvider _contentProvider; + + public QuestDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IQuestActions questActions, + IEODialogButtonService dialogButtonService, + IQuestDataProvider questDataProvider, + IENFFileProvider enfFileProvider, + IContentProvider contentProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _questActions = questActions; + _dialogButtonService = dialogButtonService; + _questDataProvider = questDataProvider; + _enfFileProvider = enfFileProvider; + _contentProvider = contentProvider; + } + + public QuestDialog Create() + { + return new QuestDialog(_nativeGraphicsManager, + _questActions, + _dialogButtonService, + _questDataProvider, + _enfFileProvider, + _contentProvider); + } } - public QuestDialog Create() + public interface IQuestDialogFactory { - return new QuestDialog(_nativeGraphicsManager, - _questActions, - _dialogButtonService, - _questDataProvider, - _enfFileProvider, - _contentProvider); + QuestDialog Create(); } -} - -public interface IQuestDialogFactory -{ - QuestDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs b/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs index 215f040d8..18ca65f3a 100644 --- a/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/QuestStatusDialogFactory.cs @@ -5,41 +5,42 @@ using EOLib.Graphics; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class QuestStatusDialogFactory : IQuestStatusDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IQuestDataProvider _questDataProvider; - private readonly ICharacterProvider _characterProvider; - - public QuestStatusDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IQuestDataProvider questDataProvider, - ICharacterProvider characterProvider) + [AutoMappedType] + public class QuestStatusDialogFactory : IQuestStatusDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _localizedStringFinder = localizedStringFinder; - _questDataProvider = questDataProvider; - _characterProvider = characterProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IQuestDataProvider _questDataProvider; + private readonly ICharacterProvider _characterProvider; + + public QuestStatusDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IQuestDataProvider questDataProvider, + ICharacterProvider characterProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _localizedStringFinder = localizedStringFinder; + _questDataProvider = questDataProvider; + _characterProvider = characterProvider; + } + + public QuestStatusDialog Create() + { + return new QuestStatusDialog(_nativeGraphicsManager, + _dialogButtonService, + _localizedStringFinder, + _questDataProvider, + _characterProvider); + } } - public QuestStatusDialog Create() + public interface IQuestStatusDialogFactory { - return new QuestStatusDialog(_nativeGraphicsManager, - _dialogButtonService, - _localizedStringFinder, - _questDataProvider, - _characterProvider); + QuestStatusDialog Create(); } -} - -public interface IQuestStatusDialogFactory -{ - QuestStatusDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs b/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs index 48a52d906..5bf061e6a 100644 --- a/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ScrollingListDialogFactory.cs @@ -2,28 +2,29 @@ using EndlessClient.Dialogs.Services; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class ScrollingListDialogFactory : IScrollingListDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - - public ScrollingListDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService) + [AutoMappedType] + public class ScrollingListDialogFactory : IScrollingListDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + + public ScrollingListDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + } + + public ScrollingListDialog Create(DialogType size) + { + return new ScrollingListDialog(_nativeGraphicsManager, _dialogButtonService, size); + } } - public ScrollingListDialog Create(DialogType size) + public interface IScrollingListDialogFactory { - return new ScrollingListDialog(_nativeGraphicsManager, _dialogButtonService, size); + ScrollingListDialog Create(DialogType size); } -} - -public interface IScrollingListDialogFactory -{ - ScrollingListDialog Create(DialogType size); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs b/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs index 5651ca3e9..548c7a48b 100644 --- a/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/SessionExpDialogFactory.cs @@ -4,45 +4,46 @@ using EOLib.Graphics; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class SessionExpDialogFactory : ISessionExpDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEODialogButtonService _dialogButtonService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ICharacterProvider _characterProvider; - private readonly IExperienceTableProvider _expTableProvider; - private readonly ICharacterSessionProvider _characterSessionProvider; - - public SessionExpDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - ICharacterProvider characterProvider, - IExperienceTableProvider expTableProvider, - ICharacterSessionProvider characterSessionProvider) + [AutoMappedType] + public class SessionExpDialogFactory : ISessionExpDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _dialogButtonService = dialogButtonService; - _localizedStringFinder = localizedStringFinder; - _characterProvider = characterProvider; - _expTableProvider = expTableProvider; - _characterSessionProvider = characterSessionProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEODialogButtonService _dialogButtonService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ICharacterProvider _characterProvider; + private readonly IExperienceTableProvider _expTableProvider; + private readonly ICharacterSessionProvider _characterSessionProvider; + + public SessionExpDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + ICharacterProvider characterProvider, + IExperienceTableProvider expTableProvider, + ICharacterSessionProvider characterSessionProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _dialogButtonService = dialogButtonService; + _localizedStringFinder = localizedStringFinder; + _characterProvider = characterProvider; + _expTableProvider = expTableProvider; + _characterSessionProvider = characterSessionProvider; + } + + public SessionExpDialog Create() + { + return new SessionExpDialog(_nativeGraphicsManager, + _dialogButtonService, + _localizedStringFinder, + _characterProvider, + _expTableProvider, + _characterSessionProvider); + } } - public SessionExpDialog Create() + public interface ISessionExpDialogFactory { - return new SessionExpDialog(_nativeGraphicsManager, - _dialogButtonService, - _localizedStringFinder, - _characterProvider, - _expTableProvider, - _characterSessionProvider); + SessionExpDialog Create(); } -} - -public interface ISessionExpDialogFactory -{ - SessionExpDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs b/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs index 711a382d4..ed7d589d5 100644 --- a/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/ShopDialogFactory.cs @@ -8,69 +8,70 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class ShopDialogFactory : IShopDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IShopActions _shopActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IItemTransferDialogFactory _itemTransferDialogFactory; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IShopDataProvider _shopDataProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - - public ShopDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IShopActions shopActions, - IEOMessageBoxFactory messageBoxFactory, - IItemTransferDialogFactory itemTransferDialogFactory, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IShopDataProvider shopDataProvider, - ICharacterInventoryProvider characterInventoryProvider, - IEIFFileProvider eifFileProvider, - ICharacterProvider characterProvider, - IInventorySpaceValidator inventorySpaceValidator) + [AutoMappedType] + public class ShopDialogFactory : IShopDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _shopActions = shopActions; - _messageBoxFactory = messageBoxFactory; - _itemTransferDialogFactory = itemTransferDialogFactory; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _shopDataProvider = shopDataProvider; - _characterInventoryProvider = characterInventoryProvider; - _eifFileProvider = eifFileProvider; - _characterProvider = characterProvider; - _inventorySpaceValidator = inventorySpaceValidator; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IShopActions _shopActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IItemTransferDialogFactory _itemTransferDialogFactory; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IShopDataProvider _shopDataProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + + public ShopDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IShopActions shopActions, + IEOMessageBoxFactory messageBoxFactory, + IItemTransferDialogFactory itemTransferDialogFactory, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IShopDataProvider shopDataProvider, + ICharacterInventoryProvider characterInventoryProvider, + IEIFFileProvider eifFileProvider, + ICharacterProvider characterProvider, + IInventorySpaceValidator inventorySpaceValidator) + { + _nativeGraphicsManager = nativeGraphicsManager; + _shopActions = shopActions; + _messageBoxFactory = messageBoxFactory; + _itemTransferDialogFactory = itemTransferDialogFactory; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _shopDataProvider = shopDataProvider; + _characterInventoryProvider = characterInventoryProvider; + _eifFileProvider = eifFileProvider; + _characterProvider = characterProvider; + _inventorySpaceValidator = inventorySpaceValidator; + } + + public ShopDialog Create() + { + return new ShopDialog(_nativeGraphicsManager, + _shopActions, + _messageBoxFactory, + _itemTransferDialogFactory, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _shopDataProvider, + _characterInventoryProvider, + _eifFileProvider, + _characterProvider, + _inventorySpaceValidator); + } } - public ShopDialog Create() + public interface IShopDialogFactory { - return new ShopDialog(_nativeGraphicsManager, - _shopActions, - _messageBoxFactory, - _itemTransferDialogFactory, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _shopDataProvider, - _characterInventoryProvider, - _eifFileProvider, - _characterProvider, - _inventorySpaceValidator); + ShopDialog Create(); } -} - -public interface IShopDialogFactory -{ - ShopDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs b/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs index 30e4e722d..e17ff74c8 100644 --- a/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/SkillmasterDialogFactory.cs @@ -8,73 +8,74 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class SkillmasterDialogFactory : ISkillmasterDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ISkillmasterActions _skillmasterActions; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ISkillDataProvider _skillDataProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IPubFileProvider _pubFileProvider; - private readonly IContentProvider _contentProvider; - - public SkillmasterDialogFactory(INativeGraphicsManager nativeGraphicsManager, - ISkillmasterActions skillmasterActions, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - ITextInputDialogFactory textInputDialogFactory, - ISkillDataProvider skillDataProvider, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IPubFileProvider pubFileProvider, - IContentProvider contentProvider) + [AutoMappedType] + public class SkillmasterDialogFactory : ISkillmasterDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _skillmasterActions = skillmasterActions; - _dialogButtonService = dialogButtonService; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _textInputDialogFactory = textInputDialogFactory; - _skillDataProvider = skillDataProvider; - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _pubFileProvider = pubFileProvider; - _contentProvider = contentProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ISkillmasterActions _skillmasterActions; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ISkillDataProvider _skillDataProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IPubFileProvider _pubFileProvider; + private readonly IContentProvider _contentProvider; + + public SkillmasterDialogFactory(INativeGraphicsManager nativeGraphicsManager, + ISkillmasterActions skillmasterActions, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + ITextInputDialogFactory textInputDialogFactory, + ISkillDataProvider skillDataProvider, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IPubFileProvider pubFileProvider, + IContentProvider contentProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _skillmasterActions = skillmasterActions; + _dialogButtonService = dialogButtonService; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _textInputDialogFactory = textInputDialogFactory; + _skillDataProvider = skillDataProvider; + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _pubFileProvider = pubFileProvider; + _contentProvider = contentProvider; + } + + public SkillmasterDialog Create() + { + return new SkillmasterDialog(_nativeGraphicsManager, + _skillmasterActions, + _dialogButtonService, + _dialogIconService, + _localizedStringFinder, + _statusLabelSetter, + _messageBoxFactory, + _textInputDialogFactory, + _skillDataProvider, + _characterProvider, + _characterInventoryProvider, + _pubFileProvider, + _contentProvider); + } } - public SkillmasterDialog Create() + public interface ISkillmasterDialogFactory { - return new SkillmasterDialog(_nativeGraphicsManager, - _skillmasterActions, - _dialogButtonService, - _dialogIconService, - _localizedStringFinder, - _statusLabelSetter, - _messageBoxFactory, - _textInputDialogFactory, - _skillDataProvider, - _characterProvider, - _characterInventoryProvider, - _pubFileProvider, - _contentProvider); + SkillmasterDialog Create(); } -} - -public interface ISkillmasterDialogFactory -{ - SkillmasterDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs b/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs index 4fec511a4..b72776cd5 100644 --- a/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/TextInputDialogFactory.cs @@ -5,44 +5,45 @@ using EndlessClient.HUD.Chat; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class TextInputDialogFactory : ITextInputDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatTextBoxActions _chatTextBoxActions; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IContentProvider _contentProvider; - private readonly ISfxPlayer _sfxPlayer; - - public TextInputDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - IContentProvider contentProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class TextInputDialogFactory : ITextInputDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _chatTextBoxActions = chatTextBoxActions; - _eoDialogButtonService = eoDialogButtonService; - _contentProvider = contentProvider; - _sfxPlayer = sfxPlayer; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatTextBoxActions _chatTextBoxActions; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IContentProvider _contentProvider; + private readonly ISfxPlayer _sfxPlayer; + + public TextInputDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + IContentProvider contentProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _chatTextBoxActions = chatTextBoxActions; + _eoDialogButtonService = eoDialogButtonService; + _contentProvider = contentProvider; + _sfxPlayer = sfxPlayer; + } + + public TextInputDialog Create(string prompt, int maxInputChars = 12) + { + var dlg = new TextInputDialog(_nativeGraphicsManager, + _chatTextBoxActions, + _eoDialogButtonService, + _contentProvider, + prompt, + maxInputChars); + dlg.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + return dlg; + } } - public TextInputDialog Create(string prompt, int maxInputChars = 12) + public interface ITextInputDialogFactory { - var dlg = new TextInputDialog(_nativeGraphicsManager, - _chatTextBoxActions, - _eoDialogButtonService, - _contentProvider, - prompt, - maxInputChars); - dlg.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - return dlg; + TextInputDialog Create(string prompt, int maxInputChars = 12); } -} - -public interface ITextInputDialogFactory -{ - TextInputDialog Create(string prompt, int maxInputChars = 12); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs b/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs index fd1da7ffa..111ddbda3 100644 --- a/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/TextInputMultiDialogFactory.cs @@ -5,49 +5,50 @@ using EndlessClient.HUD.Chat; using EOLib.Graphics; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class TextMultiInputDialogFactory : ITextMultiInputDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatTextBoxActions _chatTextBoxActions; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IContentProvider _contentProvider; - private readonly ISfxPlayer _sfxPlayer; - - public TextMultiInputDialogFactory(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - IContentProvider contentProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class TextMultiInputDialogFactory : ITextMultiInputDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _chatTextBoxActions = chatTextBoxActions; - _eoDialogButtonService = eoDialogButtonService; - _contentProvider = contentProvider; - _sfxPlayer = sfxPlayer; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatTextBoxActions _chatTextBoxActions; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IContentProvider _contentProvider; + private readonly ISfxPlayer _sfxPlayer; + + public TextMultiInputDialogFactory(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + IContentProvider contentProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _chatTextBoxActions = chatTextBoxActions; + _eoDialogButtonService = eoDialogButtonService; + _contentProvider = contentProvider; + _sfxPlayer = sfxPlayer; + } + + public TextMultiInputDialog Create(string title, string prompt, TextMultiInputDialog.DialogSize size, params TextMultiInputDialog.InputInfo[] inputInfo) + { + var dlg = new TextMultiInputDialog(_nativeGraphicsManager, + _chatTextBoxActions, + _eoDialogButtonService, + _contentProvider, + size, + title, + prompt, + inputInfo); + dlg.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + return dlg; + } } - public TextMultiInputDialog Create(string title, string prompt, TextMultiInputDialog.DialogSize size, params TextMultiInputDialog.InputInfo[] inputInfo) + public interface ITextMultiInputDialogFactory { - var dlg = new TextMultiInputDialog(_nativeGraphicsManager, - _chatTextBoxActions, - _eoDialogButtonService, - _contentProvider, - size, - title, - prompt, - inputInfo); - dlg.DialogClosing += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - return dlg; + TextMultiInputDialog Create(string title, + string prompt, + TextMultiInputDialog.DialogSize size, + params TextMultiInputDialog.InputInfo[] inputInfo); } -} - -public interface ITextMultiInputDialogFactory -{ - TextMultiInputDialog Create(string title, - string prompt, - TextMultiInputDialog.DialogSize size, - params TextMultiInputDialog.InputInfo[] inputInfo); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs b/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs index e064f5b0d..bfd49b8b4 100644 --- a/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/TradeDialogFactory.cs @@ -10,69 +10,70 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Dialogs.Factories; - -[AutoMappedType] -public class TradeDialogFactory : ITradeDialogFactory +namespace EndlessClient.Dialogs.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ITradeActions _tradeActions; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEODialogButtonService _dialogButtonService; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly ITradeProvider _tradeProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - private readonly ISfxPlayer _sfxPlayer; - - public TradeDialogFactory(INativeGraphicsManager nativeGraphicsManager, - ITradeActions tradeActions, - ILocalizedStringFinder localizedStringFinder, - IEODialogButtonService dialogButtonService, - IEOMessageBoxFactory messageBoxFactory, - IStatusLabelSetter statusLabelSetter, - IInventorySpaceValidator inventorySpaceValidator, - ITradeProvider tradeProvider, - ICharacterProvider characterProvider, - IEIFFileProvider eifFileProvider, - IMapItemGraphicProvider mapItemGraphicProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class TradeDialogFactory : ITradeDialogFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _tradeActions = tradeActions; - _localizedStringFinder = localizedStringFinder; - _dialogButtonService = dialogButtonService; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _inventorySpaceValidator = inventorySpaceValidator; - _tradeProvider = tradeProvider; - _characterProvider = characterProvider; - _eifFileProvider = eifFileProvider; - _mapItemGraphicProvider = mapItemGraphicProvider; - _sfxPlayer = sfxPlayer; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ITradeActions _tradeActions; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEODialogButtonService _dialogButtonService; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly ITradeProvider _tradeProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IMapItemGraphicProvider _mapItemGraphicProvider; + private readonly ISfxPlayer _sfxPlayer; + + public TradeDialogFactory(INativeGraphicsManager nativeGraphicsManager, + ITradeActions tradeActions, + ILocalizedStringFinder localizedStringFinder, + IEODialogButtonService dialogButtonService, + IEOMessageBoxFactory messageBoxFactory, + IStatusLabelSetter statusLabelSetter, + IInventorySpaceValidator inventorySpaceValidator, + ITradeProvider tradeProvider, + ICharacterProvider characterProvider, + IEIFFileProvider eifFileProvider, + IMapItemGraphicProvider mapItemGraphicProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _tradeActions = tradeActions; + _localizedStringFinder = localizedStringFinder; + _dialogButtonService = dialogButtonService; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _inventorySpaceValidator = inventorySpaceValidator; + _tradeProvider = tradeProvider; + _characterProvider = characterProvider; + _eifFileProvider = eifFileProvider; + _mapItemGraphicProvider = mapItemGraphicProvider; + _sfxPlayer = sfxPlayer; + } + + public TradeDialog Create() + { + return new TradeDialog(_nativeGraphicsManager, + _tradeActions, + _localizedStringFinder, + _dialogButtonService, + _messageBoxFactory, + _statusLabelSetter, + _inventorySpaceValidator, + _tradeProvider, + _characterProvider, + _eifFileProvider, + _mapItemGraphicProvider, + _sfxPlayer); + } } - public TradeDialog Create() + public interface ITradeDialogFactory { - return new TradeDialog(_nativeGraphicsManager, - _tradeActions, - _localizedStringFinder, - _dialogButtonService, - _messageBoxFactory, - _statusLabelSetter, - _inventorySpaceValidator, - _tradeProvider, - _characterProvider, - _eifFileProvider, - _mapItemGraphicProvider, - _sfxPlayer); + TradeDialog Create(); } -} - -public interface ITradeDialogFactory -{ - TradeDialog Create(); } \ No newline at end of file diff --git a/EndlessClient/Dialogs/FriendIgnoreListDialog.cs b/EndlessClient/Dialogs/FriendIgnoreListDialog.cs index c1cbccc8b..ba481f3c8 100644 --- a/EndlessClient/Dialogs/FriendIgnoreListDialog.cs +++ b/EndlessClient/Dialogs/FriendIgnoreListDialog.cs @@ -5,33 +5,34 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Dialogs; - -public class FriendIgnoreListDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private readonly IOnlinePlayerProvider _onlinePlayerProvider; + public class FriendIgnoreListDialog : ScrollingListDialog + { + private readonly IOnlinePlayerProvider _onlinePlayerProvider; - private HashSet _cachedOnlinePlayers; + private HashSet _cachedOnlinePlayers; - public FriendIgnoreListDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IOnlinePlayerProvider onlinePlayerProvider) - : base(nativeGraphicsManager, dialogButtonService, DialogType.FriendIgnore) - { - _onlinePlayerProvider = onlinePlayerProvider; - _cachedOnlinePlayers = new HashSet(); - } + public FriendIgnoreListDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IOnlinePlayerProvider onlinePlayerProvider) + : base(nativeGraphicsManager, dialogButtonService, DialogType.FriendIgnore) + { + _onlinePlayerProvider = onlinePlayerProvider; + _cachedOnlinePlayers = new HashSet(); + } - protected override void OnUpdateControl(GameTime gameTime) - { - if (!_cachedOnlinePlayers.SetEquals(_onlinePlayerProvider.OnlinePlayers)) + protected override void OnUpdateControl(GameTime gameTime) { - _cachedOnlinePlayers = _onlinePlayerProvider.OnlinePlayers.ToHashSet(); + if (!_cachedOnlinePlayers.SetEquals(_onlinePlayerProvider.OnlinePlayers)) + { + _cachedOnlinePlayers = _onlinePlayerProvider.OnlinePlayers.ToHashSet(); - ClearHighlightedText(); - HighlightTextByLabel(_cachedOnlinePlayers.Select(x => x.Name).ToList()); - } + ClearHighlightedText(); + HighlightTextByLabel(_cachedOnlinePlayers.Select(x => x.Name).ToList()); + } - base.OnUpdateControl(gameTime); + base.OnUpdateControl(gameTime); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/GameLoadingDialog.cs b/EndlessClient/Dialogs/GameLoadingDialog.cs index af9b87c4e..67fde1c75 100644 --- a/EndlessClient/Dialogs/GameLoadingDialog.cs +++ b/EndlessClient/Dialogs/GameLoadingDialog.cs @@ -8,128 +8,129 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public class GameLoadingDialog : BaseEODialog +namespace EndlessClient.Dialogs { - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly Texture2D _backgroundSprite; - private readonly IXNALabel _message, _caption; - - private DateTime _lastBackgroundUpdate; - private int _bgSrcIndex; - - public GameLoadingDialog(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - ILocalizedStringFinder localizedStringFinder) - : base(nativeGraphicsManager, gameStateProvider) + public class GameLoadingDialog : BaseEODialog { - _localizedStringFinder = localizedStringFinder; - _backgroundSprite = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 33); + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly Texture2D _backgroundSprite; + private readonly IXNALabel _message, _caption; + + private DateTime _lastBackgroundUpdate; + private int _bgSrcIndex; + + public GameLoadingDialog(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + ILocalizedStringFinder localizedStringFinder) + : base(nativeGraphicsManager, gameStateProvider) + { + _localizedStringFinder = localizedStringFinder; + _backgroundSprite = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 33); - DrawPosition = new Vector2(clientWindowSizeProvider.Width - _backgroundSprite.Width / 4 - 10, - clientWindowSizeProvider.Height - _backgroundSprite.Height - 10); + DrawPosition = new Vector2(clientWindowSizeProvider.Width - _backgroundSprite.Width / 4 - 10, + clientWindowSizeProvider.Height - _backgroundSprite.Height - 10); - SetSize(_backgroundSprite.Width / 4, _backgroundSprite.Height); + SetSize(_backgroundSprite.Width / 4, _backgroundSprite.Height); - _bgSrcIndex = 0; - _lastBackgroundUpdate = DateTime.Now; + _bgSrcIndex = 0; + _lastBackgroundUpdate = DateTime.Now; - _caption = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_PLEASE_WAIT), - ForeColor = ColorConstants.LightYellowText, - DrawPosition = new Vector2(12, 9) - }; - _caption.SetParentControl(this); - - var gen = new Random(); - var messageTextID = (EOResourceID)gen.Next((int)EOResourceID.LOADING_GAME_HINT_FIRST, (int)EOResourceID.LOADING_GAME_HINT_LAST); - var localizedMessage = _localizedStringFinder.GetString(messageTextID); - - _message = new XNALabel(Constants.FontSize08) - { - AutoSize = true, - TextWidth = 175, - ForeColor = ColorConstants.MediumGrayText, - Text = localizedMessage, - DrawPosition = new Vector2(18, 61) - }; - _message.SetParentControl(this); - } + _caption = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_PLEASE_WAIT), + ForeColor = ColorConstants.LightYellowText, + DrawPosition = new Vector2(12, 9) + }; + _caption.SetParentControl(this); + + var gen = new Random(); + var messageTextID = (EOResourceID)gen.Next((int)EOResourceID.LOADING_GAME_HINT_FIRST, (int)EOResourceID.LOADING_GAME_HINT_LAST); + var localizedMessage = _localizedStringFinder.GetString(messageTextID); + + _message = new XNALabel(Constants.FontSize08) + { + AutoSize = true, + TextWidth = 175, + ForeColor = ColorConstants.MediumGrayText, + Text = localizedMessage, + DrawPosition = new Vector2(18, 61) + }; + _message.SetParentControl(this); + } - public override void Initialize() - { - _caption.Initialize(); - _message.Initialize(); + public override void Initialize() + { + _caption.Initialize(); + _message.Initialize(); - base.Initialize(); - } + base.Initialize(); + } - protected override void OnUpdateControl(GameTime gt) - { - if ((int)(DateTime.Now - _lastBackgroundUpdate).TotalMilliseconds > 500) + protected override void OnUpdateControl(GameTime gt) { - _bgSrcIndex = _bgSrcIndex == 3 ? 0 : _bgSrcIndex + 1; - _lastBackgroundUpdate = DateTime.Now; + if ((int)(DateTime.Now - _lastBackgroundUpdate).TotalMilliseconds > 500) + { + _bgSrcIndex = _bgSrcIndex == 3 ? 0 : _bgSrcIndex + 1; + _lastBackgroundUpdate = DateTime.Now; + } + + base.OnUpdateControl(gt); } - base.OnUpdateControl(gt); - } + protected override void OnDrawControl(GameTime gt) + { + _spriteBatch.Begin(); + _spriteBatch.Draw(_backgroundSprite, + DrawAreaWithParentOffset, + new Rectangle(_bgSrcIndex * (_backgroundSprite.Width / 4), 0, _backgroundSprite.Width / 4, _backgroundSprite.Height), + Color.White); + _spriteBatch.End(); + + base.OnDrawControl(gt); + } - protected override void OnDrawControl(GameTime gt) - { - _spriteBatch.Begin(); - _spriteBatch.Draw(_backgroundSprite, - DrawAreaWithParentOffset, - new Rectangle(_bgSrcIndex * (_backgroundSprite.Width / 4), 0, _backgroundSprite.Width / 4, _backgroundSprite.Height), - Color.White); - _spriteBatch.End(); - - base.OnDrawControl(gt); - } + public void SetState(GameLoadingDialogState whichState) + { + switch (whichState) + { + case GameLoadingDialogState.Map: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_MAP); + break; + case GameLoadingDialogState.Item: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_ITEMS); + break; + case GameLoadingDialogState.NPC: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_NPCS); + break; + case GameLoadingDialogState.Spell: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_SKILLS); + break; + case GameLoadingDialogState.Class: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_CLASSES); + break; + case GameLoadingDialogState.LoadingGame: + _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_LOADING_GAME); + break; + default: + throw new ArgumentOutOfRangeException(nameof(whichState), whichState, null); + } + } - public void SetState(GameLoadingDialogState whichState) - { - switch (whichState) + public void CloseDialog() { - case GameLoadingDialogState.Map: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_MAP); - break; - case GameLoadingDialogState.Item: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_ITEMS); - break; - case GameLoadingDialogState.NPC: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_NPCS); - break; - case GameLoadingDialogState.Spell: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_SKILLS); - break; - case GameLoadingDialogState.Class: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_UPDATING_CLASSES); - break; - case GameLoadingDialogState.LoadingGame: - _caption.Text = _localizedStringFinder.GetString(EOResourceID.LOADING_GAME_LOADING_GAME); - break; - default: - throw new ArgumentOutOfRangeException(nameof(whichState), whichState, null); + Close(XNADialogResult.NO_BUTTON_PRESSED); } } - public void CloseDialog() + public enum GameLoadingDialogState { - Close(XNADialogResult.NO_BUTTON_PRESSED); + Map, + Item, + NPC, + Spell, + Class, + LoadingGame } -} - -public enum GameLoadingDialogState -{ - Map, - Item, - NPC, - Spell, - Class, - LoadingGame } \ No newline at end of file diff --git a/EndlessClient/Dialogs/InnkeeperDialog.cs b/EndlessClient/Dialogs/InnkeeperDialog.cs index a1ff42106..22bd4d0cb 100644 --- a/EndlessClient/Dialogs/InnkeeperDialog.cs +++ b/EndlessClient/Dialogs/InnkeeperDialog.cs @@ -13,241 +13,242 @@ using System.Collections.Generic; using XNAControls; -namespace EndlessClient.Dialogs; - -public class InnkeeperDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private enum InnkeeperDialogState + public class InnkeeperDialog : ScrollingListDialog { - // initial menu: Registration and Sleep items - Initial, - // registration menu: sign up and unsubscribe items - Registration, - // sign up text + link - SignUp, - // unsubscribe text + link - Unsubscribe - } - - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ICitizenActions _citizenActions; - private readonly IContentProvider _contentProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly ICitizenDataProvider _citizenDataProvider; - private InnkeeperDialogState _state; - private int _lastVendorId; - - public InnkeeperDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IEOMessageBoxFactory messageBoxFactory, - ITextInputDialogFactory textInputDialogFactory, - ICitizenActions citizenActions, - IContentProvider contentProvider, - IENFFileProvider enfFileProvider, - ICitizenDataProvider citizenDataProvider) - : base(nativeGraphicsManager, dialogButtonService, DialogType.Inn) - { - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _messageBoxFactory = messageBoxFactory; - _textInputDialogFactory = textInputDialogFactory; - _citizenActions = citizenActions; - _contentProvider = contentProvider; - _enfFileProvider = enfFileProvider; - _citizenDataProvider = citizenDataProvider; - - SetState(InnkeeperDialogState.Initial); - - BackAction += (_, _) => + private enum InnkeeperDialogState { - if (_state == InnkeeperDialogState.SignUp || _state == InnkeeperDialogState.Unsubscribe) - SetState(InnkeeperDialogState.Registration); - else if (_state == InnkeeperDialogState.Registration) - SetState(InnkeeperDialogState.Initial); - }; - } + // initial menu: Registration and Sleep items + Initial, + // registration menu: sign up and unsubscribe items + Registration, + // sign up text + link + SignUp, + // unsubscribe text + link + Unsubscribe + } - protected override void OnUpdateControl(GameTime gameTime) - { - if (_citizenDataProvider.BehaviorID.Map(x => x != _lastVendorId).ValueOr(false)) + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ICitizenActions _citizenActions; + private readonly IContentProvider _contentProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly ICitizenDataProvider _citizenDataProvider; + private InnkeeperDialogState _state; + private int _lastVendorId; + + public InnkeeperDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IEOMessageBoxFactory messageBoxFactory, + ITextInputDialogFactory textInputDialogFactory, + ICitizenActions citizenActions, + IContentProvider contentProvider, + IENFFileProvider enfFileProvider, + ICitizenDataProvider citizenDataProvider) + : base(nativeGraphicsManager, dialogButtonService, DialogType.Inn) { - _lastVendorId = _citizenDataProvider.BehaviorID.ValueOr(0); - - _enfFileProvider.ENFFile.SingleOrNone(x => x.Type == NPCType.Inn && x.VendorID == _lastVendorId) - .MatchSome(innkeeperData => Title = innkeeperData.Name); + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _messageBoxFactory = messageBoxFactory; + _textInputDialogFactory = textInputDialogFactory; + _citizenActions = citizenActions; + _contentProvider = contentProvider; + _enfFileProvider = enfFileProvider; + _citizenDataProvider = citizenDataProvider; + + SetState(InnkeeperDialogState.Initial); + + BackAction += (_, _) => + { + if (_state == InnkeeperDialogState.SignUp || _state == InnkeeperDialogState.Unsubscribe) + SetState(InnkeeperDialogState.Registration); + else if (_state == InnkeeperDialogState.Registration) + SetState(InnkeeperDialogState.Initial); + }; } - base.OnUpdateControl(gameTime); - } - - private void SetState(InnkeeperDialogState state) - { - if (state != InnkeeperDialogState.Initial && _state == state) - return; + protected override void OnUpdateControl(GameTime gameTime) + { + if (_citizenDataProvider.BehaviorID.Map(x => x != _lastVendorId).ValueOr(false)) + { + _lastVendorId = _citizenDataProvider.BehaviorID.ValueOr(0); - _state = state; + _enfFileProvider.ENFFile.SingleOrNone(x => x.Type == NPCType.Inn && x.VendorID == _lastVendorId) + .MatchSome(innkeeperData => Title = innkeeperData.Name); + } - ClearItemList(); + base.OnUpdateControl(gameTime); + } - switch (_state) + private void SetState(InnkeeperDialogState state) { - case InnkeeperDialogState.Initial: - { - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.Cancel; + if (state != InnkeeperDialogState.Initial && _state == state) + return; - var registrationItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Registration), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_REGISTRATION_SERVICE), - SubText = _localizedStringFinder.GetString(EOResourceID.INN_CITIZEN_REGISTRATION_SERVICE), - OffsetY = 45, - }; - registrationItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.Registration); - registrationItem.RightClick += (_, _) => SetState(InnkeeperDialogState.Registration); - - var sleepItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.InnSleep), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_SLEEP), - SubText = _localizedStringFinder.GetString(EOResourceID.INN_FULL_HP_RECOVERY), - OffsetY = 45, - }; - sleepItem.LeftClick += (_, _) => _citizenActions.RequestSleep(); - sleepItem.RightClick += (_, _) => _citizenActions.RequestSleep(); - - SetItemList(new List { registrationItem, sleepItem }); - } - break; - case InnkeeperDialogState.Registration: - { - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.BackCancel; - - var signUpItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + _state = state; + + ClearItemList(); + + switch (_state) + { + case InnkeeperDialogState.Initial: { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.SignUp), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_SIGN_UP), - SubText = _localizedStringFinder.GetString(EOResourceID.INN_BECOME_A_CITIZEN), - OffsetY = 45, - }; - signUpItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.SignUp); - signUpItem.RightClick += (_, _) => SetState(InnkeeperDialogState.SignUp); - - var unsubscribeItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.Cancel; + + var registrationItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + { + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Registration), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_REGISTRATION_SERVICE), + SubText = _localizedStringFinder.GetString(EOResourceID.INN_CITIZEN_REGISTRATION_SERVICE), + OffsetY = 45, + }; + registrationItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.Registration); + registrationItem.RightClick += (_, _) => SetState(InnkeeperDialogState.Registration); + + var sleepItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.InnSleep), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_SLEEP), + SubText = _localizedStringFinder.GetString(EOResourceID.INN_FULL_HP_RECOVERY), + OffsetY = 45, + }; + sleepItem.LeftClick += (_, _) => _citizenActions.RequestSleep(); + sleepItem.RightClick += (_, _) => _citizenActions.RequestSleep(); + + SetItemList(new List { registrationItem, sleepItem }); + } + break; + case InnkeeperDialogState.Registration: { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Unsubscribe), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_UNSUBSCRIBE), - SubText = _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_CITIZENSHIP), - OffsetY = 45, - }; - unsubscribeItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.Unsubscribe); - unsubscribeItem.RightClick += (_, _) => SetState(InnkeeperDialogState.Unsubscribe); - - SetItemList(new List { signUpItem, unsubscribeItem }); - } - break; - case InnkeeperDialogState.SignUp: - { - ListItemType = ListDialogItem.ListItemStyle.Small; - Buttons = ScrollingListDialogButtons.BackCancel; - - AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], - insertLineBreaks: true, - new List + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.BackCancel; + + var signUpItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) { - () => + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.SignUp), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_SIGN_UP), + SubText = _localizedStringFinder.GetString(EOResourceID.INN_BECOME_A_CITIZEN), + OffsetY = 45, + }; + signUpItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.SignUp); + signUpItem.RightClick += (_, _) => SetState(InnkeeperDialogState.SignUp); + + var unsubscribeItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Unsubscribe), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.INN_UNSUBSCRIBE), + SubText = _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_CITIZENSHIP), + OffsetY = 45, + }; + unsubscribeItem.LeftClick += (_, _) => SetState(InnkeeperDialogState.Unsubscribe); + unsubscribeItem.RightClick += (_, _) => SetState(InnkeeperDialogState.Unsubscribe); + + SetItemList(new List { signUpItem, unsubscribeItem }); + } + break; + case InnkeeperDialogState.SignUp: + { + ListItemType = ListDialogItem.ListItemStyle.Small; + Buttons = ScrollingListDialogButtons.BackCancel; + + AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], + insertLineBreaks: true, + new List { - if (_citizenDataProvider.CurrentHomeID.HasValue) - { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.INN_YOU_ARE_ALREADY_A_CITIZEN_OF_A_TOWN, EOResourceID.INN_REGISTRATION_SERVICE); - dlg.ShowDialog(); - } - else + () => { - var answers = new List(3); - - Func createDlg = i => _textInputDialogFactory.Create($"{i + 1}. {_citizenDataProvider.Questions[i]}"); - - // we can't suspend the context and await the result of the dialogs because XNAControls isn't that powerful, - // so we have to get the result in the DialogClosing event handler after we know the user is done entering their input - var dlg1 = createDlg(0); - dlg1.DialogClosing += (_, e1) => + if (_citizenDataProvider.CurrentHomeID.HasValue) { - if (e1.Result != XNADialogResult.OK) - return; + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.INN_YOU_ARE_ALREADY_A_CITIZEN_OF_A_TOWN, EOResourceID.INN_REGISTRATION_SERVICE); + dlg.ShowDialog(); + } + else + { + var answers = new List(3); + + Func createDlg = i => _textInputDialogFactory.Create($"{i + 1}. {_citizenDataProvider.Questions[i]}"); - var dlg2 = createDlg(1); - dlg2.DialogClosing += (_, e2) => + // we can't suspend the context and await the result of the dialogs because XNAControls isn't that powerful, + // so we have to get the result in the DialogClosing event handler after we know the user is done entering their input + var dlg1 = createDlg(0); + dlg1.DialogClosing += (_, e1) => { - if (e2.Result != XNADialogResult.OK) + if (e1.Result != XNADialogResult.OK) return; - var dlg3 = createDlg(2); - dlg3.DialogClosing += (_, e3) => + var dlg2 = createDlg(1); + dlg2.DialogClosing += (_, e2) => { - if (e3.Result != XNADialogResult.OK) + if (e2.Result != XNADialogResult.OK) return; - var answers = new List + var dlg3 = createDlg(2); + dlg3.DialogClosing += (_, e3) => { - dlg1.ResponseText, - dlg2.ResponseText, - dlg3.ResponseText + if (e3.Result != XNADialogResult.OK) + return; + + var answers = new List + { + dlg1.ResponseText, + dlg2.ResponseText, + dlg3.ResponseText + }; + + _citizenActions.SignUp(answers); }; - _citizenActions.SignUp(answers); + dlg3.ShowDialog(); }; - dlg3.ShowDialog(); + dlg2.ShowDialog(); }; - dlg2.ShowDialog(); - }; - - dlg1.ShowDialog(); - } + dlg1.ShowDialog(); + } + }, }, - }, - _localizedStringFinder.GetString(EOResourceID.INN_SIGN_UP), - _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_1), - _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_2), - _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_LINK)); - } - break; - case InnkeeperDialogState.Unsubscribe: - { - ListItemType = ListDialogItem.ListItemStyle.Small; - Buttons = ScrollingListDialogButtons.BackCancel; - - AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], - insertLineBreaks: true, - new List - { - () => + _localizedStringFinder.GetString(EOResourceID.INN_SIGN_UP), + _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_1), + _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_2), + _localizedStringFinder.GetString(EOResourceID.INN_BECOME_CITIZEN_TEXT_LINK)); + } + break; + case InnkeeperDialogState.Unsubscribe: + { + ListItemType = ListDialogItem.ListItemStyle.Small; + Buttons = ScrollingListDialogButtons.BackCancel; + + AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], + insertLineBreaks: true, + new List { - _citizenActions.Unsubscribe(); - SetState(InnkeeperDialogState.Registration); + () => + { + _citizenActions.Unsubscribe(); + SetState(InnkeeperDialogState.Registration); + }, }, - }, - _localizedStringFinder.GetString(EOResourceID.INN_UNSUBSCRIBE), - _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_TEXT_1), - _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_TEXT_LINK)); - } - break; + _localizedStringFinder.GetString(EOResourceID.INN_UNSUBSCRIBE), + _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_TEXT_1), + _localizedStringFinder.GetString(EOResourceID.INN_GIVE_UP_TEXT_LINK)); + } + break; + } } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ItemTransferDialog.cs b/EndlessClient/Dialogs/ItemTransferDialog.cs index 169c2528f..1ba819737 100644 --- a/EndlessClient/Dialogs/ItemTransferDialog.cs +++ b/EndlessClient/Dialogs/ItemTransferDialog.cs @@ -10,212 +10,213 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public class ItemTransferDialog : BaseEODialog +namespace EndlessClient.Dialogs { - public enum TransferType + public class ItemTransferDialog : BaseEODialog { - DropItems, - JunkItems, - GiveItems, - TradeItems, - ShopTransfer, - BankTransfer - } + public enum TransferType + { + DropItems, + JunkItems, + GiveItems, + TradeItems, + ShopTransfer, + BankTransfer + } - private readonly Texture2D _backgroundTexture; - private readonly Rectangle _backgroundTextureSource; + private readonly Texture2D _backgroundTexture; + private readonly Rectangle _backgroundTextureSource; - private readonly Rectangle? _titleBarTextureSource; + private readonly Rectangle? _titleBarTextureSource; - private readonly int _totalAmount; + private readonly int _totalAmount; - private readonly IXNALabel _descLabel; - private readonly IXNATextBox _amount; - private readonly IXNAButton _slider, _okButton, _cancelButton; + private readonly IXNALabel _descLabel; + private readonly IXNATextBox _amount; + private readonly IXNAButton _slider, _okButton, _cancelButton; - public int SelectedAmount => int.Parse(_amount.Text); + public int SelectedAmount => int.Parse(_amount.Text); - private bool _sliderDragging; + private bool _sliderDragging; - public ItemTransferDialog(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IContentProvider contentProvider, - string itemName, - TransferType transferType, - int totalAmount, - EOResourceID message) - : base(nativeGraphicsManager, isInGame: true) - { - if (!IsValidMessage(message)) - throw new ArgumentOutOfRangeException(nameof(message), "Use one of the approved messages."); + public ItemTransferDialog(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IContentProvider contentProvider, + string itemName, + TransferType transferType, + int totalAmount, + EOResourceID message) + : base(nativeGraphicsManager, isInGame: true) + { + if (!IsValidMessage(message)) + throw new ArgumentOutOfRangeException(nameof(message), "Use one of the approved messages."); - _backgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); - _backgroundTextureSource = new Rectangle(38, 0, 265, 170); + _backgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); + _backgroundTextureSource = new Rectangle(38, 0, 265, 170); - // set so CenterInGameView works properly (expected BackgroundTexture to be set) - BackgroundTexture = new Texture2D(Game.GraphicsDevice, _backgroundTextureSource.Width, _backgroundTextureSource.Height); + // set so CenterInGameView works properly (expected BackgroundTexture to be set) + BackgroundTexture = new Texture2D(Game.GraphicsDevice, _backgroundTextureSource.Width, _backgroundTextureSource.Height); - SetSize(_backgroundTextureSource.Width, _backgroundTextureSource.Height); - CenterInGameView(); + SetSize(_backgroundTextureSource.Width, _backgroundTextureSource.Height); + CenterInGameView(); - if (transferType != TransferType.DropItems) - { - _titleBarTextureSource = new Rectangle(40, 172 + ((int)transferType - 1) * 24, 240, 22); - } - - _okButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(60, 125), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)) - { - Visible = true - }; - _okButton.OnClick += (s, e) => Close(XNADialogResult.OK); - - _cancelButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(153, 125), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)) - { - Visible = true - }; - _cancelButton.OnClick += (s, e) => Close(XNADialogResult.Cancel); + if (transferType != TransferType.DropItems) + { + _titleBarTextureSource = new Rectangle(40, 172 + ((int)transferType - 1) * 24, 240, 22); + } - _descLabel = new XNALabel(Constants.FontSize10) - { - DrawArea = new Rectangle(20, 42, 231, 33), - ForeColor = ColorConstants.LightGrayDialogMessage, - TextWidth = 200, - Text = $"{localizedStringFinder.GetString(EOResourceID.DIALOG_TRANSFER_HOW_MUCH)} {itemName} {localizedStringFinder.GetString(message)}" - }; + _okButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(60, 125), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)) + { + Visible = true + }; + _okButton.OnClick += (s, e) => Close(XNADialogResult.OK); + + _cancelButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(153, 125), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)) + { + Visible = true + }; + _cancelButton.OnClick += (s, e) => Close(XNADialogResult.Cancel); - _amount = new XNATextBox(new Rectangle(163, 95, 77, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) - { - Visible = true, - Enabled = true, - MaxChars = 8, //max drop/junk at a time will be 99,999,999 - TextColor = ColorConstants.LightBeigeText, - Text = "1", - Selected = true, - }; - _amount.OnTextChanged += AmountTextChanged; - - DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); - - _totalAmount = totalAmount; - - //slider control - var sliderTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 29); - //5th index when 'out', 6th index when 'over' - Rectangle sliderOutSource = new Rectangle(0, 15 * 5, 16, 15); - Rectangle sliderOverSource = new Rectangle(0, 15 * 6, 16, 15); - - //starting coords are 25, 96 - _slider = new XNAButton(sliderTexture, new Vector2(25, 96), sliderOutSource, sliderOverSource); - _slider.OnClickDrag += SliderClickDrag; - } + _descLabel = new XNALabel(Constants.FontSize10) + { + DrawArea = new Rectangle(20, 42, 231, 33), + ForeColor = ColorConstants.LightGrayDialogMessage, + TextWidth = 200, + Text = $"{localizedStringFinder.GetString(EOResourceID.DIALOG_TRANSFER_HOW_MUCH)} {itemName} {localizedStringFinder.GetString(message)}" + }; - public override void Initialize() - { - _okButton.Initialize(); - _okButton.SetParentControl(this); + _amount = new XNATextBox(new Rectangle(163, 95, 77, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) + { + Visible = true, + Enabled = true, + MaxChars = 8, //max drop/junk at a time will be 99,999,999 + TextColor = ColorConstants.LightBeigeText, + Text = "1", + Selected = true, + }; + _amount.OnTextChanged += AmountTextChanged; + + DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); + + _totalAmount = totalAmount; + + //slider control + var sliderTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 29); + //5th index when 'out', 6th index when 'over' + Rectangle sliderOutSource = new Rectangle(0, 15 * 5, 16, 15); + Rectangle sliderOverSource = new Rectangle(0, 15 * 6, 16, 15); + + //starting coords are 25, 96 + _slider = new XNAButton(sliderTexture, new Vector2(25, 96), sliderOutSource, sliderOverSource); + _slider.OnClickDrag += SliderClickDrag; + } - _cancelButton.Initialize(); - _cancelButton.SetParentControl(this); + public override void Initialize() + { + _okButton.Initialize(); + _okButton.SetParentControl(this); - _descLabel.Initialize(); - _descLabel.SetParentControl(this); + _cancelButton.Initialize(); + _cancelButton.SetParentControl(this); - _amount.Initialize(); - _amount.SetParentControl(this); + _descLabel.Initialize(); + _descLabel.SetParentControl(this); - _slider.Initialize(); - _slider.SetParentControl(this); + _amount.Initialize(); + _amount.SetParentControl(this); - base.Initialize(); - } + _slider.Initialize(); + _slider.SetParentControl(this); - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); - _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _backgroundTextureSource, Color.White); + base.Initialize(); + } - if (_titleBarTextureSource != null) + protected override void OnDrawControl(GameTime gameTime) { - _spriteBatch.Draw(_backgroundTexture, DrawPositionWithParentOffset + new Vector2(11, 10), _titleBarTextureSource, Color.White); - } + _spriteBatch.Begin(); + _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _backgroundTextureSource, Color.White); - _spriteBatch.End(); + if (_titleBarTextureSource != null) + { + _spriteBatch.Draw(_backgroundTexture, DrawPositionWithParentOffset + new Vector2(11, 10), _titleBarTextureSource, Color.White); + } - base.OnDrawControl(gameTime); - } + _spriteBatch.End(); - protected override void Dispose(bool disposing) - { - if (disposing) - { - BackgroundTexture.Dispose(); + base.OnDrawControl(gameTime); } - base.Dispose(disposing); - } + protected override void Dispose(bool disposing) + { + if (disposing) + { + BackgroundTexture.Dispose(); + } - private void SliderClickDrag(object sender, MouseEventArgs e) - { - _sliderDragging = true; //ignores updates to slider location during text change + base.Dispose(disposing); + } - //range rectangle is 122, 15 - var sliderArea = new Rectangle(25, 96, 122 - _slider.DrawArea.Width, 15); - var newX = e.DistanceMoved.X + (int)_slider.DrawPosition.X; + private void SliderClickDrag(object sender, MouseEventArgs e) + { + _sliderDragging = true; //ignores updates to slider location during text change - if (newX < sliderArea.X) - newX = sliderArea.X; - else if (newX > sliderArea.Width + sliderArea.X) - newX = sliderArea.Width + sliderArea.X; + //range rectangle is 122, 15 + var sliderArea = new Rectangle(25, 96, 122 - _slider.DrawArea.Width, 15); + var newX = e.DistanceMoved.X + (int)_slider.DrawPosition.X; - _slider.DrawPosition = new Vector2(newX, _slider.DrawPosition.Y); + if (newX < sliderArea.X) + newX = sliderArea.X; + else if (newX > sliderArea.Width + sliderArea.X) + newX = sliderArea.Width + sliderArea.X; - var ratio = (newX - sliderArea.X) / (float)sliderArea.Width; - _amount.Text = ((int)Math.Round(ratio * _totalAmount) + 1).ToString(); + _slider.DrawPosition = new Vector2(newX, _slider.DrawPosition.Y); - _sliderDragging = false; - } + var ratio = (newX - sliderArea.X) / (float)sliderArea.Width; + _amount.Text = ((int)Math.Round(ratio * _totalAmount) + 1).ToString(); - private void AmountTextChanged(object sender, EventArgs e) - { - int amt = 0; - if (_amount.Text != "" && (!int.TryParse(_amount.Text, out amt) || amt > _totalAmount)) - { - amt = _totalAmount; - _amount.Text = $"{_totalAmount}"; - } - else if (_amount.Text != "" && amt < 0) - { - amt = 1; - _amount.Text = $"{amt}"; + _sliderDragging = false; } - if (!_sliderDragging) + private void AmountTextChanged(object sender, EventArgs e) { - if (amt <= 1) + int amt = 0; + if (_amount.Text != "" && (!int.TryParse(_amount.Text, out amt) || amt > _totalAmount)) + { + amt = _totalAmount; + _amount.Text = $"{_totalAmount}"; + } + else if (_amount.Text != "" && amt < 0) { - _slider.DrawPosition = new Vector2(25, 96); + amt = 1; + _amount.Text = $"{amt}"; } - else + + if (!_sliderDragging) { - int xCoord = (int)Math.Round((amt / (double)_totalAmount) * (122 - _slider.DrawArea.Width)); - _slider.DrawPosition = new Vector2(25 + xCoord, 96); + if (amt <= 1) + { + _slider.DrawPosition = new Vector2(25, 96); + } + else + { + int xCoord = (int)Math.Round((amt / (double)_totalAmount) * (122 - _slider.DrawArea.Width)); + _slider.DrawPosition = new Vector2(25 + xCoord, 96); + } } } - } - private static bool IsValidMessage(EOResourceID msg) - { - var name = Enum.GetName(typeof(EOResourceID), msg); - return name.Contains("DIALOG_TRANSFER"); + private static bool IsValidMessage(EOResourceID msg) + { + var name = Enum.GetName(typeof(EOResourceID), msg); + return name.Contains("DIALOG_TRANSFER"); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/JukeboxDialog.cs b/EndlessClient/Dialogs/JukeboxDialog.cs index 95db75c58..f6df54d5a 100644 --- a/EndlessClient/Dialogs/JukeboxDialog.cs +++ b/EndlessClient/Dialogs/JukeboxDialog.cs @@ -13,162 +13,163 @@ using System.Collections.Generic; using XNAControls; -namespace EndlessClient.Dialogs; - -public class JukeboxDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IJukeboxActions _jukeboxActions; - private readonly IJukeboxRepository _jukeboxRepository; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly ISfxPlayer _sfxPlayer; - - private readonly IEDFFile _songNames; - - private ListDialogItem _changeSongItem, _playSongItem; - - private DateTime _openedTime; - - private Option _lastRequestedName; - private int _songIndex; - - public JukeboxDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IDataFileProvider dataFileProvider, - IEOMessageBoxFactory messageBoxFactory, - IJukeboxActions jukeboxActions, - IJukeboxRepository jukeboxRepository, - ICharacterInventoryProvider characterInventoryProvider, - ISfxPlayer sfxPlayer) - : base(nativeGraphicsManager, dialogButtonService, DialogType.Jukebox) + public class JukeboxDialog : ScrollingListDialog { - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _messageBoxFactory = messageBoxFactory; - _jukeboxActions = jukeboxActions; - _jukeboxRepository = jukeboxRepository; - _characterInventoryProvider = characterInventoryProvider; - _sfxPlayer = sfxPlayer; - - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.Cancel; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IJukeboxActions _jukeboxActions; + private readonly IJukeboxRepository _jukeboxRepository; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly ISfxPlayer _sfxPlayer; + + private readonly IEDFFile _songNames; + + private ListDialogItem _changeSongItem, _playSongItem; + + private DateTime _openedTime; + + private Option _lastRequestedName; + private int _songIndex; + + public JukeboxDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IDataFileProvider dataFileProvider, + IEOMessageBoxFactory messageBoxFactory, + IJukeboxActions jukeboxActions, + IJukeboxRepository jukeboxRepository, + ICharacterInventoryProvider characterInventoryProvider, + ISfxPlayer sfxPlayer) + : base(nativeGraphicsManager, dialogButtonService, DialogType.Jukebox) + { + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _messageBoxFactory = messageBoxFactory; + _jukeboxActions = jukeboxActions; + _jukeboxRepository = jukeboxRepository; + _characterInventoryProvider = characterInventoryProvider; + _sfxPlayer = sfxPlayer; - _songNames = dataFileProvider.DataFiles[DataFiles.JukeBoxSongs]; - _openedTime = DateTime.Now; + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.Cancel; - Title = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_IS_READY); - } + _songNames = dataFileProvider.DataFiles[DataFiles.JukeBoxSongs]; + _openedTime = DateTime.Now; - public override void Initialize() - { - _changeSongItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.JukeboxBrowse), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_BROWSE_THROUGH_SONGS), - SubText = FormatSubtitle(_songNames.Data[_songIndex]), - ShowIconBackGround = false, - OffsetY = 60, - }; - _changeSongItem.LeftClick += ChangeSongItem_Click; - - _playSongItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.JukeboxPlay), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_PLAY_SONG), - SubText = FormatSubtitle("25 gold"), - ShowIconBackGround = false, - OffsetY = 60, - }; - _playSongItem.LeftClick += PlaySongItem_Click; - - SetItemList(new List { _changeSongItem, _playSongItem }); - - base.Initialize(); - } + Title = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_IS_READY); + } - public override void Update(GameTime gameTime) - { - if ((DateTime.Now - _openedTime).TotalSeconds >= 95) + public override void Initialize() { - _jukeboxRepository.PlayingRequestName = Option.None(); - _openedTime = DateTime.Now.AddMinutes(100); + _changeSongItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + { + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.JukeboxBrowse), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_BROWSE_THROUGH_SONGS), + SubText = FormatSubtitle(_songNames.Data[_songIndex]), + ShowIconBackGround = false, + OffsetY = 60, + }; + _changeSongItem.LeftClick += ChangeSongItem_Click; + + _playSongItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.JukeboxPlay), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_PLAY_SONG), + SubText = FormatSubtitle("25 gold"), + ShowIconBackGround = false, + OffsetY = 60, + }; + _playSongItem.LeftClick += PlaySongItem_Click; + + SetItemList(new List { _changeSongItem, _playSongItem }); + + base.Initialize(); } - _jukeboxRepository.PlayingRequestName.Match( - requestedName => + public override void Update(GameTime gameTime) + { + if ((DateTime.Now - _openedTime).TotalSeconds >= 95) { - if (_lastRequestedName.Map(x => !x.Equals(requestedName)).ValueOr(true)) - { - _lastRequestedName = Option.Some(requestedName); - - var titleString = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_PLAYING_REQUEST); - if (!string.IsNullOrWhiteSpace(requestedName)) - titleString += $" ({requestedName})"; + _jukeboxRepository.PlayingRequestName = Option.None(); + _openedTime = DateTime.Now.AddMinutes(100); + } - Title = titleString; - } - }, - () => - { - if (_lastRequestedName.HasValue) + _jukeboxRepository.PlayingRequestName.Match( + requestedName => { - _lastRequestedName = Option.None(); - Title = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_IS_READY); - } - }); - - base.Update(gameTime); - } - - private void ChangeSongItem_Click(object sender, MouseEventArgs e) - { - _songIndex = (_songIndex + 1) % _songNames.Data.Count; - _changeSongItem.SubText = FormatSubtitle(_songNames.Data[_songIndex]); - } - - private void PlaySongItem_Click(object sender, MouseEventArgs e) - { - if (_jukeboxRepository.PlayingRequestName.HasValue) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.JUKEBOX_REQUESTED_RECENTLY); - dlg.ShowDialog(); - return; + if (_lastRequestedName.Map(x => !x.Equals(requestedName)).ValueOr(true)) + { + _lastRequestedName = Option.Some(requestedName); + + var titleString = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_PLAYING_REQUEST); + if (!string.IsNullOrWhiteSpace(requestedName)) + titleString += $" ({requestedName})"; + + Title = titleString; + } + }, + () => + { + if (_lastRequestedName.HasValue) + { + _lastRequestedName = Option.None(); + Title = _localizedStringFinder.GetString(EOResourceID.JUKEBOX_IS_READY); + } + }); + + base.Update(gameTime); } - if (_characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1).Map(x => x.Amount < 25).ValueOr(true)) + private void ChangeSongItem_Click(object sender, MouseEventArgs e) { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, " gold"); - dlg.ShowDialog(); - return; + _songIndex = (_songIndex + 1) % _songNames.Data.Count; + _changeSongItem.SubText = FormatSubtitle(_songNames.Data[_songIndex]); } - var confirmDlg = _messageBoxFactory.CreateMessageBox( - $"{_localizedStringFinder.GetString(EOResourceID.JUKEBOX_REQUEST_SONG_FOR)} 25 gold?", - _localizedStringFinder.GetString(EOResourceID.JUKEBOX_REQUEST_SONG), - EODialogButtons.OkCancel); - - confirmDlg.DialogClosing += (_, e) => + private void PlaySongItem_Click(object sender, MouseEventArgs e) { - if (e.Result == XNADialogResult.OK) + if (_jukeboxRepository.PlayingRequestName.HasValue) { - _jukeboxActions.RequestSong(_songIndex); - _sfxPlayer.PlaySfx(SoundEffectID.BuySell); + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.JUKEBOX_REQUESTED_RECENTLY); + dlg.ShowDialog(); + return; + } - Close(XNADialogResult.NO_BUTTON_PRESSED); + if (_characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1).Map(x => x.Amount < 25).ValueOr(true)) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, " gold"); + dlg.ShowDialog(); + return; } - }; - confirmDlg.ShowDialog(); - } + var confirmDlg = _messageBoxFactory.CreateMessageBox( + $"{_localizedStringFinder.GetString(EOResourceID.JUKEBOX_REQUEST_SONG_FOR)} 25 gold?", + _localizedStringFinder.GetString(EOResourceID.JUKEBOX_REQUEST_SONG), + EODialogButtons.OkCancel); - private string FormatSubtitle(string additionalText) - { - return _localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT) + " : " + additionalText; + confirmDlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + { + _jukeboxActions.RequestSong(_songIndex); + _sfxPlayer.PlaySfx(SoundEffectID.BuySell); + + Close(XNADialogResult.NO_BUTTON_PRESSED); + } + }; + + confirmDlg.ShowDialog(); + } + + private string FormatSubtitle(string additionalText) + { + return _localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_CURRENT) + " : " + additionalText; + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/LawDialog.cs b/EndlessClient/Dialogs/LawDialog.cs index 825efd9c4..1a8a8f950 100644 --- a/EndlessClient/Dialogs/LawDialog.cs +++ b/EndlessClient/Dialogs/LawDialog.cs @@ -14,184 +14,185 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs; - -public class LawDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private enum LawDialogState - { - // initial menu - Initial, - // registration menu: marriage/divorce items - Registration, - Marriage, - Divorce, - } - - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ILawActions _lawActions; - private readonly IContentProvider _contentProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IENFFileProvider _enfFileProvider; - - private LawDialogState _state; - - public LawDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - ITextInputDialogFactory textInputDialogFactory, - ILawActions lawActions, - IContentProvider contentProvider, - ICurrentMapStateProvider currentMapStateProvider, - IENFFileProvider enfFileProvider) - : base(nativeGraphicsManager, dialogButtonService, DialogType.Law) + public class LawDialog : ScrollingListDialog { - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _textInputDialogFactory = textInputDialogFactory; - _lawActions = lawActions; - _contentProvider = contentProvider; - _currentMapStateProvider = currentMapStateProvider; - _enfFileProvider = enfFileProvider; - - SetState(LawDialogState.Initial); - - BackAction += (_, _) => + private enum LawDialogState { - if (_state == LawDialogState.Marriage || _state == LawDialogState.Divorce) - SetState(LawDialogState.Registration); - else if (_state == LawDialogState.Registration) - SetState(LawDialogState.Initial); - }; - - _currentMapStateProvider.NPCs - .Select(x => _enfFileProvider.ENFFile[x.ID]) - .SingleOrNone(x => x.Type == NPCType.Law) - .MatchSome(x => Title = x.Name); - } + // initial menu + Initial, + // registration menu: marriage/divorce items + Registration, + Marriage, + Divorce, + } - private void SetState(LawDialogState state) - { - if (state != LawDialogState.Initial && _state == state) - return; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ILawActions _lawActions; + private readonly IContentProvider _contentProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IENFFileProvider _enfFileProvider; + + private LawDialogState _state; + + public LawDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + ITextInputDialogFactory textInputDialogFactory, + ILawActions lawActions, + IContentProvider contentProvider, + ICurrentMapStateProvider currentMapStateProvider, + IENFFileProvider enfFileProvider) + : base(nativeGraphicsManager, dialogButtonService, DialogType.Law) + { + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _textInputDialogFactory = textInputDialogFactory; + _lawActions = lawActions; + _contentProvider = contentProvider; + _currentMapStateProvider = currentMapStateProvider; + _enfFileProvider = enfFileProvider; + + SetState(LawDialogState.Initial); + + BackAction += (_, _) => + { + if (_state == LawDialogState.Marriage || _state == LawDialogState.Divorce) + SetState(LawDialogState.Registration); + else if (_state == LawDialogState.Registration) + SetState(LawDialogState.Initial); + }; + + _currentMapStateProvider.NPCs + .Select(x => _enfFileProvider.ENFFile[x.ID]) + .SingleOrNone(x => x.Type == NPCType.Law) + .MatchSome(x => Title = x.Name); + } - _state = state; + private void SetState(LawDialogState state) + { + if (state != LawDialogState.Initial && _state == state) + return; - ClearItemList(); + _state = state; - switch (_state) - { - case LawDialogState.Initial: - { - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.Cancel; + ClearItemList(); - var registrationItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + switch (_state) + { + case LawDialogState.Initial: { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Registration), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REGISTRATION_SERVICE), - SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_MARRIAGE_OR_DIVORCE), - OffsetY = 45, - }; - registrationItem.LeftClick += (_, _) => SetState(LawDialogState.Registration); - registrationItem.RightClick += (_, _) => SetState(LawDialogState.Registration); - - AddItemToList(registrationItem, sortList: false); - } - break; - case LawDialogState.Registration: - { - ListItemType = ListDialogItem.ListItemStyle.Large; - Buttons = ScrollingListDialogButtons.BackCancel; - - var marriageItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.SignUp), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_MARRIAGE), - SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_WEDDING_APPROVAL), - OffsetY = 45, - }; - marriageItem.LeftClick += (_, _) => SetState(LawDialogState.Marriage); - marriageItem.RightClick += (_, _) => SetState(LawDialogState.Marriage); - - var divorceItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.Cancel; + + var registrationItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + { + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Registration), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REGISTRATION_SERVICE), + SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_MARRIAGE_OR_DIVORCE), + OffsetY = 45, + }; + registrationItem.LeftClick += (_, _) => SetState(LawDialogState.Registration); + registrationItem.RightClick += (_, _) => SetState(LawDialogState.Registration); + + AddItemToList(registrationItem, sortList: false); + } + break; + case LawDialogState.Registration: { - ShowIconBackGround = false, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Unsubscribe), - PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE), - SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_BREAK_UP), - OffsetY = 45, - }; - divorceItem.LeftClick += (_, _) => SetState(LawDialogState.Divorce); - divorceItem.RightClick += (_, _) => SetState(LawDialogState.Divorce); - - SetItemList(new List { marriageItem, divorceItem }); - } - break; - case LawDialogState.Marriage: - { - ListItemType = ListDialogItem.ListItemStyle.Small; - Buttons = ScrollingListDialogButtons.BackCancel; - - AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], - insertLineBreaks: true, - new List + ListItemType = ListDialogItem.ListItemStyle.Large; + Buttons = ScrollingListDialogButtons.BackCancel; + + var marriageItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) + { + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.SignUp), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_MARRIAGE), + SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_WEDDING_APPROVAL), + OffsetY = 45, + }; + marriageItem.LeftClick += (_, _) => SetState(LawDialogState.Marriage); + marriageItem.RightClick += (_, _) => SetState(LawDialogState.Marriage); + + var divorceItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) { - () => + ShowIconBackGround = false, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Unsubscribe), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE), + SubText = _localizedStringFinder.GetString(EOResourceID.WEDDING_BREAK_UP), + OffsetY = 45, + }; + divorceItem.LeftClick += (_, _) => SetState(LawDialogState.Divorce); + divorceItem.RightClick += (_, _) => SetState(LawDialogState.Divorce); + + SetItemList(new List { marriageItem, divorceItem }); + } + break; + case LawDialogState.Marriage: + { + ListItemType = ListDialogItem.ListItemStyle.Small; + Buttons = ScrollingListDialogButtons.BackCancel; + + AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], + insertLineBreaks: true, + new List { - var dlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PROMPT_ENTER_NAME_MARRY)); - dlg.DialogClosing += (_, e) => + () => { - if (e.Result != XNADialogResult.OK) - return; - - _lawActions.RequestMarriage(dlg.ResponseText); - }; - dlg.ShowDialog(); + var dlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PROMPT_ENTER_NAME_MARRY)); + dlg.DialogClosing += (_, e) => + { + if (e.Result != XNADialogResult.OK) + return; + + _lawActions.RequestMarriage(dlg.ResponseText); + }; + dlg.ShowDialog(); + }, }, - }, - _localizedStringFinder.GetString(EOResourceID.WEDDING_MARRIAGE), - _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_1), - _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_2), - _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_LINK)); - } - break; - case LawDialogState.Divorce: - { - ListItemType = ListDialogItem.ListItemStyle.Small; - Buttons = ScrollingListDialogButtons.BackCancel; - - AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], - insertLineBreaks: true, - new List - { - () => + _localizedStringFinder.GetString(EOResourceID.WEDDING_MARRIAGE), + _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_1), + _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_2), + _localizedStringFinder.GetString(EOResourceID.WEDDING_REQUEST_TEXT_LINK)); + } + break; + case LawDialogState.Divorce: + { + ListItemType = ListDialogItem.ListItemStyle.Small; + Buttons = ScrollingListDialogButtons.BackCancel; + + AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], + insertLineBreaks: true, + new List { - var dlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PROMPT_ENTER_NAME_DIVORCE)); - dlg.DialogClosing += (_, e) => + () => { - if (e.Result != XNADialogResult.OK) - return; - - _lawActions.RequestDivorce(dlg.ResponseText); - }; - dlg.ShowDialog(); + var dlg = _textInputDialogFactory.Create(_localizedStringFinder.GetString(EOResourceID.WEDDING_PROMPT_ENTER_NAME_DIVORCE)); + dlg.DialogClosing += (_, e) => + { + if (e.Result != XNADialogResult.OK) + return; + + _lawActions.RequestDivorce(dlg.ResponseText); + }; + dlg.ShowDialog(); + }, }, - }, - _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE), - _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_1), - _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_2), - _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_LINK)); - } - break; + _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE), + _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_1), + _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_2), + _localizedStringFinder.GetString(EOResourceID.WEDDING_DIVORCE_TEXT_LINK)); + } + break; + } } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ListDialogItem.cs b/EndlessClient/Dialogs/ListDialogItem.cs index 6fb3858df..ffa4f2e5d 100644 --- a/EndlessClient/Dialogs/ListDialogItem.cs +++ b/EndlessClient/Dialogs/ListDialogItem.cs @@ -7,293 +7,294 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public class ListDialogItem : XNAControl +namespace EndlessClient.Dialogs { - public enum ListItemStyle + public class ListDialogItem : XNAControl { - Small, - SmallKeyValue, - Large - } + public enum ListItemStyle + { + Small, + SmallKeyValue, + Large + } - private int _index; - private int _xOffset, _yOffset; + private int _index; + private int _xOffset, _yOffset; - protected IXNALabel _primaryText; - protected IXNALabel _subText; + protected IXNALabel _primaryText; + protected IXNALabel _subText; - private readonly Texture2D _gfxPadThing; - private readonly Texture2D _backgroundColor; + private readonly Texture2D _gfxPadThing; + private readonly Texture2D _backgroundColor; - private readonly BaseEODialog _parentDialog; + private readonly BaseEODialog _parentDialog; - private bool _drawBackground; + private bool _drawBackground; - public int Index - { - get { return _index; } - set + public int Index { - _index = value; - DrawPosition = new Vector2(DrawPosition.X, OffsetY + (_index * (Style == ListItemStyle.Large ? 36 : 16))); + get { return _index; } + set + { + _index = value; + DrawPosition = new Vector2(DrawPosition.X, OffsetY + (_index * (Style == ListItemStyle.Large ? 36 : 16))); + } } - } - public int OffsetX - { - get + public int OffsetX { - return _xOffset; - } - set - { - int oldOff = _xOffset; - _xOffset = value; - DrawPosition += new Vector2(_xOffset - oldOff, 0); + get + { + return _xOffset; + } + set + { + int oldOff = _xOffset; + _xOffset = value; + DrawPosition += new Vector2(_xOffset - oldOff, 0); + } } - } - public int OffsetY - { - get - { - return _yOffset; - } - set + public int OffsetY { - int oldOff = _yOffset; - _yOffset = value; - DrawPosition += new Vector2(0, _yOffset - oldOff); + get + { + return _yOffset; + } + set + { + int oldOff = _yOffset; + _yOffset = value; + DrawPosition += new Vector2(0, _yOffset - oldOff); + } } - } - public ListItemStyle Style { get; set; } + public ListItemStyle Style { get; set; } - public string PrimaryText - { - get { return _primaryText.Text; } - set + public string PrimaryText { - _primaryText.Text = value; - _primaryText.ResizeBasedOnText(); + get { return _primaryText.Text; } + set + { + _primaryText.Text = value; + _primaryText.ResizeBasedOnText(); + } } - } - public string SubText - { - get { return _subText.Text; } - set + public string SubText { - _subText.Text = value; - if (Style != ListItemStyle.SmallKeyValue) - _subText.ResizeBasedOnText(); + get { return _subText.Text; } + set + { + _subText.Text = value; + if (Style != ListItemStyle.SmallKeyValue) + _subText.ResizeBasedOnText(); + } } - } - public Texture2D IconGraphic { get; set; } + public Texture2D IconGraphic { get; set; } - public Rectangle? IconGraphicSource { get; set; } + public Rectangle? IconGraphicSource { get; set; } - public bool ShowIconBackGround { get; set; } + public bool ShowIconBackGround { get; set; } - public bool ShowSubtext - { - get => _subText.Visible; - set => ((XNAControl)_subText).Visible = value; - } + public bool ShowSubtext + { + get => _subText.Visible; + set => ((XNAControl)_subText).Visible = value; + } - public bool UnderlineLinks { get; set; } = true; + public bool UnderlineLinks { get; set; } = true; - public object Data { get; set; } + public object Data { get; set; } - public event EventHandler RightClick; - public event EventHandler LeftClick; + public event EventHandler RightClick; + public event EventHandler LeftClick; - public ListDialogItem(BaseEODialog parent, ListItemStyle style, int listIndex = -1) - { - _parentDialog = parent; + public ListDialogItem(BaseEODialog parent, ListItemStyle style, int listIndex = -1) + { + _parentDialog = parent; - DrawPosition += new Vector2(17, 0); + DrawPosition += new Vector2(17, 0); - Style = style; - if (listIndex >= 0) - Index = listIndex; + Style = style; + if (listIndex >= 0) + Index = listIndex; - SetSize(232, Style == ListItemStyle.Large ? 36 : 13); + SetSize(232, Style == ListItemStyle.Large ? 36 : 13); - int colorFactor = Style == ListItemStyle.Large ? 0xc8 : 0xb4; + int colorFactor = Style == ListItemStyle.Large ? 0xc8 : 0xb4; - _primaryText = new XNALabel(Constants.FontSize08pt5) - { - AutoSize = false, - BackColor = Color.Transparent, - ForeColor = Color.FromNonPremultiplied(colorFactor, colorFactor, colorFactor, 0xff), - DrawPosition = Style == ListItemStyle.Large ? new Vector2(56, 5) : new Vector2(2, 0), - TextAlign = LabelAlignment.TopLeft, - Text = " " - }; - _primaryText.ResizeBasedOnText(); - _primaryText.SetParentControl(this); - _primaryText.Initialize(); - - if (Style == ListItemStyle.SmallKeyValue) - { - _subText = new XNALabel(Constants.FontSize08pt5) + _primaryText = new XNALabel(Constants.FontSize08pt5) { - BackColor = _primaryText.BackColor, - ForeColor = _primaryText.ForeColor, - DrawArea = new Rectangle(2, 0, 225, 13), - TextAlign = LabelAlignment.Right, - Text = " ", - Visible = true + AutoSize = false, + BackColor = Color.Transparent, + ForeColor = Color.FromNonPremultiplied(colorFactor, colorFactor, colorFactor, 0xff), + DrawPosition = Style == ListItemStyle.Large ? new Vector2(56, 5) : new Vector2(2, 0), + TextAlign = LabelAlignment.TopLeft, + Text = " " }; - } - else - { - _subText = new XNALabel(Constants.FontSize08pt5) + _primaryText.ResizeBasedOnText(); + _primaryText.SetParentControl(this); + _primaryText.Initialize(); + + if (Style == ListItemStyle.SmallKeyValue) { - AutoSize = true, - BackColor = _primaryText.BackColor, - ForeColor = _primaryText.ForeColor, - DrawPosition = Style == ListItemStyle.Large ? new Vector2(56, 20) : new Vector2(100, 0), - Text = " ", - Visible = Style == ListItemStyle.Large - }; - _subText.ResizeBasedOnText(); - } - _subText.SetParentControl(this); - _subText.Initialize(); + _subText = new XNALabel(Constants.FontSize08pt5) + { + BackColor = _primaryText.BackColor, + ForeColor = _primaryText.ForeColor, + DrawArea = new Rectangle(2, 0, 225, 13), + TextAlign = LabelAlignment.Right, + Text = " ", + Visible = true + }; + } + else + { + _subText = new XNALabel(Constants.FontSize08pt5) + { + AutoSize = true, + BackColor = _primaryText.BackColor, + ForeColor = _primaryText.ForeColor, + DrawPosition = Style == ListItemStyle.Large ? new Vector2(56, 20) : new Vector2(100, 0), + Text = " ", + Visible = Style == ListItemStyle.Large + }; + _subText.ResizeBasedOnText(); + } + _subText.SetParentControl(this); + _subText.Initialize(); - _gfxPadThing = parent.GraphicsManager.TextureFromResource(GFXTypes.MapTiles, 0, true); - ShowIconBackGround = Style == ListItemStyle.Large; + _gfxPadThing = parent.GraphicsManager.TextureFromResource(GFXTypes.MapTiles, 0, true); + ShowIconBackGround = Style == ListItemStyle.Large; - _backgroundColor = new Texture2D(Game.GraphicsDevice, 1, 1); - _backgroundColor.SetData(new[] { Color.White }); + _backgroundColor = new Texture2D(Game.GraphicsDevice, 1, 1); + _backgroundColor.SetData(new[] { Color.White }); - SetParentControl(parent); + SetParentControl(parent); - OnMouseEnter += (_, _) => _drawBackground = true; - OnMouseLeave += (_, _) => _drawBackground = false; + OnMouseEnter += (_, _) => _drawBackground = true; + OnMouseLeave += (_, _) => _drawBackground = false; - OffsetY = Style == ListItemStyle.Large ? 25 : 45; - } + OffsetY = Style == ListItemStyle.Large ? 25 : 45; + } - public void SetPrimaryClickAction(EventHandler onClickAction) - { - var oldText = _primaryText; - _primaryText = new XNAHyperLink(Constants.FontSize08pt5) + public void SetPrimaryClickAction(EventHandler onClickAction) { - AutoSize = false, - BackColor = oldText.BackColor, - DrawArea = oldText.DrawArea, - ForeColor = oldText.ForeColor, - MouseOverColor = oldText.ForeColor, - Text = oldText.Text, - Underline = UnderlineLinks - }; - - ((XNAHyperLink)_primaryText).OnClick += onClickAction; + var oldText = _primaryText; + _primaryText = new XNAHyperLink(Constants.FontSize08pt5) + { + AutoSize = false, + BackColor = oldText.BackColor, + DrawArea = oldText.DrawArea, + ForeColor = oldText.ForeColor, + MouseOverColor = oldText.ForeColor, + Text = oldText.Text, + Underline = UnderlineLinks + }; - _primaryText.SetParentControl(this); - _primaryText.Initialize(); - _primaryText.ResizeBasedOnText(); + ((XNAHyperLink)_primaryText).OnClick += onClickAction; - oldText.Dispose(); + _primaryText.SetParentControl(this); + _primaryText.Initialize(); + _primaryText.ResizeBasedOnText(); - if (Style == ListItemStyle.Small || Style == ListItemStyle.SmallKeyValue) - LeftClick += onClickAction; - } + oldText.Dispose(); - public void SetSubtextClickAction(EventHandler onClickAction) - { - if (Style == ListItemStyle.Small || Style == ListItemStyle.SmallKeyValue) - throw new InvalidOperationException("Unable to set subtext click action when style is Small"); + if (Style == ListItemStyle.Small || Style == ListItemStyle.SmallKeyValue) + LeftClick += onClickAction; + } - var oldText = _subText; - _subText = new XNAHyperLink(Constants.FontSize08pt5) + public void SetSubtextClickAction(EventHandler onClickAction) { - AutoSize = false, - BackColor = oldText.BackColor, - DrawArea = oldText.DrawArea, - ForeColor = oldText.ForeColor, - MouseOverColor = oldText.ForeColor, - Text = oldText.Text, - Underline = UnderlineLinks - }; - - ((XNAHyperLink)_subText).OnClick += onClickAction; - - _subText.SetParentControl(this); - _subText.Initialize(); - _subText.ResizeBasedOnText(); - - oldText.Dispose(); - } + if (Style == ListItemStyle.Small || Style == ListItemStyle.SmallKeyValue) + throw new InvalidOperationException("Unable to set subtext click action when style is Small"); - public void Highlight() - { - _primaryText.ForeColor = Color.FromNonPremultiplied(0xf0, 0xf0, 0xf0, 0xff); - } + var oldText = _subText; + _subText = new XNAHyperLink(Constants.FontSize08pt5) + { + AutoSize = false, + BackColor = oldText.BackColor, + DrawArea = oldText.DrawArea, + ForeColor = oldText.ForeColor, + MouseOverColor = oldText.ForeColor, + Text = oldText.Text, + Underline = UnderlineLinks + }; - public void ClearHighlight() - { - int colorFactor = Style == ListItemStyle.Large ? 0xc8 : 0xb4; - _primaryText.ForeColor = Color.FromNonPremultiplied(colorFactor, colorFactor, colorFactor, 0xff); - } + ((XNAHyperLink)_subText).OnClick += onClickAction; - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + _subText.SetParentControl(this); + _subText.Initialize(); + _subText.ResizeBasedOnText(); - _spriteBatch.Begin(); - if (_drawBackground) + oldText.Dispose(); + } + + public void Highlight() + { + _primaryText.ForeColor = Color.FromNonPremultiplied(0xf0, 0xf0, 0xf0, 0xff); + } + + public void ClearHighlight() { - _spriteBatch.Draw(_backgroundColor, DrawAreaWithParentOffset, Color.FromNonPremultiplied(255, 255, 255, 16)); + int colorFactor = Style == ListItemStyle.Large ? 0xc8 : 0xb4; + _primaryText.ForeColor = Color.FromNonPremultiplied(colorFactor, colorFactor, colorFactor, 0xff); } - if (Style == ListItemStyle.Large) + protected override void OnDrawControl(GameTime gameTime) { - if (ShowIconBackGround) + base.OnDrawControl(gameTime); + + _spriteBatch.Begin(); + if (_drawBackground) { - _spriteBatch.Draw(_gfxPadThing, DrawPositionWithParentOffset + GetCoordsFromGraphic(_gfxPadThing.Bounds), Color.White); + _spriteBatch.Draw(_backgroundColor, DrawAreaWithParentOffset, Color.FromNonPremultiplied(255, 255, 255, 16)); } - if (IconGraphic != null) + if (Style == ListItemStyle.Large) { - var graphicOffset = IconGraphicSource.HasValue ? GetCoordsFromGraphic(IconGraphicSource.Value) : GetCoordsFromGraphic(IconGraphic.Bounds); - _spriteBatch.Draw(IconGraphic, DrawPositionWithParentOffset + graphicOffset, IconGraphicSource, Color.White); + if (ShowIconBackGround) + { + _spriteBatch.Draw(_gfxPadThing, DrawPositionWithParentOffset + GetCoordsFromGraphic(_gfxPadThing.Bounds), Color.White); + } + + if (IconGraphic != null) + { + var graphicOffset = IconGraphicSource.HasValue ? GetCoordsFromGraphic(IconGraphicSource.Value) : GetCoordsFromGraphic(IconGraphic.Bounds); + _spriteBatch.Draw(IconGraphic, DrawPositionWithParentOffset + graphicOffset, IconGraphicSource, Color.White); + } } - } - _spriteBatch.End(); - } + _spriteBatch.End(); + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (eventArgs.Button == MouseButton.Left) + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) { - LeftClick?.Invoke(this, eventArgs); + if (eventArgs.Button == MouseButton.Left) + { + LeftClick?.Invoke(this, eventArgs); + } + else if (eventArgs.Button == MouseButton.Right) + { + RightClick?.Invoke(this, eventArgs); + } + + return true; } - else if (eventArgs.Button == MouseButton.Right) + + private static Vector2 GetCoordsFromGraphic(Rectangle sourceTextureArea) { - RightClick?.Invoke(this, eventArgs); + return new Vector2((float)Math.Round((56 - sourceTextureArea.Width) / 2f), (float)Math.Round((36 - sourceTextureArea.Height) / 2f)); } - return true; - } - - private static Vector2 GetCoordsFromGraphic(Rectangle sourceTextureArea) - { - return new Vector2((float)Math.Round((56 - sourceTextureArea.Width) / 2f), (float)Math.Round((36 - sourceTextureArea.Height) / 2f)); - } - - protected override void Dispose(bool disposing) - { - if (disposing) - _backgroundColor.Dispose(); + protected override void Dispose(bool disposing) + { + if (disposing) + _backgroundColor.Dispose(); - base.Dispose(disposing); + base.Dispose(disposing); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/LockerDialog.cs b/EndlessClient/Dialogs/LockerDialog.cs index 93371fa05..accc1eb83 100644 --- a/EndlessClient/Dialogs/LockerDialog.cs +++ b/EndlessClient/Dialogs/LockerDialog.cs @@ -16,108 +16,109 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Dialogs; - -public class LockerDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private readonly ILockerActions _lockerActions; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ICharacterProvider _characterProvider; - private readonly ILockerDataProvider _lockerDataProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly InventoryPanel _inventoryPanel; - - private HashSet _cachedItems; - - public LockerDialog(INativeGraphicsManager nativeGraphicsManager, - ILockerActions lockerActions, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IInventorySpaceValidator inventorySpaceValidator, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - ICharacterProvider characterProvider, - ILockerDataProvider lockerDataProvider, - IHudControlProvider hudControlProvider, - IEIFFileProvider eifFileProvider) - : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.Locker) - { - _lockerActions = lockerActions; - _localizedStringFinder = localizedStringFinder; - _inventorySpaceValidator = inventorySpaceValidator; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _characterProvider = characterProvider; - _lockerDataProvider = lockerDataProvider; - _eifFileProvider = eifFileProvider; - _inventoryPanel = hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); - - _cachedItems = new HashSet(); - - Title = GetDialogTitle(); - Buttons = ScrollingListDialogButtons.Cancel; - ListItemType = ListDialogItem.ListItemStyle.Large; - } - - protected override void OnUpdateControl(GameTime gameTime) + public class LockerDialog : ScrollingListDialog { - if (!_cachedItems.SetEquals(_lockerDataProvider.Items)) + private readonly ILockerActions _lockerActions; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ICharacterProvider _characterProvider; + private readonly ILockerDataProvider _lockerDataProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly InventoryPanel _inventoryPanel; + + private HashSet _cachedItems; + + public LockerDialog(INativeGraphicsManager nativeGraphicsManager, + ILockerActions lockerActions, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IInventorySpaceValidator inventorySpaceValidator, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + ICharacterProvider characterProvider, + ILockerDataProvider lockerDataProvider, + IHudControlProvider hudControlProvider, + IEIFFileProvider eifFileProvider) + : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.Locker) { - _cachedItems = _lockerDataProvider.Items.ToHashSet(); - UpdateItemList(); + _lockerActions = lockerActions; + _localizedStringFinder = localizedStringFinder; + _inventorySpaceValidator = inventorySpaceValidator; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _characterProvider = characterProvider; + _lockerDataProvider = lockerDataProvider; + _eifFileProvider = eifFileProvider; + _inventoryPanel = hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); + + _cachedItems = new HashSet(); + + Title = GetDialogTitle(); + Buttons = ScrollingListDialogButtons.Cancel; + ListItemType = ListDialogItem.ListItemStyle.Large; } - base.OnUpdateControl(gameTime); - } - - private void UpdateItemList() - { - ClearItemList(); - - Title = GetDialogTitle(); - - foreach (var item in _cachedItems) + protected override void OnUpdateControl(GameTime gameTime) { - var itemData = _eifFileProvider.EIFFile[item.ItemID]; - - var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + if (!_cachedItems.SetEquals(_lockerDataProvider.Items)) { - PrimaryText = itemData.Name, - SubText = $"x{item.Amount} {(itemData.Type == ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - itemData.Gender)})" : string.Empty)}", - IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * itemData.Graphic - 1, true), - OffsetY = 45 - }; - listItem.RightClick += (_, _) => TakeItem(itemData, item); + _cachedItems = _lockerDataProvider.Items.ToHashSet(); + UpdateItemList(); + } - AddItemToList(listItem, sortList: false); + base.OnUpdateControl(gameTime); } - } - private void TakeItem(EIFRecord itemData, InventoryItem item) - { - if (!_inventorySpaceValidator.ItemFits(item.ItemID)) + private void UpdateItemList() { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); + ClearItemList(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); + Title = GetDialogTitle(); + + foreach (var item in _cachedItems) + { + var itemData = _eifFileProvider.EIFFile[item.ItemID]; + + var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + { + PrimaryText = itemData.Name, + SubText = $"x{item.Amount} {(itemData.Type == ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - itemData.Gender)})" : string.Empty)}", + IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * itemData.Graphic - 1, true), + OffsetY = 45 + }; + listItem.RightClick += (_, _) => TakeItem(itemData, item); + + AddItemToList(listItem, sortList: false); + } } - else if (itemData.Weight * item.Amount + _characterProvider.MainCharacter.Stats[CharacterStat.Weight] > _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]) + + private void TakeItem(EIFRecord itemData, InventoryItem item) { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); + if (!_inventorySpaceValidator.ItemFits(item.ItemID)) + { + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_NO_SPACE_LEFT); + } + else if (itemData.Weight * item.Amount + _characterProvider.MainCharacter.Stats[CharacterStat.Weight] > _characterProvider.MainCharacter.Stats[CharacterStat.MaxWeight]) + { + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_ITS_TOO_HEAVY_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + } + else + { + _lockerActions.TakeItemFromLocker(item.ItemID); + } } - else + + private string GetDialogTitle() { - _lockerActions.TakeItemFromLocker(item.ItemID); + return _characterProvider.MainCharacter.Name + "'s " + _localizedStringFinder.GetString(EOResourceID.DIALOG_TITLE_PRIVATE_LOCKER) + $" [{_lockerDataProvider.Items.Count}]"; } } - - private string GetDialogTitle() - { - return _characterProvider.MainCharacter.Name + "'s " + _localizedStringFinder.GetString(EOResourceID.DIALOG_TITLE_PRIVATE_LOCKER) + $" [{_lockerDataProvider.Items.Count}]"; - } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/PaperdollDialog.cs b/EndlessClient/Dialogs/PaperdollDialog.cs index 3d603f334..5d102b03d 100644 --- a/EndlessClient/Dialogs/PaperdollDialog.cs +++ b/EndlessClient/Dialogs/PaperdollDialog.cs @@ -19,139 +19,140 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Dialogs; - -public class PaperdollDialog : PlayerInfoDialog +namespace EndlessClient.Dialogs { - private readonly IInventoryController _inventoryController; - private readonly IPubFileProvider _pubFileProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ISfxPlayer _sfxPlayer; - - private readonly InventoryPanel _inventoryPanel; - - private readonly List _childItems; - - public PaperdollDialog(INativeGraphicsManager nativeGraphicsManager, - IInventoryController inventoryController, - IPaperdollProvider paperdollProvider, - IPubFileProvider pubFileProvider, - IHudControlProvider hudControlProvider, - IEODialogButtonService eoDialogButtonService, - IInventorySpaceValidator inventorySpaceValidator, - IEOMessageBoxFactory eoMessageBoxFactory, - IStatusLabelSetter statusLabelSetter, - ISfxPlayer sfxPlayer, - Character character, bool isMainCharacter) - : base(nativeGraphicsManager, eoDialogButtonService, pubFileProvider, paperdollProvider, character, isMainCharacter) + public class PaperdollDialog : PlayerInfoDialog { - _pubFileProvider = pubFileProvider; - _hudControlProvider = hudControlProvider; - _inventorySpaceValidator = inventorySpaceValidator; - _eoMessageBoxFactory = eoMessageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _sfxPlayer = sfxPlayer; - _inventoryController = inventoryController; - - _inventoryPanel = _hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); - - _childItems = new List(); + private readonly IInventoryController _inventoryController; + private readonly IPubFileProvider _pubFileProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ISfxPlayer _sfxPlayer; + + private readonly InventoryPanel _inventoryPanel; + + private readonly List _childItems; + + public PaperdollDialog(INativeGraphicsManager nativeGraphicsManager, + IInventoryController inventoryController, + IPaperdollProvider paperdollProvider, + IPubFileProvider pubFileProvider, + IHudControlProvider hudControlProvider, + IEODialogButtonService eoDialogButtonService, + IInventorySpaceValidator inventorySpaceValidator, + IEOMessageBoxFactory eoMessageBoxFactory, + IStatusLabelSetter statusLabelSetter, + ISfxPlayer sfxPlayer, + Character character, bool isMainCharacter) + : base(nativeGraphicsManager, eoDialogButtonService, pubFileProvider, paperdollProvider, character, isMainCharacter) + { + _pubFileProvider = pubFileProvider; + _hudControlProvider = hudControlProvider; + _inventorySpaceValidator = inventorySpaceValidator; + _eoMessageBoxFactory = eoMessageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _sfxPlayer = sfxPlayer; + _inventoryController = inventoryController; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 49); - BackgroundTextureSource = new Rectangle(0, BackgroundTexture.Height / 2 * Character.RenderProperties.Gender, DrawArea.Width, BackgroundTexture.Height / 2); + _inventoryPanel = _hudControlProvider.GetComponent(HudControlIdentifier.InventoryPanel); - CenterInGameView(); + _childItems = new List(); - if (!Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, 15); - } + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 49); + BackgroundTextureSource = new Rectangle(0, BackgroundTexture.Height / 2 * Character.RenderProperties.Gender, DrawArea.Width, BackgroundTexture.Height / 2); - public bool NoItemsDragging() => !_childItems.Any(x => x.IsBeingDragged); + CenterInGameView(); - protected override void UpdateDisplayedData(PaperdollData paperdollData) - { - base.UpdateDisplayedData(paperdollData); - - foreach (var control in _childItems) - { - control.SetControlUnparented(); - control.Dispose(); + if (!Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, 15); } - foreach (EquipLocation equipLocation in Enum.GetValues(typeof(EquipLocation))) - { - if (equipLocation == EquipLocation.PAPERDOLL_MAX) - break; + public bool NoItemsDragging() => !_childItems.Any(x => x.IsBeingDragged); - if (!paperdollData.Paperdoll.ContainsKey(equipLocation)) - continue; + protected override void UpdateDisplayedData(PaperdollData paperdollData) + { + base.UpdateDisplayedData(paperdollData); - var id = paperdollData.Paperdoll[equipLocation]; - var eifRecord = id.SomeWhen(i => i > 0).Map(i => _pubFileProvider.EIFFile[i]); - var paperdollItem = new PaperdollDialogItem(GraphicsManager, _sfxPlayer, _inventoryPanel, this, _isMainCharacter, equipLocation, eifRecord) + foreach (var control in _childItems) { - DrawArea = equipLocation.GetEquipLocationRectangle() - }; + control.SetControlUnparented(); + control.Dispose(); + } - paperdollItem.OnMouseEnter += (_, _) => + foreach (EquipLocation equipLocation in Enum.GetValues(typeof(EquipLocation))) { - EOResourceID msg; - switch (equipLocation) + if (equipLocation == EquipLocation.PAPERDOLL_MAX) + break; + + if (!paperdollData.Paperdoll.ContainsKey(equipLocation)) + continue; + + var id = paperdollData.Paperdoll[equipLocation]; + var eifRecord = id.SomeWhen(i => i > 0).Map(i => _pubFileProvider.EIFFile[i]); + var paperdollItem = new PaperdollDialogItem(GraphicsManager, _sfxPlayer, _inventoryPanel, this, _isMainCharacter, equipLocation, eifRecord) { - case EquipLocation.Boots: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BOOTS_EQUIPMENT; break; - case EquipLocation.Accessory: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_MISC_EQUIPMENT; break; - case EquipLocation.Gloves: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_GLOVES_EQUIPMENT; break; - case EquipLocation.Belt: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BELT_EQUIPMENT; break; - case EquipLocation.Armor: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_ARMOR_EQUIPMENT; break; - case EquipLocation.Necklace: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_NECKLACE_EQUIPMENT; break; - case EquipLocation.Hat: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_HAT_EQUIPMENT; break; - case EquipLocation.Shield: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_SHIELD_EQUIPMENT; break; - case EquipLocation.Weapon: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_WEAPON_EQUIPMENT; break; - case EquipLocation.Ring1: - case EquipLocation.Ring2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_RING_EQUIPMENT; break; - case EquipLocation.Armlet1: - case EquipLocation.Armlet2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_ARMLET_EQUIPMENT; break; - case EquipLocation.Bracer1: - case EquipLocation.Bracer2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BRACER_EQUIPMENT; break; - default: throw new ArgumentOutOfRangeException(); - } - - var extra = eifRecord.Match(rec => $", {rec.Name}", () => string.Empty); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, msg, extra); - }; - - paperdollItem.UnequipAction += itemInfo => - { - if (itemInfo.Special == ItemSpecial.Cursed) + DrawArea = equipLocation.GetEquipLocationRectangle() + }; + + paperdollItem.OnMouseEnter += (_, _) => { - var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_CURSED_ITEM, EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); - msgBox.ShowDialog(); - } - else + EOResourceID msg; + switch (equipLocation) + { + case EquipLocation.Boots: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BOOTS_EQUIPMENT; break; + case EquipLocation.Accessory: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_MISC_EQUIPMENT; break; + case EquipLocation.Gloves: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_GLOVES_EQUIPMENT; break; + case EquipLocation.Belt: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BELT_EQUIPMENT; break; + case EquipLocation.Armor: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_ARMOR_EQUIPMENT; break; + case EquipLocation.Necklace: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_NECKLACE_EQUIPMENT; break; + case EquipLocation.Hat: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_HAT_EQUIPMENT; break; + case EquipLocation.Shield: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_SHIELD_EQUIPMENT; break; + case EquipLocation.Weapon: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_WEAPON_EQUIPMENT; break; + case EquipLocation.Ring1: + case EquipLocation.Ring2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_RING_EQUIPMENT; break; + case EquipLocation.Armlet1: + case EquipLocation.Armlet2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_ARMLET_EQUIPMENT; break; + case EquipLocation.Bracer1: + case EquipLocation.Bracer2: msg = EOResourceID.STATUS_LABEL_PAPERDOLL_BRACER_EQUIPMENT; break; + default: throw new ArgumentOutOfRangeException(); + } + + var extra = eifRecord.Match(rec => $", {rec.Name}", () => string.Empty); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, msg, extra); + }; + + paperdollItem.UnequipAction += itemInfo => { - eifRecord.MatchSome(rec => + if (itemInfo.Special == ItemSpecial.Cursed) { - if (!_inventorySpaceValidator.ItemFits(rec.ID)) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_UNEQUIP_NO_SPACE_LEFT); - } - else + var msgBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.ITEM_IS_CURSED_ITEM, EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader); + msgBox.ShowDialog(); + } + else + { + eifRecord.MatchSome(rec => { - // packet reply handles updating the paperdoll for the character which will unrender the equipment - _inventoryController.UnequipItem(equipLocation); - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - } - }); - } - }; - - paperdollItem.SetParentControl(this); - paperdollItem.Initialize(); - - _childItems.Add(paperdollItem); + if (!_inventorySpaceValidator.ItemFits(rec.ID)) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_UNEQUIP_NO_SPACE_LEFT); + } + else + { + // packet reply handles updating the paperdoll for the character which will unrender the equipment + _inventoryController.UnequipItem(equipLocation); + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + } + }); + } + }; + + paperdollItem.SetParentControl(this); + paperdollItem.Initialize(); + + _childItems.Add(paperdollItem); + } } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/PaperdollDialogItem.cs b/EndlessClient/Dialogs/PaperdollDialogItem.cs index 4b97403a7..5209495bf 100644 --- a/EndlessClient/Dialogs/PaperdollDialogItem.cs +++ b/EndlessClient/Dialogs/PaperdollDialogItem.cs @@ -11,113 +11,114 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public class PaperdollDialogItem : XNAPictureBox +namespace EndlessClient.Dialogs { - private readonly ISfxPlayer _sfxPlayer; - private readonly InventoryPanel _inventoryPanel; - private readonly PaperdollDialog _paperdollDialog; - private readonly bool _isMainCharacter; - private readonly Option _itemInfo; - - private bool _beingDragged; + public class PaperdollDialogItem : XNAPictureBox + { + private readonly ISfxPlayer _sfxPlayer; + private readonly InventoryPanel _inventoryPanel; + private readonly PaperdollDialog _paperdollDialog; + private readonly bool _isMainCharacter; + private readonly Option _itemInfo; - public EquipLocation EquipLocation { get; } + private bool _beingDragged; - public int ItemID => _itemInfo.Match(r => r.ID, () => 0); + public EquipLocation EquipLocation { get; } - public event Action UnequipAction; + public int ItemID => _itemInfo.Match(r => r.ID, () => 0); - public bool IsBeingDragged => _beingDragged; + public event Action UnequipAction; - public PaperdollDialogItem(INativeGraphicsManager nativeGraphicsManager, - ISfxPlayer sfxPlayer, - InventoryPanel inventoryPanel, - PaperdollDialog paperdollDialog, - bool isMainCharacter, - EquipLocation location, - Option itemInfo) - { - _sfxPlayer = sfxPlayer; - _inventoryPanel = inventoryPanel; - _paperdollDialog = paperdollDialog; - _isMainCharacter = isMainCharacter; - EquipLocation = location; - _itemInfo = itemInfo; - - _itemInfo.MatchSome(r => Texture = nativeGraphicsManager.TextureFromResource(GFXTypes.Items, r.Graphic * 2, true)); - StretchMode = StretchMode.CenterInFrame; - } + public bool IsBeingDragged => _beingDragged; - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_isMainCharacter || !_itemInfo.HasValue) - return false; + public PaperdollDialogItem(INativeGraphicsManager nativeGraphicsManager, + ISfxPlayer sfxPlayer, + InventoryPanel inventoryPanel, + PaperdollDialog paperdollDialog, + bool isMainCharacter, + EquipLocation location, + Option itemInfo) + { + _sfxPlayer = sfxPlayer; + _inventoryPanel = inventoryPanel; + _paperdollDialog = paperdollDialog; + _isMainCharacter = isMainCharacter; + EquipLocation = location; + _itemInfo = itemInfo; + + _itemInfo.MatchSome(r => Texture = nativeGraphicsManager.TextureFromResource(GFXTypes.Items, r.Graphic * 2, true)); + StretchMode = StretchMode.CenterInFrame; + } - if (eventArgs.Button == MouseButton.Left) + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) { - if (_inventoryPanel.MouseOver && _inventoryPanel.MouseOverPreviously) + if (!_isMainCharacter || !_itemInfo.HasValue) + return false; + + if (eventArgs.Button == MouseButton.Left) { - StopDragging(); - _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); + if (_inventoryPanel.MouseOver && _inventoryPanel.MouseOverPreviously) + { + StopDragging(); + _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); + } + } + else if (eventArgs.Button == MouseButton.Right) + { + if (_beingDragged) + StopDragging(); + else + _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); } - } - else if (eventArgs.Button == MouseButton.Right) - { - if (_beingDragged) - StopDragging(); - else - _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); - } - return true; - } + return true; + } - protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_isMainCharacter || !_itemInfo.HasValue) - return false; + protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_isMainCharacter || !_itemInfo.HasValue) + return false; - _beingDragged = true; - SetControlUnparented(); - Game.Components.Add(this); + _beingDragged = true; + SetControlUnparented(); + Game.Components.Add(this); - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - DrawOrder = 1000; - return true; - } + DrawOrder = 1000; + return true; + } - protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_isMainCharacter || !_itemInfo.HasValue) - return false; + protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_isMainCharacter || !_itemInfo.HasValue) + return false; - DrawPosition = new Vector2(eventArgs.Position.X - (DrawArea.Width / 2), eventArgs.Position.Y - (DrawArea.Height / 2)); + DrawPosition = new Vector2(eventArgs.Position.X - (DrawArea.Width / 2), eventArgs.Position.Y - (DrawArea.Height / 2)); - return true; - } + return true; + } - protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_isMainCharacter || !_itemInfo.HasValue) - return false; + protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_isMainCharacter || !_itemInfo.HasValue) + return false; - if (_inventoryPanel.MouseOver && _inventoryPanel.MouseOverPreviously) - _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); + if (_inventoryPanel.MouseOver && _inventoryPanel.MouseOverPreviously) + _itemInfo.MatchSome(itemInfo => UnequipAction?.Invoke(itemInfo)); - StopDragging(); + StopDragging(); - return true; - } + return true; + } - private void StopDragging() - { - _beingDragged = false; - SetParentControl(_paperdollDialog); - DrawArea = EquipLocation.GetEquipLocationRectangle(); + private void StopDragging() + { + _beingDragged = false; + SetParentControl(_paperdollDialog); + DrawArea = EquipLocation.GetEquipLocationRectangle(); - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/PlayerInfoDialog.cs b/EndlessClient/Dialogs/PlayerInfoDialog.cs index c4c1b13e7..ca98e9f21 100644 --- a/EndlessClient/Dialogs/PlayerInfoDialog.cs +++ b/EndlessClient/Dialogs/PlayerInfoDialog.cs @@ -12,153 +12,154 @@ using Optional.Unsafe; using XNAControls; -namespace EndlessClient.Dialogs; - -public class PlayerInfoDialog : BaseEODialog +namespace EndlessClient.Dialogs { - private static readonly Rectangle _iconDrawRect = new Rectangle(227, 258, 44, 21); - - private readonly IPubFileProvider _pubFileProvider; - private readonly IPaperdollProvider _paperdollProvider; - protected readonly bool _isMainCharacter; - - private readonly Texture2D _characterIconSheet; - private Option _characterIconSourceRect; - - private readonly IXNALabel _name, - _home, - _class, - _partner, - _title, - _guild, - _rank; - - public Character Character { get; } - - private Option _paperdollData; - - public PlayerInfoDialog(INativeGraphicsManager graphicsManager, - IEODialogButtonService eoDialogButtonService, - IPubFileProvider pubFileProvider, - IPaperdollProvider paperdollProvider, - Character character, - bool isMainCharacter) - : base(graphicsManager, isInGame: true) + public class PlayerInfoDialog : BaseEODialog { - _pubFileProvider = pubFileProvider; - _paperdollProvider = paperdollProvider; - - Character = character; - _isMainCharacter = isMainCharacter; + private static readonly Rectangle _iconDrawRect = new Rectangle(227, 258, 44, 21); + + private readonly IPubFileProvider _pubFileProvider; + private readonly IPaperdollProvider _paperdollProvider; + protected readonly bool _isMainCharacter; + + private readonly Texture2D _characterIconSheet; + private Option _characterIconSourceRect; + + private readonly IXNALabel _name, + _home, + _class, + _partner, + _title, + _guild, + _rank; + + public Character Character { get; } + + private Option _paperdollData; + + public PlayerInfoDialog(INativeGraphicsManager graphicsManager, + IEODialogButtonService eoDialogButtonService, + IPubFileProvider pubFileProvider, + IPaperdollProvider paperdollProvider, + Character character, + bool isMainCharacter) + : base(graphicsManager, isInGame: true) + { + _pubFileProvider = pubFileProvider; + _paperdollProvider = paperdollProvider; - _characterIconSheet = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); - _characterIconSourceRect = Option.None(); + Character = character; + _isMainCharacter = isMainCharacter; - _name = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 22, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _name.SetParentControl(this); + _characterIconSheet = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); + _characterIconSourceRect = Option.None(); - _home = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 52, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _home.SetParentControl(this); + _name = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 22, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _name.SetParentControl(this); - _class = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 82, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _class.SetParentControl(this); + _home = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 52, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _home.SetParentControl(this); - _partner = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 112, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _partner.SetParentControl(this); + _class = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 82, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _class.SetParentControl(this); - _title = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 142, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _title.SetParentControl(this); + _partner = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 112, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _partner.SetParentControl(this); - _guild = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 202, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _guild.SetParentControl(this); + _title = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 142, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _title.SetParentControl(this); - _rank = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 232, 1, 1), ForeColor = ColorConstants.LightGrayText }; - _rank.SetParentControl(this); + _guild = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 202, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _guild.SetParentControl(this); - var okButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(276, 253), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - okButton.OnClick += (_, _) => Close(XNADialogResult.OK); - okButton.Initialize(); - okButton.SetParentControl(this); + _rank = new XNALabel(Constants.FontSize08pt5) { DrawArea = new Rectangle(228, 232, 1, 1), ForeColor = ColorConstants.LightGrayText }; + _rank.SetParentControl(this); - _paperdollData = Option.None(); - } + var okButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(276, 253), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + okButton.OnClick += (_, _) => Close(XNADialogResult.OK); + okButton.Initialize(); + okButton.SetParentControl(this); - public override void Initialize() - { - _name.Initialize(); - _home.Initialize(); - _class.Initialize(); - _partner.Initialize(); - _title.Initialize(); - _guild.Initialize(); - _rank.Initialize(); - - base.Initialize(); - } + _paperdollData = Option.None(); + } - protected override void OnUpdateControl(GameTime gameTime) - { - _paperdollData = _paperdollData.FlatMap(paperdollData => - paperdollData.NoneWhen(d => _paperdollProvider.VisibleCharacterPaperdolls.ContainsKey(Character.ID) && - !_paperdollProvider.VisibleCharacterPaperdolls[Character.ID].Equals(d))); - - _paperdollData.MatchNone(() => + public override void Initialize() { - if (_paperdollProvider.VisibleCharacterPaperdolls.ContainsKey(Character.ID)) - { - var paperdollData = _paperdollProvider.VisibleCharacterPaperdolls[Character.ID]; - _paperdollData = Option.Some(paperdollData); - UpdateDisplayedData(paperdollData); - } - }); - - base.OnUpdateControl(gameTime); - } + _name.Initialize(); + _home.Initialize(); + _class.Initialize(); + _partner.Initialize(); + _title.Initialize(); + _guild.Initialize(); + _rank.Initialize(); + + base.Initialize(); + } + + protected override void OnUpdateControl(GameTime gameTime) + { + _paperdollData = _paperdollData.FlatMap(paperdollData => + paperdollData.NoneWhen(d => _paperdollProvider.VisibleCharacterPaperdolls.ContainsKey(Character.ID) && + !_paperdollProvider.VisibleCharacterPaperdolls[Character.ID].Equals(d))); - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + _paperdollData.MatchNone(() => + { + if (_paperdollProvider.VisibleCharacterPaperdolls.ContainsKey(Character.ID)) + { + var paperdollData = _paperdollProvider.VisibleCharacterPaperdolls[Character.ID]; + _paperdollData = Option.Some(paperdollData); + UpdateDisplayedData(paperdollData); + } + }); + + base.OnUpdateControl(gameTime); + } + + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - _spriteBatch.Begin(); + _spriteBatch.Begin(); - _characterIconSourceRect.MatchSome(sourceRect => + _characterIconSourceRect.MatchSome(sourceRect => + { + _spriteBatch.Draw(_characterIconSheet, + new Vector2( + DrawAreaWithParentOffset.X + _iconDrawRect.X + (_iconDrawRect.Width / 2) - (sourceRect.Width / 2), + DrawAreaWithParentOffset.Y + _iconDrawRect.Y + (_iconDrawRect.Height / 2) - (sourceRect.Height / 2)), + sourceRect, + Color.White); + }); + + _spriteBatch.End(); + } + + protected virtual void UpdateDisplayedData(PaperdollData paperdollData) { - _spriteBatch.Draw(_characterIconSheet, - new Vector2( - DrawAreaWithParentOffset.X + _iconDrawRect.X + (_iconDrawRect.Width / 2) - (sourceRect.Width / 2), - DrawAreaWithParentOffset.Y + _iconDrawRect.Y + (_iconDrawRect.Height / 2) - (sourceRect.Height / 2)), - sourceRect, - Color.White); - }); - - _spriteBatch.End(); - } + _name.Text = Capitalize(paperdollData.Name); + _home.Text = Capitalize(paperdollData.Home); - protected virtual void UpdateDisplayedData(PaperdollData paperdollData) - { - _name.Text = Capitalize(paperdollData.Name); - _home.Text = Capitalize(paperdollData.Home); - - paperdollData.Class.SomeWhen(x => x != 0) - .MatchSome(classId => _class.Text = Capitalize(_pubFileProvider.ECFFile[classId].Name)); + paperdollData.Class.SomeWhen(x => x != 0) + .MatchSome(classId => _class.Text = Capitalize(_pubFileProvider.ECFFile[classId].Name)); - _partner.Text = Capitalize(paperdollData.Partner); - _title.Text = Capitalize(paperdollData.Title); - _guild.Text = Capitalize(paperdollData.Guild); - _rank.Text = Capitalize(paperdollData.Rank); + _partner.Text = Capitalize(paperdollData.Partner); + _title.Text = Capitalize(paperdollData.Title); + _guild.Text = Capitalize(paperdollData.Guild); + _rank.Text = Capitalize(paperdollData.Rank); - _characterIconSourceRect = Option.Some(GetOnlineIconSourceRectangle(paperdollData.Icon)); - } + _characterIconSourceRect = Option.Some(GetOnlineIconSourceRectangle(paperdollData.Icon)); + } - private static string Capitalize(string input) => - string.IsNullOrEmpty(input) ? string.Empty : char.ToUpper(input[0]) + input[1..].ToLower(); + private static string Capitalize(string input) => + string.IsNullOrEmpty(input) ? string.Empty : char.ToUpper(input[0]) + input[1..].ToLower(); - private static Rectangle GetOnlineIconSourceRectangle(CharacterIcon icon) - { - var (x, y, width, height) = icon.ToChatIcon().GetChatIconRectangleBounds().ValueOrDefault(); - return new Rectangle(x, y, width, height); + private static Rectangle GetOnlineIconSourceRectangle(CharacterIcon icon) + { + var (x, y, width, height) = icon.ToChatIcon().GetChatIconRectangleBounds().ValueOrDefault(); + return new Rectangle(x, y, width, height); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ProgressDialog.cs b/EndlessClient/Dialogs/ProgressDialog.cs index fc05181fc..1bcf03e12 100644 --- a/EndlessClient/Dialogs/ProgressDialog.cs +++ b/EndlessClient/Dialogs/ProgressDialog.cs @@ -9,116 +9,117 @@ using System.Threading; using XNAControls; -namespace EndlessClient.Dialogs; - -public class ProgressDialog : BaseEODialog +namespace EndlessClient.Dialogs { - private readonly IConfigurationProvider _configurationProvider; - - private readonly IXNALabel _messageLabel, _captionLabel; - private readonly IXNAButton _cancelButton; - - private TimeSpan? timeOpened; - private readonly Texture2D _pbBackgroundTexture, _pbForegroundTexture; - private int _pbWidth, _cancelRequests; - - public ProgressDialog(INativeGraphicsManager nativeGraphicsManager, - IGameStateProvider gameStateProvider, - IConfigurationProvider configurationProvider, - IEODialogButtonService eoDialogButtonService, - string messageText, - string captionText) - : base(nativeGraphicsManager, gameStateProvider) + public class ProgressDialog : BaseEODialog { - _configurationProvider = configurationProvider; - - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 18); - - _messageLabel = new XNALabel(Constants.FontSize10) + private readonly IConfigurationProvider _configurationProvider; + + private readonly IXNALabel _messageLabel, _captionLabel; + private readonly IXNAButton _cancelButton; + + private TimeSpan? timeOpened; + private readonly Texture2D _pbBackgroundTexture, _pbForegroundTexture; + private int _pbWidth, _cancelRequests; + + public ProgressDialog(INativeGraphicsManager nativeGraphicsManager, + IGameStateProvider gameStateProvider, + IConfigurationProvider configurationProvider, + IEODialogButtonService eoDialogButtonService, + string messageText, + string captionText) + : base(nativeGraphicsManager, gameStateProvider) { - AutoSize = true, - ForeColor = ColorConstants.LightYellowText, - Text = messageText, - TextWidth = 254, - DrawPosition = new Vector2(18, 57) - }; - _messageLabel.SetParentControl(this); - - _captionLabel = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - ForeColor = ColorConstants.LightYellowText, - Text = captionText, - DrawPosition = new Vector2(59, 23) - }; - _captionLabel.SetParentControl(this); - - _cancelButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(181, 113), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - _cancelButton.OnClick += DoCancel; - _cancelButton.SetParentControl(this); - - _pbBackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 19); - - _pbForegroundTexture = new Texture2D(Game.GraphicsDevice, 1, _pbBackgroundTexture.Height - 2); //foreground texture is just a fill - var pbForeFill = new Color[_pbForegroundTexture.Width * _pbForegroundTexture.Height]; - for (int i = 0; i < pbForeFill.Length; ++i) - pbForeFill[i] = Color.FromNonPremultiplied(0xb4, 0xdc, 0xe6, 0xff); - _pbForegroundTexture.SetData(pbForeFill); - - CenterInGameView(); - } - - public override void Initialize() - { - _messageLabel.Initialize(); - _captionLabel.Initialize(); - _cancelButton.Initialize(); - - base.Initialize(); - } + _configurationProvider = configurationProvider; + + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 18); + + _messageLabel = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + ForeColor = ColorConstants.LightYellowText, + Text = messageText, + TextWidth = 254, + DrawPosition = new Vector2(18, 57) + }; + _messageLabel.SetParentControl(this); + + _captionLabel = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + ForeColor = ColorConstants.LightYellowText, + Text = captionText, + DrawPosition = new Vector2(59, 23) + }; + _captionLabel.SetParentControl(this); + + _cancelButton = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(181, 113), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + _cancelButton.OnClick += DoCancel; + _cancelButton.SetParentControl(this); + + _pbBackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 19); + + _pbForegroundTexture = new Texture2D(Game.GraphicsDevice, 1, _pbBackgroundTexture.Height - 2); //foreground texture is just a fill + var pbForeFill = new Color[_pbForegroundTexture.Width * _pbForegroundTexture.Height]; + for (int i = 0; i < pbForeFill.Length; ++i) + pbForeFill[i] = Color.FromNonPremultiplied(0xb4, 0xdc, 0xe6, 0xff); + _pbForegroundTexture.SetData(pbForeFill); + + CenterInGameView(); + } - protected override void OnUpdateControl(GameTime gt) - { - if (timeOpened == null) - timeOpened = gt.TotalGameTime; + public override void Initialize() + { + _messageLabel.Initialize(); + _captionLabel.Initialize(); + _cancelButton.Initialize(); - var pbPercent = (int)((gt.TotalGameTime.TotalSeconds - timeOpened.Value.TotalSeconds) / _configurationProvider.AccountCreateTimeout.TotalSeconds * 100); - _pbWidth = (int)Math.Round(pbPercent / 100.0f * _pbBackgroundTexture.Width); + base.Initialize(); + } - if (pbPercent >= 100) - Close(XNADialogResult.NO_BUTTON_PRESSED); + protected override void OnUpdateControl(GameTime gt) + { + if (timeOpened == null) + timeOpened = gt.TotalGameTime; - base.OnUpdateControl(gt); - } + var pbPercent = (int)((gt.TotalGameTime.TotalSeconds - timeOpened.Value.TotalSeconds) / _configurationProvider.AccountCreateTimeout.TotalSeconds * 100); + _pbWidth = (int)Math.Round(pbPercent / 100.0f * _pbBackgroundTexture.Width); - protected override void OnDrawControl(GameTime gt) - { - base.OnDrawControl(gt); + if (pbPercent >= 100) + Close(XNADialogResult.NO_BUTTON_PRESSED); - var pbBackgroundPosition = new Vector2(15 + DrawPositionWithParentOffset.X, 95 + DrawPositionWithParentOffset.Y); - var pbForgroundArea = new Rectangle(18 + DrawAreaWithParentOffset.X, 98 + DrawAreaWithParentOffset.Y, _pbWidth - 6, _pbForegroundTexture.Height - 4); + base.OnUpdateControl(gt); + } - _spriteBatch.Begin(); - _spriteBatch.Draw(_pbBackgroundTexture, pbBackgroundPosition, Color.White); - _spriteBatch.Draw(_pbForegroundTexture, pbForgroundArea, Color.White); - _spriteBatch.End(); - } + protected override void OnDrawControl(GameTime gt) + { + base.OnDrawControl(gt); - private void DoCancel(object sender, EventArgs e) - { - if (Interlocked.Increment(ref _cancelRequests) != 1) - return; + var pbBackgroundPosition = new Vector2(15 + DrawPositionWithParentOffset.X, 95 + DrawPositionWithParentOffset.Y); + var pbForgroundArea = new Rectangle(18 + DrawAreaWithParentOffset.X, 98 + DrawAreaWithParentOffset.Y, _pbWidth - 6, _pbForegroundTexture.Height - 4); - try - { - Close(XNADialogResult.Cancel); + _spriteBatch.Begin(); + _spriteBatch.Draw(_pbBackgroundTexture, pbBackgroundPosition, Color.White); + _spriteBatch.Draw(_pbForegroundTexture, pbForgroundArea, Color.White); + _spriteBatch.End(); } - finally + + private void DoCancel(object sender, EventArgs e) { - Interlocked.Exchange(ref _cancelRequests, 0); + if (Interlocked.Increment(ref _cancelRequests) != 1) + return; + + try + { + Close(XNADialogResult.Cancel); + } + finally + { + Interlocked.Exchange(ref _cancelRequests, 0); + } } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/QuestDialog.cs b/EndlessClient/Dialogs/QuestDialog.cs index d9e2309bc..de1328595 100644 --- a/EndlessClient/Dialogs/QuestDialog.cs +++ b/EndlessClient/Dialogs/QuestDialog.cs @@ -12,179 +12,180 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs; - -public class QuestDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private readonly IQuestActions _questActions; - private readonly IQuestDataProvider _questDataProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly IContentProvider _contentProvider; - - private Option _cachedData; - - private int _pageIndex = 0; - - public event EventHandler LinkClickAction; - - public QuestDialog(INativeGraphicsManager nativeGraphicsManager, - IQuestActions questActions, - IEODialogButtonService dialogButtonService, - IQuestDataProvider questDataProvider, - IENFFileProvider enfFileProvider, - IContentProvider contentProvider) - : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.NpcQuestDialog) + public class QuestDialog : ScrollingListDialog { - _questActions = questActions; - _questDataProvider = questDataProvider; - _enfFileProvider = enfFileProvider; - _contentProvider = contentProvider; + private readonly IQuestActions _questActions; + private readonly IQuestDataProvider _questDataProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly IContentProvider _contentProvider; - _cachedData = Option.None(); + private Option _cachedData; - ListItemType = ListDialogItem.ListItemStyle.Small; + private int _pageIndex = 0; - NextAction += NextPage; - BackAction += PreviousPage; - DialogClosing += (_, e) => - { - if (e.Result == XNADialogResult.OK) - _questActions.RespondToQuestDialog(DialogReply.Ok); - }; - } + public event EventHandler LinkClickAction; - protected override void OnUpdateControl(GameTime gameTime) - { - _questDataProvider.QuestDialogData.MatchSome(data => UpdateCachedDataIfNeeded(_cachedData, data)); - base.OnUpdateControl(gameTime); - } + public QuestDialog(INativeGraphicsManager nativeGraphicsManager, + IQuestActions questActions, + IEODialogButtonService dialogButtonService, + IQuestDataProvider questDataProvider, + IENFFileProvider enfFileProvider, + IContentProvider contentProvider) + : base(nativeGraphicsManager, dialogButtonService, dialogType: DialogType.NpcQuestDialog) + { + _questActions = questActions; + _questDataProvider = questDataProvider; + _enfFileProvider = enfFileProvider; + _contentProvider = contentProvider; - private void UpdateCachedDataIfNeeded(Option cachedData, QuestDialogData repoData) - { - cachedData.Match( - some: cached => - { - _cachedData = Option.Some(repoData); - if (!cached.Equals(repoData)) - UpdateDialogControls(repoData); - }, - none: () => - { - _cachedData = Option.Some(repoData); - UpdateDialogControls(repoData); - }); - } + _cachedData = Option.None(); - private void UpdateDialogControls(QuestDialogData repoData) - { - _pageIndex = 0; + ListItemType = ListDialogItem.ListItemStyle.Small; - UpdateTitle(repoData); - UpdateDialogDisplayText(repoData); - UpdateButtons(repoData); - } + NextAction += NextPage; + BackAction += PreviousPage; + DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + _questActions.RespondToQuestDialog(DialogReply.Ok); + }; + } - private void UpdateTitle(QuestDialogData repoData) - { - if (_questDataProvider.RequestedNPC != null) + protected override void OnUpdateControl(GameTime gameTime) { - var npcName = _enfFileProvider.ENFFile[_questDataProvider.RequestedNPC.ID].Name; - var titleText = npcName; - if (!repoData.DialogTitles.ContainsKey(repoData.VendorID) && repoData.DialogTitles.Count == 1) - titleText += $" - {repoData.DialogTitles.Single().Value}"; - else if (repoData.DialogTitles.ContainsKey(repoData.VendorID)) - titleText += $" - {repoData.DialogTitles[repoData.VendorID]}"; - - _titleText.Text = titleText; - _titleText.ResizeBasedOnText(); + _questDataProvider.QuestDialogData.MatchSome(data => UpdateCachedDataIfNeeded(_cachedData, data)); + base.OnUpdateControl(gameTime); } - else + + private void UpdateCachedDataIfNeeded(Option cachedData, QuestDialogData repoData) { - _titleText.Text = string.Empty; + cachedData.Match( + some: cached => + { + _cachedData = Option.Some(repoData); + if (!cached.Equals(repoData)) + UpdateDialogControls(repoData); + }, + none: () => + { + _cachedData = Option.Some(repoData); + UpdateDialogControls(repoData); + }); } - } - private void UpdateDialogDisplayText(QuestDialogData repoData) - { - ClearItemList(); - - var rows = new List(); + private void UpdateDialogControls(QuestDialogData repoData) + { + _pageIndex = 0; - var ts = new TextSplitter(repoData.PageText[_pageIndex], _contentProvider.Fonts[Constants.FontSize09]); - if (!ts.NeedsProcessing) - rows.Add(repoData.PageText[_pageIndex]); - else - rows.AddRange(ts.SplitIntoLines()); + UpdateTitle(repoData); + UpdateDialogDisplayText(repoData); + UpdateButtons(repoData); + } - int index = 0; - foreach (var row in rows) + private void UpdateTitle(QuestDialogData repoData) { - var rowItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) + if (_questDataProvider.RequestedNPC != null) { - PrimaryText = row, - }; - - AddItemToList(rowItem, sortList: false); + var npcName = _enfFileProvider.ENFFile[_questDataProvider.RequestedNPC.ID].Name; + var titleText = npcName; + if (!repoData.DialogTitles.ContainsKey(repoData.VendorID) && repoData.DialogTitles.Count == 1) + titleText += $" - {repoData.DialogTitles.Single().Value}"; + else if (repoData.DialogTitles.ContainsKey(repoData.VendorID)) + titleText += $" - {repoData.DialogTitles[repoData.VendorID]}"; + + _titleText.Text = titleText; + _titleText.ResizeBasedOnText(); + } + else + { + _titleText.Text = string.Empty; + } } - // The links are only shown on the last page of the quest dialog - if (_pageIndex < repoData.PageText.Count - 1) - return; + private void UpdateDialogDisplayText(QuestDialogData repoData) + { + ClearItemList(); - var item = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) { PrimaryText = " " }; - AddItemToList(item, sortList: false); + var rows = new List(); - foreach (var action in repoData.Actions) - { - var actionItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) - { - PrimaryText = action.DisplayText - }; + var ts = new TextSplitter(repoData.PageText[_pageIndex], _contentProvider.Fonts[Constants.FontSize09]); + if (!ts.NeedsProcessing) + rows.Add(repoData.PageText[_pageIndex]); + else + rows.AddRange(ts.SplitIntoLines()); - var linkIndex = action.ActionID; - actionItem.SetPrimaryClickAction((_, _) => + int index = 0; + foreach (var row in rows) { - _questActions.RespondToQuestDialog(DialogReply.Link, linkIndex); - LinkClickAction?.Invoke(this, EventArgs.Empty); - Close(XNADialogResult.Cancel); - }); + var rowItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) + { + PrimaryText = row, + }; + + AddItemToList(rowItem, sortList: false); + } + + // The links are only shown on the last page of the quest dialog + if (_pageIndex < repoData.PageText.Count - 1) + return; - AddItemToList(actionItem, sortList: false); + var item = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) { PrimaryText = " " }; + AddItemToList(item, sortList: false); + + foreach (var action in repoData.Actions) + { + var actionItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small, index++) + { + PrimaryText = action.DisplayText + }; + + var linkIndex = action.ActionID; + actionItem.SetPrimaryClickAction((_, _) => + { + _questActions.RespondToQuestDialog(DialogReply.Link, linkIndex); + LinkClickAction?.Invoke(this, EventArgs.Empty); + Close(XNADialogResult.Cancel); + }); + + AddItemToList(actionItem, sortList: false); + } } - } - private void UpdateButtons(QuestDialogData repoData) - { - bool morePages = _pageIndex < repoData.PageText.Count - 1; - bool firstPage = _pageIndex == 0; - - if (firstPage && morePages) - Buttons = ScrollingListDialogButtons.CancelNext; - else if (!firstPage && morePages) - Buttons = ScrollingListDialogButtons.BackNext; - else if (firstPage) - Buttons = ScrollingListDialogButtons.CancelOk; - else - Buttons = ScrollingListDialogButtons.BackOk; - } + private void UpdateButtons(QuestDialogData repoData) + { + bool morePages = _pageIndex < repoData.PageText.Count - 1; + bool firstPage = _pageIndex == 0; + + if (firstPage && morePages) + Buttons = ScrollingListDialogButtons.CancelNext; + else if (!firstPage && morePages) + Buttons = ScrollingListDialogButtons.BackNext; + else if (firstPage) + Buttons = ScrollingListDialogButtons.CancelOk; + else + Buttons = ScrollingListDialogButtons.BackOk; + } - private void NextPage(object sender, EventArgs e) - { - _cachedData.MatchSome(data => + private void NextPage(object sender, EventArgs e) { - _pageIndex++; - UpdateDialogDisplayText(data); - UpdateButtons(data); - }); - } + _cachedData.MatchSome(data => + { + _pageIndex++; + UpdateDialogDisplayText(data); + UpdateButtons(data); + }); + } - private void PreviousPage(object sender, EventArgs e) - { - _cachedData.MatchSome(data => + private void PreviousPage(object sender, EventArgs e) { - _pageIndex--; - UpdateDialogDisplayText(data); - UpdateButtons(data); - }); + _cachedData.MatchSome(data => + { + _pageIndex--; + UpdateDialogDisplayText(data); + UpdateButtons(data); + }); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/QuestStatusDialog.cs b/EndlessClient/Dialogs/QuestStatusDialog.cs index 2f12a4a29..2d3b4e65f 100644 --- a/EndlessClient/Dialogs/QuestStatusDialog.cs +++ b/EndlessClient/Dialogs/QuestStatusDialog.cs @@ -7,127 +7,128 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using System.Collections.Generic; -namespace EndlessClient.Dialogs; - -public class QuestStatusDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IQuestDataProvider _questDataProvider; - private readonly ICharacterProvider _characterProvider; - - - private IReadOnlyList _cachedProgress = new List(); - private IReadOnlyList _cachedHistory = new List(); - - private QuestPage _page; - - public QuestStatusDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - IQuestDataProvider questDataProvider, - ICharacterProvider characterProvider) - : base(nativeGraphicsManager, dialogButtonService, DialogType.QuestProgressHistory) + public class QuestStatusDialog : ScrollingListDialog { - ListItemType = ListDialogItem.ListItemStyle.Small; - Buttons = ScrollingListDialogButtons.HistoryOk; - _localizedStringFinder = localizedStringFinder; - _questDataProvider = questDataProvider; - _characterProvider = characterProvider; - HistoryAction += (_, _) => ShowHistory(); - ProgressAction += (_, _) => ShowProgress(); - - _page = QuestPage.Progress; - } + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IQuestDataProvider _questDataProvider; + private readonly ICharacterProvider _characterProvider; - protected override void OnUpdateControl(GameTime gameTime) - { - if (_questDataProvider.QuestHistory != _cachedHistory) - { - _cachedHistory = _questDataProvider.QuestHistory; - if (_page == QuestPage.History) - ShowHistory(); - } - else if (_questDataProvider.QuestProgress != _cachedProgress) - { - _cachedProgress = _questDataProvider.QuestProgress; - if (_page == QuestPage.Progress) - ShowProgress(); - } - base.OnUpdateControl(gameTime); - } + private IReadOnlyList _cachedProgress = new List(); + private IReadOnlyList _cachedHistory = new List(); - private void ShowHistory() - { - ClearItemList(); - SetTitle(QuestPage.History); + private QuestPage _page; - if (_cachedHistory.Count == 0) + public QuestStatusDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + IQuestDataProvider questDataProvider, + ICharacterProvider characterProvider) + : base(nativeGraphicsManager, dialogButtonService, DialogType.QuestProgressHistory) { - var nextItem = new QuestStatusListDialogItem(this, QuestPage.History) - { - QuestName = _localizedStringFinder.GetString(EOResourceID.QUEST_DID_NOT_FINISH_ANY), - ShowIcons = false - }; - nextItem.SetScrollWheelHandler(this); - AddItemToList(nextItem, sortList: false); + ListItemType = ListDialogItem.ListItemStyle.Small; + Buttons = ScrollingListDialogButtons.HistoryOk; + _localizedStringFinder = localizedStringFinder; + _questDataProvider = questDataProvider; + _characterProvider = characterProvider; + HistoryAction += (_, _) => ShowHistory(); + ProgressAction += (_, _) => ShowProgress(); + + _page = QuestPage.Progress; } - foreach (var questName in _cachedHistory) + protected override void OnUpdateControl(GameTime gameTime) { - var nextItem = new QuestStatusListDialogItem(this, QuestPage.History) + if (_questDataProvider.QuestHistory != _cachedHistory) { - QuestName = questName, - QuestProgress = _localizedStringFinder.GetString(EOResourceID.QUEST_COMPLETED), - }; - nextItem.SetScrollWheelHandler(this); - AddItemToList(nextItem, sortList: false); - } - - _scrollBar.ScrollToTop(); - Buttons = ScrollingListDialogButtons.ProgressOk; - } + _cachedHistory = _questDataProvider.QuestHistory; + if (_page == QuestPage.History) + ShowHistory(); + } + else if (_questDataProvider.QuestProgress != _cachedProgress) + { + _cachedProgress = _questDataProvider.QuestProgress; + if (_page == QuestPage.Progress) + ShowProgress(); + } - private void ShowProgress() - { - ClearItemList(); - SetTitle(QuestPage.Progress); + base.OnUpdateControl(gameTime); + } - if (_cachedProgress.Count == 0) + private void ShowHistory() { - var nextItem = new QuestStatusListDialogItem(this, QuestPage.Progress) + ClearItemList(); + SetTitle(QuestPage.History); + + if (_cachedHistory.Count == 0) + { + var nextItem = new QuestStatusListDialogItem(this, QuestPage.History) + { + QuestName = _localizedStringFinder.GetString(EOResourceID.QUEST_DID_NOT_FINISH_ANY), + ShowIcons = false + }; + nextItem.SetScrollWheelHandler(this); + AddItemToList(nextItem, sortList: false); + } + + foreach (var questName in _cachedHistory) { - QuestName = _localizedStringFinder.GetString(EOResourceID.QUEST_DID_NOT_START_ANY), - ShowIcons = false, - }; - nextItem.SetScrollWheelHandler(this); - AddItemToList(nextItem, sortList: false); + var nextItem = new QuestStatusListDialogItem(this, QuestPage.History) + { + QuestName = questName, + QuestProgress = _localizedStringFinder.GetString(EOResourceID.QUEST_COMPLETED), + }; + nextItem.SetScrollWheelHandler(this); + AddItemToList(nextItem, sortList: false); + } + + _scrollBar.ScrollToTop(); + Buttons = ScrollingListDialogButtons.ProgressOk; } - foreach (var quest in _cachedProgress) + private void ShowProgress() { - var nextItem = new QuestStatusListDialogItem(this, QuestPage.Progress) + ClearItemList(); + SetTitle(QuestPage.Progress); + + if (_cachedProgress.Count == 0) + { + var nextItem = new QuestStatusListDialogItem(this, QuestPage.Progress) + { + QuestName = _localizedStringFinder.GetString(EOResourceID.QUEST_DID_NOT_START_ANY), + ShowIcons = false, + }; + nextItem.SetScrollWheelHandler(this); + AddItemToList(nextItem, sortList: false); + } + + foreach (var quest in _cachedProgress) { - QuestName = quest.Name, - QuestStep = quest.Description, - Icon = (QuestStatusListDialogItem.QuestStatusIcon)quest.IconIndex, - QuestProgress = quest.Target > 0 ? $"{quest.Progress} / {quest.Target}" : "n / a" - }; - nextItem.SetScrollWheelHandler(this); - AddItemToList(nextItem, sortList: false); + var nextItem = new QuestStatusListDialogItem(this, QuestPage.Progress) + { + QuestName = quest.Name, + QuestStep = quest.Description, + Icon = (QuestStatusListDialogItem.QuestStatusIcon)quest.IconIndex, + QuestProgress = quest.Target > 0 ? $"{quest.Progress} / {quest.Target}" : "n / a" + }; + nextItem.SetScrollWheelHandler(this); + AddItemToList(nextItem, sortList: false); + } + + _scrollBar.ScrollToTop(); + Buttons = ScrollingListDialogButtons.HistoryOk; } - _scrollBar.ScrollToTop(); - Buttons = ScrollingListDialogButtons.HistoryOk; - } - - private void SetTitle(QuestPage page) - { - var resource = page == QuestPage.Progress - ? EOResourceID.QUEST_PROGRESS - : EOResourceID.QUEST_HISTORY; - var description = _localizedStringFinder.GetString(resource); + private void SetTitle(QuestPage page) + { + var resource = page == QuestPage.Progress + ? EOResourceID.QUEST_PROGRESS + : EOResourceID.QUEST_HISTORY; + var description = _localizedStringFinder.GetString(resource); - Title = $"{_characterProvider.MainCharacter.Name}'s {description}"; + Title = $"{_characterProvider.MainCharacter.Name}'s {description}"; + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/QuestStatusListDialogItem.cs b/EndlessClient/Dialogs/QuestStatusListDialogItem.cs index a728e179d..2e3f99dfc 100644 --- a/EndlessClient/Dialogs/QuestStatusListDialogItem.cs +++ b/EndlessClient/Dialogs/QuestStatusListDialogItem.cs @@ -5,129 +5,130 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using XNAControls; -namespace EndlessClient.Dialogs; - -public class QuestStatusListDialogItem : ListDialogItem +namespace EndlessClient.Dialogs { - public enum QuestStatusIcon - { - None = 0, - Talk = 1, - Item = 2, - Kill = 3, - Step = 4, - Complete = 5, - None2 = 6, // ? - None3 = 7, // ? - }; - - private static readonly Vector2 _firstIconPosition = new Vector2(6, 0); - private static readonly Vector2 _secondIconPosition = new Vector2(151, 0); - private readonly Vector2 _signalPosition; - - private readonly IXNALabel _progress; - private readonly Texture2D _iconTexture; - private readonly QuestPage _page; - - public QuestStatusIcon Icon { get; set; } - - public string QuestName + public class QuestStatusListDialogItem : ListDialogItem { - get => PrimaryText; - set => PrimaryText = value; - } + public enum QuestStatusIcon + { + None = 0, + Talk = 1, + Item = 2, + Kill = 3, + Step = 4, + Complete = 5, + None2 = 6, // ? + None3 = 7, // ? + }; - public string QuestStep - { - get => SubText; - set => SubText = value; - } + private static readonly Vector2 _firstIconPosition = new Vector2(6, 0); + private static readonly Vector2 _secondIconPosition = new Vector2(151, 0); + private readonly Vector2 _signalPosition; - public string QuestProgress - { - get => _progress.Text; - set => _progress.Text = value; - } + private readonly IXNALabel _progress; + private readonly Texture2D _iconTexture; + private readonly QuestPage _page; - public bool ShowIcons { get; set; } + public QuestStatusIcon Icon { get; set; } - public QuestStatusListDialogItem(QuestStatusDialog parent, QuestPage page) - : base(parent, ListItemStyle.Small) - { - _iconTexture = parent.GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); - ShowIcons = true; + public string QuestName + { + get => PrimaryText; + set => PrimaryText = value; + } - SetSize(427, 16); + public string QuestStep + { + get => SubText; + set => SubText = value; + } - _primaryText.DrawPosition += new Vector2(25, 2); - _subText.DrawPosition = new Vector2(169, _primaryText.DrawPosition.Y); - ((DrawableGameComponent)_subText).Visible = true; + public string QuestProgress + { + get => _progress.Text; + set => _progress.Text = value; + } - PrimaryText = " "; - SubText = " "; + public bool ShowIcons { get; set; } - _progress = new XNALabel(Constants.FontSize08pt5) + public QuestStatusListDialogItem(QuestStatusDialog parent, QuestPage page) + : base(parent, ListItemStyle.Small) { - DrawPosition = new Vector2(page == QuestPage.Progress ? 353 : 289, _primaryText.DrawPosition.Y), - AutoSize = true, - BackColor = _primaryText.BackColor, - ForeColor = _primaryText.ForeColor, - Text = " ", - Visible = true, - }; + _iconTexture = parent.GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); + ShowIcons = true; - _signalPosition = page == QuestPage.Progress - ? new Vector2(334, 2) - : new Vector2(270, 2); + SetSize(427, 16); - Icon = page == QuestPage.Progress - ? QuestStatusIcon.None - : QuestStatusIcon.Complete; - _page = page; - } - - public override void Initialize() - { - _progress.Initialize(); - _progress.SetParentControl(this); + _primaryText.DrawPosition += new Vector2(25, 2); + _subText.DrawPosition = new Vector2(169, _primaryText.DrawPosition.Y); + ((DrawableGameComponent)_subText).Visible = true; - base.Initialize(); - } + PrimaryText = " "; + SubText = " "; - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + _progress = new XNALabel(Constants.FontSize08pt5) + { + DrawPosition = new Vector2(page == QuestPage.Progress ? 353 : 289, _primaryText.DrawPosition.Y), + AutoSize = true, + BackColor = _primaryText.BackColor, + ForeColor = _primaryText.ForeColor, + Text = " ", + Visible = true, + }; + + _signalPosition = page == QuestPage.Progress + ? new Vector2(334, 2) + : new Vector2(270, 2); + + Icon = page == QuestPage.Progress + ? QuestStatusIcon.None + : QuestStatusIcon.Complete; + _page = page; + } - if (ShowIcons) + public override void Initialize() { - _spriteBatch.Begin(); + _progress.Initialize(); + _progress.SetParentControl(this); + + base.Initialize(); + } - _spriteBatch.Draw(_iconTexture, - DrawPositionWithParentOffset + _firstIconPosition, - GetIconSourceRectangle(_page == QuestPage.Progress ? QuestStatusIcon.None : QuestStatusIcon.Complete), Color.White); + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - if (_page == QuestPage.Progress) + if (ShowIcons) { + _spriteBatch.Begin(); + _spriteBatch.Draw(_iconTexture, - DrawPositionWithParentOffset + _secondIconPosition, - GetIconSourceRectangle(Icon), Color.White); - } + DrawPositionWithParentOffset + _firstIconPosition, + GetIconSourceRectangle(_page == QuestPage.Progress ? QuestStatusIcon.None : QuestStatusIcon.Complete), Color.White); + + if (_page == QuestPage.Progress) + { + _spriteBatch.Draw(_iconTexture, + DrawPositionWithParentOffset + _secondIconPosition, + GetIconSourceRectangle(Icon), Color.White); + } - _spriteBatch.Draw(_iconTexture, - DrawPositionWithParentOffset + _signalPosition, - GetSignalSourceRectangle(), Color.White); + _spriteBatch.Draw(_iconTexture, + DrawPositionWithParentOffset + _signalPosition, + GetSignalSourceRectangle(), Color.White); - _spriteBatch.End(); + _spriteBatch.End(); + } } - } - private static Rectangle GetIconSourceRectangle(QuestStatusIcon index) - { - return new Rectangle((int)index * 15, 0, 15, 15); - } + private static Rectangle GetIconSourceRectangle(QuestStatusIcon index) + { + return new Rectangle((int)index * 15, 0, 15, 15); + } - private static Rectangle GetSignalSourceRectangle() - { - return new Rectangle(0, 15, 15, 15); + private static Rectangle GetSignalSourceRectangle() + { + return new Rectangle(0, 15, 15, 15); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ScrollingListDialog.cs b/EndlessClient/Dialogs/ScrollingListDialog.cs index 9095866bf..d4eb5596c 100644 --- a/EndlessClient/Dialogs/ScrollingListDialog.cs +++ b/EndlessClient/Dialogs/ScrollingListDialog.cs @@ -13,596 +13,597 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs; - -[Flags] -public enum ScrollingListDialogButtons -{ - None = 0x00, - Add = 0x01, - Cancel = 0x02, - Back = 0x04, - Next = 0x08, - Ok = 0x10, - History = 0x20, - Progress = 0x40, - Delete = 0x80, - DualButtons = 0x800, - // indicates a configuration in which a pairing of DualButtons is already defined, but the order is reversed - Alternate = 0x1000, - - AddCancel = DualButtons | Add | Cancel, - BackCancel = DualButtons | Back | Cancel, - BackOk = DualButtons | Back | Ok, - CancelOk = DualButtons | Cancel | Ok, - OkCancel = DualButtons | Cancel | Ok | Alternate, - BackNext = DualButtons | Back | Next, - CancelNext = DualButtons | Cancel | Next, - HistoryOk = DualButtons | History | Ok, - ProgressOk = DualButtons | Progress | Ok, - DeleteCancel = DualButtons | Delete | Cancel, - - // There is only one button, but we want it to show on the right side as if it were a dual button setting - OffsetCancel = DualButtons | Alternate | Cancel, -} - -public enum DialogType +namespace EndlessClient.Dialogs { - // large - Shop, - FriendIgnore = Shop, - Locker = Shop, - Message = Shop, - Guild = Shop, - Inn = Shop, - Law = Shop, + [Flags] + public enum ScrollingListDialogButtons + { + None = 0x00, + Add = 0x01, + Cancel = 0x02, + Back = 0x04, + Next = 0x08, + Ok = 0x10, + History = 0x20, + Progress = 0x40, + Delete = 0x80, + DualButtons = 0x800, + // indicates a configuration in which a pairing of DualButtons is already defined, but the order is reversed + Alternate = 0x1000, + + AddCancel = DualButtons | Add | Cancel, + BackCancel = DualButtons | Back | Cancel, + BackOk = DualButtons | Back | Ok, + CancelOk = DualButtons | Cancel | Ok, + OkCancel = DualButtons | Cancel | Ok | Alternate, + BackNext = DualButtons | Back | Next, + CancelNext = DualButtons | Cancel | Next, + HistoryOk = DualButtons | History | Ok, + ProgressOk = DualButtons | Progress | Ok, + DeleteCancel = DualButtons | Delete | Cancel, + + // There is only one button, but we want it to show on the right side as if it were a dual button setting + OffsetCancel = DualButtons | Alternate | Cancel, + } - // large / alternate background - Help, + public enum DialogType + { + // large + Shop, + FriendIgnore = Shop, + Locker = Shop, + Message = Shop, + Guild = Shop, + Inn = Shop, + Law = Shop, - // large no scroll - Chest, + // large / alternate background + Help, - // medium - QuestProgressHistory, - Board = QuestProgressHistory, + // large no scroll + Chest, - // small - NpcQuestDialog, + // medium + QuestProgressHistory, + Board = QuestProgressHistory, - // small no scroll - BankAccountDialog, + // small + NpcQuestDialog, - Jukebox, - Barber, -} + // small no scroll + BankAccountDialog, -public class ScrollingListDialog : BaseEODialog -{ - private readonly List _listItems; - protected readonly ScrollBar _scrollBar; + Jukebox, + Barber, + } - protected readonly IXNALabel _titleText; - private ListDialogItem.ListItemStyle _listItemType; + public class ScrollingListDialog : BaseEODialog + { + private readonly List _listItems; + protected readonly ScrollBar _scrollBar; - protected readonly XNAButton _add, _back, _cancel; - protected readonly XNAButton _next, _ok, _delete; - protected readonly XNAButton _history, _progress; + protected readonly IXNALabel _titleText; + private ListDialogItem.ListItemStyle _listItemType; - protected readonly Vector2 _button1Position, _button2Position, _buttonCenterPosition; + protected readonly XNAButton _add, _back, _cancel; + protected readonly XNAButton _next, _ok, _delete; + protected readonly XNAButton _history, _progress; - private ScrollingListDialogButtons _buttons; + protected readonly Vector2 _button1Position, _button2Position, _buttonCenterPosition; - public IReadOnlyList NamesList => _listItems.Select(item => item.PrimaryText).ToList(); + private ScrollingListDialogButtons _buttons; - public string Title - { - get => _titleText.Text; - set => _titleText.Text = value; - } + public IReadOnlyList NamesList => _listItems.Select(item => item.PrimaryText).ToList(); - public int ItemsToShow - { - get + public string Title { - if (ListItemType == ListDialogItem.ListItemStyle.Large) - return 5; + get => _titleText.Text; + set => _titleText.Text = value; + } - switch (DialogType) + public int ItemsToShow + { + get { + if (ListItemType == ListDialogItem.ListItemStyle.Large) + return 5; - case DialogType.Shop: - case DialogType.Help: - case DialogType.QuestProgressHistory: - return 12; - case DialogType.NpcQuestDialog: return 6; - default: throw new NotImplementedException(); + switch (DialogType) + { + + case DialogType.Shop: + case DialogType.Help: + case DialogType.QuestProgressHistory: + return 12; + case DialogType.NpcQuestDialog: return 6; + default: throw new NotImplementedException(); + } } } - } - public ListDialogItem.ListItemStyle ListItemType - { - get => _listItemType; - set + public ListDialogItem.ListItemStyle ListItemType { - if (value == ListDialogItem.ListItemStyle.Large && DialogType == DialogType.NpcQuestDialog) - throw new InvalidOperationException("Can't use large ListDialogItem with small scrolling dialog"); + get => _listItemType; + set + { + if (value == ListDialogItem.ListItemStyle.Large && DialogType == DialogType.NpcQuestDialog) + throw new InvalidOperationException("Can't use large ListDialogItem with small scrolling dialog"); - _listItemType = value; - _scrollBar.LinesToRender = ItemsToShow; + _listItemType = value; + _scrollBar.LinesToRender = ItemsToShow; + } } - } - public ScrollingListDialogButtons Buttons - { - get => _buttons; - set + public ScrollingListDialogButtons Buttons { - _buttons = value; - _add.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Add); - _back.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Back); - _next.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Next); - _ok.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Ok); - _cancel.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Cancel); - _history.Visible = Buttons.HasFlag(ScrollingListDialogButtons.History); - _progress.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Progress); - _delete.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Delete); - - if (Buttons.HasFlag(ScrollingListDialogButtons.DualButtons)) + get => _buttons; + set { - if (Buttons == ScrollingListDialogButtons.BackCancel || - Buttons == ScrollingListDialogButtons.AddCancel || - Buttons == ScrollingListDialogButtons.DeleteCancel) + _buttons = value; + _add.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Add); + _back.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Back); + _next.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Next); + _ok.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Ok); + _cancel.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Cancel); + _history.Visible = Buttons.HasFlag(ScrollingListDialogButtons.History); + _progress.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Progress); + _delete.Visible = Buttons.HasFlag(ScrollingListDialogButtons.Delete); + + if (Buttons.HasFlag(ScrollingListDialogButtons.DualButtons)) { - _add.DrawPosition = _button1Position; - _back.DrawPosition = _button1Position; - _delete.DrawPosition = _button1Position; - _cancel.DrawPosition = _button2Position; + if (Buttons == ScrollingListDialogButtons.BackCancel || + Buttons == ScrollingListDialogButtons.AddCancel || + Buttons == ScrollingListDialogButtons.DeleteCancel) + { + _add.DrawPosition = _button1Position; + _back.DrawPosition = _button1Position; + _delete.DrawPosition = _button1Position; + _cancel.DrawPosition = _button2Position; + } + else + { + var alternate = Buttons.HasFlag(ScrollingListDialogButtons.Alternate); + + _back.DrawPosition = _button1Position; + _cancel.DrawPosition = alternate ? _button2Position : _button1Position; + _history.DrawPosition = _button1Position; + _progress.DrawPosition = _button1Position; + + _next.DrawPosition = _button2Position; + _ok.DrawPosition = alternate ? _button1Position : _button2Position; + } } else { - var alternate = Buttons.HasFlag(ScrollingListDialogButtons.Alternate); - - _back.DrawPosition = _button1Position; - _cancel.DrawPosition = alternate ? _button2Position : _button1Position; - _history.DrawPosition = _button1Position; - _progress.DrawPosition = _button1Position; - - _next.DrawPosition = _button2Position; - _ok.DrawPosition = alternate ? _button1Position : _button2Position; + _add.DrawPosition = _buttonCenterPosition; + _back.DrawPosition = _buttonCenterPosition; + _next.DrawPosition = _buttonCenterPosition; + _ok.DrawPosition = _buttonCenterPosition; + _cancel.DrawPosition = _buttonCenterPosition; } } - else - { - _add.DrawPosition = _buttonCenterPosition; - _back.DrawPosition = _buttonCenterPosition; - _next.DrawPosition = _buttonCenterPosition; - _ok.DrawPosition = _buttonCenterPosition; - _cancel.DrawPosition = _buttonCenterPosition; - } } - } - public DialogType DialogType { get; } + public DialogType DialogType { get; } - public event EventHandler AddAction; + public event EventHandler AddAction; - public event EventHandler BackAction; + public event EventHandler BackAction; - public event EventHandler NextAction; + public event EventHandler NextAction; - public event EventHandler HistoryAction; + public event EventHandler HistoryAction; - public event EventHandler ProgressAction; + public event EventHandler ProgressAction; - public ScrollingListDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - DialogType dialogType = DialogType.Shop) - : base(nativeGraphicsManager, isInGame: true) - { - DialogType = dialogType; + public ScrollingListDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + DialogType dialogType = DialogType.Shop) + : base(nativeGraphicsManager, isInGame: true) + { + DialogType = dialogType; - _listItems = new List(); + _listItems = new List(); - _titleText = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = GetTitleDrawArea(DialogType), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText, - Visible = DialogType != DialogType.Chest, - }; - _titleText.SetParentControl(this); - - _scrollBar = new ScrollBar(new Vector2(DialogType == DialogType.QuestProgressHistory ? 449 : 252, 44), new Vector2(16, GetScrollBarHeight(DialogType)), ScrollBarColors.LightOnMed, GraphicsManager) - { - Visible = DialogType != DialogType.Chest && DialogType != DialogType.BankAccountDialog && DialogType != DialogType.Jukebox, - }; - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); + _titleText = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = GetTitleDrawArea(DialogType), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText, + Visible = DialogType != DialogType.Chest, + }; + _titleText.SetParentControl(this); - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, GetBackgroundTexture(DialogType)); - BackgroundTextureSource = GetBackgroundSourceRectangle(BackgroundTexture, DialogType); + _scrollBar = new ScrollBar(new Vector2(DialogType == DialogType.QuestProgressHistory ? 449 : 252, 44), new Vector2(16, GetScrollBarHeight(DialogType)), ScrollBarColors.LightOnMed, GraphicsManager) + { + Visible = DialogType != DialogType.Chest && DialogType != DialogType.BankAccountDialog && DialogType != DialogType.Jukebox, + }; + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); - _add = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Add), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Add)) - { - Visible = false, - UpdateOrder = 1, - }; - _add.SetParentControl(this); - _add.OnClick += (o, e) => AddAction?.Invoke(o, e); - - _back = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Back), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Back)) - { - Visible = false, - UpdateOrder = 1, - }; - _back.SetParentControl(this); - _back.OnClick += (o, e) => BackAction?.Invoke(o, e); - - _next = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Next), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Next)) - { - Visible = false, - UpdateOrder = 1, - }; - _next.SetParentControl(this); - _next.OnClick += (o, e) => NextAction?.Invoke(o, e); - - _history = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.History), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.History)) - { - Visible = false, - UpdateOrder = 1, - }; - _history.SetParentControl(this); - _history.OnClick += (o, e) => HistoryAction?.Invoke(o, e); - - _progress = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Progress), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Progress)) - { - Visible = false, - UpdateOrder = 1, - }; - _progress.SetParentControl(this); - _progress.OnClick += (o, e) => ProgressAction?.Invoke(o, e); - - _delete = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Delete), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Delete)) - { - Visible = false, - UpdateOrder = 1, - }; - _delete.SetParentControl(this); - _delete.OnClick += (o, e) => ProgressAction?.Invoke(o, e); - - _ok = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)) - { - Visible = false, - UpdateOrder = 2, - }; - _ok.SetParentControl(this); - _ok.OnClick += CloseButton_Click; - - _cancel = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)) - { - Visible = false, - UpdateOrder = 2, - }; - _cancel.SetParentControl(this); - _cancel.OnClick += CloseButton_Click; + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, GetBackgroundTexture(DialogType)); + BackgroundTextureSource = GetBackgroundSourceRectangle(BackgroundTexture, DialogType); - _button1Position = GetButton1Position(DrawArea, _ok.DrawArea, DialogType); - _button2Position = GetButton2Position(DrawArea, _ok.DrawArea, DialogType); - _buttonCenterPosition = GetButtonCenterPosition(DrawArea, _ok.DrawArea, DialogType); + _add = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Add), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Add)) + { + Visible = false, + UpdateOrder = 1, + }; + _add.SetParentControl(this); + _add.OnClick += (o, e) => AddAction?.Invoke(o, e); - Buttons = ScrollingListDialogButtons.AddCancel; + _back = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Back), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Back)) + { + Visible = false, + UpdateOrder = 1, + }; + _back.SetParentControl(this); + _back.OnClick += (o, e) => BackAction?.Invoke(o, e); - CenterInGameView(); + _next = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Next), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Next)) + { + Visible = false, + UpdateOrder = 1, + }; + _next.SetParentControl(this); + _next.OnClick += (o, e) => NextAction?.Invoke(o, e); - if (!Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, 15); - } + _history = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.History), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.History)) + { + Visible = false, + UpdateOrder = 1, + }; + _history.SetParentControl(this); + _history.OnClick += (o, e) => HistoryAction?.Invoke(o, e); - protected virtual void CloseButton_Click(object sender, MouseEventArgs e) - { - if (sender == _ok) - Close(XNADialogResult.OK); - else if (sender == _cancel) - Close(XNADialogResult.Cancel); - } + _progress = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Progress), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Progress)) + { + Visible = false, + UpdateOrder = 1, + }; + _progress.SetParentControl(this); + _progress.OnClick += (o, e) => ProgressAction?.Invoke(o, e); - public void SetItemList(List itemList) - { - if (!itemList.All(x => x.Style == ListItemType)) - throw new ArgumentException($"Expected items of type {ListItemType}", nameof(itemList)); + _delete = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Delete), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Delete)) + { + Visible = false, + UpdateOrder = 1, + }; + _delete.SetParentControl(this); + _delete.OnClick += (o, e) => ProgressAction?.Invoke(o, e); - ClearItemList(); + _ok = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)) + { + Visible = false, + UpdateOrder = 2, + }; + _ok.SetParentControl(this); + _ok.OnClick += CloseButton_Click; - _scrollBar.UpdateDimensions(itemList.Count); + _cancel = new XNAButton(dialogButtonService.SmallButtonSheet, Vector2.Zero, + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)) + { + Visible = false, + UpdateOrder = 2, + }; + _cancel.SetParentControl(this); + _cancel.OnClick += CloseButton_Click; - for (int i = 0; i < itemList.Count; ++i) - { - _listItems.Add(itemList[i]); - _listItems[i].Index = i; - if (i > _scrollBar.LinesToRender) - _listItems[i].Visible = false; + _button1Position = GetButton1Position(DrawArea, _ok.DrawArea, DialogType); + _button2Position = GetButton2Position(DrawArea, _ok.DrawArea, DialogType); + _buttonCenterPosition = GetButtonCenterPosition(DrawArea, _ok.DrawArea, DialogType); + + Buttons = ScrollingListDialogButtons.AddCancel; + + CenterInGameView(); - _listItems[i].Initialize(); + if (!Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, 15); } - } - public void AddItemToList(ListDialogItem item, bool sortList) - { - _listItems.Add(item); + protected virtual void CloseButton_Click(object sender, MouseEventArgs e) + { + if (sender == _ok) + Close(XNADialogResult.OK); + else if (sender == _cancel) + Close(XNADialogResult.Cancel); + } - if (sortList) - _listItems.Sort((item1, item2) => item1.PrimaryText.CompareTo(item2.PrimaryText)); + public void SetItemList(List itemList) + { + if (!itemList.All(x => x.Style == ListItemType)) + throw new ArgumentException($"Expected items of type {ListItemType}", nameof(itemList)); - for (int i = 0; i < _listItems.Count; ++i) - _listItems[i].Index = i; + ClearItemList(); - item.Initialize(); + _scrollBar.UpdateDimensions(itemList.Count); - _scrollBar.UpdateDimensions(_listItems.Count); - } + for (int i = 0; i < itemList.Count; ++i) + { + _listItems.Add(itemList[i]); + _listItems[i].Index = i; + if (i > _scrollBar.LinesToRender) + _listItems[i].Visible = false; - public void RemoveFromList(ListDialogItem item) - { - _listItems.Remove(item); + _listItems[i].Initialize(); + } + } - _scrollBar.UpdateDimensions(_listItems.Count); - if (_listItems.Count <= _scrollBar.LinesToRender) - _scrollBar.ScrollToTop(); + public void AddItemToList(ListDialogItem item, bool sortList) + { + _listItems.Add(item); - for (int i = 0; i < _listItems.Count; ++i) - _listItems[i].Index = i; + if (sortList) + _listItems.Sort((item1, item2) => item1.PrimaryText.CompareTo(item2.PrimaryText)); - item.Dispose(); - } + for (int i = 0; i < _listItems.Count; ++i) + _listItems[i].Index = i; - public void HighlightTextByLabel(IReadOnlyList activeLabels) - { - var matchingListItems = _listItems.Where(x => activeLabels.Any(y => y.Equals(x.PrimaryText, StringComparison.InvariantCultureIgnoreCase))); - foreach (var item in matchingListItems) - { - item.Highlight(); + item.Initialize(); + + _scrollBar.UpdateDimensions(_listItems.Count); } - } - public void ClearHighlightedText() - { - foreach (var item in _listItems) - item.ClearHighlight(); - } + public void RemoveFromList(ListDialogItem item) + { + _listItems.Remove(item); - public void ClearItemList() - { - foreach (var item in _listItems) - item.Dispose(); + _scrollBar.UpdateDimensions(_listItems.Count); + if (_listItems.Count <= _scrollBar.LinesToRender) + _scrollBar.ScrollToTop(); - _listItems.Clear(); - _scrollBar.UpdateDimensions(0); - _scrollBar.ScrollToTop(); - } + for (int i = 0; i < _listItems.Count; ++i) + _listItems[i].Index = i; - public void AddTextAsListItems(BitmapFont font, bool insertLineBreaks, List linkClickActions, params string[] messages) - { - ListItemType = ListDialogItem.ListItemStyle.Small; + item.Dispose(); + } - var drawStrings = new List(); - var ts = new TextSplitter(string.Empty, font) { LineLength = 200 }; - foreach (string s in messages) + public void HighlightTextByLabel(IReadOnlyList activeLabels) { - ts.Text = s; - drawStrings.AddRange(ts.NeedsProcessing ? ts.SplitIntoLines() : new[] { s }); - if (insertLineBreaks) + var matchingListItems = _listItems.Where(x => activeLabels.Any(y => y.Equals(x.PrimaryText, StringComparison.InvariantCultureIgnoreCase))); + foreach (var item in matchingListItems) { - drawStrings.Add(" "); + item.Highlight(); } } - int linkIndex = 0; - - foreach (string s in drawStrings) + public void ClearHighlightedText() { - var link = s.Length > 0 && s[0] == '*'; - var nextItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small) - { - PrimaryText = link ? s.Remove(0, 1) : s - }; - - if (link && linkIndex < linkClickActions.Count) - { - var linkClickAction = linkClickActions[linkIndex++]; - nextItem.SetPrimaryClickAction((_, _) => linkClickAction()); - } - - AddItemToList(nextItem, sortList: false); + foreach (var item in _listItems) + item.ClearHighlight(); } - } + public void ClearItemList() + { + foreach (var item in _listItems) + item.Dispose(); - public override void Initialize() - { - _add.Initialize(); - _back.Initialize(); - _next.Initialize(); - _ok.Initialize(); - _cancel.Initialize(); - _scrollBar.Initialize(); - _titleText.Initialize(); - - base.Initialize(); - } + _listItems.Clear(); + _scrollBar.UpdateDimensions(0); + _scrollBar.ScrollToTop(); + } - protected override void OnUpdateControl(GameTime gameTime) - { - if (_listItems.Count > _scrollBar.LinesToRender) + public void AddTextAsListItems(BitmapFont font, bool insertLineBreaks, List linkClickActions, params string[] messages) { - for (int i = 0; i < _listItems.Count; ++i) + ListItemType = ListDialogItem.ListItemStyle.Small; + + var drawStrings = new List(); + var ts = new TextSplitter(string.Empty, font) { LineLength = 200 }; + foreach (string s in messages) { - var curr = _listItems[i]; - if (i < _scrollBar.ScrollOffset) + ts.Text = s; + drawStrings.AddRange(ts.NeedsProcessing ? ts.SplitIntoLines() : new[] { s }); + if (insertLineBreaks) { - curr.Visible = false; - continue; + drawStrings.Add(" "); } + } + + int linkIndex = 0; - if (i < _scrollBar.LinesToRender + _scrollBar.ScrollOffset) + foreach (string s in drawStrings) + { + var link = s.Length > 0 && s[0] == '*'; + var nextItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Small) { - curr.Visible = true; - curr.Index = i - _scrollBar.ScrollOffset; - } - else + PrimaryText = link ? s.Remove(0, 1) : s + }; + + if (link && linkIndex < linkClickActions.Count) { - curr.Visible = false; + var linkClickAction = linkClickActions[linkIndex++]; + nextItem.SetPrimaryClickAction((_, _) => linkClickAction()); } + + AddItemToList(nextItem, sortList: false); } + } - else if (_listItems.Any(_item => !_item.Visible)) + + public override void Initialize() { - _listItems.ForEach(_item => _item.Visible = true); + _add.Initialize(); + _back.Initialize(); + _next.Initialize(); + _ok.Initialize(); + _cancel.Initialize(); + _scrollBar.Initialize(); + _titleText.Initialize(); + + base.Initialize(); } - base.OnUpdateControl(gameTime); - } + protected override void OnUpdateControl(GameTime gameTime) + { + if (_listItems.Count > _scrollBar.LinesToRender) + { + for (int i = 0; i < _listItems.Count; ++i) + { + var curr = _listItems[i]; + if (i < _scrollBar.ScrollOffset) + { + curr.Visible = false; + continue; + } + + if (i < _scrollBar.LinesToRender + _scrollBar.ScrollOffset) + { + curr.Visible = true; + curr.Index = i - _scrollBar.ScrollOffset; + } + else + { + curr.Visible = false; + } + } + } + else if (_listItems.Any(_item => !_item.Visible)) + { + _listItems.ForEach(_item => _item.Visible = true); + } - protected static Rectangle GetTitleDrawArea(DialogType size) - { - switch (size) + base.OnUpdateControl(gameTime); + } + + protected static Rectangle GetTitleDrawArea(DialogType size) { - case DialogType.Shop: - case DialogType.Help: - case DialogType.Chest: return new Rectangle(16, 13, 253, 19); - case DialogType.QuestProgressHistory: - return new Rectangle(18, 14, 452, 19); - case DialogType.Jukebox: return new Rectangle(24, 20, 263, 19); - case DialogType.NpcQuestDialog: return new Rectangle(16, 16, 255, 18); - case DialogType.BankAccountDialog: return new Rectangle(129, 20, 121, 16); - default: throw new NotImplementedException(); + switch (size) + { + case DialogType.Shop: + case DialogType.Help: + case DialogType.Chest: return new Rectangle(16, 13, 253, 19); + case DialogType.QuestProgressHistory: + return new Rectangle(18, 14, 452, 19); + case DialogType.Jukebox: return new Rectangle(24, 20, 263, 19); + case DialogType.NpcQuestDialog: return new Rectangle(16, 16, 255, 18); + case DialogType.BankAccountDialog: return new Rectangle(129, 20, 121, 16); + default: throw new NotImplementedException(); + } } - } - protected static int GetScrollBarHeight(DialogType size) - { - switch (size) + protected static int GetScrollBarHeight(DialogType size) { - case DialogType.Shop: - case DialogType.Help: - case DialogType.Chest: - case DialogType.QuestProgressHistory: - return 199; - case DialogType.Jukebox: - case DialogType.NpcQuestDialog: - case DialogType.BankAccountDialog: return 99; - default: throw new NotImplementedException(); + switch (size) + { + case DialogType.Shop: + case DialogType.Help: + case DialogType.Chest: + case DialogType.QuestProgressHistory: + return 199; + case DialogType.Jukebox: + case DialogType.NpcQuestDialog: + case DialogType.BankAccountDialog: return 99; + default: throw new NotImplementedException(); + } } - } - private static int GetBackgroundTexture(DialogType size) - { - switch (size) + private static int GetBackgroundTexture(DialogType size) { - case DialogType.Shop: return 52; - case DialogType.Help: return 64; - case DialogType.Chest: return 51; - case DialogType.QuestProgressHistory: return 59; - case DialogType.Jukebox: return 60; - case DialogType.NpcQuestDialog: return 67; - case DialogType.BankAccountDialog: return 53; - default: throw new NotImplementedException(); + switch (size) + { + case DialogType.Shop: return 52; + case DialogType.Help: return 64; + case DialogType.Chest: return 51; + case DialogType.QuestProgressHistory: return 59; + case DialogType.Jukebox: return 60; + case DialogType.NpcQuestDialog: return 67; + case DialogType.BankAccountDialog: return 53; + default: throw new NotImplementedException(); + } } - } - protected static Rectangle? GetBackgroundSourceRectangle(Texture2D backgroundTexture, DialogType size) - { - switch (size) + protected static Rectangle? GetBackgroundSourceRectangle(Texture2D backgroundTexture, DialogType size) { - case DialogType.Shop: - case DialogType.Help: - case DialogType.Chest: return null; - case DialogType.QuestProgressHistory: - return new Rectangle(0, 0, backgroundTexture.Width, backgroundTexture.Height / 2); - case DialogType.Jukebox: - case DialogType.NpcQuestDialog: - case DialogType.BankAccountDialog: return null; - default: throw new NotImplementedException(); + switch (size) + { + case DialogType.Shop: + case DialogType.Help: + case DialogType.Chest: return null; + case DialogType.QuestProgressHistory: + return new Rectangle(0, 0, backgroundTexture.Width, backgroundTexture.Height / 2); + case DialogType.Jukebox: + case DialogType.NpcQuestDialog: + case DialogType.BankAccountDialog: return null; + default: throw new NotImplementedException(); + } } - } - private static Vector2 GetButton1Position(Rectangle dialogArea, Rectangle buttonArea, DialogType size) - { - var yCoord = GetButtonYCoordinate(dialogArea); - switch (size) + private static Vector2 GetButton1Position(Rectangle dialogArea, Rectangle buttonArea, DialogType size) { - // buttons are centered on these dialogs - case DialogType.Shop: - case DialogType.Help: - case DialogType.Chest: - case DialogType.BankAccountDialog: - case DialogType.Jukebox: return new Vector2((int)Math.Floor((dialogArea.Width - buttonArea.Width) / 2.0) - 48, yCoord); - // buttons are offset from center on these dialogs - case DialogType.QuestProgressHistory: - return new Vector2(288, yCoord); - case DialogType.NpcQuestDialog: return new Vector2(89, yCoord); - default: throw new NotImplementedException(); + var yCoord = GetButtonYCoordinate(dialogArea); + switch (size) + { + // buttons are centered on these dialogs + case DialogType.Shop: + case DialogType.Help: + case DialogType.Chest: + case DialogType.BankAccountDialog: + case DialogType.Jukebox: return new Vector2((int)Math.Floor((dialogArea.Width - buttonArea.Width) / 2.0) - 48, yCoord); + // buttons are offset from center on these dialogs + case DialogType.QuestProgressHistory: + return new Vector2(288, yCoord); + case DialogType.NpcQuestDialog: return new Vector2(89, yCoord); + default: throw new NotImplementedException(); + } } - } - private static Vector2 GetButton2Position(Rectangle dialogArea, Rectangle buttonArea, DialogType size) - { - var yCoord = GetButtonYCoordinate(dialogArea); - switch (size) + private static Vector2 GetButton2Position(Rectangle dialogArea, Rectangle buttonArea, DialogType size) { - // buttons are centered on these dialogs - case DialogType.Shop: - case DialogType.Help: - case DialogType.Chest: - case DialogType.BankAccountDialog: - case DialogType.Jukebox: return new Vector2((int)Math.Floor((dialogArea.Width - buttonArea.Width) / 2.0) + 48, yCoord); - // buttons are offset from center on these dialogs - case DialogType.QuestProgressHistory: - return new Vector2(380, yCoord); - case DialogType.NpcQuestDialog: return new Vector2(183, yCoord); - default: throw new NotImplementedException(); + var yCoord = GetButtonYCoordinate(dialogArea); + switch (size) + { + // buttons are centered on these dialogs + case DialogType.Shop: + case DialogType.Help: + case DialogType.Chest: + case DialogType.BankAccountDialog: + case DialogType.Jukebox: return new Vector2((int)Math.Floor((dialogArea.Width - buttonArea.Width) / 2.0) + 48, yCoord); + // buttons are offset from center on these dialogs + case DialogType.QuestProgressHistory: + return new Vector2(380, yCoord); + case DialogType.NpcQuestDialog: return new Vector2(183, yCoord); + default: throw new NotImplementedException(); + } } - } - private static Vector2 GetButtonCenterPosition(Rectangle dialogArea, Rectangle buttonArea, DialogType dialogSize) - { - // chest dialog has a button built in to the graphic that needs to be covered up... - if (dialogSize == DialogType.Chest) - return new Vector2(92, 227); + private static Vector2 GetButtonCenterPosition(Rectangle dialogArea, Rectangle buttonArea, DialogType dialogSize) + { + // chest dialog has a button built in to the graphic that needs to be covered up... + if (dialogSize == DialogType.Chest) + return new Vector2(92, 227); - // bank dialog has a button built in to the graphic that needs to be covered up... - if (dialogSize == DialogType.BankAccountDialog) - return new Vector2(92, 191); + // bank dialog has a button built in to the graphic that needs to be covered up... + if (dialogSize == DialogType.BankAccountDialog) + return new Vector2(92, 191); - // jukebox dialog has a button built in to the graphic that needs to be covered up... - if (dialogSize == DialogType.Jukebox) - return new Vector2(92, 158); + // jukebox dialog has a button built in to the graphic that needs to be covered up... + if (dialogSize == DialogType.Jukebox) + return new Vector2(92, 158); - var yCoord = GetButtonYCoordinate(dialogArea); - return new Vector2((dialogArea.Width - buttonArea.Width) / 2, yCoord); - } + var yCoord = GetButtonYCoordinate(dialogArea); + return new Vector2((dialogArea.Width - buttonArea.Width) / 2, yCoord); + } - private static int GetButtonYCoordinate(Rectangle dialogArea) - { - // this should always be 38 from the bottom - return dialogArea.Height - 38; + private static int GetButtonYCoordinate(Rectangle dialogArea) + { + // this should always be 38 from the bottom + return dialogArea.Height - 38; + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ScrollingMessageDialog.cs b/EndlessClient/Dialogs/ScrollingMessageDialog.cs index 619831db4..26d4762e5 100644 --- a/EndlessClient/Dialogs/ScrollingMessageDialog.cs +++ b/EndlessClient/Dialogs/ScrollingMessageDialog.cs @@ -10,107 +10,108 @@ using System.Collections.Generic; using XNAControls; -namespace EndlessClient.Dialogs; - -public class ScrollingMessageDialog : BaseEODialog +namespace EndlessClient.Dialogs { - const int TEXT_LINE_HEIGHT = 16; + public class ScrollingMessageDialog : BaseEODialog + { + const int TEXT_LINE_HEIGHT = 16; - private readonly XNAButton _ok; - private readonly ScrollBar _scrollBar; - private readonly List _chatStrings = new List(); - private readonly TextSplitter _textSplitter; - private readonly BitmapFont _font; + private readonly XNAButton _ok; + private readonly ScrollBar _scrollBar; + private readonly List _chatStrings = new List(); + private readonly TextSplitter _textSplitter; + private readonly BitmapFont _font; - private static readonly Rectangle TextArea = new Rectangle(27, 69, 300, 110); + private static readonly Rectangle TextArea = new Rectangle(27, 69, 300, 110); - public string MessageText - { - set + public string MessageText { - _chatStrings.Clear(); - _textSplitter.Text = value; - - //special case: blank line, like in the news panel between news items - if (string.IsNullOrWhiteSpace(value)) + set { - _chatStrings.Add(" "); - _scrollBar.UpdateDimensions(_chatStrings.Count); - return; - } + _chatStrings.Clear(); + _textSplitter.Text = value; + + //special case: blank line, like in the news panel between news items + if (string.IsNullOrWhiteSpace(value)) + { + _chatStrings.Add(" "); + _scrollBar.UpdateDimensions(_chatStrings.Count); + return; + } + + //don't do multi-line processing if we don't need to + if (!_textSplitter.NeedsProcessing) + { + _chatStrings.Add(value); + _scrollBar.UpdateDimensions(_chatStrings.Count); + return; + } + + _chatStrings.AddRange(_textSplitter.SplitIntoLines()); - //don't do multi-line processing if we don't need to - if (!_textSplitter.NeedsProcessing) - { - _chatStrings.Add(value); _scrollBar.UpdateDimensions(_chatStrings.Count); - return; + _scrollBar.LinesToRender = (int)Math.Round(110.0f / TEXT_LINE_HEIGHT); + if (_scrollBar.LinesToRender < _chatStrings.Count) + _scrollBar.SetDownArrowFlashSpeed(500); } - - _chatStrings.AddRange(_textSplitter.SplitIntoLines()); - - _scrollBar.UpdateDimensions(_chatStrings.Count); - _scrollBar.LinesToRender = (int)Math.Round(110.0f / TEXT_LINE_HEIGHT); - if (_scrollBar.LinesToRender < _chatStrings.Count) - _scrollBar.SetDownArrowFlashSpeed(500); } - } - public ScrollingMessageDialog(INativeGraphicsManager nativeGraphicsManager, - IContentProvider contentProvider, - IGameStateProvider gameStateProvider, - IEODialogButtonService eoDialogButtonService) - : base(nativeGraphicsManager, gameStateProvider) - { - _font = contentProvider.Fonts[Constants.FontSize08]; - _textSplitter = new TextSplitter("", _font) { LineLength = 280 }; + public ScrollingMessageDialog(INativeGraphicsManager nativeGraphicsManager, + IContentProvider contentProvider, + IGameStateProvider gameStateProvider, + IEODialogButtonService eoDialogButtonService) + : base(nativeGraphicsManager, gameStateProvider) + { + _font = contentProvider.Fonts[Constants.FontSize08]; + _textSplitter = new TextSplitter("", _font) { LineLength = 280 }; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 40); + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 40); - var smallButtonSheet = eoDialogButtonService.SmallButtonSheet; + var smallButtonSheet = eoDialogButtonService.SmallButtonSheet; - _ok = new XNAButton(smallButtonSheet, - new Vector2(138, 197), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); - _ok.SetParentControl(this); + _ok = new XNAButton(smallButtonSheet, + new Vector2(138, 197), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + _ok.OnClick += (sender, e) => Close(XNADialogResult.OK); + _ok.SetParentControl(this); - _scrollBar = new ScrollBar(new Vector2(320, 66), new Vector2(16, 119), - ScrollBarColors.LightOnMed, GraphicsManager); - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); + _scrollBar = new ScrollBar(new Vector2(320, 66), new Vector2(16, 119), + ScrollBarColors.LightOnMed, GraphicsManager); + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); - MessageText = ""; + MessageText = ""; - CenterInGameView(); - } + CenterInGameView(); + } - public override void Initialize() - { - _ok.Initialize(); - _scrollBar.Initialize(); + public override void Initialize() + { + _ok.Initialize(); + _scrollBar.Initialize(); - base.Initialize(); - } + base.Initialize(); + } - protected override void OnDrawControl(GameTime gt) - { - base.OnDrawControl(gt); + protected override void OnDrawControl(GameTime gt) + { + base.OnDrawControl(gt); - _spriteBatch.Begin(); - var pos = new Vector2(27 + (int)DrawPosition.X, 69 + (int)DrawPosition.Y); + _spriteBatch.Begin(); + var pos = new Vector2(27 + (int)DrawPosition.X, 69 + (int)DrawPosition.Y); - for (int i = _scrollBar.ScrollOffset; i < _scrollBar.ScrollOffset + _scrollBar.LinesToRender; ++i) - { - if (i >= _chatStrings.Count) - break; + for (int i = _scrollBar.ScrollOffset; i < _scrollBar.ScrollOffset + _scrollBar.LinesToRender; ++i) + { + if (i >= _chatStrings.Count) + break; - var strToDraw = _chatStrings[i]; + var strToDraw = _chatStrings[i]; - _spriteBatch.DrawString(_font, strToDraw, new Vector2(pos.X, pos.Y + (i - _scrollBar.ScrollOffset) * TEXT_LINE_HEIGHT), ColorConstants.LightGrayText); - } + _spriteBatch.DrawString(_font, strToDraw, new Vector2(pos.X, pos.Y + (i - _scrollBar.ScrollOffset) * TEXT_LINE_HEIGHT), ColorConstants.LightGrayText); + } - _spriteBatch.End(); + _spriteBatch.End(); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Services/EODialogButtonService.cs b/EndlessClient/Dialogs/Services/EODialogButtonService.cs index e417c80ae..84ee583cc 100644 --- a/EndlessClient/Dialogs/Services/EODialogButtonService.cs +++ b/EndlessClient/Dialogs/Services/EODialogButtonService.cs @@ -3,54 +3,55 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Dialogs.Services; - -public enum SmallButton -{ - Connect = 0, - Cancel, - Login, - Delete, - Ok, - Back, - Add, - Next, - History, - Progress, - NUM_BUTTONS -} - -[AutoMappedType] -public class EODialogButtonService : IEODialogButtonService +namespace EndlessClient.Dialogs.Services { - private readonly INativeGraphicsManager _nativeGraphicsManager; - - public Texture2D SmallButtonSheet => _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 15, true); - - public EODialogButtonService(INativeGraphicsManager nativeGraphicsManager) + public enum SmallButton { - _nativeGraphicsManager = nativeGraphicsManager; + Connect = 0, + Cancel, + Login, + Delete, + Ok, + Back, + Add, + Next, + History, + Progress, + NUM_BUTTONS } - public Rectangle GetSmallDialogButtonOutSource(SmallButton whichButton) + [AutoMappedType] + public class EODialogButtonService : IEODialogButtonService { - var widthDelta = SmallButtonSheet.Width / 2; - var heightDelta = SmallButtonSheet.Height / (int)SmallButton.NUM_BUTTONS; - return new Rectangle(0, heightDelta * (int)whichButton, widthDelta, heightDelta); + private readonly INativeGraphicsManager _nativeGraphicsManager; + + public Texture2D SmallButtonSheet => _nativeGraphicsManager.TextureFromResource(GFXTypes.PreLoginUI, 15, true); + + public EODialogButtonService(INativeGraphicsManager nativeGraphicsManager) + { + _nativeGraphicsManager = nativeGraphicsManager; + } + + public Rectangle GetSmallDialogButtonOutSource(SmallButton whichButton) + { + var widthDelta = SmallButtonSheet.Width / 2; + var heightDelta = SmallButtonSheet.Height / (int)SmallButton.NUM_BUTTONS; + return new Rectangle(0, heightDelta * (int)whichButton, widthDelta, heightDelta); + } + + public Rectangle GetSmallDialogButtonOverSource(SmallButton whichButton) + { + var widthDelta = SmallButtonSheet.Width / 2; + var heightDelta = SmallButtonSheet.Height / (int)SmallButton.NUM_BUTTONS; + return new Rectangle(widthDelta, heightDelta * (int)whichButton, widthDelta, heightDelta); + } } - public Rectangle GetSmallDialogButtonOverSource(SmallButton whichButton) + public interface IEODialogButtonService { - var widthDelta = SmallButtonSheet.Width / 2; - var heightDelta = SmallButtonSheet.Height / (int)SmallButton.NUM_BUTTONS; - return new Rectangle(widthDelta, heightDelta * (int)whichButton, widthDelta, heightDelta); - } -} - -public interface IEODialogButtonService -{ - Texture2D SmallButtonSheet { get; } + Texture2D SmallButtonSheet { get; } - Rectangle GetSmallDialogButtonOutSource(SmallButton whichButton); - Rectangle GetSmallDialogButtonOverSource(SmallButton whichButton); + Rectangle GetSmallDialogButtonOutSource(SmallButton whichButton); + Rectangle GetSmallDialogButtonOverSource(SmallButton whichButton); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/Services/EODialogIconService.cs b/EndlessClient/Dialogs/Services/EODialogIconService.cs index d746b3a2d..09f0d4dea 100644 --- a/EndlessClient/Dialogs/Services/EODialogIconService.cs +++ b/EndlessClient/Dialogs/Services/EODialogIconService.cs @@ -3,56 +3,57 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Dialogs.Services; - -public enum DialogIcon -{ - Buy = 0, - Sell, - JukeboxBrowse = Sell, - BankDeposit, - BankWithdraw, - Craft, - BankLockerUpgrade, - - BarberHairModel = 6, - BarberChangeHairColor = 7, - BarberOk = 8, - - JukeboxPlay = 8, - Registration = 9, - - Learn = 20, - Forget = 21, - InnSleep = 22, - SignUp = 23, - Unsubscribe = 24 -} - -[AutoMappedType] -public class EODialogIconService : IEODialogIconService +namespace EndlessClient.Dialogs.Services { - private readonly INativeGraphicsManager _nativeGraphicsManager; - - public Texture2D IconSheet => _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); - - public EODialogIconService(INativeGraphicsManager nativeGraphicsManager) + public enum DialogIcon { - _nativeGraphicsManager = nativeGraphicsManager; + Buy = 0, + Sell, + JukeboxBrowse = Sell, + BankDeposit, + BankWithdraw, + Craft, + BankLockerUpgrade, + + BarberHairModel = 6, + BarberChangeHairColor = 7, + BarberOk = 8, + + JukeboxPlay = 8, + Registration = 9, + + Learn = 20, + Forget = 21, + InnSleep = 22, + SignUp = 23, + Unsubscribe = 24 } - public Rectangle GetDialogIconSource(DialogIcon whichIcon) + [AutoMappedType] + public class EODialogIconService : IEODialogIconService { - const int NUM_PER_ROW = 9; - const int ICON_SIZE = 31; + private readonly INativeGraphicsManager _nativeGraphicsManager; + + public Texture2D IconSheet => _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); - return new Rectangle(((int)whichIcon % NUM_PER_ROW) * ICON_SIZE, 291 + ((int)whichIcon / NUM_PER_ROW) * ICON_SIZE, ICON_SIZE, ICON_SIZE); + public EODialogIconService(INativeGraphicsManager nativeGraphicsManager) + { + _nativeGraphicsManager = nativeGraphicsManager; + } + + public Rectangle GetDialogIconSource(DialogIcon whichIcon) + { + const int NUM_PER_ROW = 9; + const int ICON_SIZE = 31; + + return new Rectangle(((int)whichIcon % NUM_PER_ROW) * ICON_SIZE, 291 + ((int)whichIcon / NUM_PER_ROW) * ICON_SIZE, ICON_SIZE, ICON_SIZE); + } } -} -public interface IEODialogIconService -{ - Texture2D IconSheet { get; } + public interface IEODialogIconService + { + Texture2D IconSheet { get; } - Rectangle GetDialogIconSource(DialogIcon whichIcon); + Rectangle GetDialogIconSource(DialogIcon whichIcon); + } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/SessionExpDialog.cs b/EndlessClient/Dialogs/SessionExpDialog.cs index c2bd5f5b1..f24dfda7b 100644 --- a/EndlessClient/Dialogs/SessionExpDialog.cs +++ b/EndlessClient/Dialogs/SessionExpDialog.cs @@ -8,118 +8,119 @@ using System; using XNAControls; -namespace EndlessClient.Dialogs; - -public class SessionExpDialog : BaseEODialog +namespace EndlessClient.Dialogs { - private static readonly Rectangle _signalSource; - private static readonly Rectangle _iconSource; + public class SessionExpDialog : BaseEODialog + { + private static readonly Rectangle _signalSource; + private static readonly Rectangle _iconSource; - private readonly Texture2D _icons; + private readonly Texture2D _icons; - static SessionExpDialog() - { - _signalSource = new Rectangle(0, 15, 15, 15); - _iconSource = new Rectangle(0, 0, 15, 15); - } + static SessionExpDialog() + { + _signalSource = new Rectangle(0, 15, 15, 15); + _iconSource = new Rectangle(0, 0, 15, 15); + } - public SessionExpDialog(INativeGraphicsManager nativeGraphicsManager, - IEODialogButtonService dialogButtonService, - ILocalizedStringFinder localizedStringFinder, - ICharacterProvider characterProvider, - IExperienceTableProvider expTableProvider, - ICharacterSessionProvider characterSessionProvider) - : base(nativeGraphicsManager, isInGame: true) - { - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 61); + public SessionExpDialog(INativeGraphicsManager nativeGraphicsManager, + IEODialogButtonService dialogButtonService, + ILocalizedStringFinder localizedStringFinder, + ICharacterProvider characterProvider, + IExperienceTableProvider expTableProvider, + ICharacterSessionProvider characterSessionProvider) + : base(nativeGraphicsManager, isInGame: true) + { + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 61); - _icons = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); + _icons = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 68, true); - var okButton = new XNAButton(dialogButtonService.SmallButtonSheet, - new Vector2(98, 214), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - okButton.OnClick += (_, _) => Close(XNADialogResult.OK); - okButton.SetParentControl(this); - okButton.Initialize(); + var okButton = new XNAButton(dialogButtonService.SmallButtonSheet, + new Vector2(98, 214), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + okButton.OnClick += (_, _) => Close(XNADialogResult.OK); + okButton.SetParentControl(this); + okButton.Initialize(); - var title = new XNALabel(Constants.FontSize08pt5) - { - DrawPosition = new Vector2(20, 16), - AutoSize = false, - Text = localizedStringFinder.GetString(EOResourceID.DIALOG_TITLE_PERFORMANCE), - ForeColor = ColorConstants.LightGrayText - }; - title.SetParentControl(this); - title.Initialize(); - - XNALabel[] leftSide = new XNALabel[8], rightSide = new XNALabel[8]; - for (int i = 0; i < leftSide.Length; i++) - { - leftSide[i] = new XNALabel(Constants.FontSize08pt5) + var title = new XNALabel(Constants.FontSize08pt5) { - DrawPosition = new Vector2(38, 48 + 16 * i), + DrawPosition = new Vector2(20, 16), AutoSize = false, + Text = localizedStringFinder.GetString(EOResourceID.DIALOG_TITLE_PERFORMANCE), ForeColor = ColorConstants.LightGrayText }; - leftSide[i].SetParentControl(this); - leftSide[i].Initialize(); + title.SetParentControl(this); + title.Initialize(); - rightSide[i] = new XNALabel(Constants.FontSize08pt5) + XNALabel[] leftSide = new XNALabel[8], rightSide = new XNALabel[8]; + for (int i = 0; i < leftSide.Length; i++) { - DrawPosition = new Vector2(158, 48 + 16 * i), - AutoSize = false, - ForeColor = ColorConstants.LightGrayText - }; - rightSide[i].SetParentControl(this); - rightSide[i].Initialize(); + leftSide[i] = new XNALabel(Constants.FontSize08pt5) + { + DrawPosition = new Vector2(38, 48 + 16 * i), + AutoSize = false, + ForeColor = ColorConstants.LightGrayText + }; + leftSide[i].SetParentControl(this); + leftSide[i].Initialize(); + + rightSide[i] = new XNALabel(Constants.FontSize08pt5) + { + DrawPosition = new Vector2(158, 48 + 16 * i), + AutoSize = false, + ForeColor = ColorConstants.LightGrayText + }; + rightSide[i].SetParentControl(this); + rightSide[i].Initialize(); + } + + leftSide[0].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TOTALEXP); + leftSide[1].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_NEXT_LEVEL); + leftSide[2].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_EXP_NEEDED); + leftSide[3].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TODAY_EXP); + leftSide[4].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TOTAL_AVG); + leftSide[5].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TODAY_AVG); + leftSide[6].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_BEST_KILL); + leftSide[7].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_LAST_KILL); + + var c = characterProvider.MainCharacter; + var level = c.Stats[CharacterStat.Level]; + var exp = c.Stats[CharacterStat.Experience]; + var usage = c.Stats[CharacterStat.Usage]; + + rightSide[0].Text = $"{exp}"; + rightSide[1].Text = $"{expTableProvider.ExperienceByLevel[level + 1]}"; + rightSide[2].Text = $"{expTableProvider.ExperienceByLevel[level + 1] - exp}"; + rightSide[3].Text = $"{characterSessionProvider.TodayTotalExp}"; + rightSide[4].Text = $"{(int)(exp / (usage / 60.0))}"; + int sessionTimeMinutes = (int)(DateTime.Now - characterSessionProvider.SessionStartTime).TotalMinutes; + rightSide[5].Text = $"{(sessionTimeMinutes > 0 ? (int)(characterSessionProvider.TodayTotalExp / (sessionTimeMinutes / 60.0)) : 0)}"; + rightSide[6].Text = $"{characterSessionProvider.BestKillExp}"; + rightSide[7].Text = $"{characterSessionProvider.LastKillExp}"; + + Array.ForEach(leftSide, lbl => lbl.ResizeBasedOnText()); + Array.ForEach(rightSide, lbl => lbl.ResizeBasedOnText()); + + CenterInGameView(); + + if (!Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, 15); } - leftSide[0].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TOTALEXP); - leftSide[1].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_NEXT_LEVEL); - leftSide[2].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_EXP_NEEDED); - leftSide[3].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TODAY_EXP); - leftSide[4].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TOTAL_AVG); - leftSide[5].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_TODAY_AVG); - leftSide[6].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_BEST_KILL); - leftSide[7].Text = localizedStringFinder.GetString(EOResourceID.DIALOG_PERFORMANCE_LAST_KILL); - - var c = characterProvider.MainCharacter; - var level = c.Stats[CharacterStat.Level]; - var exp = c.Stats[CharacterStat.Experience]; - var usage = c.Stats[CharacterStat.Usage]; - - rightSide[0].Text = $"{exp}"; - rightSide[1].Text = $"{expTableProvider.ExperienceByLevel[level + 1]}"; - rightSide[2].Text = $"{expTableProvider.ExperienceByLevel[level + 1] - exp}"; - rightSide[3].Text = $"{characterSessionProvider.TodayTotalExp}"; - rightSide[4].Text = $"{(int)(exp / (usage / 60.0))}"; - int sessionTimeMinutes = (int)(DateTime.Now - characterSessionProvider.SessionStartTime).TotalMinutes; - rightSide[5].Text = $"{(sessionTimeMinutes > 0 ? (int)(characterSessionProvider.TodayTotalExp / (sessionTimeMinutes / 60.0)) : 0)}"; - rightSide[6].Text = $"{characterSessionProvider.BestKillExp}"; - rightSide[7].Text = $"{characterSessionProvider.LastKillExp}"; - - Array.ForEach(leftSide, lbl => lbl.ResizeBasedOnText()); - Array.ForEach(rightSide, lbl => lbl.ResizeBasedOnText()); - - CenterInGameView(); - - if (!Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, 15); - } - - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - _spriteBatch.Begin(); + _spriteBatch.Begin(); - for (int i = 0; i < 8; i++) - _spriteBatch.Draw(_icons, new Vector2(DrawPositionWithParentOffset.X + 18, DrawPositionWithParentOffset.Y + 47 + 16 * i), _iconSource, Color.White); + for (int i = 0; i < 8; i++) + _spriteBatch.Draw(_icons, new Vector2(DrawPositionWithParentOffset.X + 18, DrawPositionWithParentOffset.Y + 47 + 16 * i), _iconSource, Color.White); - for (int i = 0; i < 3; i++) - _spriteBatch.Draw(_icons, new Vector2(DrawPositionWithParentOffset.X + 142, DrawPositionWithParentOffset.Y + 48 + 16 * i), _signalSource, Color.White); + for (int i = 0; i < 3; i++) + _spriteBatch.Draw(_icons, new Vector2(DrawPositionWithParentOffset.X + 142, DrawPositionWithParentOffset.Y + 48 + 16 * i), _signalSource, Color.White); - _spriteBatch.End(); + _spriteBatch.End(); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/ShopDialog.cs b/EndlessClient/Dialogs/ShopDialog.cs index a11634219..29e5c7efc 100644 --- a/EndlessClient/Dialogs/ShopDialog.cs +++ b/EndlessClient/Dialogs/ShopDialog.cs @@ -14,400 +14,401 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs; - -public class ShopDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private enum ShopState - { - None, - Initial, - Buying, - Selling, - Crafting - } - - private readonly IShopActions _shopActions; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IItemTransferDialogFactory _itemTransferDialogFactory; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IShopDataProvider _shopDataProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private IReadOnlyList _buyItems, _sellItems; - private IReadOnlyList _craftItems; - - private ShopState _state; - - private Option _cachedShopId; - private HashSet _cachedInventory; - private ulong _tick; - - public ShopDialog(INativeGraphicsManager nativeGraphicsManager, - IShopActions shopActions, - IEOMessageBoxFactory messageBoxFactory, - IItemTransferDialogFactory itemTransferDialogFactory, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IShopDataProvider shopDataProvider, - ICharacterInventoryProvider characterInventoryProvider, - IEIFFileProvider eifFileProvider, - ICharacterProvider characterProvider, - IInventorySpaceValidator inventorySpaceValidator) - : base(nativeGraphicsManager, dialogButtonService) - { - _shopActions = shopActions; - _messageBoxFactory = messageBoxFactory; - _itemTransferDialogFactory = itemTransferDialogFactory; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _shopDataProvider = shopDataProvider; - _characterInventoryProvider = characterInventoryProvider; - _eifFileProvider = eifFileProvider; - _characterProvider = characterProvider; - _inventorySpaceValidator = inventorySpaceValidator; - - Buttons = ScrollingListDialogButtons.Cancel; - ListItemType = ListDialogItem.ListItemStyle.Large; - - BackAction += (_, _) => SetState(ShopState.Initial); - - _cachedInventory = new HashSet(_characterInventoryProvider.ItemInventory); - } - - protected override void OnUpdateControl(GameTime gameTime) + public class ShopDialog : ScrollingListDialog { - _cachedShopId.MatchNone(() => + private enum ShopState { - _shopDataProvider.SessionID.SomeWhen(x => x > 0) - .MatchSome(x => - { - _cachedShopId = Option.Some(_shopDataProvider.SessionID); - - Title = _shopDataProvider.ShopName; + None, + Initial, + Buying, + Selling, + Crafting + } - _buyItems = _shopDataProvider.TradeItems.Where(x => x.Buy > 0).ToList(); - _sellItems = _shopDataProvider.TradeItems.Where(x => x.Sell > 0 && _characterInventoryProvider.ItemInventory.Any(inv => inv.ItemID == x.ID && inv.Amount > 0)).ToList(); - _craftItems = _shopDataProvider.CraftItems; + private readonly IShopActions _shopActions; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IItemTransferDialogFactory _itemTransferDialogFactory; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IShopDataProvider _shopDataProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private IReadOnlyList _buyItems, _sellItems; + private IReadOnlyList _craftItems; + + private ShopState _state; + + private Option _cachedShopId; + private HashSet _cachedInventory; + private ulong _tick; + + public ShopDialog(INativeGraphicsManager nativeGraphicsManager, + IShopActions shopActions, + IEOMessageBoxFactory messageBoxFactory, + IItemTransferDialogFactory itemTransferDialogFactory, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IShopDataProvider shopDataProvider, + ICharacterInventoryProvider characterInventoryProvider, + IEIFFileProvider eifFileProvider, + ICharacterProvider characterProvider, + IInventorySpaceValidator inventorySpaceValidator) + : base(nativeGraphicsManager, dialogButtonService) + { + _shopActions = shopActions; + _messageBoxFactory = messageBoxFactory; + _itemTransferDialogFactory = itemTransferDialogFactory; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _shopDataProvider = shopDataProvider; + _characterInventoryProvider = characterInventoryProvider; + _eifFileProvider = eifFileProvider; + _characterProvider = characterProvider; + _inventorySpaceValidator = inventorySpaceValidator; + + Buttons = ScrollingListDialogButtons.Cancel; + ListItemType = ListDialogItem.ListItemStyle.Large; + + BackAction += (_, _) => SetState(ShopState.Initial); - SetState(ShopState.Initial); - }); - }); + _cachedInventory = new HashSet(_characterInventoryProvider.ItemInventory); + } - if (++_tick % 8 == 0 && !_cachedInventory.SetEquals(_characterInventoryProvider.ItemInventory)) + protected override void OnUpdateControl(GameTime gameTime) { - _sellItems = _shopDataProvider.TradeItems.Where(x => x.Sell > 0 && _characterInventoryProvider.ItemInventory.Any(inv => inv.ItemID == x.ID && inv.Amount > 0)).ToList(); - _cachedInventory = new HashSet(_characterInventoryProvider.ItemInventory); + _cachedShopId.MatchNone(() => + { + _shopDataProvider.SessionID.SomeWhen(x => x > 0) + .MatchSome(x => + { + _cachedShopId = Option.Some(_shopDataProvider.SessionID); - if (_state == ShopState.Selling) - SetState(ShopState.Selling); - } + Title = _shopDataProvider.ShopName; - base.OnUpdateControl(gameTime); - } + _buyItems = _shopDataProvider.TradeItems.Where(x => x.Buy > 0).ToList(); + _sellItems = _shopDataProvider.TradeItems.Where(x => x.Sell > 0 && _characterInventoryProvider.ItemInventory.Any(inv => inv.ItemID == x.ID && inv.Amount > 0)).ToList(); + _craftItems = _shopDataProvider.CraftItems; - private void SetState(ShopState state) - { - if (state == ShopState.None) - return; + SetState(ShopState.Initial); + }); + }); - if (state == ShopState.Buying && _buyItems.Count == 0) - { - var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOTHING_IS_FOR_SALE); - msg.ShowDialog(); + if (++_tick % 8 == 0 && !_cachedInventory.SetEquals(_characterInventoryProvider.ItemInventory)) + { + _sellItems = _shopDataProvider.TradeItems.Where(x => x.Sell > 0 && _characterInventoryProvider.ItemInventory.Any(inv => inv.ItemID == x.ID && inv.Amount > 0)).ToList(); + _cachedInventory = new HashSet(_characterInventoryProvider.ItemInventory); - if (_state != ShopState.Initial) - SetState(ShopState.Initial); + if (_state == ShopState.Selling) + SetState(ShopState.Selling); + } - return; + base.OnUpdateControl(gameTime); } - else if (state == ShopState.Selling && _sellItems.Count == 0) + + private void SetState(ShopState state) { - var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOT_BUYING_YOUR_ITEMS); - msg.ShowDialog(); + if (state == ShopState.None) + return; - if (_state != ShopState.Initial) - SetState(ShopState.Initial); + if (state == ShopState.Buying && _buyItems.Count == 0) + { + var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOTHING_IS_FOR_SALE); + msg.ShowDialog(); - return; - } + if (_state != ShopState.Initial) + SetState(ShopState.Initial); - ClearItemList(); + return; + } + else if (state == ShopState.Selling && _sellItems.Count == 0) + { + var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOT_BUYING_YOUR_ITEMS); + msg.ShowDialog(); - switch (state) - { - case ShopState.Initial: - { - var buyItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_BUY_ITEMS), - SubText = $"{_buyItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_IN_STORE)}", - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Buy), - ShowIconBackGround = false, - OffsetY = 45, - }; - buyItem.LeftClick += (_, _) => SetState(ShopState.Buying); - - var sellItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_SELL_ITEMS), - SubText = $"{_sellItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_ACCEPTED)}", - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Sell), - ShowIconBackGround = false, - OffsetY = 45, - }; - sellItem.LeftClick += (_, _) => SetState(ShopState.Selling); - - AddItemToList(buyItem, sortList: false); - AddItemToList(sellItem, sortList: false); - - if (_craftItems.Count > 0) + if (_state != ShopState.Initial) + SetState(ShopState.Initial); + + return; + } + + ClearItemList(); + + switch (state) + { + case ShopState.Initial: { - var craftItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + var buyItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_CRAFT_ITEMS), - SubText = $"{_craftItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_ACCEPTED)}", + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_BUY_ITEMS), + SubText = $"{_buyItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_IN_STORE)}", IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Craft), + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Buy), ShowIconBackGround = false, OffsetY = 45, }; - craftItem.LeftClick += (_, _) => SetState(ShopState.Crafting); - - AddItemToList(craftItem, sortList: false); - } - - Buttons = ScrollingListDialogButtons.Cancel; - } - break; + buyItem.LeftClick += (_, _) => SetState(ShopState.Buying); - case ShopState.Buying: - case ShopState.Selling: - { - var buying = state == ShopState.Buying; - var items = new List(); - foreach (var item in buying ? _buyItems : _sellItems) - { - var data = _eifFileProvider.EIFFile[item.ID]; - var genderExtra = data.Type == EOLib.IO.ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - data.Gender)})" : string.Empty; - var subText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_PRICE)}: {(buying ? item.Buy : item.Sell)} {genderExtra}"; - - var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + var sellItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) { - PrimaryText = data.Name, - SubText = subText, - IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic - 1, transparent: true), - OffsetY = 45 + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_SELL_ITEMS), + SubText = $"{_sellItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_ACCEPTED)}", + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Sell), + ShowIconBackGround = false, + OffsetY = 45, }; - listItem.LeftClick += TradeItem; - listItem.RightClick += TradeItem; + sellItem.LeftClick += (_, _) => SetState(ShopState.Selling); - items.Add(listItem); - } + AddItemToList(buyItem, sortList: false); + AddItemToList(sellItem, sortList: false); - SetItemList(items); - Buttons = ScrollingListDialogButtons.BackCancel; - } - break; + if (_craftItems.Count > 0) + { + var craftItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_CRAFT_ITEMS), + SubText = $"{_craftItems.Count} {_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_ITEMS_ACCEPTED)}", + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Craft), + ShowIconBackGround = false, + OffsetY = 45, + }; + craftItem.LeftClick += (_, _) => SetState(ShopState.Crafting); + + AddItemToList(craftItem, sortList: false); + } + + Buttons = ScrollingListDialogButtons.Cancel; + } + break; - case ShopState.Crafting: - { - var items = new List(); - foreach (var item in _craftItems) + case ShopState.Buying: + case ShopState.Selling: { - var data = _eifFileProvider.EIFFile[item.ID]; - var genderExtra = data.Type == EOLib.IO.ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - data.Gender)})" : string.Empty; - var subText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS)}: {item.Ingredients.Count} {genderExtra}"; - - var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + var buying = state == ShopState.Buying; + var items = new List(); + foreach (var item in buying ? _buyItems : _sellItems) { - PrimaryText = data.Name, - SubText = subText, - IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic - 1, transparent: true), - OffsetY = 45 - }; - listItem.LeftClick += CraftItem; - listItem.RightClick += CraftItem; + var data = _eifFileProvider.EIFFile[item.ID]; + var genderExtra = data.Type == EOLib.IO.ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - data.Gender)})" : string.Empty; + var subText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_PRICE)}: {(buying ? item.Buy : item.Sell)} {genderExtra}"; + + var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + { + PrimaryText = data.Name, + SubText = subText, + IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic - 1, transparent: true), + OffsetY = 45 + }; + listItem.LeftClick += TradeItem; + listItem.RightClick += TradeItem; + + items.Add(listItem); + } + + SetItemList(items); + Buttons = ScrollingListDialogButtons.BackCancel; + } + break; - items.Add(listItem); + case ShopState.Crafting: + { + var items = new List(); + foreach (var item in _craftItems) + { + var data = _eifFileProvider.EIFFile[item.ID]; + var genderExtra = data.Type == EOLib.IO.ItemType.Armor ? $"({_localizedStringFinder.GetString(EOResourceID.FEMALE - data.Gender)})" : string.Empty; + var subText = $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS)}: {item.Ingredients.Count} {genderExtra}"; + + var listItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + { + PrimaryText = data.Name, + SubText = subText, + IconGraphic = GraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic - 1, transparent: true), + OffsetY = 45 + }; + listItem.LeftClick += CraftItem; + listItem.RightClick += CraftItem; + + items.Add(listItem); + } + + SetItemList(items); + Buttons = ScrollingListDialogButtons.BackCancel; } + break; + } - SetItemList(items); - Buttons = ScrollingListDialogButtons.BackCancel; - } - break; + _state = state; } - _state = state; - } - - private void TradeItem(object sender, EventArgs e) - { - if (_state != ShopState.Buying && _state != ShopState.Selling) - return; + private void TradeItem(object sender, EventArgs e) + { + if (_state != ShopState.Buying && _state != ShopState.Selling) + return; - var listItemIndex = ((ListDialogItem)sender).Index + _scrollBar.ScrollOffset; - var buying = _state == ShopState.Buying; + var listItemIndex = ((ListDialogItem)sender).Index + _scrollBar.ScrollOffset; + var buying = _state == ShopState.Buying; - var collection = (buying ? _buyItems : _sellItems); - if (listItemIndex >= collection.Count) - return; + var collection = (buying ? _buyItems : _sellItems); + if (listItemIndex >= collection.Count) + return; - // todo: move some of this stuff into a controller class? - var shopItem = collection[listItemIndex]; - var data = _eifFileProvider.EIFFile[shopItem.ID]; + // todo: move some of this stuff into a controller class? + var shopItem = collection[listItemIndex]; + var data = _eifFileProvider.EIFFile[shopItem.ID]; - var inventoryItem = _characterInventoryProvider.ItemInventory - .SingleOrNone(x => buying ? x.ItemID == 1 : x.ItemID == shopItem.ID); + var inventoryItem = _characterInventoryProvider.ItemInventory + .SingleOrNone(x => buying ? x.ItemID == 1 : x.ItemID == shopItem.ID); - // todo: move this stuff into a validator class? - if (buying) - { - if (!_inventorySpaceValidator.ItemFits(data.ID)) + // todo: move this stuff into a validator class? + if (buying) { - var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); - msg.ShowDialog(); - return; - } + if (!_inventorySpaceValidator.ItemFits(data.ID)) + { + var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); + msg.ShowDialog(); + return; + } - var stats = _characterProvider.MainCharacter.Stats; - if (data.Weight + stats[CharacterStat.Weight] > stats[CharacterStat.MaxWeight]) - { - var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - msg.ShowDialog(); - return; - } + var stats = _characterProvider.MainCharacter.Stats; + if (data.Weight + stats[CharacterStat.Weight] > stats[CharacterStat.MaxWeight]) + { + var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + msg.ShowDialog(); + return; + } - var hasEnoughGold = inventoryItem.Match(some: x => x.Amount >= shopItem.Buy, none: () => false); - if (!hasEnoughGold) - { - var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, " gold."); - msg.ShowDialog(); - return; + var hasEnoughGold = inventoryItem.Match(some: x => x.Amount >= shopItem.Buy, none: () => false); + if (!hasEnoughGold) + { + var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.WARNING_YOU_HAVE_NOT_ENOUGH, " gold."); + msg.ShowDialog(); + return; + } } - } - else - { - var hasEnoughItem = inventoryItem.Match(some: x => x.Amount > 0, none: () => false); - if (!hasEnoughItem) + else { - var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOT_BUYING_YOUR_ITEMS); - msg.ShowDialog(); - return; + var hasEnoughItem = inventoryItem.Match(some: x => x.Amount > 0, none: () => false); + if (!hasEnoughItem) + { + var msg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SHOP_NOT_BUYING_YOUR_ITEMS); + msg.ShowDialog(); + return; + } } - } - var needItemTransferDialog = (buying && shopItem.MaxBuy != 1) || (!buying && inventoryItem.Match(x => x.Amount != 1, () => false)); + var needItemTransferDialog = (buying && shopItem.MaxBuy != 1) || (!buying && inventoryItem.Match(x => x.Amount != 1, () => false)); - if (needItemTransferDialog) - { - var itemTransferDialog = _itemTransferDialogFactory.CreateItemTransferDialog(data.Name, - ItemTransferDialog.TransferType.ShopTransfer, - buying ? shopItem.MaxBuy : inventoryItem.Match(x => x.Amount, () => 0), - buying ? EOResourceID.DIALOG_TRANSFER_BUY : EOResourceID.DIALOG_TRANSFER_SELL); - itemTransferDialog.DialogClosing += (_, e) => + if (needItemTransferDialog) { - if (e.Result == XNADialogResult.OK) - ConfirmAndExecuteTrade(itemTransferDialog.SelectedAmount); - }; - - itemTransferDialog.ShowDialog(); - } - else - { - ConfirmAndExecuteTrade(amount: 1); - } + var itemTransferDialog = _itemTransferDialogFactory.CreateItemTransferDialog(data.Name, + ItemTransferDialog.TransferType.ShopTransfer, + buying ? shopItem.MaxBuy : inventoryItem.Match(x => x.Amount, () => 0), + buying ? EOResourceID.DIALOG_TRANSFER_BUY : EOResourceID.DIALOG_TRANSFER_SELL); + itemTransferDialog.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + ConfirmAndExecuteTrade(itemTransferDialog.SelectedAmount); + }; - void ConfirmAndExecuteTrade(int amount) - { - var message = $"{_localizedStringFinder.GetString(buying ? EOResourceID.DIALOG_WORD_BUY : EOResourceID.DIALOG_WORD_SELL)} {amount} {data.Name} " + - $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_FOR)} {(buying ? shopItem.Buy : shopItem.Sell) * amount} gold?"; - var dlg = _messageBoxFactory.CreateMessageBox(message, _localizedStringFinder.GetString(buying ? EOResourceID.DIALOG_SHOP_BUY_ITEMS : EOResourceID.DIALOG_SHOP_SELL_ITEMS), EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => + itemTransferDialog.ShowDialog(); + } + else { - if (e.Result == XNADialogResult.Cancel) - return; + ConfirmAndExecuteTrade(amount: 1); + } - if (buying) - _shopActions.BuyItem(shopItem.ID, amount); - else - _shopActions.SellItem(shopItem.ID, amount); - }; - dlg.ShowDialog(); + void ConfirmAndExecuteTrade(int amount) + { + var message = $"{_localizedStringFinder.GetString(buying ? EOResourceID.DIALOG_WORD_BUY : EOResourceID.DIALOG_WORD_SELL)} {amount} {data.Name} " + + $"{_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_FOR)} {(buying ? shopItem.Buy : shopItem.Sell) * amount} gold?"; + var dlg = _messageBoxFactory.CreateMessageBox(message, _localizedStringFinder.GetString(buying ? EOResourceID.DIALOG_SHOP_BUY_ITEMS : EOResourceID.DIALOG_SHOP_SELL_ITEMS), EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.Cancel) + return; + + if (buying) + _shopActions.BuyItem(shopItem.ID, amount); + else + _shopActions.SellItem(shopItem.ID, amount); + }; + dlg.ShowDialog(); + } } - } - private void CraftItem(object sender, EventArgs e) - { - if (_state != ShopState.Crafting) - return; + private void CraftItem(object sender, EventArgs e) + { + if (_state != ShopState.Crafting) + return; - var listItemIndex = ((ListDialogItem)sender).Index + _scrollBar.ScrollOffset; + var listItemIndex = ((ListDialogItem)sender).Index + _scrollBar.ScrollOffset; - if (listItemIndex >= _craftItems.Count) - return; + if (listItemIndex >= _craftItems.Count) + return; - // todo: move some of this stuff into a controller class? - var craftItem = _craftItems[listItemIndex]; - var data = _eifFileProvider.EIFFile[craftItem.ID]; + // todo: move some of this stuff into a controller class? + var craftItem = _craftItems[listItemIndex]; + var data = _eifFileProvider.EIFFile[craftItem.ID]; - // todo: move this stuff into a validator class? - foreach (var ingredient in craftItem.Ingredients) - { - if (!_characterInventoryProvider.ItemInventory.Any(x => x.ItemID == ingredient.ID && x.Amount >= ingredient.Amount)) + // todo: move this stuff into a validator class? + foreach (var ingredient in craftItem.Ingredients) { - var message = BuildMessage(EOResourceID.DIALOG_SHOP_CRAFT_MISSING_INGREDIENTS); - var caption = BuildCaption(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS); + if (!_characterInventoryProvider.ItemInventory.Any(x => x.ItemID == ingredient.ID && x.Amount >= ingredient.Amount)) + { + var message = BuildMessage(EOResourceID.DIALOG_SHOP_CRAFT_MISSING_INGREDIENTS); + var caption = BuildCaption(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS); - var dlg = _messageBoxFactory.CreateMessageBox(message, caption, EODialogButtons.Cancel, EOMessageBoxStyle.LargeDialogSmallHeader); - dlg.ShowDialog(); + var dlg = _messageBoxFactory.CreateMessageBox(message, caption, EODialogButtons.Cancel, EOMessageBoxStyle.LargeDialogSmallHeader); + dlg.ShowDialog(); + + return; + } + } + if (!_inventorySpaceValidator.ItemFits(data.ID)) + { + var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); + msg.ShowDialog(); return; } - } - if (!_inventorySpaceValidator.ItemFits(data.ID)) - { - var msg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); - msg.ShowDialog(); - return; - } + var message2 = BuildMessage(EOResourceID.DIALOG_SHOP_CRAFT_PUT_INGREDIENTS_TOGETHER); + var caption2 = BuildCaption(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS); - var message2 = BuildMessage(EOResourceID.DIALOG_SHOP_CRAFT_PUT_INGREDIENTS_TOGETHER); - var caption2 = BuildCaption(EOResourceID.DIALOG_SHOP_CRAFT_INGREDIENTS); + var dlg2 = _messageBoxFactory.CreateMessageBox(message2, caption2, EODialogButtons.OkCancel, EOMessageBoxStyle.LargeDialogSmallHeader); + dlg2.DialogClosing += (o, e) => + { + if (e.Result == XNADialogResult.Cancel) + return; - var dlg2 = _messageBoxFactory.CreateMessageBox(message2, caption2, EODialogButtons.OkCancel, EOMessageBoxStyle.LargeDialogSmallHeader); - dlg2.DialogClosing += (o, e) => - { - if (e.Result == XNADialogResult.Cancel) - return; + _shopActions.CraftItem(craftItem.ID); + }; + dlg2.ShowDialog(); - _shopActions.CraftItem(craftItem.ID); - }; - dlg2.ShowDialog(); + string BuildMessage(EOResourceID resource) + { + var message = _localizedStringFinder.GetString(resource) + "\n\n"; - string BuildMessage(EOResourceID resource) - { - var message = _localizedStringFinder.GetString(resource) + "\n\n"; + foreach (var ingred in craftItem.Ingredients) + { + var ingredData = _eifFileProvider.EIFFile[ingred.ID]; + message += $"+ {ingred.Amount} {ingredData.Name}\n"; + } - foreach (var ingred in craftItem.Ingredients) - { - var ingredData = _eifFileProvider.EIFFile[ingred.ID]; - message += $"+ {ingred.Amount} {ingredData.Name}\n"; + return message; } - return message; - } - - string BuildCaption(EOResourceID resource) - { - return $"{_localizedStringFinder.GetString(resource)} {_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_FOR)} {data.Name}"; + string BuildCaption(EOResourceID resource) + { + return $"{_localizedStringFinder.GetString(resource)} {_localizedStringFinder.GetString(EOResourceID.DIALOG_WORD_FOR)} {data.Name}"; + } } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/SkillmasterDialog.cs b/EndlessClient/Dialogs/SkillmasterDialog.cs index aeba45ab5..3f58ec8f2 100644 --- a/EndlessClient/Dialogs/SkillmasterDialog.cs +++ b/EndlessClient/Dialogs/SkillmasterDialog.cs @@ -16,385 +16,386 @@ using System.Text; using XNAControls; -namespace EndlessClient.Dialogs; - -public class SkillmasterDialog : ScrollingListDialog +namespace EndlessClient.Dialogs { - private enum SkillState - { - Initial, - Learn, - Forget, - ForgetAll - } - - private SkillState _state; - - private HashSet _cachedSkills; - private HashSet _cachedSpells; - private string _cachedTitle; - - private bool _showingRequirements; - private readonly ISkillmasterActions _skillmasterActions; - private readonly IEODialogIconService _dialogIconService; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITextInputDialogFactory _textInputDialogFactory; - private readonly ISkillDataProvider _skillDataProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IPubFileProvider _pubFileProvider; - private readonly IContentProvider _contentProvider; - - public SkillmasterDialog(INativeGraphicsManager nativeGraphicsManager, - ISkillmasterActions skillmasterActions, - IEODialogButtonService dialogButtonService, - IEODialogIconService dialogIconService, - ILocalizedStringFinder localizedStringFinder, - IStatusLabelSetter statusLabelSetter, - IEOMessageBoxFactory messageBoxFactory, - ITextInputDialogFactory textInputDialogFactory, - ISkillDataProvider skillDataProvider, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IPubFileProvider pubFileProvider, - IContentProvider contentProvider) - : base(nativeGraphicsManager, dialogButtonService) + public class SkillmasterDialog : ScrollingListDialog { - Buttons = ScrollingListDialogButtons.Cancel; - ListItemType = ListDialogItem.ListItemStyle.Large; - - _cachedSkills = new HashSet(); - _cachedSpells = new HashSet(); - _cachedTitle = string.Empty; - - BackAction += BackClicked; - - _skillmasterActions = skillmasterActions; - _dialogIconService = dialogIconService; - _localizedStringFinder = localizedStringFinder; - _statusLabelSetter = statusLabelSetter; - _messageBoxFactory = messageBoxFactory; - _textInputDialogFactory = textInputDialogFactory; - _skillDataProvider = skillDataProvider; - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _pubFileProvider = pubFileProvider; - _contentProvider = contentProvider; - SetState(SkillState.Initial, regen: true); - } - - protected override void OnUpdateControl(GameTime gameTime) - { - if (_cachedTitle != _skillDataProvider.Title) + private enum SkillState { - Title = _cachedTitle = _skillDataProvider.Title; + Initial, + Learn, + Forget, + ForgetAll } - if (!_cachedSkills.SetEquals(_skillDataProvider.Skills)) + private SkillState _state; + + private HashSet _cachedSkills; + private HashSet _cachedSpells; + private string _cachedTitle; + + private bool _showingRequirements; + private readonly ISkillmasterActions _skillmasterActions; + private readonly IEODialogIconService _dialogIconService; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITextInputDialogFactory _textInputDialogFactory; + private readonly ISkillDataProvider _skillDataProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IPubFileProvider _pubFileProvider; + private readonly IContentProvider _contentProvider; + + public SkillmasterDialog(INativeGraphicsManager nativeGraphicsManager, + ISkillmasterActions skillmasterActions, + IEODialogButtonService dialogButtonService, + IEODialogIconService dialogIconService, + ILocalizedStringFinder localizedStringFinder, + IStatusLabelSetter statusLabelSetter, + IEOMessageBoxFactory messageBoxFactory, + ITextInputDialogFactory textInputDialogFactory, + ISkillDataProvider skillDataProvider, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IPubFileProvider pubFileProvider, + IContentProvider contentProvider) + : base(nativeGraphicsManager, dialogButtonService) { - _cachedSkills = _skillDataProvider.Skills.ToHashSet(); - SetState(_state, regen: true); + Buttons = ScrollingListDialogButtons.Cancel; + ListItemType = ListDialogItem.ListItemStyle.Large; + + _cachedSkills = new HashSet(); + _cachedSpells = new HashSet(); + _cachedTitle = string.Empty; + + BackAction += BackClicked; + + _skillmasterActions = skillmasterActions; + _dialogIconService = dialogIconService; + _localizedStringFinder = localizedStringFinder; + _statusLabelSetter = statusLabelSetter; + _messageBoxFactory = messageBoxFactory; + _textInputDialogFactory = textInputDialogFactory; + _skillDataProvider = skillDataProvider; + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _pubFileProvider = pubFileProvider; + _contentProvider = contentProvider; + SetState(SkillState.Initial, regen: true); } - if (!_cachedSpells.SetEquals(_characterInventoryProvider.SpellInventory)) + protected override void OnUpdateControl(GameTime gameTime) { - _cachedSpells = _characterInventoryProvider.SpellInventory.ToHashSet(); - SetState(_state, regen: true); - } + if (_cachedTitle != _skillDataProvider.Title) + { + Title = _cachedTitle = _skillDataProvider.Title; + } - base.OnUpdateControl(gameTime); - } + if (!_cachedSkills.SetEquals(_skillDataProvider.Skills)) + { + _cachedSkills = _skillDataProvider.Skills.ToHashSet(); + SetState(_state, regen: true); + } - private void BackClicked(object sender, EventArgs e) - { - ListItemType = ListDialogItem.ListItemStyle.Large; + if (!_cachedSpells.SetEquals(_characterInventoryProvider.SpellInventory)) + { + _cachedSpells = _characterInventoryProvider.SpellInventory.ToHashSet(); + SetState(_state, regen: true); + } - if (_state == SkillState.Learn && _showingRequirements) - { - SetState(SkillState.Learn, regen: true); - _showingRequirements = false; + base.OnUpdateControl(gameTime); } - else + + private void BackClicked(object sender, EventArgs e) { - SetState(SkillState.Initial); - } - } + ListItemType = ListDialogItem.ListItemStyle.Large; - private void SetState(SkillState newState, bool regen = false) - { - SkillState old = _state; + if (_state == SkillState.Learn && _showingRequirements) + { + SetState(SkillState.Learn, regen: true); + _showingRequirements = false; + } + else + { + SetState(SkillState.Initial); + } + } - if (old == newState && !regen) - return; + private void SetState(SkillState newState, bool regen = false) + { + SkillState old = _state; - int numToLearn = _cachedSkills.Count(x => !_cachedSpells.Any(si => si.ID == x.Id)); - int numToForget = _cachedSpells.Count; + if (old == newState && !regen) + return; - ClearItemList(); + int numToLearn = _cachedSkills.Count(x => !_cachedSpells.Any(si => si.ID == x.Id)); + int numToForget = _cachedSpells.Count; - if (newState == SkillState.Learn && numToLearn == 0) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_NOTHING_MORE_TO_LEARN); - dlg.ShowDialog(); - return; - } + ClearItemList(); - switch (newState) - { - case SkillState.Initial: - { - string learnNum = $"{numToLearn}{_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_ITEMS_TO_LEARN)}"; - string forgetNum = $"{numToForget}{_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_ITEMS_LEARNED)}"; + if (newState == SkillState.Learn && numToLearn == 0) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_NOTHING_MORE_TO_LEARN); + dlg.ShowDialog(); + return; + } - var learn = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEARN), - SubText = learnNum, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Learn), - ShowIconBackGround = false, - OffsetY = 45 - }; - learn.LeftClick += (_, _) => SetState(SkillState.Learn); - learn.RightClick += (_, _) => SetState(SkillState.Learn); - learn.SetParentControl(this); - - var forget = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_FORGET), - SubText = forgetNum, - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Forget), - ShowIconBackGround = false, - OffsetY = 45 - }; - forget.LeftClick += (_, _) => SetState(SkillState.Forget); - forget.RightClick += (_, _) => SetState(SkillState.Forget); - forget.SetParentControl(this); - - var forgetAll = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) - { - PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL), - SubText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_RESET_YOUR_CHARACTER), - IconGraphic = _dialogIconService.IconSheet, - IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Forget), - ShowIconBackGround = false, - OffsetY = 45 - }; - forgetAll.LeftClick += (_, _) => SetState(SkillState.ForgetAll); - forgetAll.RightClick += (_, _) => SetState(SkillState.ForgetAll); - forgetAll.SetParentControl(this); - - SetItemList(new List { learn, forget, forgetAll }); - - Buttons = ScrollingListDialogButtons.Cancel; - } - break; - case SkillState.Learn: - { - foreach (var skill in _cachedSkills.Where(x => !_cachedSpells.Any(y => y.ID == x.Id))) + switch (newState) + { + case SkillState.Initial: { - var skillRef = skill; - var spellData = _pubFileProvider.ESFFile[skill.Id]; + string learnNum = $"{numToLearn}{_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_ITEMS_TO_LEARN)}"; + string forgetNum = $"{numToForget}{_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_ITEMS_LEARNED)}"; - var icon = GraphicsManager.TextureFromResource(GFXTypes.SpellIcons, spellData.Icon); - var nextListItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + var learn = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 0) { - Visible = false, - PrimaryText = spellData.Name, - SubText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_REQUIREMENTS), - IconGraphic = icon, - IconGraphicSource = new Rectangle(0, 0, icon.Width / 2, icon.Height), + PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEARN), + SubText = learnNum, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Learn), ShowIconBackGround = false, OffsetY = 45 }; - nextListItem.LeftClick += (_, _) => Learn(skillRef); - nextListItem.RightClick += (o, e) => Learn(skillRef); - nextListItem.OnMouseEnter += (o, e) => ShowRequirementsLabel(skillRef); - nextListItem.SetSubtextClickAction((_, _) => ShowRequirements(skillRef)); - AddItemToList(nextListItem, false); - } + learn.LeftClick += (_, _) => SetState(SkillState.Learn); + learn.RightClick += (_, _) => SetState(SkillState.Learn); + learn.SetParentControl(this); - Buttons = ScrollingListDialogButtons.BackCancel; - } - break; - case SkillState.Forget: - { - var input = _textInputDialogFactory.Create(_localizedStringFinder.GetString(DialogResourceID.SKILL_PROMPT_TO_FORGET), 32); + var forget = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 1) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_FORGET), + SubText = forgetNum, + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Forget), + ShowIconBackGround = false, + OffsetY = 45 + }; + forget.LeftClick += (_, _) => SetState(SkillState.Forget); + forget.RightClick += (_, _) => SetState(SkillState.Forget); + forget.SetParentControl(this); + + var forgetAll = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large, 2) + { + PrimaryText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL), + SubText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_RESET_YOUR_CHARACTER), + IconGraphic = _dialogIconService.IconSheet, + IconGraphicSource = _dialogIconService.GetDialogIconSource(DialogIcon.Forget), + ShowIconBackGround = false, + OffsetY = 45 + }; + forgetAll.LeftClick += (_, _) => SetState(SkillState.ForgetAll); + forgetAll.RightClick += (_, _) => SetState(SkillState.ForgetAll); + forgetAll.SetParentControl(this); - input.DialogClosing += (_, args) => + SetItemList(new List { learn, forget, forgetAll }); + + Buttons = ScrollingListDialogButtons.Cancel; + } + break; + case SkillState.Learn: { - if (args.Result == XNADialogResult.Cancel) - return; - - _cachedSpells.SingleOrNone(s => string.Equals(_pubFileProvider.ESFFile[s.ID].Name, input.ResponseText, StringComparison.OrdinalIgnoreCase)) - .Match( - some: si => - { - _skillmasterActions.ForgetSkill(si.ID); - }, - none: () => - { - args.Cancel = true; - - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_FORGET_ERROR_NOT_LEARNED); - dlg.ShowDialog(); - }); - }; - - input.ShowDialog(); - - //should show initial info in the actual dialog since this uses a pop-up input box - // to select a skill to remove - newState = SkillState.Initial; - goto case SkillState.Initial; - } - case SkillState.ForgetAll: - { - ShowForgetAllMessage(); - Buttons = ScrollingListDialogButtons.BackCancel; - } - break; - } + foreach (var skill in _cachedSkills.Where(x => !_cachedSpells.Any(y => y.ID == x.Id))) + { + var skillRef = skill; + var spellData = _pubFileProvider.ESFFile[skill.Id]; + + var icon = GraphicsManager.TextureFromResource(GFXTypes.SpellIcons, spellData.Icon); + var nextListItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + { + Visible = false, + PrimaryText = spellData.Name, + SubText = _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_REQUIREMENTS), + IconGraphic = icon, + IconGraphicSource = new Rectangle(0, 0, icon.Width / 2, icon.Height), + ShowIconBackGround = false, + OffsetY = 45 + }; + nextListItem.LeftClick += (_, _) => Learn(skillRef); + nextListItem.RightClick += (o, e) => Learn(skillRef); + nextListItem.OnMouseEnter += (o, e) => ShowRequirementsLabel(skillRef); + nextListItem.SetSubtextClickAction((_, _) => ShowRequirements(skillRef)); + AddItemToList(nextListItem, false); + } + + Buttons = ScrollingListDialogButtons.BackCancel; + } + break; + case SkillState.Forget: + { + var input = _textInputDialogFactory.Create(_localizedStringFinder.GetString(DialogResourceID.SKILL_PROMPT_TO_FORGET), 32); - _state = newState; - } + input.DialogClosing += (_, args) => + { + if (args.Result == XNADialogResult.Cancel) + return; + + _cachedSpells.SingleOrNone(s => string.Equals(_pubFileProvider.ESFFile[s.ID].Name, input.ResponseText, StringComparison.OrdinalIgnoreCase)) + .Match( + some: si => + { + _skillmasterActions.ForgetSkill(si.ID); + }, + none: () => + { + args.Cancel = true; + + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_FORGET_ERROR_NOT_LEARNED); + dlg.ShowDialog(); + }); + }; - private void Learn(Skill skill) - { + input.ShowDialog(); - bool skillReqsMet = true; - foreach (var req in skill.SkillRequirements.Where(x => x > 0)) + //should show initial info in the actual dialog since this uses a pop-up input box + // to select a skill to remove + newState = SkillState.Initial; + goto case SkillState.Initial; + } + case SkillState.ForgetAll: + { + ShowForgetAllMessage(); + Buttons = ScrollingListDialogButtons.BackCancel; + } + break; + } + + _state = newState; + } + + private void Learn(Skill skill) { - if (!_characterInventoryProvider.SpellInventory.Any(s => s.ID == req)) + + bool skillReqsMet = true; + foreach (var req in skill.SkillRequirements.Where(x => x > 0)) { - skillReqsMet = false; - break; + if (!_characterInventoryProvider.SpellInventory.Any(s => s.ID == req)) + { + skillReqsMet = false; + break; + } } - } - var stats = _characterProvider.MainCharacter.Stats; + var stats = _characterProvider.MainCharacter.Stats; - if (!skillReqsMet || - stats[CharacterStat.Strength] < skill.StrRequirement || stats[CharacterStat.Intelligence] < skill.IntRequirement || stats[CharacterStat.Wisdom] < skill.WisRequirement || - stats[CharacterStat.Agility] < skill.AgiRequirement || stats[CharacterStat.Constitution] < skill.ConRequirement || stats[CharacterStat.Charisma] < skill.ChaRequirement || - stats[CharacterStat.Level] < skill.LevelRequirement || !_characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1 && x.Amount >= skill.GoldRequirement).HasValue) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_REQS_NOT_MET); - dlg.ShowDialog(); - } - else if (skill.ClassRequirement > 0 && _characterProvider.MainCharacter.ClassID != skill.ClassRequirement) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_WRONG_CLASS, $" {_pubFileProvider.ECFFile[skill.ClassRequirement].Name}!"); - dlg.ShowDialog(); - return; + if (!skillReqsMet || + stats[CharacterStat.Strength] < skill.StrRequirement || stats[CharacterStat.Intelligence] < skill.IntRequirement || stats[CharacterStat.Wisdom] < skill.WisRequirement || + stats[CharacterStat.Agility] < skill.AgiRequirement || stats[CharacterStat.Constitution] < skill.ConRequirement || stats[CharacterStat.Charisma] < skill.ChaRequirement || + stats[CharacterStat.Level] < skill.LevelRequirement || !_characterInventoryProvider.ItemInventory.SingleOrNone(x => x.ItemID == 1 && x.Amount >= skill.GoldRequirement).HasValue) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_REQS_NOT_MET); + dlg.ShowDialog(); + } + else if (skill.ClassRequirement > 0 && _characterProvider.MainCharacter.ClassID != skill.ClassRequirement) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_WRONG_CLASS, $" {_pubFileProvider.ECFFile[skill.ClassRequirement].Name}!"); + dlg.ShowDialog(); + return; + } + else + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_CONFIRMATION, $" {_pubFileProvider.ESFFile[skill.Id].Name}?", EODialogButtons.OkCancel); + dlg.DialogClosing += (o, e) => + { + if (e.Result == XNADialogResult.OK) + _skillmasterActions.LearnSkill(skill.Id); + }; + dlg.ShowDialog(); + } } - else + + private void ShowRequirements(Skill skill) { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_LEARN_CONFIRMATION, $" {_pubFileProvider.ESFFile[skill.Id].Name}?", EODialogButtons.OkCancel); - dlg.DialogClosing += (o, e) => + _showingRequirements = true; + + ClearItemList(); + ListItemType = ListDialogItem.ListItemStyle.Small; + + var drawStrings = new List { - if (e.Result == XNADialogResult.OK) - _skillmasterActions.LearnSkill(skill.Id); + _pubFileProvider.ESFFile[skill.Id].Name + (skill.ClassRequirement > 0 ? $" [{_pubFileProvider.ECFFile[skill.ClassRequirement].Name}]" : string.Empty), + " " }; - dlg.ShowDialog(); - } - } - - private void ShowRequirements(Skill skill) - { - _showingRequirements = true; - ClearItemList(); - ListItemType = ListDialogItem.ListItemStyle.Small; + if (skill.SkillRequirements.Any(x => x != 0)) + { + drawStrings.AddRange( + from req in skill.SkillRequirements + where req != 0 + select _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_SKILL) + ": " + _pubFileProvider.ESFFile[req].Name); + drawStrings.Add(" "); + } - var drawStrings = new List - { - _pubFileProvider.ESFFile[skill.Id].Name + (skill.ClassRequirement > 0 ? $" [{_pubFileProvider.ECFFile[skill.ClassRequirement].Name}]" : string.Empty), - " " - }; + if (skill.StrRequirement > 0) + drawStrings.Add($"{skill.StrRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_STRENGTH)}"); + if (skill.IntRequirement > 0) + drawStrings.Add($"{skill.IntRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_INTELLIGENCE)}"); + if (skill.WisRequirement > 0) + drawStrings.Add($"{skill.WisRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_WISDOM)}"); + if (skill.AgiRequirement > 0) + drawStrings.Add($"{skill.AgiRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_AGILITY)}"); + if (skill.ConRequirement > 0) + drawStrings.Add($"{skill.ConRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CONSTITUTION)}"); + if (skill.ChaRequirement > 0) + drawStrings.Add($"{skill.ChaRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CHARISMA)}"); - if (skill.SkillRequirements.Any(x => x != 0)) - { - drawStrings.AddRange( - from req in skill.SkillRequirements - where req != 0 - select _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_SKILL) + ": " + _pubFileProvider.ESFFile[req].Name); drawStrings.Add(" "); - } + drawStrings.Add($"{skill.LevelRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEVEL)}"); + drawStrings.Add($"{skill.GoldRequirement} {_pubFileProvider.EIFFile[1].Name}"); - if (skill.StrRequirement > 0) - drawStrings.Add($"{skill.StrRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_STRENGTH)}"); - if (skill.IntRequirement > 0) - drawStrings.Add($"{skill.IntRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_INTELLIGENCE)}"); - if (skill.WisRequirement > 0) - drawStrings.Add($"{skill.WisRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_WISDOM)}"); - if (skill.AgiRequirement > 0) - drawStrings.Add($"{skill.AgiRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_AGILITY)}"); - if (skill.ConRequirement > 0) - drawStrings.Add($"{skill.ConRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CONSTITUTION)}"); - if (skill.ChaRequirement > 0) - drawStrings.Add($"{skill.ChaRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CHARISMA)}"); - - drawStrings.Add(" "); - drawStrings.Add($"{skill.LevelRequirement} {_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEVEL)}"); - drawStrings.Add($"{skill.GoldRequirement} {_pubFileProvider.EIFFile[1].Name}"); - - SetItemList(drawStrings.Select(x => new ListDialogItem(this, ListItemType) { PrimaryText = x }).ToList()); - } + SetItemList(drawStrings.Select(x => new ListDialogItem(this, ListItemType) { PrimaryText = x }).ToList()); + } - private void ShowRequirementsLabel(Skill skill) - { - var full = new StringBuilder(); - - full.Append($"{_pubFileProvider.ESFFile[skill.Id].Name} {skill.LevelRequirement} LVL, "); - - if (skill.StrRequirement > 0) - full.Append($"{skill.StrRequirement} STR, "); - if (skill.IntRequirement > 0) - full.Append($"{skill.IntRequirement} INT, "); - if (skill.WisRequirement > 0) - full.Append($"{skill.WisRequirement} WIS, "); - if (skill.AgiRequirement > 0) - full.Append($"{skill.AgiRequirement} AGI, "); - if (skill.ConRequirement > 0) - full.Append($"{skill.ConRequirement} CON, "); - if (skill.ChaRequirement > 0) - full.Append($"{skill.ChaRequirement} CHA, "); - if (skill.GoldRequirement > 0) - full.Append($"{skill.GoldRequirement} {_pubFileProvider.EIFFile[1].Name}"); - if (skill.ClassRequirement > 0) - full.Append($", {_pubFileProvider.ECFFile[skill.ClassRequirement].Name}"); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, full.ToString()); - } + private void ShowRequirementsLabel(Skill skill) + { + var full = new StringBuilder(); + + full.Append($"{_pubFileProvider.ESFFile[skill.Id].Name} {skill.LevelRequirement} LVL, "); + + if (skill.StrRequirement > 0) + full.Append($"{skill.StrRequirement} STR, "); + if (skill.IntRequirement > 0) + full.Append($"{skill.IntRequirement} INT, "); + if (skill.WisRequirement > 0) + full.Append($"{skill.WisRequirement} WIS, "); + if (skill.AgiRequirement > 0) + full.Append($"{skill.AgiRequirement} AGI, "); + if (skill.ConRequirement > 0) + full.Append($"{skill.ConRequirement} CON, "); + if (skill.ChaRequirement > 0) + full.Append($"{skill.ChaRequirement} CHA, "); + if (skill.GoldRequirement > 0) + full.Append($"{skill.GoldRequirement} {_pubFileProvider.EIFFile[1].Name}"); + if (skill.ClassRequirement > 0) + full.Append($", {_pubFileProvider.ECFFile[skill.ClassRequirement].Name}"); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, full.ToString()); + } - private void ShowForgetAllMessage() - { - AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], - insertLineBreaks: true, - new List { ConfirmResetCharacter }, - _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL), - _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_1), - _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_2), - _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_3), - _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_CLICK_HERE_TO_FORGET_ALL) - ); - } + private void ShowForgetAllMessage() + { + AddTextAsListItems(_contentProvider.Fonts[Constants.FontSize09], + insertLineBreaks: true, + new List { ConfirmResetCharacter }, + _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL), + _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_1), + _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_2), + _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_FORGET_ALL_MSG_3), + _localizedStringFinder.GetString(EOResourceID.SKILLMASTER_CLICK_HERE_TO_FORGET_ALL) + ); + } - private void ConfirmResetCharacter() - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_CONFIRMATION, EODialogButtons.OkCancel); - dlg.DialogClosing += (_, args) => + private void ConfirmResetCharacter() { - // todo: test how GameServer handles character reset with paperdoll items still equipped - if (args.Result == XNADialogResult.OK) + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SKILL_RESET_CHARACTER_CONFIRMATION, EODialogButtons.OkCancel); + dlg.DialogClosing += (_, args) => { - _skillmasterActions.ResetCharacter(); - } - }; - dlg.ShowDialog(); + // todo: test how GameServer handles character reset with paperdoll items still equipped + if (args.Result == XNADialogResult.OK) + { + _skillmasterActions.ResetCharacter(); + } + }; + dlg.ShowDialog(); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/TextInputDialog.cs b/EndlessClient/Dialogs/TextInputDialog.cs index 910ea6c3f..4e6bea597 100644 --- a/EndlessClient/Dialogs/TextInputDialog.cs +++ b/EndlessClient/Dialogs/TextInputDialog.cs @@ -6,70 +6,71 @@ using Microsoft.Xna.Framework; using XNAControls; -namespace EndlessClient.Dialogs; - -public class TextInputDialog : BaseEODialog +namespace EndlessClient.Dialogs { - private readonly IXNATextBox _inputBox; - - public string ResponseText => _inputBox.Text; - - public TextInputDialog(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - IContentProvider contentProvider, - string prompt, - int maxInputChars = 12) - : base(nativeGraphicsManager, isInGame: true) + public class TextInputDialog : BaseEODialog { - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 54); - SetSize(BackgroundTexture.Width, BackgroundTexture.Height); + private readonly IXNATextBox _inputBox; - var lblPrompt = new XNALabel(Constants.FontSize10) - { - AutoSize = false, - DrawArea = new Rectangle(21, 19, 230, 49), - ForeColor = ColorConstants.LightGrayDialogMessage, - TextWidth = 225, - Text = prompt - }; - lblPrompt.Initialize(); - lblPrompt.SetParentControl(this); + public string ResponseText => _inputBox.Text; - _inputBox = new XNATextBox(new Rectangle(37, 74, 192, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) + public TextInputDialog(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + IContentProvider contentProvider, + string prompt, + int maxInputChars = 12) + : base(nativeGraphicsManager, isInGame: true) { - MaxChars = maxInputChars, - LeftPadding = 4, - TextColor = ColorConstants.LightBeigeText, - }; - _inputBox.SetParentControl(this); + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 54); + SetSize(BackgroundTexture.Width, BackgroundTexture.Height); - var ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(41, 103), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - ok.OnClick += (_, _) => Close(XNADialogResult.OK); - ok.SetParentControl(this); + var lblPrompt = new XNALabel(Constants.FontSize10) + { + AutoSize = false, + DrawArea = new Rectangle(21, 19, 230, 49), + ForeColor = ColorConstants.LightGrayDialogMessage, + TextWidth = 225, + Text = prompt + }; + lblPrompt.Initialize(); + lblPrompt.SetParentControl(this); - var cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(134, 103), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); - cancel.SetParentControl(this); + _inputBox = new XNATextBox(new Rectangle(37, 74, 192, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) + { + MaxChars = maxInputChars, + LeftPadding = 4, + TextColor = ColorConstants.LightBeigeText, + }; + _inputBox.SetParentControl(this); - DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); + var ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(41, 103), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + ok.OnClick += (_, _) => Close(XNADialogResult.OK); + ok.SetParentControl(this); - CenterInGameView(); - DrawPosition += new Vector2(0, 17); - } + var cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(134, 103), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); + cancel.SetParentControl(this); - public override void Initialize() - { - _inputBox.Initialize(); + DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); + + CenterInGameView(); + DrawPosition += new Vector2(0, 17); + } + + public override void Initialize() + { + _inputBox.Initialize(); - _inputBox.Selected = true; + _inputBox.Selected = true; - base.Initialize(); + base.Initialize(); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/TextMultiInputDialog.cs b/EndlessClient/Dialogs/TextMultiInputDialog.cs index 3db0f1c18..73af29c43 100644 --- a/EndlessClient/Dialogs/TextMultiInputDialog.cs +++ b/EndlessClient/Dialogs/TextMultiInputDialog.cs @@ -10,152 +10,153 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs; - -public class TextMultiInputDialog : BaseEODialog +namespace EndlessClient.Dialogs { - public enum DialogSize + public class TextMultiInputDialog : BaseEODialog { - Two, - Three, - Four, - Five, - FiveWithScroll, - } - - public struct InputInfo - { - public string Label; - public int MaxChars; - } + public enum DialogSize + { + Two, + Three, + Four, + Five, + FiveWithScroll, + } - // can't use base class functionality because otherwise the bottom part of the dialog is drawn over the buttons - private readonly Texture2D _background; - private readonly Rectangle _backgroundSourceRectangle; + public struct InputInfo + { + public string Label; + public int MaxChars; + } - private readonly Vector2 _bottomOverlayDrawPosition; - private readonly Rectangle _bottomOverlaySource; + // can't use base class functionality because otherwise the bottom part of the dialog is drawn over the buttons + private readonly Texture2D _background; + private readonly Rectangle _backgroundSourceRectangle; - private readonly IXNATextBox[] _inputBoxes; + private readonly Vector2 _bottomOverlayDrawPosition; + private readonly Rectangle _bottomOverlaySource; - public IReadOnlyList Responses => _inputBoxes.Select(x => x.Text).ToList(); + private readonly IXNATextBox[] _inputBoxes; - public TextMultiInputDialog(INativeGraphicsManager nativeGraphicsManager, - IChatTextBoxActions chatTextBoxActions, - IEODialogButtonService eoDialogButtonService, - IContentProvider contentProvider, - DialogSize size, - string title, - string prompt, - InputInfo[] inputInfo) - : base(nativeGraphicsManager, isInGame: true) - { - _background = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 57); + public IReadOnlyList Responses => _inputBoxes.Select(x => x.Text).ToList(); - switch (size) + public TextMultiInputDialog(INativeGraphicsManager nativeGraphicsManager, + IChatTextBoxActions chatTextBoxActions, + IEODialogButtonService eoDialogButtonService, + IContentProvider contentProvider, + DialogSize size, + string title, + string prompt, + InputInfo[] inputInfo) + : base(nativeGraphicsManager, isInGame: true) { - case DialogSize.Two: - if (inputInfo.Length != 2) - { - throw new ArgumentException("Not enough input labels were provided"); - } + _background = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 57); - _backgroundSourceRectangle = new Rectangle(0, 0, 330, 170); + switch (size) + { + case DialogSize.Two: + if (inputInfo.Length != 2) + { + throw new ArgumentException("Not enough input labels were provided"); + } - SetSize(330, 170); - _bottomOverlayDrawPosition = new Vector2(0, 111); - _bottomOverlaySource = new Rectangle(0, 240, 330, 59); + _backgroundSourceRectangle = new Rectangle(0, 0, 330, 170); - _inputBoxes = new IXNATextBox[2]; - break; - default: throw new NotImplementedException(); - } + SetSize(330, 170); + _bottomOverlayDrawPosition = new Vector2(0, 111); + _bottomOverlaySource = new Rectangle(0, 240, 330, 59); - var lblTitle = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - ForeColor = ColorConstants.LightYellowText, - Text = title, - TextWidth = 254, - DrawPosition = new Vector2(18, 12), - }; - lblTitle.Initialize(); - lblTitle.SetParentControl(this); - - var lblPrompt = new XNALabel(Constants.FontSize10) - { - AutoSize = true, - ForeColor = ColorConstants.LightGrayDialogMessage, - Text = prompt, - TextWidth = 254, - DrawPosition = new Vector2(19, 40), - WrapBehavior = WrapBehavior.WrapToNewLine, - }; - lblPrompt.Initialize(); - lblPrompt.SetParentControl(this); - - int yCoord = 69; - for (int i = 0; i < inputInfo.Length; i++) - { - var nextLabel = new XNALabel(Constants.FontSize10) + _inputBoxes = new IXNATextBox[2]; + break; + default: throw new NotImplementedException(); + } + + var lblTitle = new XNALabel(Constants.FontSize10) { AutoSize = true, - ForeColor = ColorConstants.LightGrayDialogMessage, - Text = inputInfo[i].Label, - DrawPosition = new Vector2(24, yCoord), + ForeColor = ColorConstants.LightYellowText, + Text = title, + TextWidth = 254, + DrawPosition = new Vector2(18, 12), }; - nextLabel.Initialize(); - nextLabel.SetParentControl(this); + lblTitle.Initialize(); + lblTitle.SetParentControl(this); - _inputBoxes[i] = new XNATextBox(new Rectangle(126, yCoord, 168, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) + var lblPrompt = new XNALabel(Constants.FontSize10) { - MaxChars = inputInfo[i].MaxChars, - LeftPadding = 4, - TextColor = ColorConstants.LightBeigeText, - MaxWidth = 160, + AutoSize = true, + ForeColor = ColorConstants.LightGrayDialogMessage, + Text = prompt, + TextWidth = 254, + DrawPosition = new Vector2(19, 40), + WrapBehavior = WrapBehavior.WrapToNewLine, }; - _inputBoxes[i].SetParentControl(this); + lblPrompt.Initialize(); + lblPrompt.SetParentControl(this); - yCoord += 24; + int yCoord = 69; + for (int i = 0; i < inputInfo.Length; i++) + { + var nextLabel = new XNALabel(Constants.FontSize10) + { + AutoSize = true, + ForeColor = ColorConstants.LightGrayDialogMessage, + Text = inputInfo[i].Label, + DrawPosition = new Vector2(24, yCoord), + }; + nextLabel.Initialize(); + nextLabel.SetParentControl(this); + + _inputBoxes[i] = new XNATextBox(new Rectangle(126, yCoord, 168, 19), Constants.FontSize08, caretTexture: contentProvider.Textures[ContentProvider.Cursor]) + { + MaxChars = inputInfo[i].MaxChars, + LeftPadding = 4, + TextColor = ColorConstants.LightBeigeText, + MaxWidth = 160, + }; + _inputBoxes[i].SetParentControl(this); + + yCoord += 24; + } + + var ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(73, 125), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + ok.OnClick += (_, _) => Close(XNADialogResult.OK); + ok.SetParentControl(this); + + var cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, + new Vector2(166, 125), + eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); + cancel.SetParentControl(this); + + DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); + + CenterInGameView(); } - var ok = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(73, 125), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - ok.OnClick += (_, _) => Close(XNADialogResult.OK); - ok.SetParentControl(this); - - var cancel = new XNAButton(eoDialogButtonService.SmallButtonSheet, - new Vector2(166, 125), - eoDialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - eoDialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - cancel.OnClick += (_, _) => Close(XNADialogResult.Cancel); - cancel.SetParentControl(this); - - DialogClosed += (_, _) => chatTextBoxActions.FocusChatTextBox(); - - CenterInGameView(); - } - - public override void Initialize() - { - foreach (var box in _inputBoxes) - box.Initialize(); + public override void Initialize() + { + foreach (var box in _inputBoxes) + box.Initialize(); - _inputBoxes[0].Selected = true; + _inputBoxes[0].Selected = true; - base.Initialize(); - } + base.Initialize(); + } - protected override void OnDrawControl(GameTime gameTime) - { - // need to redo drawing background image so controls get drawn on top of background - _spriteBatch.Begin(); - _spriteBatch.Draw(_background, DrawAreaWithParentOffset, _backgroundSourceRectangle, Color.White); - _spriteBatch.Draw(_background, DrawPositionWithParentOffset + _bottomOverlayDrawPosition, _bottomOverlaySource, Color.White); - _spriteBatch.End(); + protected override void OnDrawControl(GameTime gameTime) + { + // need to redo drawing background image so controls get drawn on top of background + _spriteBatch.Begin(); + _spriteBatch.Draw(_background, DrawAreaWithParentOffset, _backgroundSourceRectangle, Color.White); + _spriteBatch.Draw(_background, DrawPositionWithParentOffset + _bottomOverlayDrawPosition, _bottomOverlaySource, Color.White); + _spriteBatch.End(); - base.OnDrawControl(gameTime); + base.OnDrawControl(gameTime); + } } } \ No newline at end of file diff --git a/EndlessClient/Dialogs/TradeDialog.cs b/EndlessClient/Dialogs/TradeDialog.cs index 1a52c7ab7..3a4f56235 100644 --- a/EndlessClient/Dialogs/TradeDialog.cs +++ b/EndlessClient/Dialogs/TradeDialog.cs @@ -20,384 +20,385 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Dialogs; - -public class TradeDialog : BaseEODialog +namespace EndlessClient.Dialogs { - private readonly ITradeActions _tradeActions; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IInventorySpaceValidator _inventorySpaceValidator; - private readonly ITradeProvider _tradeProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - private readonly ISfxPlayer _sfxPlayer; - - private readonly IXNAPanel _leftPanel, _rightPanel; - private readonly IXNALabel _leftPlayerName, _rightPlayerName; - private readonly IXNALabel _leftPlayerStatus, _rightPlayerStatus; - private readonly ScrollBar _leftScroll, _rightScroll; - - private readonly IXNAButton _ok, _cancel; - - private readonly List _leftItems, _rightItems; - - // cached values: updated/compared from domain state - private TradeOffer _leftOffer, _rightOffer; - private int _leftScrollOffset, _rightScrollOffset; - - // tracks state around the trade partner quickly changing an offer - // pops up warning for "other player trying to trick you" - private int _recentPartnerItemChanges; - private Stopwatch _partnerItemChangeTick; - - public TradeDialog(INativeGraphicsManager nativeGraphicsManager, - ITradeActions tradeActions, - ILocalizedStringFinder localizedStringFinder, - IEODialogButtonService dialogButtonService, - IEOMessageBoxFactory messageBoxFactory, - IStatusLabelSetter statusLabelSetter, - IInventorySpaceValidator inventorySpaceValidator, - ITradeProvider tradeProvider, - ICharacterProvider characterProvider, - IEIFFileProvider eifFileProvider, - IMapItemGraphicProvider mapItemGraphicProvider, - ISfxPlayer sfxPlayer) - : base(nativeGraphicsManager, isInGame: true) + public class TradeDialog : BaseEODialog { - _tradeActions = tradeActions; - _localizedStringFinder = localizedStringFinder; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _inventorySpaceValidator = inventorySpaceValidator; - _tradeProvider = tradeProvider; - _characterProvider = characterProvider; - _eifFileProvider = eifFileProvider; - _mapItemGraphicProvider = mapItemGraphicProvider; - _sfxPlayer = sfxPlayer; - BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 50); - - _leftPanel = new XNAPanel - { - DrawArea = new Rectangle(0, 0, BackgroundTexture.Width / 2, BackgroundTexture.Height), - }; - _leftPanel.SetParentControl(this); - - _rightPanel = new XNAPanel - { - DrawArea = new Rectangle(BackgroundTexture.Width / 2, 0, BackgroundTexture.Width / 2, BackgroundTexture.Height), - }; - _rightPanel.SetParentControl(this); - - _leftPlayerName = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(20, 14, 166, 20), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText - }; - _leftPlayerName.SetParentControl(_leftPanel); - - _rightPlayerName = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(11, 14, 166, 20), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText - }; - _rightPlayerName.SetParentControl(_rightPanel); - - _leftPlayerStatus = new XNALabel(Constants.FontSize08pt5) + private readonly ITradeActions _tradeActions; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IInventorySpaceValidator _inventorySpaceValidator; + private readonly ITradeProvider _tradeProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IMapItemGraphicProvider _mapItemGraphicProvider; + private readonly ISfxPlayer _sfxPlayer; + + private readonly IXNAPanel _leftPanel, _rightPanel; + private readonly IXNALabel _leftPlayerName, _rightPlayerName; + private readonly IXNALabel _leftPlayerStatus, _rightPlayerStatus; + private readonly ScrollBar _leftScroll, _rightScroll; + + private readonly IXNAButton _ok, _cancel; + + private readonly List _leftItems, _rightItems; + + // cached values: updated/compared from domain state + private TradeOffer _leftOffer, _rightOffer; + private int _leftScrollOffset, _rightScrollOffset; + + // tracks state around the trade partner quickly changing an offer + // pops up warning for "other player trying to trick you" + private int _recentPartnerItemChanges; + private Stopwatch _partnerItemChangeTick; + + public TradeDialog(INativeGraphicsManager nativeGraphicsManager, + ITradeActions tradeActions, + ILocalizedStringFinder localizedStringFinder, + IEODialogButtonService dialogButtonService, + IEOMessageBoxFactory messageBoxFactory, + IStatusLabelSetter statusLabelSetter, + IInventorySpaceValidator inventorySpaceValidator, + ITradeProvider tradeProvider, + ICharacterProvider characterProvider, + IEIFFileProvider eifFileProvider, + IMapItemGraphicProvider mapItemGraphicProvider, + ISfxPlayer sfxPlayer) + : base(nativeGraphicsManager, isInGame: true) { - DrawArea = new Rectangle(195, 14, 79, 20), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText, - Text = _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING) - }; - _leftPlayerStatus.SetParentControl(_leftPanel); - - _rightPlayerStatus = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(185, 14, 79, 20), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText, - Text = _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING) - }; - _rightPlayerStatus.SetParentControl(_rightPanel); - - _leftScroll = new ScrollBar(new Vector2(252, 44), new Vector2(16, 199), ScrollBarColors.LightOnMed, GraphicsManager) { LinesToRender = 5 }; - _leftScroll.SetParentControl(_leftPanel); - _leftPanel.SetScrollWheelHandler(_leftScroll); - - _rightScroll = new ScrollBar(new Vector2(243, 44), new Vector2(16, 199), ScrollBarColors.LightOnMed, GraphicsManager) { LinesToRender = 5 }; - _rightScroll.SetParentControl(_rightPanel); - _rightPanel.SetScrollWheelHandler(_rightScroll); - - _ok = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(356, 252), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); - _ok.OnClick += OkButtonClicked; - _ok.SetParentControl(this); - - _cancel = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(449, 252), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); - _cancel.OnClick += CancelButtonClicked; - _cancel.SetParentControl(this); - - _leftItems = new List(); - _rightItems = new List(); - _leftOffer = new TradeOffer.Builder().ToImmutable(); - _rightOffer = new TradeOffer.Builder().ToImmutable(); - - CenterInGameView(); - - if (!Game.Window.AllowUserResizing) - DrawPosition = new Vector2(DrawPosition.X, 15); - } - - public override void Initialize() - { - base.Initialize(); + _tradeActions = tradeActions; + _localizedStringFinder = localizedStringFinder; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _inventorySpaceValidator = inventorySpaceValidator; + _tradeProvider = tradeProvider; + _characterProvider = characterProvider; + _eifFileProvider = eifFileProvider; + _mapItemGraphicProvider = mapItemGraphicProvider; + _sfxPlayer = sfxPlayer; + BackgroundTexture = GraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 50); + + _leftPanel = new XNAPanel + { + DrawArea = new Rectangle(0, 0, BackgroundTexture.Width / 2, BackgroundTexture.Height), + }; + _leftPanel.SetParentControl(this); - _leftPanel.Initialize(); - _rightPanel.Initialize(); + _rightPanel = new XNAPanel + { + DrawArea = new Rectangle(BackgroundTexture.Width / 2, 0, BackgroundTexture.Width / 2, BackgroundTexture.Height), + }; + _rightPanel.SetParentControl(this); - _leftPlayerName.Initialize(); - _rightPlayerName.Initialize(); + _leftPlayerName = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(20, 14, 166, 20), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText + }; + _leftPlayerName.SetParentControl(_leftPanel); + + _rightPlayerName = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(11, 14, 166, 20), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText + }; + _rightPlayerName.SetParentControl(_rightPanel); + + _leftPlayerStatus = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(195, 14, 79, 20), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText, + Text = _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING) + }; + _leftPlayerStatus.SetParentControl(_leftPanel); + + _rightPlayerStatus = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(185, 14, 79, 20), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText, + Text = _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING) + }; + _rightPlayerStatus.SetParentControl(_rightPanel); + + _leftScroll = new ScrollBar(new Vector2(252, 44), new Vector2(16, 199), ScrollBarColors.LightOnMed, GraphicsManager) { LinesToRender = 5 }; + _leftScroll.SetParentControl(_leftPanel); + _leftPanel.SetScrollWheelHandler(_leftScroll); + + _rightScroll = new ScrollBar(new Vector2(243, 44), new Vector2(16, 199), ScrollBarColors.LightOnMed, GraphicsManager) { LinesToRender = 5 }; + _rightScroll.SetParentControl(_rightPanel); + _rightPanel.SetScrollWheelHandler(_rightScroll); + + _ok = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(356, 252), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Ok), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Ok)); + _ok.OnClick += OkButtonClicked; + _ok.SetParentControl(this); + + _cancel = new XNAButton(dialogButtonService.SmallButtonSheet, new Vector2(449, 252), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Cancel), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Cancel)); + _cancel.OnClick += CancelButtonClicked; + _cancel.SetParentControl(this); + + _leftItems = new List(); + _rightItems = new List(); + _leftOffer = new TradeOffer.Builder().ToImmutable(); + _rightOffer = new TradeOffer.Builder().ToImmutable(); + + CenterInGameView(); + + if (!Game.Window.AllowUserResizing) + DrawPosition = new Vector2(DrawPosition.X, 15); + } - _leftPlayerStatus.Initialize(); - _rightPlayerStatus.Initialize(); + public override void Initialize() + { + base.Initialize(); - _leftScroll.Initialize(); - _rightScroll.Initialize(); + _leftPanel.Initialize(); + _rightPanel.Initialize(); - _ok.Initialize(); - _cancel.Initialize(); - } + _leftPlayerName.Initialize(); + _rightPlayerName.Initialize(); - protected override void OnUnconditionalUpdateControl(GameTime gameTime) - { - var updateItemVisibility = false; + _leftPlayerStatus.Initialize(); + _rightPlayerStatus.Initialize(); - // player one offer will always be on the left; player two always on the right - if (_tradeProvider.PlayerOneOffer != null && !_tradeProvider.PlayerOneOffer.Equals(_leftOffer)) - { - UpdateOffer(_tradeProvider.PlayerOneOffer, _leftOffer, _leftPlayerName, _leftPlayerStatus, _leftPanel, _leftItems, -3); - _leftOffer = _tradeProvider.PlayerOneOffer; - _leftScroll.UpdateDimensions(_leftOffer.Items.Count); - updateItemVisibility = true; - } + _leftScroll.Initialize(); + _rightScroll.Initialize(); - if (_tradeProvider.PlayerTwoOffer != null && !_tradeProvider.PlayerTwoOffer.Equals(_rightOffer)) - { - UpdateOffer(_tradeProvider.PlayerTwoOffer, _rightOffer, _rightPlayerName, _rightPlayerStatus, _rightPanel, _rightItems, -10); - _rightOffer = _tradeProvider.PlayerTwoOffer; - _rightScroll.UpdateDimensions(_rightOffer.Items.Count); - updateItemVisibility = true; + _ok.Initialize(); + _cancel.Initialize(); } - if (updateItemVisibility || _leftScrollOffset != _leftScroll.ScrollOffset) + protected override void OnUnconditionalUpdateControl(GameTime gameTime) { - UpdateItemScrollIndexes(_leftScroll, _leftItems); - _leftScrollOffset = _leftScroll.ScrollOffset; - } + var updateItemVisibility = false; - if (updateItemVisibility || _rightScrollOffset != _rightScroll.ScrollOffset) - { - UpdateItemScrollIndexes(_rightScroll, _rightItems); - _rightScrollOffset = _rightScroll.ScrollOffset; - } - - if (_partnerItemChangeTick?.ElapsedMilliseconds > 1000 && _recentPartnerItemChanges > 0) - { - _recentPartnerItemChanges--; - _partnerItemChangeTick = Stopwatch.StartNew(); - } - - base.OnUnconditionalUpdateControl(gameTime); - } + // player one offer will always be on the left; player two always on the right + if (_tradeProvider.PlayerOneOffer != null && !_tradeProvider.PlayerOneOffer.Equals(_leftOffer)) + { + UpdateOffer(_tradeProvider.PlayerOneOffer, _leftOffer, _leftPlayerName, _leftPlayerStatus, _leftPanel, _leftItems, -3); + _leftOffer = _tradeProvider.PlayerOneOffer; + _leftScroll.UpdateDimensions(_leftOffer.Items.Count); + updateItemVisibility = true; + } - private void UpdateOffer(TradeOffer actualOffer, TradeOffer cachedOffer, - IXNALabel playerNameLabel, IXNALabel playerStatusLabel, - IXNAPanel parentPanel, - List listItems, - int listitemOffset) - { - if (actualOffer.PlayerName != cachedOffer.PlayerName || actualOffer.Items.Count != cachedOffer.Items.Count) - { - if (!string.IsNullOrEmpty(actualOffer.PlayerName)) + if (_tradeProvider.PlayerTwoOffer != null && !_tradeProvider.PlayerTwoOffer.Equals(_rightOffer)) { - playerNameLabel.Text = $"{char.ToUpper(actualOffer.PlayerName[0]) + actualOffer.PlayerName[1..]}{(actualOffer.Items.Any() ? $"[{actualOffer.Items.Count}]" : "")}"; + UpdateOffer(_tradeProvider.PlayerTwoOffer, _rightOffer, _rightPlayerName, _rightPlayerStatus, _rightPanel, _rightItems, -10); + _rightOffer = _tradeProvider.PlayerTwoOffer; + _rightScroll.UpdateDimensions(_rightOffer.Items.Count); + updateItemVisibility = true; } - } - // todo: check if packets properly reset agrees to false when items change - if (actualOffer.Agrees != cachedOffer.Agrees) - { - playerStatusLabel.Text = actualOffer.Agrees - ? _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_AGREE) - : _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING); + if (updateItemVisibility || _leftScrollOffset != _leftScroll.ScrollOffset) + { + UpdateItemScrollIndexes(_leftScroll, _leftItems); + _leftScrollOffset = _leftScroll.ScrollOffset; + } - if (actualOffer.Agrees) + if (updateItemVisibility || _rightScrollOffset != _rightScroll.ScrollOffset) { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - actualOffer.PlayerID == _characterProvider.MainCharacter.ID - ? EOResourceID.STATUS_LABEL_TRADE_YOU_ACCEPT - : EOResourceID.STATUS_LABEL_TRADE_OTHER_ACCEPT); + UpdateItemScrollIndexes(_rightScroll, _rightItems); + _rightScrollOffset = _rightScroll.ScrollOffset; } - else + + if (_partnerItemChangeTick?.ElapsedMilliseconds > 1000 && _recentPartnerItemChanges > 0) { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - actualOffer.PlayerID == _characterProvider.MainCharacter.ID - ? EOResourceID.STATUS_LABEL_TRADE_YOU_CANCEL - : EOResourceID.STATUS_LABEL_TRADE_OTHER_CANCEL); + _recentPartnerItemChanges--; + _partnerItemChangeTick = Stopwatch.StartNew(); } + + base.OnUnconditionalUpdateControl(gameTime); } - if (cachedOffer.Items == null || !actualOffer.Items.ToHashSet().SetEquals(cachedOffer.Items)) + private void UpdateOffer(TradeOffer actualOffer, TradeOffer cachedOffer, + IXNALabel playerNameLabel, IXNALabel playerStatusLabel, + IXNAPanel parentPanel, + List listItems, + int listitemOffset) { - var added = actualOffer.Items.Except(cachedOffer.Items ?? Enumerable.Empty()); - var removed = (cachedOffer.Items ?? Enumerable.Empty()).Where(i => !actualOffer.Items.Contains(i)); - - foreach (var addedItem in added) + if (actualOffer.PlayerName != cachedOffer.PlayerName || actualOffer.Items.Count != cachedOffer.Items.Count) { - var itemRec = _eifFileProvider.EIFFile[addedItem.ItemID]; - var subText = $"x {addedItem.Amount} {(itemRec.Type == ItemType.Armor ? $"({_localizedStringFinder.GetString(itemRec.Gender == 0 ? EOResourceID.FEMALE : EOResourceID.MALE)})" : string.Empty)}"; - - var newListItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + if (!string.IsNullOrEmpty(actualOffer.PlayerName)) { - Data = addedItem, - PrimaryText = itemRec.Name, - SubText = subText, - IconGraphic = _mapItemGraphicProvider.GetItemGraphic(addedItem.ItemID, addedItem.Amount), - OffsetX = listitemOffset, - OffsetY = 46 - }; - - if (actualOffer.PlayerID == _characterProvider.MainCharacter.ID) - newListItem.RightClick += (_, _) => _tradeActions.RemoveItemFromOffer(itemRec.ID); - - newListItem.SetParentControl(parentPanel); - listItems.Add(newListItem); - - _sfxPlayer.PlaySfx(SoundEffectID.TradeItemOfferChanged); + playerNameLabel.Text = $"{char.ToUpper(actualOffer.PlayerName[0]) + actualOffer.PlayerName[1..]}{(actualOffer.Items.Any() ? $"[{actualOffer.Items.Count}]" : "")}"; + } } - foreach (var removedItem in removed) + // todo: check if packets properly reset agrees to false when items change + if (actualOffer.Agrees != cachedOffer.Agrees) { - listItems.SingleOrNone(y => ((InventoryItem)y.Data).Equals(removedItem)) - .MatchSome(listItem => - { - listItems.Remove(listItem); - listItem.Dispose(); - }); + playerStatusLabel.Text = actualOffer.Agrees + ? _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_AGREE) + : _localizedStringFinder.GetString(EOResourceID.DIALOG_TRADE_WORD_TRADING); - _sfxPlayer.PlaySfx(SoundEffectID.TradeItemOfferChanged); + if (actualOffer.Agrees) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + actualOffer.PlayerID == _characterProvider.MainCharacter.ID + ? EOResourceID.STATUS_LABEL_TRADE_YOU_ACCEPT + : EOResourceID.STATUS_LABEL_TRADE_OTHER_ACCEPT); + } + else + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + actualOffer.PlayerID == _characterProvider.MainCharacter.ID + ? EOResourceID.STATUS_LABEL_TRADE_YOU_CANCEL + : EOResourceID.STATUS_LABEL_TRADE_OTHER_CANCEL); + } } - if (cachedOffer.Items != null && actualOffer.PlayerID != 0 && actualOffer.PlayerID != _characterProvider.MainCharacter.ID) + if (cachedOffer.Items == null || !actualOffer.Items.ToHashSet().SetEquals(cachedOffer.Items)) { - _partnerItemChangeTick = Stopwatch.StartNew(); - _recentPartnerItemChanges++; + var added = actualOffer.Items.Except(cachedOffer.Items ?? Enumerable.Empty()); + var removed = (cachedOffer.Items ?? Enumerable.Empty()).Where(i => !actualOffer.Items.Contains(i)); - if (_recentPartnerItemChanges == 2) + foreach (var addedItem in added) { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_OTHER_PLAYER_TRICK_YOU); - dlg.ShowDialog(); + var itemRec = _eifFileProvider.EIFFile[addedItem.ItemID]; + var subText = $"x {addedItem.Amount} {(itemRec.Type == ItemType.Armor ? $"({_localizedStringFinder.GetString(itemRec.Gender == 0 ? EOResourceID.FEMALE : EOResourceID.MALE)})" : string.Empty)}"; + + var newListItem = new ListDialogItem(this, ListDialogItem.ListItemStyle.Large) + { + Data = addedItem, + PrimaryText = itemRec.Name, + SubText = subText, + IconGraphic = _mapItemGraphicProvider.GetItemGraphic(addedItem.ItemID, addedItem.Amount), + OffsetX = listitemOffset, + OffsetY = 46 + }; - // this will prevent the message from showing more than once per trade (I'm too lazy to find something more elegant) - _recentPartnerItemChanges = -1000; + if (actualOffer.PlayerID == _characterProvider.MainCharacter.ID) + newListItem.RightClick += (_, _) => _tradeActions.RemoveItemFromOffer(itemRec.ID); + + newListItem.SetParentControl(parentPanel); + listItems.Add(newListItem); + + _sfxPlayer.PlaySfx(SoundEffectID.TradeItemOfferChanged); } - else if ((_leftOffer == cachedOffer ? _rightOffer : _leftOffer).Agrees) - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_ABORTED_OFFER_CHANGED); - dlg.ShowDialog(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_TRADE_OTHER_PLAYER_CHANGED_OFFER); + foreach (var removedItem in removed) + { + listItems.SingleOrNone(y => ((InventoryItem)y.Data).Equals(removedItem)) + .MatchSome(listItem => + { + listItems.Remove(listItem); + listItem.Dispose(); + }); + + _sfxPlayer.PlaySfx(SoundEffectID.TradeItemOfferChanged); } - } - } - } - private void UpdateItemScrollIndexes(ScrollBar scrollBar, List items) - { - var scrollOffset = items.Count > scrollBar.LinesToRender ? scrollBar.ScrollOffset : 0; + if (cachedOffer.Items != null && actualOffer.PlayerID != 0 && actualOffer.PlayerID != _characterProvider.MainCharacter.ID) + { + _partnerItemChangeTick = Stopwatch.StartNew(); + _recentPartnerItemChanges++; - for (int i = 0; i < items.Count; i++) - { - items[i].Visible = i >= scrollOffset && i < scrollBar.LinesToRender + scrollOffset; - items[i].Index = i - scrollOffset; - } - } + if (_recentPartnerItemChanges == 2) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_OTHER_PLAYER_TRICK_YOU); + dlg.ShowDialog(); - private void OkButtonClicked(object sender, EventArgs e) - { - var (offer, partnerOffer) = _leftOffer.PlayerID == _characterProvider.MainCharacter.ID - ? (_leftOffer, _rightOffer) - : (_rightOffer, _leftOffer); + // this will prevent the message from showing more than once per trade (I'm too lazy to find something more elegant) + _recentPartnerItemChanges = -1000; + } + else if ((_leftOffer == cachedOffer ? _rightOffer : _leftOffer).Agrees) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_ABORTED_OFFER_CHANGED); + dlg.ShowDialog(); - if (offer.Agrees) - return; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_TRADE_OTHER_PLAYER_CHANGED_OFFER); + } + } + } + } - if (_leftOffer.Items.Count == 0 || _rightOffer.Items.Count == 0) + private void UpdateItemScrollIndexes(ScrollBar scrollBar, List items) { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRADE_BOTH_PLAYERS_OFFER_ONE_ITEM, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); - return; + var scrollOffset = items.Count > scrollBar.LinesToRender ? scrollBar.ScrollOffset : 0; + + for (int i = 0; i < items.Count; i++) + { + items[i].Visible = i >= scrollOffset && i < scrollBar.LinesToRender + scrollOffset; + items[i].Index = i - scrollOffset; + } } - if (!_inventorySpaceValidator.ItemsFit(offer.Items, partnerOffer.Items)) + private void OkButtonClicked(object sender, EventArgs e) { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); - return; - } + var (offer, partnerOffer) = _leftOffer.PlayerID == _characterProvider.MainCharacter.ID + ? (_leftOffer, _rightOffer) + : (_rightOffer, _leftOffer); - var partnerItemWeight = partnerOffer.Items - .Select(x => _eifFileProvider.EIFFile[x.ItemID].Weight * x.Amount) - .Aggregate((a, b) => a + b); - var offerItemWeight = offer.Items - .Select(x => _eifFileProvider.EIFFile[x.ItemID].Weight * x.Amount) - .Aggregate((a, b) => a + b); + if (offer.Agrees) + return; - var stats = _characterProvider.MainCharacter.Stats; - if (stats[CharacterStat.Weight] - offerItemWeight + partnerItemWeight > stats[CharacterStat.MaxWeight]) - { - var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); - dlg.ShowDialog(); - return; - } + if (_leftOffer.Items.Count == 0 || _rightOffer.Items.Count == 0) + { + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRADE_BOTH_PLAYERS_OFFER_ONE_ITEM, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + return; + } - var finalCheckDlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_DO_YOU_AGREE, EODialogButtons.OkCancel); - finalCheckDlg.DialogClosing += (o, e) => - { - if (e.Result == XNADialogResult.OK) + if (!_inventorySpaceValidator.ItemsFit(offer.Items, partnerOffer.Items)) { - _tradeActions.AgreeToTrade(true); + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_SPACE, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + return; } - }; - finalCheckDlg.ShowDialog(); - } - private void CancelButtonClicked(object sender, EventArgs e) - { - var offer = _leftOffer.PlayerID == _characterProvider.MainCharacter.ID - ? _leftOffer - : _rightOffer; + var partnerItemWeight = partnerOffer.Items + .Select(x => _eifFileProvider.EIFFile[x.ItemID].Weight * x.Amount) + .Aggregate((a, b) => a + b); + var offerItemWeight = offer.Items + .Select(x => _eifFileProvider.EIFFile[x.ItemID].Weight * x.Amount) + .Aggregate((a, b) => a + b); - if (!offer.Agrees) - { - _tradeActions.CancelTrade(); - Close(XNADialogResult.Cancel); + var stats = _characterProvider.MainCharacter.Stats; + if (stats[CharacterStat.Weight] - offerItemWeight + partnerItemWeight > stats[CharacterStat.MaxWeight]) + { + var dlg = _messageBoxFactory.CreateMessageBox(EOResourceID.DIALOG_TRANSFER_NOT_ENOUGH_WEIGHT, EOResourceID.STATUS_LABEL_TYPE_WARNING); + dlg.ShowDialog(); + return; + } + + var finalCheckDlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.TRADE_DO_YOU_AGREE, EODialogButtons.OkCancel); + finalCheckDlg.DialogClosing += (o, e) => + { + if (e.Result == XNADialogResult.OK) + { + _tradeActions.AgreeToTrade(true); + } + }; + finalCheckDlg.ShowDialog(); } - else + + private void CancelButtonClicked(object sender, EventArgs e) { - _tradeActions.AgreeToTrade(false); + var offer = _leftOffer.PlayerID == _characterProvider.MainCharacter.ID + ? _leftOffer + : _rightOffer; + + if (!offer.Agrees) + { + _tradeActions.CancelTrade(); + Close(XNADialogResult.Cancel); + } + else + { + _tradeActions.AgreeToTrade(false); + } } } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/DebugGameRunner.cs b/EndlessClient/GameExecution/DebugGameRunner.cs index 2a108fc7a..80eb2abab 100644 --- a/EndlessClient/GameExecution/DebugGameRunner.cs +++ b/EndlessClient/GameExecution/DebugGameRunner.cs @@ -1,12 +1,13 @@ using AutomaticTypeMapper; -namespace EndlessClient.GameExecution; - -/// -/// A game runner that does not catch any exceptions -/// -public class DebugGameRunner : GameRunnerBase +namespace EndlessClient.GameExecution { - public DebugGameRunner(ITypeRegistry registry, string[] args) - : base(registry, args) { } + /// + /// A game runner that does not catch any exceptions + /// + public class DebugGameRunner : GameRunnerBase + { + public DebugGameRunner(ITypeRegistry registry, string[] args) + : base(registry, args) { } + } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/EndlessGame.cs b/EndlessClient/GameExecution/EndlessGame.cs index fef84a3b3..2cb41e3e2 100644 --- a/EndlessClient/GameExecution/EndlessGame.cs +++ b/EndlessClient/GameExecution/EndlessGame.cs @@ -24,276 +24,277 @@ using System.Linq; using System.Runtime.InteropServices; -namespace EndlessClient.GameExecution; - -[MappedType(BaseType = typeof(IEndlessGame), IsSingleton = true)] -public class EndlessGame : Game, IEndlessGame +namespace EndlessClient.GameExecution { - private readonly IClientWindowSizeRepository _windowSizeRepository; - private readonly IContentProvider _contentProvider; - private readonly IGraphicsDeviceRepository _graphicsDeviceRepository; - private readonly IGameWindowRepository _gameWindowRepository; - private readonly IControlSetRepository _controlSetRepository; - private readonly IControlSetFactory _controlSetFactory; - private readonly ITestModeLauncher _testModeLauncher; - private readonly IPubFileLoadActions _pubFileLoadActions; - private readonly ILoggerProvider _loggerProvider; - private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; - private readonly IConfigurationProvider _configurationProvider; - private readonly IMfxPlayer _mfxPlayer; - private readonly IXnaControlSoundMapper _soundMapper; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - private readonly IMainButtonController _mainButtonController; - - private GraphicsDeviceManager _graphicsDeviceManager; - - private KeyboardState _previousKeyState; - private TimeSpan _lastFrameUpdate; + [MappedType(BaseType = typeof(IEndlessGame), IsSingleton = true)] + public class EndlessGame : Game, IEndlessGame + { + private readonly IClientWindowSizeRepository _windowSizeRepository; + private readonly IContentProvider _contentProvider; + private readonly IGraphicsDeviceRepository _graphicsDeviceRepository; + private readonly IGameWindowRepository _gameWindowRepository; + private readonly IControlSetRepository _controlSetRepository; + private readonly IControlSetFactory _controlSetFactory; + private readonly ITestModeLauncher _testModeLauncher; + private readonly IPubFileLoadActions _pubFileLoadActions; + private readonly ILoggerProvider _loggerProvider; + private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; + private readonly IConfigurationProvider _configurationProvider; + private readonly IMfxPlayer _mfxPlayer; + private readonly IXnaControlSoundMapper _soundMapper; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + private readonly IMainButtonController _mainButtonController; + + private GraphicsDeviceManager _graphicsDeviceManager; + + private KeyboardState _previousKeyState; + private TimeSpan _lastFrameUpdate; #if DEBUG - private SpriteBatch _spriteBatch; - private Stopwatch _lastFrameRenderTime = Stopwatch.StartNew(); - private int _frames, _displayFrames; - private Texture2D _black; + private SpriteBatch _spriteBatch; + private Stopwatch _lastFrameRenderTime = Stopwatch.StartNew(); + private int _frames, _displayFrames; + private Texture2D _black; #endif - public EndlessGame(IClientWindowSizeRepository windowSizeRepository, - IContentProvider contentProvider, - IGraphicsDeviceRepository graphicsDeviceRepository, - IGameWindowRepository gameWindowRepository, - IControlSetRepository controlSetRepository, - IControlSetFactory controlSetFactory, - ITestModeLauncher testModeLauncher, - IPubFileLoadActions pubFileLoadActions, - ILoggerProvider loggerProvider, - IChatBubbleTextureProvider chatBubbleTextureProvider, - IConfigurationProvider configurationProvider, - IMfxPlayer mfxPlayer, - IXnaControlSoundMapper soundMapper, - IFixedTimeStepRepository fixedTimeStepRepository, - IMainButtonController mainButtonController) - { - _windowSizeRepository = windowSizeRepository; - _contentProvider = contentProvider; - _graphicsDeviceRepository = graphicsDeviceRepository; - _gameWindowRepository = gameWindowRepository; - _controlSetRepository = controlSetRepository; - _controlSetFactory = controlSetFactory; - _testModeLauncher = testModeLauncher; - _pubFileLoadActions = pubFileLoadActions; - _loggerProvider = loggerProvider; - _chatBubbleTextureProvider = chatBubbleTextureProvider; - _configurationProvider = configurationProvider; - _mfxPlayer = mfxPlayer; - _soundMapper = soundMapper; - _fixedTimeStepRepository = fixedTimeStepRepository; - _mainButtonController = mainButtonController; - - _graphicsDeviceManager = new GraphicsDeviceManager(this) + public EndlessGame(IClientWindowSizeRepository windowSizeRepository, + IContentProvider contentProvider, + IGraphicsDeviceRepository graphicsDeviceRepository, + IGameWindowRepository gameWindowRepository, + IControlSetRepository controlSetRepository, + IControlSetFactory controlSetFactory, + ITestModeLauncher testModeLauncher, + IPubFileLoadActions pubFileLoadActions, + ILoggerProvider loggerProvider, + IChatBubbleTextureProvider chatBubbleTextureProvider, + IConfigurationProvider configurationProvider, + IMfxPlayer mfxPlayer, + IXnaControlSoundMapper soundMapper, + IFixedTimeStepRepository fixedTimeStepRepository, + IMainButtonController mainButtonController) { - PreferredBackBufferWidth = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH, - PreferredBackBufferHeight = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT - }; + _windowSizeRepository = windowSizeRepository; + _contentProvider = contentProvider; + _graphicsDeviceRepository = graphicsDeviceRepository; + _gameWindowRepository = gameWindowRepository; + _controlSetRepository = controlSetRepository; + _controlSetFactory = controlSetFactory; + _testModeLauncher = testModeLauncher; + _pubFileLoadActions = pubFileLoadActions; + _loggerProvider = loggerProvider; + _chatBubbleTextureProvider = chatBubbleTextureProvider; + _configurationProvider = configurationProvider; + _mfxPlayer = mfxPlayer; + _soundMapper = soundMapper; + _fixedTimeStepRepository = fixedTimeStepRepository; + _mainButtonController = mainButtonController; + + _graphicsDeviceManager = new GraphicsDeviceManager(this) + { + PreferredBackBufferWidth = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH, + PreferredBackBufferHeight = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT + }; - Content.RootDirectory = "Content"; - } + Content.RootDirectory = "Content"; + } - protected override void Initialize() - { - Components.ComponentAdded += (o, e) => + protected override void Initialize() { - // this is bad hack - // all pre-game controls have a specific sound that should be mapped to them. - // in-game controls get their sounds mapped individually. - // - // Checking for GameStates.LoggedIn because the in-game controls are - // added to the components in the LoggedIn state - if (_controlSetRepository.CurrentControlSet.GameState != GameStates.LoggedIn) + Components.ComponentAdded += (o, e) => { - _soundMapper.BindSoundToControl(e.GameComponent); - } - }; + // this is bad hack + // all pre-game controls have a specific sound that should be mapped to them. + // in-game controls get their sounds mapped individually. + // + // Checking for GameStates.LoggedIn because the in-game controls are + // added to the components in the LoggedIn state + if (_controlSetRepository.CurrentControlSet.GameState != GameStates.LoggedIn) + { + _soundMapper.BindSoundToControl(e.GameComponent); + } + }; - base.Initialize(); + base.Initialize(); - IsMouseVisible = true; - IsFixedTimeStep = false; + IsMouseVisible = true; + IsFixedTimeStep = false; - TargetElapsedTime = TimeSpan.FromMilliseconds(FixedTimeStepRepository.TICK_TIME_MS); - InactiveSleepTime = TimeSpan.FromMilliseconds(0); + TargetElapsedTime = TimeSpan.FromMilliseconds(FixedTimeStepRepository.TICK_TIME_MS); + InactiveSleepTime = TimeSpan.FromMilliseconds(0); - _previousKeyState = Keyboard.GetState(); + _previousKeyState = Keyboard.GetState(); - // setting Width/Height in window size repository applies the change to disable vsync - _graphicsDeviceManager.SynchronizeWithVerticalRetrace = false; - _graphicsDeviceManager.IsFullScreen = false; - _windowSizeRepository.Width = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH; - _windowSizeRepository.Height = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT; + // setting Width/Height in window size repository applies the change to disable vsync + _graphicsDeviceManager.SynchronizeWithVerticalRetrace = false; + _graphicsDeviceManager.IsFullScreen = false; + _windowSizeRepository.Width = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH; + _windowSizeRepository.Height = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT; - _windowSizeRepository.GameWindowSizeChanged += (_, _) => - { - if (_windowSizeRepository.Width < ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT) - _windowSizeRepository.Width = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH; + _windowSizeRepository.GameWindowSizeChanged += (_, _) => + { + if (_windowSizeRepository.Width < ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT) + _windowSizeRepository.Width = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_WIDTH; - if (_windowSizeRepository.Height < ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT) - _windowSizeRepository.Height = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT; - }; + if (_windowSizeRepository.Height < ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT) + _windowSizeRepository.Height = ClientWindowSizeRepository.DEFAULT_BACKBUFFER_HEIGHT; + }; - Exiting += (_, _) => _mfxPlayer.StopBackgroundMusic(); - } + Exiting += (_, _) => _mfxPlayer.StopBackgroundMusic(); + } - protected override void LoadContent() - { + protected override void LoadContent() + { #if DEBUG - _spriteBatch = new SpriteBatch(GraphicsDevice); - _black = new Texture2D(GraphicsDevice, 1, 1); - _black.SetData(new[] { Color.Black }); + _spriteBatch = new SpriteBatch(GraphicsDevice); + _black = new Texture2D(GraphicsDevice, 1, 1); + _black.SetData(new[] { Color.Black }); #endif - _contentProvider.Load(); + _contentProvider.Load(); - //todo: all the things that should load stuff as part of game's load/initialize should be broken into a pattern - _chatBubbleTextureProvider.LoadContent(); + //todo: all the things that should load stuff as part of game's load/initialize should be broken into a pattern + _chatBubbleTextureProvider.LoadContent(); - //the GraphicsDevice/Window don't exist until Initialize() is called by the framework - //Ideally, this would be set in a DependencyContainer, but I'm not sure of a way to do that now - _graphicsDeviceRepository.GraphicsDevice = GraphicsDevice; - _graphicsDeviceRepository.GraphicsDeviceManager = _graphicsDeviceManager; - _gameWindowRepository.Window = Window; + //the GraphicsDevice/Window don't exist until Initialize() is called by the framework + //Ideally, this would be set in a DependencyContainer, but I'm not sure of a way to do that now + _graphicsDeviceRepository.GraphicsDevice = GraphicsDevice; + _graphicsDeviceRepository.GraphicsDeviceManager = _graphicsDeviceManager; + _gameWindowRepository.Window = Window; - SetUpInitialControlSet(); + SetUpInitialControlSet(); - if (_configurationProvider.MusicEnabled) - { - _mfxPlayer.PlayBackgroundMusic(1, EOLib.IO.Map.MusicControl.InterruptPlayRepeat); - } + if (_configurationProvider.MusicEnabled) + { + _mfxPlayer.PlayBackgroundMusic(1, EOLib.IO.Map.MusicControl.InterruptPlayRepeat); + } - AttemptToLoadPubFiles(); + AttemptToLoadPubFiles(); - base.LoadContent(); - } + base.LoadContent(); + } - protected override void Update(GameTime gameTime) - { - // Force updates to wait every 12ms - // Some game components rely on slower update times. 60FPS was the original, but 12ms factors nicely in 120ms "ticks" - // See: https://github.com/ethanmoffat/EndlessClient/issues/199 - // Using IsFixedTimeStep = true with TargetUpdateTime set to 60FPS also limits the draw rate, which is not desired - if ((gameTime.TotalGameTime - _lastFrameUpdate).TotalMilliseconds >= FixedTimeStepRepository.TICK_TIME_MS) + protected override void Update(GameTime gameTime) { -#if DEBUG - var currentKeyState = Keyboard.GetState(); - if (KeyboardExtended.GetState().WasKeyJustDown(Keys.F5)) + // Force updates to wait every 12ms + // Some game components rely on slower update times. 60FPS was the original, but 12ms factors nicely in 120ms "ticks" + // See: https://github.com/ethanmoffat/EndlessClient/issues/199 + // Using IsFixedTimeStep = true with TargetUpdateTime set to 60FPS also limits the draw rate, which is not desired + if ((gameTime.TotalGameTime - _lastFrameUpdate).TotalMilliseconds >= FixedTimeStepRepository.TICK_TIME_MS) { - _testModeLauncher.LaunchTestMode(); - } +#if DEBUG + var currentKeyState = Keyboard.GetState(); + if (KeyboardExtended.GetState().WasKeyJustDown(Keys.F5)) + { + _testModeLauncher.LaunchTestMode(); + } - _previousKeyState = currentKeyState; + _previousKeyState = currentKeyState; #endif - _fixedTimeStepRepository.Tick(); + _fixedTimeStepRepository.Tick(); #if !DEBUG - try - { - base.Update(gameTime); - } - catch - { - if (_configurationProvider.DebugCrashes) + try { - throw; + base.Update(gameTime); } - else + catch { - _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); + if (_configurationProvider.DebugCrashes) + { + throw; + } + else + { + _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); + } } - } #else - base.Update(gameTime); + base.Update(gameTime); #endif - _lastFrameUpdate = gameTime.TotalGameTime; + _lastFrameUpdate = gameTime.TotalGameTime; + } } - } - protected override void Draw(GameTime gameTime) - { - var isTestMode = _controlSetRepository.CurrentControlSet.GameState == GameStates.TestMode; - GraphicsDevice.Clear(isTestMode ? Color.White : Color.Black); + protected override void Draw(GameTime gameTime) + { + var isTestMode = _controlSetRepository.CurrentControlSet.GameState == GameStates.TestMode; + GraphicsDevice.Clear(isTestMode ? Color.White : Color.Black); - base.Draw(gameTime); + base.Draw(gameTime); #if DEBUG - _frames++; + _frames++; - var fpsString = $"FPS: {_displayFrames}{(gameTime.IsRunningSlowly ? " (SLOW)" : string.Empty)}"; - var dim = _contentProvider.Fonts[Constants.FontSize09].MeasureString(fpsString); + var fpsString = $"FPS: {_displayFrames}{(gameTime.IsRunningSlowly ? " (SLOW)" : string.Empty)}"; + var dim = _contentProvider.Fonts[Constants.FontSize09].MeasureString(fpsString); - _spriteBatch.Begin(); - _spriteBatch.Draw(_black, new Rectangle(18, 18, (int)dim.Width + 4, (int)dim.Height + 4), Color.White); - _spriteBatch.DrawString(_contentProvider.Fonts[Constants.FontSize09], fpsString, new Vector2(20, 20), Color.White); - _spriteBatch.End(); + _spriteBatch.Begin(); + _spriteBatch.Draw(_black, new Rectangle(18, 18, (int)dim.Width + 4, (int)dim.Height + 4), Color.White); + _spriteBatch.DrawString(_contentProvider.Fonts[Constants.FontSize09], fpsString, new Vector2(20, 20), Color.White); + _spriteBatch.End(); - if (_lastFrameRenderTime.ElapsedMilliseconds > 1000) - { - _displayFrames = _frames; - _frames = 0; - _lastFrameRenderTime = Stopwatch.StartNew(); - } + if (_lastFrameRenderTime.ElapsedMilliseconds > 1000) + { + _displayFrames = _frames; + _frames = 0; + _lastFrameRenderTime = Stopwatch.StartNew(); + } #endif - } - - private void AttemptToLoadPubFiles() - { - const string PUB_LOG_MSG = "**** Unable to load default PUB file: {0}. Exception message: {1}"; - - try - { - _pubFileLoadActions.LoadItemFile(); - } - catch (Exception ex) when (ex is IOException || ex is ArgumentException) - { - _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.EIFFormat, 1), ex.Message); } - try + private void AttemptToLoadPubFiles() { - _pubFileLoadActions.LoadNPCFile(); - } - catch (Exception ex) when (ex is IOException || ex is ArgumentException) - { - _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ENFFormat, 1), ex.Message); - } + const string PUB_LOG_MSG = "**** Unable to load default PUB file: {0}. Exception message: {1}"; - try - { - _pubFileLoadActions.LoadSpellFile(); - } - catch (Exception ex) when (ex is IOException || ex is ArgumentException) - { - _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ESFFormat, 1), ex.Message); - } + try + { + _pubFileLoadActions.LoadItemFile(); + } + catch (Exception ex) when (ex is IOException || ex is ArgumentException) + { + _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.EIFFormat, 1), ex.Message); + } - try - { - _pubFileLoadActions.LoadClassFile(); + try + { + _pubFileLoadActions.LoadNPCFile(); + } + catch (Exception ex) when (ex is IOException || ex is ArgumentException) + { + _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ENFFormat, 1), ex.Message); + } + + try + { + _pubFileLoadActions.LoadSpellFile(); + } + catch (Exception ex) when (ex is IOException || ex is ArgumentException) + { + _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ESFFormat, 1), ex.Message); + } + + try + { + _pubFileLoadActions.LoadClassFile(); + } + catch (Exception ex) when (ex is IOException || ex is ArgumentException) + { + _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ECFFormat, 1), ex.Message); + } } - catch (Exception ex) when (ex is IOException || ex is ArgumentException) + + private void SetUpInitialControlSet() { - _loggerProvider.Logger.Log(PUB_LOG_MSG, string.Format(PubFileNameConstants.ECFFormat, 1), ex.Message); + var controls = _controlSetFactory.CreateControlsForState( + GameStates.Initial, + _controlSetRepository.CurrentControlSet); + _controlSetRepository.CurrentControlSet = controls; + + //since the controls are being created in LoadContent(), adding them to the default game + // doesn't call the Initialize() method on any controls, so it must be done here + foreach (var xnaControl in _controlSetRepository.CurrentControlSet.AllComponents) + xnaControl.Initialize(); } } - - private void SetUpInitialControlSet() - { - var controls = _controlSetFactory.CreateControlsForState( - GameStates.Initial, - _controlSetRepository.CurrentControlSet); - _controlSetRepository.CurrentControlSet = controls; - - //since the controls are being created in LoadContent(), adding them to the default game - // doesn't call the Initialize() method on any controls, so it must be done here - foreach (var xnaControl in _controlSetRepository.CurrentControlSet.AllComponents) - xnaControl.Initialize(); - } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/GameRunnerBase.cs b/EndlessClient/GameExecution/GameRunnerBase.cs index 72c538559..5d9eaf43f 100644 --- a/EndlessClient/GameExecution/GameRunnerBase.cs +++ b/EndlessClient/GameExecution/GameRunnerBase.cs @@ -12,136 +12,137 @@ using System.Windows.Forms; #endif -namespace EndlessClient.GameExecution; - -public abstract class GameRunnerBase : IGameRunner +namespace EndlessClient.GameExecution { - private readonly ITypeRegistry _registry; - private readonly string[] _args; - - protected GameRunnerBase(ITypeRegistry registry, string[] args) + public abstract class GameRunnerBase : IGameRunner { - _registry = registry; - _args = args; - } + private readonly ITypeRegistry _registry; + private readonly string[] _args; - public virtual bool SetupDependencies() - { - _registry.RegisterDiscoveredTypes(); - - var initializers = _registry.ResolveAll(); - try - { - foreach (var initializer in initializers) - { - initializer.Initialize(); - } - } - catch (ConfigLoadException cle) - { - ShowErrorMessage(cle.Message, "Error loading config file!"); - return false; - } - catch (DataFileLoadException dfle) - { - ShowErrorMessage(dfle.Message, "Error loading data files!"); - return false; - } - catch (DirectoryNotFoundException dnfe) - { - ShowErrorMessage(dnfe.Message, "Missing required directory"); - return false; - } - catch (FileNotFoundException fnfe) - { - ShowErrorMessage(fnfe.Message, "Missing required file"); - return false; - } - catch (LibraryLoadException lle) + protected GameRunnerBase(ITypeRegistry registry, string[] args) { - var message = - $"There was an error loading GFX{(int)lle.WhichGFX:000}.EGF : {lle.WhichGFX}. Place all .GFX files in .\\gfx\\. The error message is:\n\n\"{lle.Message}\""; - ShowErrorMessage(message, "GFX Load Error"); - return false; + _registry = registry; + _args = args; } - for (int i = 0; i < _args.Length; ++i) + public virtual bool SetupDependencies() { - var arg = _args[i]; + _registry.RegisterDiscoveredTypes(); - if (string.Equals(arg, "--host") && i < _args.Length - 1) + var initializers = _registry.ResolveAll(); + try { - var host = _args[i + 1]; - _registry.Resolve().Host = host; - - i++; + foreach (var initializer in initializers) + { + initializer.Initialize(); + } + } + catch (ConfigLoadException cle) + { + ShowErrorMessage(cle.Message, "Error loading config file!"); + return false; + } + catch (DataFileLoadException dfle) + { + ShowErrorMessage(dfle.Message, "Error loading data files!"); + return false; + } + catch (DirectoryNotFoundException dnfe) + { + ShowErrorMessage(dnfe.Message, "Missing required directory"); + return false; + } + catch (FileNotFoundException fnfe) + { + ShowErrorMessage(fnfe.Message, "Missing required file"); + return false; } - else if (string.Equals(arg, "--port") && i < _args.Length - 1) + catch (LibraryLoadException lle) { - var port = _args[i + 1]; + var message = + $"There was an error loading GFX{(int)lle.WhichGFX:000}.EGF : {lle.WhichGFX}. Place all .GFX files in .\\gfx\\. The error message is:\n\n\"{lle.Message}\""; + ShowErrorMessage(message, "GFX Load Error"); + return false; + } + + for (int i = 0; i < _args.Length; ++i) + { + var arg = _args[i]; - if (int.TryParse(port, out var intPort)) + if (string.Equals(arg, "--host") && i < _args.Length - 1) { - _registry.Resolve().Port = intPort; + var host = _args[i + 1]; + _registry.Resolve().Host = host; + + i++; } + else if (string.Equals(arg, "--port") && i < _args.Length - 1) + { + var port = _args[i + 1]; - i++; - } - else if (string.Equals(arg, "--version") && i < _args.Length - 1) - { - var versionStr = _args[i + 1]; - if (!byte.TryParse(versionStr, out var version)) + if (int.TryParse(port, out var intPort)) + { + _registry.Resolve().Port = intPort; + } + + i++; + } + else if (string.Equals(arg, "--version") && i < _args.Length - 1) { - Debug.WriteLine($"Version must be a byte (0-255)."); + var versionStr = _args[i + 1]; + if (!byte.TryParse(versionStr, out var version)) + { + Debug.WriteLine($"Version must be a byte (0-255)."); + } + else + { + _registry.Resolve() + .VersionBuild = version; + } + + i++; } - else + else if (string.Equals(arg, "--account_delay_ms") && i < _args.Length - 1) { - _registry.Resolve() - .VersionBuild = version; + var accountCreateTimeStr = _args[i + 1]; + if (!int.TryParse(accountCreateTimeStr, out var accountCreateTime) || accountCreateTime < 2000) + { + Debug.WriteLine($"Account create timeout must be greater than or equal to 2000ms."); + } + else + { + _registry.Resolve() + .AccountCreateTimeout = TimeSpan.FromMilliseconds(accountCreateTime); + } + + i++; } - - i++; - } - else if (string.Equals(arg, "--account_delay_ms") && i < _args.Length - 1) - { - var accountCreateTimeStr = _args[i + 1]; - if (!int.TryParse(accountCreateTimeStr, out var accountCreateTime) || accountCreateTime < 2000) + else if (string.Equals(arg, "--debug")) { - Debug.WriteLine($"Account create timeout must be greater than or equal to 2000ms."); + _registry.Resolve().DebugCrashes = true; } else { - _registry.Resolve() - .AccountCreateTimeout = TimeSpan.FromMilliseconds(accountCreateTime); + Debug.WriteLine($"Unrecognized argument: {arg}. Will be ignored."); } - - i++; } - else if (string.Equals(arg, "--debug")) - { - _registry.Resolve().DebugCrashes = true; - } - else - { - Debug.WriteLine($"Unrecognized argument: {arg}. Will be ignored."); - } - } - return true; - } + return true; + } - private void ShowErrorMessage(string message, string caption) - { + private void ShowErrorMessage(string message, string caption) + { #if !LINUX && !OSX - MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); #else - Console.WriteLine(message); + Console.WriteLine(message); #endif - } + } - public virtual void RunGame() - { - var game = _registry.Resolve(); - game.Run(); + public virtual void RunGame() + { + var game = _registry.Resolve(); + game.Run(); + } } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/GameStateActions.cs b/EndlessClient/GameExecution/GameStateActions.cs index 0175db872..2673b7105 100644 --- a/EndlessClient/GameExecution/GameStateActions.cs +++ b/EndlessClient/GameExecution/GameStateActions.cs @@ -14,148 +14,149 @@ using System.Linq; using XNAControls.Input; -namespace EndlessClient.GameExecution; - -[MappedType(BaseType = typeof(IGameStateActions))] -public class GameStateActions : IGameStateActions +namespace EndlessClient.GameExecution { - private readonly IGameStateRepository _gameStateRepository; - private readonly IControlSetRepository _controlSetRepository; - private readonly IControlSetFactory _controlSetFactory; - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IPlayerInfoRepository _playerInfoRepository; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IMfxPlayer _mfxPlayer; - - public GameStateActions(IGameStateRepository gameStateRepository, - IControlSetRepository controlSetRepository, - IControlSetFactory controlSetFactory, - IEndlessGameProvider endlessGameProvider, - IPlayerInfoRepository playerInfoRepository, - IClientWindowSizeProvider clientWindowSizeProvider, - ISfxPlayer sfxPlayer, - IMfxPlayer mfxPlayer) + [MappedType(BaseType = typeof(IGameStateActions))] + public class GameStateActions : IGameStateActions { - _gameStateRepository = gameStateRepository; - _controlSetRepository = controlSetRepository; - _controlSetFactory = controlSetFactory; - _endlessGameProvider = endlessGameProvider; - _playerInfoRepository = playerInfoRepository; - _clientWindowSizeProvider = clientWindowSizeProvider; - _sfxPlayer = sfxPlayer; - _mfxPlayer = mfxPlayer; - } - - public void ChangeToState(GameStates newState) - { - if (newState == _gameStateRepository.CurrentState) - return; - - if (_gameStateRepository.CurrentState == GameStates.PlayingTheGame) + private readonly IGameStateRepository _gameStateRepository; + private readonly IControlSetRepository _controlSetRepository; + private readonly IControlSetFactory _controlSetFactory; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IPlayerInfoRepository _playerInfoRepository; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IMfxPlayer _mfxPlayer; + + public GameStateActions(IGameStateRepository gameStateRepository, + IControlSetRepository controlSetRepository, + IControlSetFactory controlSetFactory, + IEndlessGameProvider endlessGameProvider, + IPlayerInfoRepository playerInfoRepository, + IClientWindowSizeProvider clientWindowSizeProvider, + ISfxPlayer sfxPlayer, + IMfxPlayer mfxPlayer) { - _playerInfoRepository.PlayerIsInGame = false; - - StorePanelLayout(Game, EventArgs.Empty); - Game.Exiting -= StorePanelLayout; + _gameStateRepository = gameStateRepository; + _controlSetRepository = controlSetRepository; + _controlSetFactory = controlSetFactory; + _endlessGameProvider = endlessGameProvider; + _playerInfoRepository = playerInfoRepository; + _clientWindowSizeProvider = clientWindowSizeProvider; + _sfxPlayer = sfxPlayer; + _mfxPlayer = mfxPlayer; } - var currentSet = _controlSetRepository.CurrentControlSet; - var nextSet = _controlSetFactory.CreateControlsForState(newState, currentSet); + public void ChangeToState(GameStates newState) + { + if (newState == _gameStateRepository.CurrentState) + return; + + if (_gameStateRepository.CurrentState == GameStates.PlayingTheGame) + { + _playerInfoRepository.PlayerIsInGame = false; + + StorePanelLayout(Game, EventArgs.Empty); + Game.Exiting -= StorePanelLayout; + } + + var currentSet = _controlSetRepository.CurrentControlSet; + var nextSet = _controlSetFactory.CreateControlsForState(newState, currentSet); + + RemoveOldComponents(currentSet, nextSet); + AddNewComponents(nextSet); + + _gameStateRepository.CurrentState = newState; + _controlSetRepository.CurrentControlSet = nextSet; + + switch (_gameStateRepository.CurrentState) + { + case GameStates.None: + case GameStates.Initial: + { + _sfxPlayer.StopLoopingSfx(); + + // this replicates behavior of the vanilla client where returning to the main menu stops playing the background music + _mfxPlayer.StopBackgroundMusic(); + } + break; + case GameStates.LoggedIn: _sfxPlayer.PlaySfx(SoundEffectID.Login); break; + case GameStates.PlayingTheGame: + { + Game.Exiting += StorePanelLayout; + } + break; + } + } - RemoveOldComponents(currentSet, nextSet); - AddNewComponents(nextSet); + public void RefreshCurrentState() + { + var currentSet = _controlSetRepository.CurrentControlSet; + var emptySet = new EmptyControlSet(); - _gameStateRepository.CurrentState = newState; - _controlSetRepository.CurrentControlSet = nextSet; + RemoveOldComponents(currentSet, emptySet); + var refreshedSet = _controlSetFactory.CreateControlsForState(currentSet.GameState, emptySet); + AddNewComponents(refreshedSet); + _controlSetRepository.CurrentControlSet = refreshedSet; + } - switch (_gameStateRepository.CurrentState) + public void ExitGame() { - case GameStates.None: - case GameStates.Initial: - { - _sfxPlayer.StopLoopingSfx(); - - // this replicates behavior of the vanilla client where returning to the main menu stops playing the background music - _mfxPlayer.StopBackgroundMusic(); - } - break; - case GameStates.LoggedIn: _sfxPlayer.PlaySfx(SoundEffectID.Login); break; - case GameStates.PlayingTheGame: - { - Game.Exiting += StorePanelLayout; - } - break; + Game.Exit(); } - } - - public void RefreshCurrentState() - { - var currentSet = _controlSetRepository.CurrentControlSet; - var emptySet = new EmptyControlSet(); - RemoveOldComponents(currentSet, emptySet); - var refreshedSet = _controlSetFactory.CreateControlsForState(currentSet.GameState, emptySet); - AddNewComponents(refreshedSet); - _controlSetRepository.CurrentControlSet = refreshedSet; - } + private void AddNewComponents(IControlSet nextSet) + { + foreach (var component in nextSet.AllComponents.Except(nextSet.XNAControlComponents)) + if (!Game.Components.Contains(component)) + Game.Components.Add(component); + } - public void ExitGame() - { - Game.Exit(); - } + private void RemoveOldComponents(IControlSet currentSet, IControlSet nextSet) + { + var componentsToRemove = FindUnusedComponents(currentSet, nextSet); + var disposableComponents = componentsToRemove + .Where(x => x is not PacketHandlerGameComponent && x is not InputManager && x is not DispatcherGameComponent) + .OfType(); - private void AddNewComponents(IControlSet nextSet) - { - foreach (var component in nextSet.AllComponents.Except(nextSet.XNAControlComponents)) - if (!Game.Components.Contains(component)) - Game.Components.Add(component); - } + foreach (var component in disposableComponents) + component.Dispose(); + foreach (var component in componentsToRemove.Where(Game.Components.Contains)) + Game.Components.Remove(component); - private void RemoveOldComponents(IControlSet currentSet, IControlSet nextSet) - { - var componentsToRemove = FindUnusedComponents(currentSet, nextSet); - var disposableComponents = componentsToRemove - .Where(x => x is not PacketHandlerGameComponent && x is not InputManager && x is not DispatcherGameComponent) - .OfType(); + currentSet.Dispose(); + } - foreach (var component in disposableComponents) - component.Dispose(); - foreach (var component in componentsToRemove.Where(Game.Components.Contains)) - Game.Components.Remove(component); + private List FindUnusedComponents(IControlSet current, IControlSet next) + { + return current.AllComponents + .Where(component => !next.AllComponents.Contains(component)) + .ToList(); + } - currentSet.Dispose(); - } + private void StorePanelLayout(object sender, EventArgs e) + { + if (!_clientWindowSizeProvider.Resizable) return; - private List FindUnusedComponents(IControlSet current, IControlSet next) - { - return current.AllComponents - .Where(component => !next.AllComponents.Contains(component)) - .ToList(); - } + var panelConfig = new IniReader(Constants.PanelLayoutFile); + panelConfig.Sections["PANELS"] = new SortedList(); - private void StorePanelLayout(object sender, EventArgs e) - { - if (!_clientWindowSizeProvider.Resizable) return; + var panels = _controlSetRepository.CurrentControlSet.AllComponents.OfType(); + foreach (var panel in panels) + { + panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:X"] = ((int)panel.DrawPositionWithParentOffset.X).ToString(); + panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:Y"] = ((int)panel.DrawPositionWithParentOffset.Y).ToString(); + panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:Visible"] = panel.Visible.ToString(); + panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:DrawOrder"] = panel.DrawOrder.ToString(); + } - var panelConfig = new IniReader(Constants.PanelLayoutFile); - panelConfig.Sections["PANELS"] = new SortedList(); + panelConfig.Sections["DISPLAY"] = new SortedList(); + panelConfig.Sections["DISPLAY"]["Width"] = _clientWindowSizeProvider.Width.ToString(); + panelConfig.Sections["DISPLAY"]["Height"] = _clientWindowSizeProvider.Height.ToString(); - var panels = _controlSetRepository.CurrentControlSet.AllComponents.OfType(); - foreach (var panel in panels) - { - panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:X"] = ((int)panel.DrawPositionWithParentOffset.X).ToString(); - panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:Y"] = ((int)panel.DrawPositionWithParentOffset.Y).ToString(); - panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:Visible"] = panel.Visible.ToString(); - panelConfig.Sections["PANELS"][$"{panel.GetType().Name}:DrawOrder"] = panel.DrawOrder.ToString(); + panelConfig.Save(); } - panelConfig.Sections["DISPLAY"] = new SortedList(); - panelConfig.Sections["DISPLAY"]["Width"] = _clientWindowSizeProvider.Width.ToString(); - panelConfig.Sections["DISPLAY"]["Height"] = _clientWindowSizeProvider.Height.ToString(); - - panelConfig.Save(); + private IEndlessGame Game => _endlessGameProvider.Game; } - - private IEndlessGame Game => _endlessGameProvider.Game; } \ No newline at end of file diff --git a/EndlessClient/GameExecution/GameStates.cs b/EndlessClient/GameExecution/GameStates.cs index a2e4ad5c6..c73fd08df 100644 --- a/EndlessClient/GameExecution/GameStates.cs +++ b/EndlessClient/GameExecution/GameStates.cs @@ -1,40 +1,41 @@ -namespace EndlessClient.GameExecution; - -/// -/// Game states -/// -public enum GameStates +namespace EndlessClient.GameExecution { /// - /// Represents an noninitialized state (during game initialization) - /// - None, - /// - /// Initial State when game is launched - /// - Initial, - /// - /// State when an account is being created - /// - CreateAccount, - /// - /// State when Login button is clicked, but account is not yet authenticated - /// - Login, - /// - /// Account is authenticated. Show available characters for account - /// - LoggedIn, - /// - /// Roll credits... - /// - ViewCredits, - /// - /// In game - /// - PlayingTheGame, - /// - /// Test mode - for testing different character render states - /// - TestMode + /// Game states + /// + public enum GameStates + { + /// + /// Represents an noninitialized state (during game initialization) + /// + None, + /// + /// Initial State when game is launched + /// + Initial, + /// + /// State when an account is being created + /// + CreateAccount, + /// + /// State when Login button is clicked, but account is not yet authenticated + /// + Login, + /// + /// Account is authenticated. Show available characters for account + /// + LoggedIn, + /// + /// Roll credits... + /// + ViewCredits, + /// + /// In game + /// + PlayingTheGame, + /// + /// Test mode - for testing different character render states + /// + TestMode + } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/IEndlessGame.cs b/EndlessClient/GameExecution/IEndlessGame.cs index f3af9b0ee..d9066581d 100644 --- a/EndlessClient/GameExecution/IEndlessGame.cs +++ b/EndlessClient/GameExecution/IEndlessGame.cs @@ -2,21 +2,22 @@ using Microsoft.Xna.Framework.Content; using System; -namespace EndlessClient.GameExecution; - -public interface IEndlessGame : IDisposable +namespace EndlessClient.GameExecution { - event EventHandler Exiting; + public interface IEndlessGame : IDisposable + { + event EventHandler Exiting; - GameComponentCollection Components { get; } + GameComponentCollection Components { get; } - ContentManager Content { get; } + ContentManager Content { get; } - GameWindow Window { get; } + GameWindow Window { get; } - bool IsActive { get; } + bool IsActive { get; } - void Run(); + void Run(); - void Exit(); + void Exit(); + } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/IEndlessGameProvider.cs b/EndlessClient/GameExecution/IEndlessGameProvider.cs index e5cc34860..5320faa60 100644 --- a/EndlessClient/GameExecution/IEndlessGameProvider.cs +++ b/EndlessClient/GameExecution/IEndlessGameProvider.cs @@ -1,20 +1,21 @@ using AutomaticTypeMapper; -namespace EndlessClient.GameExecution; - -public interface IEndlessGameRepository +namespace EndlessClient.GameExecution { - IEndlessGame Game { get; set; } -} + public interface IEndlessGameRepository + { + IEndlessGame Game { get; set; } + } -public interface IEndlessGameProvider -{ - IEndlessGame Game { get; } -} + public interface IEndlessGameProvider + { + IEndlessGame Game { get; } + } -[MappedType(BaseType = typeof(IEndlessGameRepository), IsSingleton = true)] -[MappedType(BaseType = typeof(IEndlessGameProvider), IsSingleton = true)] -public class EndlessGameRepository : IEndlessGameRepository, IEndlessGameProvider -{ - public IEndlessGame Game { get; set; } + [MappedType(BaseType = typeof(IEndlessGameRepository), IsSingleton = true)] + [MappedType(BaseType = typeof(IEndlessGameProvider), IsSingleton = true)] + public class EndlessGameRepository : IEndlessGameRepository, IEndlessGameProvider + { + public IEndlessGame Game { get; set; } + } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/IGameRunner.cs b/EndlessClient/GameExecution/IGameRunner.cs index 6d020b636..48347f597 100644 --- a/EndlessClient/GameExecution/IGameRunner.cs +++ b/EndlessClient/GameExecution/IGameRunner.cs @@ -1,8 +1,9 @@ -namespace EndlessClient.GameExecution; - -public interface IGameRunner +namespace EndlessClient.GameExecution { - bool SetupDependencies(); + public interface IGameRunner + { + bool SetupDependencies(); - void RunGame(); + void RunGame(); + } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/IGameStateActions.cs b/EndlessClient/GameExecution/IGameStateActions.cs index 37fbdf4dc..cf109642b 100644 --- a/EndlessClient/GameExecution/IGameStateActions.cs +++ b/EndlessClient/GameExecution/IGameStateActions.cs @@ -1,10 +1,11 @@ -namespace EndlessClient.GameExecution; - -public interface IGameStateActions +namespace EndlessClient.GameExecution { - void ChangeToState(GameStates newState); + public interface IGameStateActions + { + void ChangeToState(GameStates newState); - void RefreshCurrentState(); + void RefreshCurrentState(); - void ExitGame(); + void ExitGame(); + } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/IGameStateRepository.cs b/EndlessClient/GameExecution/IGameStateRepository.cs index e37dd0434..288123615 100644 --- a/EndlessClient/GameExecution/IGameStateRepository.cs +++ b/EndlessClient/GameExecution/IGameStateRepository.cs @@ -1,20 +1,21 @@ using AutomaticTypeMapper; -namespace EndlessClient.GameExecution; - -public interface IGameStateRepository +namespace EndlessClient.GameExecution { - GameStates CurrentState { get; set; } -} + public interface IGameStateRepository + { + GameStates CurrentState { get; set; } + } -public interface IGameStateProvider -{ - GameStates CurrentState { get; } -} + public interface IGameStateProvider + { + GameStates CurrentState { get; } + } -[MappedType(BaseType = typeof(IGameStateProvider), IsSingleton = true)] -[MappedType(BaseType = typeof(IGameStateRepository), IsSingleton = true)] -public class GameStateRepository : IGameStateRepository, IGameStateProvider -{ - public GameStates CurrentState { get; set; } + [MappedType(BaseType = typeof(IGameStateProvider), IsSingleton = true)] + [MappedType(BaseType = typeof(IGameStateRepository), IsSingleton = true)] + public class GameStateRepository : IGameStateRepository, IGameStateProvider + { + public GameStates CurrentState { get; set; } + } } \ No newline at end of file diff --git a/EndlessClient/GameExecution/ReleaseGameRunner.cs b/EndlessClient/GameExecution/ReleaseGameRunner.cs index e1702b853..a03d47224 100644 --- a/EndlessClient/GameExecution/ReleaseGameRunner.cs +++ b/EndlessClient/GameExecution/ReleaseGameRunner.cs @@ -7,107 +7,108 @@ using System.Windows.Forms; #endif -namespace EndlessClient.GameExecution; - -/// -/// A game runner that catches exceptions and display exception information -/// -public class ReleaseGameRunner : GameRunnerBase +namespace EndlessClient.GameExecution { - public ReleaseGameRunner(ITypeRegistry registry, string[] args) - : base(registry, args) { } - - public override bool SetupDependencies() + /// + /// A game runner that catches exceptions and display exception information + /// + public class ReleaseGameRunner : GameRunnerBase { - try - { - return base.SetupDependencies(); - } - catch (Exception ex) + public ReleaseGameRunner(ITypeRegistry registry, string[] args) + : base(registry, args) { } + + public override bool SetupDependencies() { - if (OperatingSystem.IsWindows()) - ShowExceptionDialog(ex); - else - Console.WriteLine($"Exception thrown during dependency setup: {ex.Message}\n\n{ex.StackTrace}"); + try + { + return base.SetupDependencies(); + } + catch (Exception ex) + { + if (OperatingSystem.IsWindows()) + ShowExceptionDialog(ex); + else + Console.WriteLine($"Exception thrown during dependency setup: {ex.Message}\n\n{ex.StackTrace}"); - return false; + return false; + } } - } - public override void RunGame() - { - try - { - base.RunGame(); - } - catch (Exception ex) + public override void RunGame() { - if (OperatingSystem.IsWindows()) - ShowExceptionDialog(ex); - else - Console.WriteLine($"Exception thrown during game execution: {ex.Message}\n\n{ex.StackTrace}"); + try + { + base.RunGame(); + } + catch (Exception ex) + { + if (OperatingSystem.IsWindows()) + ShowExceptionDialog(ex); + else + Console.WriteLine($"Exception thrown during game execution: {ex.Message}\n\n{ex.StackTrace}"); + } } - } - [SupportedOSPlatform("Windows")] - private static void ShowExceptionDialog(Exception ex) - { + [SupportedOSPlatform("Windows")] + private static void ShowExceptionDialog(Exception ex) + { #if !LINUX && !OSX - Application.EnableVisualStyles(); + Application.EnableVisualStyles(); - var exForm = new Form - { - Width = 350, - Height = 200, - MaximizeBox = false, - MinimizeBox = false, - Padding = new Padding(10), - Text = "Application Error", - BackColor = System.Drawing.Color.White, - Icon = System.Drawing.SystemIcons.Error, - StartPosition = FormStartPosition.CenterScreen, - MinimumSize = new System.Drawing.Size(350, 200) - }; - exForm.FormClosed += (sender, e) => Environment.Exit(1); + var exForm = new Form + { + Width = 350, + Height = 200, + MaximizeBox = false, + MinimizeBox = false, + Padding = new Padding(10), + Text = "Application Error", + BackColor = System.Drawing.Color.White, + Icon = System.Drawing.SystemIcons.Error, + StartPosition = FormStartPosition.CenterScreen, + MinimumSize = new System.Drawing.Size(350, 200) + }; + exForm.FormClosed += (sender, e) => Environment.Exit(1); - var exLabel1 = new Label - { - AutoEllipsis = true, - Dock = DockStyle.Top, - Font = new System.Drawing.Font(Control.DefaultFont, System.Drawing.FontStyle.Bold), - Text = "An unhandled exception has caused the game to crash:" - }; + var exLabel1 = new Label + { + AutoEllipsis = true, + Dock = DockStyle.Top, + Font = new System.Drawing.Font(Control.DefaultFont, System.Drawing.FontStyle.Bold), + Text = "An unhandled exception has caused the game to crash:" + }; - var exLabel2 = new Label - { - AutoEllipsis = true, - Dock = DockStyle.Top, - Padding = new Padding(5, 0, 0, 0), - Text = ex.Message - }; + var exLabel2 = new Label + { + AutoEllipsis = true, + Dock = DockStyle.Top, + Padding = new Padding(5, 0, 0, 0), + Text = ex.Message + }; - var exLabel3 = new Label - { - AutoEllipsis = true, - Dock = DockStyle.Top, - Font = new System.Drawing.Font(Control.DefaultFont, System.Drawing.FontStyle.Bold), - Text = "Stack trace:" - }; + var exLabel3 = new Label + { + AutoEllipsis = true, + Dock = DockStyle.Top, + Font = new System.Drawing.Font(Control.DefaultFont, System.Drawing.FontStyle.Bold), + Text = "Stack trace:" + }; - var exTextBox1 = new TextBox - { - Dock = DockStyle.Fill, - Multiline = true, - ReadOnly = true, - ScrollBars = ScrollBars.Vertical, - Text = ex.StackTrace - }; + var exTextBox1 = new TextBox + { + Dock = DockStyle.Fill, + Multiline = true, + ReadOnly = true, + ScrollBars = ScrollBars.Vertical, + Text = ex.StackTrace + }; - exForm.Controls.Add(exTextBox1); - exForm.Controls.Add(exLabel3); - exForm.Controls.Add(exLabel2); - exForm.Controls.Add(exLabel1); - exForm.ShowDialog(); + exForm.Controls.Add(exTextBox1); + exForm.Controls.Add(exLabel3); + exForm.Controls.Add(exLabel2); + exForm.Controls.Add(exLabel1); + exForm.ShowDialog(); #endif + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/AStarPathFinder.cs b/EndlessClient/HUD/AStarPathFinder.cs index 99a214a14..c3902916c 100644 --- a/EndlessClient/HUD/AStarPathFinder.cs +++ b/EndlessClient/HUD/AStarPathFinder.cs @@ -5,106 +5,107 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.HUD; - -// Implemented from https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode -[AutoMappedType] -public class AStarPathFinder : IPathFinder +namespace EndlessClient.HUD { - private readonly IWalkValidationActions _walkValidationActions; - - public AStarPathFinder(IWalkValidationActions walkValidationActions) - { - _walkValidationActions = walkValidationActions; - } - - public Queue FindPath(MapCoordinate start, MapCoordinate finish) + // Implemented from https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode + [AutoMappedType] + public class AStarPathFinder : IPathFinder { - var openSet = new HashSet(new[] { start }); - var cameFrom = new Dictionary(); + private readonly IWalkValidationActions _walkValidationActions; - var scores = new Dictionary + public AStarPathFinder(IWalkValidationActions walkValidationActions) { - { start, 0 } - }; + _walkValidationActions = walkValidationActions; + } - var guessScores = new Dictionary + public Queue FindPath(MapCoordinate start, MapCoordinate finish) { - { start, heuristic(start, finish) } - }; + var openSet = new HashSet(new[] { start }); + var cameFrom = new Dictionary(); - while (openSet.Any()) - { - MapCoordinate current = new MapCoordinate(0, 0); - var lowest = int.MaxValue; - foreach (var n in openSet) + var scores = new Dictionary { - if (guessScores[n] < lowest) - { - current = n; - lowest = guessScores[n]; - } - } + { start, 0 } + }; - if (current.Equals(finish)) - return reconstructPath(start, cameFrom, current); - - openSet.Remove(current); - foreach (var neighbor in getNeighbors(current)) + var guessScores = new Dictionary { - var tentativeScore = scores[current] + 1; - if (!scores.TryGetValue(neighbor, out var _)) - scores.Add(neighbor, int.MaxValue); + { start, heuristic(start, finish) } + }; - if (tentativeScore < scores[neighbor]) + while (openSet.Any()) + { + MapCoordinate current = new MapCoordinate(0, 0); + var lowest = int.MaxValue; + foreach (var n in openSet) { - cameFrom[neighbor] = current; - scores[neighbor] = tentativeScore; - guessScores[neighbor] = tentativeScore + heuristic(neighbor, finish); + if (guessScores[n] < lowest) + { + current = n; + lowest = guessScores[n]; + } + } + + if (current.Equals(finish)) + return reconstructPath(start, cameFrom, current); - if (!openSet.Contains(neighbor)) - openSet.Add(neighbor); + openSet.Remove(current); + foreach (var neighbor in getNeighbors(current)) + { + var tentativeScore = scores[current] + 1; + if (!scores.TryGetValue(neighbor, out var _)) + scores.Add(neighbor, int.MaxValue); + + if (tentativeScore < scores[neighbor]) + { + cameFrom[neighbor] = current; + scores[neighbor] = tentativeScore; + guessScores[neighbor] = tentativeScore + heuristic(neighbor, finish); + + if (!openSet.Contains(neighbor)) + openSet.Add(neighbor); + } } } - } - return new Queue(); - } + return new Queue(); + } - private static int heuristic(MapCoordinate current, MapCoordinate goal) - => Math.Abs(current.X - goal.X) + Math.Abs(current.Y - goal.Y); + private static int heuristic(MapCoordinate current, MapCoordinate goal) + => Math.Abs(current.X - goal.X) + Math.Abs(current.Y - goal.Y); - private Queue reconstructPath(MapCoordinate start, Dictionary cameFrom, MapCoordinate current) - { - var retList = new List { current }; - while (cameFrom.ContainsKey(current)) + private Queue reconstructPath(MapCoordinate start, Dictionary cameFrom, MapCoordinate current) { - current = cameFrom[current]; - if (current != start) - retList.Insert(0, current); + var retList = new List { current }; + while (cameFrom.ContainsKey(current)) + { + current = cameFrom[current]; + if (current != start) + retList.Insert(0, current); + } + return new Queue(retList); } - return new Queue(retList); - } - private IEnumerable getNeighbors(MapCoordinate current) - { - var points = new MapCoordinate[] + private IEnumerable getNeighbors(MapCoordinate current) { - new MapCoordinate(-1, 0), - new MapCoordinate(1, 0), - new MapCoordinate(0, -1), - new MapCoordinate(0, 1) - }; + var points = new MapCoordinate[] + { + new MapCoordinate(-1, 0), + new MapCoordinate(1, 0), + new MapCoordinate(0, -1), + new MapCoordinate(0, 1) + }; - foreach (var coordinateOffset in points) - { - if (_walkValidationActions.CanMoveToCoordinates(current.X + coordinateOffset.X, current.Y + coordinateOffset.Y) == WalkValidationResult.Walkable) - yield return new MapCoordinate(current.X + coordinateOffset.X, current.Y + coordinateOffset.Y); + foreach (var coordinateOffset in points) + { + if (_walkValidationActions.CanMoveToCoordinates(current.X + coordinateOffset.X, current.Y + coordinateOffset.Y) == WalkValidationResult.Walkable) + yield return new MapCoordinate(current.X + coordinateOffset.X, current.Y + coordinateOffset.Y); + } } } -} -public interface IPathFinder -{ - Queue FindPath(MapCoordinate start, MapCoordinate finish); + public interface IPathFinder + { + Queue FindPath(MapCoordinate start, MapCoordinate finish); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatBubbleActions.cs b/EndlessClient/HUD/Chat/ChatBubbleActions.cs index dcdd6eaa6..2bfa991a7 100644 --- a/EndlessClient/HUD/Chat/ChatBubbleActions.cs +++ b/EndlessClient/HUD/Chat/ChatBubbleActions.cs @@ -7,47 +7,48 @@ using Optional; using System.Linq; -namespace EndlessClient.HUD.Chat; - -[AutoMappedType] -public class ChatBubbleActions : IChatBubbleActions +namespace EndlessClient.HUD.Chat { - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly INPCRendererProvider _npcRendererProvider; - private readonly IPartyDataProvider _partyDataProvider; - - public ChatBubbleActions(ICharacterRendererProvider characterRendererProvider, - INPCRendererProvider npcRendererProvider, - IPartyDataProvider partyDataProvider) + [AutoMappedType] + public class ChatBubbleActions : IChatBubbleActions { - _characterRendererProvider = characterRendererProvider; - _npcRendererProvider = npcRendererProvider; - _partyDataProvider = partyDataProvider; - } + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly INPCRendererProvider _npcRendererProvider; + private readonly IPartyDataProvider _partyDataProvider; - public void ShowChatBubbleForMainCharacter(string text, bool isPartyChat = false) - { - _characterRendererProvider.MainCharacterRenderer.MatchSome(r => + public ChatBubbleActions(ICharacterRendererProvider characterRendererProvider, + INPCRendererProvider npcRendererProvider, + IPartyDataProvider partyDataProvider) + { + _characterRendererProvider = characterRendererProvider; + _npcRendererProvider = npcRendererProvider; + _partyDataProvider = partyDataProvider; + } + + public void ShowChatBubbleForMainCharacter(string text, bool isPartyChat = false) { - if (!_partyDataProvider.Members.Any() && isPartyChat) + _characterRendererProvider.MainCharacterRenderer.MatchSome(r => + { + if (!_partyDataProvider.Members.Any() && isPartyChat) + return; + + r.ShowChatBubble(text, isPartyChat); + }); + } + + public void ShowChatBubbleForNPC(int index, string input) + { + if (!_npcRendererProvider.NPCRenderers.ContainsKey(index)) return; - r.ShowChatBubble(text, isPartyChat); - }); + _npcRendererProvider.NPCRenderers[index].ShowChatBubble(input); + } } - public void ShowChatBubbleForNPC(int index, string input) + public interface IChatBubbleActions { - if (!_npcRendererProvider.NPCRenderers.ContainsKey(index)) - return; + void ShowChatBubbleForMainCharacter(string input, bool isPartyChat = false); - _npcRendererProvider.NPCRenderers[index].ShowChatBubble(input); + void ShowChatBubbleForNPC(int index, string input); } -} - -public interface IChatBubbleActions -{ - void ShowChatBubbleForMainCharacter(string input, bool isPartyChat = false); - - void ShowChatBubbleForNPC(int index, string input); } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatModeCalculator.cs b/EndlessClient/HUD/Chat/ChatModeCalculator.cs index f71759509..39dde4b17 100644 --- a/EndlessClient/HUD/Chat/ChatModeCalculator.cs +++ b/EndlessClient/HUD/Chat/ChatModeCalculator.cs @@ -3,39 +3,40 @@ using EOLib.Domain.Character; using Moffat.EndlessOnline.SDK.Protocol; -namespace EndlessClient.HUD.Chat; - -[MappedType(BaseType = typeof(IChatModeCalculator))] -public class ChatModeCalculator : IChatModeCalculator +namespace EndlessClient.HUD.Chat { - private readonly ICharacterProvider _characterProvider; - - public ChatModeCalculator(ICharacterProvider characterProvider) + [MappedType(BaseType = typeof(IChatModeCalculator))] + public class ChatModeCalculator : IChatModeCalculator { - _characterProvider = characterProvider; - } + private readonly ICharacterProvider _characterProvider; - public ChatModePictureBox.ChatMode CalculateMode(string fullTextString) - { - if (string.IsNullOrEmpty(fullTextString)) - return ChatModePictureBox.ChatMode.NoText; + public ChatModeCalculator(ICharacterProvider characterProvider) + { + _characterProvider = characterProvider; + } + + public ChatModePictureBox.ChatMode CalculateMode(string fullTextString) + { + if (string.IsNullOrEmpty(fullTextString)) + return ChatModePictureBox.ChatMode.NoText; - var playerIsAdmin = _characterProvider.MainCharacter.AdminLevel != AdminLevel.Player; - var playerIsInGuild = !string.IsNullOrEmpty(_characterProvider.MainCharacter.GuildName); + var playerIsAdmin = _characterProvider.MainCharacter.AdminLevel != AdminLevel.Player; + var playerIsInGuild = !string.IsNullOrEmpty(_characterProvider.MainCharacter.GuildName); - if (((fullTextString[0] == '@' || fullTextString[0] == '+') && !playerIsAdmin) || - (fullTextString[0] == '&' && !playerIsInGuild)) - return ChatModePictureBox.ChatMode.Public; + if (((fullTextString[0] == '@' || fullTextString[0] == '+') && !playerIsAdmin) || + (fullTextString[0] == '&' && !playerIsInGuild)) + return ChatModePictureBox.ChatMode.Public; - switch (fullTextString[0]) - { - case '!': return ChatModePictureBox.ChatMode.Private; - case '@': - case '~': return ChatModePictureBox.ChatMode.Global; - case '+': return ChatModePictureBox.ChatMode.Admin; - case '\'': return ChatModePictureBox.ChatMode.Group; - case '&': return ChatModePictureBox.ChatMode.Guild; - default: return ChatModePictureBox.ChatMode.Public; + switch (fullTextString[0]) + { + case '!': return ChatModePictureBox.ChatMode.Private; + case '@': + case '~': return ChatModePictureBox.ChatMode.Global; + case '+': return ChatModePictureBox.ChatMode.Admin; + case '\'': return ChatModePictureBox.ChatMode.Group; + case '&': return ChatModePictureBox.ChatMode.Guild; + default: return ChatModePictureBox.ChatMode.Public; + } } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatNotificationActions.cs b/EndlessClient/HUD/Chat/ChatNotificationActions.cs index b719b3d1b..ab8d4d06b 100644 --- a/EndlessClient/HUD/Chat/ChatNotificationActions.cs +++ b/EndlessClient/HUD/Chat/ChatNotificationActions.cs @@ -13,98 +13,99 @@ using System.Globalization; using System.Windows; -namespace EndlessClient.HUD.Chat; - -[AutoMappedType] -public class ChatNotificationActions : IChatEventNotifier +namespace EndlessClient.HUD.Chat { - private readonly IChatRepository _chatRepository; - private readonly IHudControlProvider _hudControlProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IServerMessageHandler _serverMessageHandler; - private readonly ISfxPlayer _sfxPlayer; - - public ChatNotificationActions(IChatRepository chatRepository, - IHudControlProvider hudControlProvider, - ILocalizedStringFinder localizedStringFinder, - IStatusLabelSetter statusLabelSetter, - IServerMessageHandler serverMessageHandler, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class ChatNotificationActions : IChatEventNotifier { - _chatRepository = chatRepository; - _hudControlProvider = hudControlProvider; - _localizedStringFinder = localizedStringFinder; - _statusLabelSetter = statusLabelSetter; - _serverMessageHandler = serverMessageHandler; - _sfxPlayer = sfxPlayer; - } + private readonly IChatRepository _chatRepository; + private readonly IHudControlProvider _hudControlProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IServerMessageHandler _serverMessageHandler; + private readonly ISfxPlayer _sfxPlayer; - public void NotifyChatReceived(ChatEventType eventType) - { - _sfxPlayer.PlaySfx(eventType switch + public ChatNotificationActions(IChatRepository chatRepository, + IHudControlProvider hudControlProvider, + ILocalizedStringFinder localizedStringFinder, + IStatusLabelSetter statusLabelSetter, + IServerMessageHandler serverMessageHandler, + ISfxPlayer sfxPlayer) { - ChatEventType.PrivateMessage => SoundEffectID.PrivateMessageReceived, - ChatEventType.AdminChat => SoundEffectID.AdminChatReceived, - ChatEventType.AdminAnnounce => SoundEffectID.AdminAnnounceReceived, - ChatEventType.Group => SoundEffectID.GroupChatReceived, - _ => SoundEffectID.LayeredTechIntro, // this will be funny if it ever gets hit - }); - } + _chatRepository = chatRepository; + _hudControlProvider = hudControlProvider; + _localizedStringFinder = localizedStringFinder; + _statusLabelSetter = statusLabelSetter; + _serverMessageHandler = serverMessageHandler; + _sfxPlayer = sfxPlayer; + } - public void NotifyPrivateMessageRecipientNotFound(string recipientName) - { - var whichTab = _chatRepository.PMTarget1.ToLower() == recipientName.ToLower() - ? Option.Some(ChatTab.Private1) - : _chatRepository.PMTarget2.ToLower() == recipientName.ToLower() - ? Option.Some(ChatTab.Private2) - : Option.None(); + public void NotifyChatReceived(ChatEventType eventType) + { + _sfxPlayer.PlaySfx(eventType switch + { + ChatEventType.PrivateMessage => SoundEffectID.PrivateMessageReceived, + ChatEventType.AdminChat => SoundEffectID.AdminChatReceived, + ChatEventType.AdminAnnounce => SoundEffectID.AdminAnnounceReceived, + ChatEventType.Group => SoundEffectID.GroupChatReceived, + _ => SoundEffectID.LayeredTechIntro, // this will be funny if it ever gets hit + }); + } - whichTab.MatchSome(tab => + public void NotifyPrivateMessageRecipientNotFound(string recipientName) { - if (tab == ChatTab.Private1) - _chatRepository.PMTarget1 = null; - else if (tab == ChatTab.Private2) - _chatRepository.PMTarget2 = null; + var whichTab = _chatRepository.PMTarget1.ToLower() == recipientName.ToLower() + ? Option.Some(ChatTab.Private1) + : _chatRepository.PMTarget2.ToLower() == recipientName.ToLower() + ? Option.Some(ChatTab.Private2) + : Option.None(); - _chatRepository.AllChat[tab].Clear(); + whichTab.MatchSome(tab => + { + if (tab == ChatTab.Private1) + _chatRepository.PMTarget1 = null; + else if (tab == ChatTab.Private2) + _chatRepository.PMTarget2 = null; - var chatPanel = _hudControlProvider.GetComponent(HudControlIdentifier.ChatPanel); - chatPanel.ClosePMTab(tab); - }); - } + _chatRepository.AllChat[tab].Clear(); - public void NotifyPlayerMutedByAdmin(string adminName) - { - var chatTextBox = _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); - var chatMode = _hudControlProvider.GetComponent(HudControlIdentifier.ChatModePictureBox); + var chatPanel = _hudControlProvider.GetComponent(HudControlIdentifier.ChatPanel); + chatPanel.ClosePMTab(tab); + }); + } - var endMuteTime = DateTime.Now.AddMinutes(Constants.MuteDefaultTimeMinutes); - chatTextBox.SetMuted(endMuteTime); - chatMode.SetMuted(endMuteTime); + public void NotifyPlayerMutedByAdmin(string adminName) + { + var chatTextBox = _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); + var chatMode = _hudControlProvider.GetComponent(HudControlIdentifier.ChatModePictureBox); - chatTextBox.Text = string.Empty; + var endMuteTime = DateTime.Now.AddMinutes(Constants.MuteDefaultTimeMinutes); + chatTextBox.SetMuted(endMuteTime); + chatMode.SetMuted(endMuteTime); - var chatData = new ChatData(ChatTab.Local, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), - _localizedStringFinder.GetString(EOResourceID.CHAT_MESSAGE_MUTED_BY) + " " + adminName, - ChatIcon.Exclamation, - ChatColor.Server); - _chatRepository.AllChat[ChatTab.Local].Add(chatData); + chatTextBox.Text = string.Empty; - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - Constants.MuteDefaultTimeMinutes.ToString(CultureInfo.InvariantCulture) + " ", - EOResourceID.STATUS_LABEL_MINUTES_MUTED); - } + var chatData = new ChatData(ChatTab.Local, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), + _localizedStringFinder.GetString(EOResourceID.CHAT_MESSAGE_MUTED_BY) + " " + adminName, + ChatIcon.Exclamation, + ChatColor.Server); + _chatRepository.AllChat[ChatTab.Local].Add(chatData); - public void NotifyServerMessage(string serverMessage) - { - _serverMessageHandler.AddServerMessage(serverMessage); - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + Constants.MuteDefaultTimeMinutes.ToString(CultureInfo.InvariantCulture) + " ", + EOResourceID.STATUS_LABEL_MINUTES_MUTED); + } - public void NotifyServerPing(int timeInMS) - { - var message = $"[x] Current ping to the server is: {timeInMS} ms."; - var chatData = new ChatData(ChatTab.Local, "System", message, ChatIcon.LookingDude); - _chatRepository.AllChat[ChatTab.Local].Add(chatData); + public void NotifyServerMessage(string serverMessage) + { + _serverMessageHandler.AddServerMessage(serverMessage); + } + + public void NotifyServerPing(int timeInMS) + { + var message = $"[x] Current ping to the server is: {timeInMS} ms."; + var chatData = new ChatData(ChatTab.Local, "System", message, ChatIcon.LookingDude); + _chatRepository.AllChat[ChatTab.Local].Add(chatData); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatPanelTab.cs b/EndlessClient/HUD/Chat/ChatPanelTab.cs index 95473541f..382c57040 100644 --- a/EndlessClient/HUD/Chat/ChatPanelTab.cs +++ b/EndlessClient/HUD/Chat/ChatPanelTab.cs @@ -16,231 +16,232 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Chat; - -public class ChatPanelTab : XNAControl +namespace EndlessClient.HUD.Chat { - private readonly IChatProvider _chatProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly IChatRenderableGenerator _chatRenderableGenerator; + public class ChatPanelTab : XNAControl + { + private readonly IChatProvider _chatProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly IChatRenderableGenerator _chatRenderableGenerator; - private readonly ChatPanel _parentPanel; - private readonly ScrollBar _scrollBar; - private readonly ISpriteSheet _tabSheetSelected, _tabSheetUnselected; - private readonly BitmapFont _chatFont; + private readonly ChatPanel _parentPanel; + private readonly ScrollBar _scrollBar; + private readonly ISpriteSheet _tabSheetSelected, _tabSheetUnselected; + private readonly BitmapFont _chatFont; - private readonly IXNAButton _closeButton, _tab; - private readonly IXNALabel _label; + private readonly IXNAButton _closeButton, _tab; + private readonly IXNALabel _label; - private bool _active; - private int _cachedScrollOffset; - private HashSet _cachedChat; - private List _renderables; - private bool _closeButtonClicked; + private bool _active; + private int _cachedScrollOffset; + private HashSet _cachedChat; + private List _renderables; + private bool _closeButtonClicked; - public ChatTab Tab { get; } + public ChatTab Tab { get; } - public string Text { get => _label.Text; set => _label.Text = value; } + public string Text { get => _label.Text; set => _label.Text = value; } - public bool Active - { - get => _active; - set + public bool Active { - if (_active = value) - { - _scrollBar.SetScrollOffset(_cachedScrollOffset); - _label.ForeColor = Color.White; - } - else + get => _active; + set { - _cachedScrollOffset = _scrollBar.ScrollOffset; - _label.ForeColor = Color.Black; + if (_active = value) + { + _scrollBar.SetScrollOffset(_cachedScrollOffset); + _label.ForeColor = Color.White; + } + else + { + _cachedScrollOffset = _scrollBar.ScrollOffset; + _label.ForeColor = Color.Black; + } } } - } - public event EventHandler OnClosed; - - public ChatPanelTab(IChatProvider chatProvider, - IHudControlProvider hudControlProvider, - IChatRenderableGenerator chatRenderableGenerator, - ChatPanel parentPanel, - ScrollBar scrollBar, - ChatTab whichTab, - ISpriteSheet tabSheetSelected, - ISpriteSheet tabSheetUnselected, - BitmapFont chatFont) - { - _chatProvider = chatProvider; - _hudControlProvider = hudControlProvider; - _chatRenderableGenerator = chatRenderableGenerator; + public event EventHandler OnClosed; + + public ChatPanelTab(IChatProvider chatProvider, + IHudControlProvider hudControlProvider, + IChatRenderableGenerator chatRenderableGenerator, + ChatPanel parentPanel, + ScrollBar scrollBar, + ChatTab whichTab, + ISpriteSheet tabSheetSelected, + ISpriteSheet tabSheetUnselected, + BitmapFont chatFont) + { + _chatProvider = chatProvider; + _hudControlProvider = hudControlProvider; + _chatRenderableGenerator = chatRenderableGenerator; - _parentPanel = parentPanel; - _scrollBar = scrollBar; - Tab = whichTab; - _tabSheetSelected = tabSheetSelected; - _tabSheetUnselected = tabSheetUnselected; - _chatFont = chatFont; + _parentPanel = parentPanel; + _scrollBar = scrollBar; + Tab = whichTab; + _tabSheetSelected = tabSheetSelected; + _tabSheetUnselected = tabSheetUnselected; + _chatFont = chatFont; - DrawArea = new Rectangle(0, 0, _parentPanel.DrawArea.Width, _parentPanel.DrawArea.Height); + DrawArea = new Rectangle(0, 0, _parentPanel.DrawArea.Width, _parentPanel.DrawArea.Height); - if (Tab == ChatTab.Private1) - { - _closeButton = new ClickableArea(new Rectangle(23, 102, 11, 11)); - _closeButton.OnClick += (_, _) => CloseTab(); - _closeButton.SetParentControl(this); - } - else if (Tab == ChatTab.Private2) - { - _closeButton = new ClickableArea(new Rectangle(156, 102, 11, 11)); - _closeButton.OnClick += (_, _) => CloseTab(); - _closeButton.SetParentControl(this); - } + if (Tab == ChatTab.Private1) + { + _closeButton = new ClickableArea(new Rectangle(23, 102, 11, 11)); + _closeButton.OnClick += (_, _) => CloseTab(); + _closeButton.SetParentControl(this); + } + else if (Tab == ChatTab.Private2) + { + _closeButton = new ClickableArea(new Rectangle(156, 102, 11, 11)); + _closeButton.OnClick += (_, _) => CloseTab(); + _closeButton.SetParentControl(this); + } - _tab = new ClickableArea(GetTabClickableArea()); - _tab.OnClick += (_, _) => SelectThisTab(); - _tab.SetParentControl(this); + _tab = new ClickableArea(GetTabClickableArea()); + _tab.OnClick += (_, _) => SelectThisTab(); + _tab.SetParentControl(this); - _label = new XNALabel(Constants.FontSize08) - { - Text = GetTabTextLabel(), - DrawPosition = GetTabClickableArea().Location.ToVector2() + new Vector2(16, 2) - }; - _label.SetParentControl(this); - - _cachedChat = new HashSet(); - _renderables = new List(); - } + _label = new XNALabel(Constants.FontSize08) + { + Text = GetTabTextLabel(), + DrawPosition = GetTabClickableArea().Location.ToVector2() + new Vector2(16, 2) + }; + _label.SetParentControl(this); - public override void Initialize() - { - _tab.Initialize(); - _closeButton?.Initialize(); - _label.Initialize(); + _cachedChat = new HashSet(); + _renderables = new List(); + } - base.Initialize(); - } + public override void Initialize() + { + _tab.Initialize(); + _closeButton?.Initialize(); + _label.Initialize(); - public void CloseTab() - { - if (Tab != ChatTab.Private1 && Tab != ChatTab.Private2) - throw new InvalidOperationException("Unable to close chat tab that isn't a PM tab"); + base.Initialize(); + } - _closeButtonClicked = true; + public void CloseTab() + { + if (Tab != ChatTab.Private1 && Tab != ChatTab.Private2) + throw new InvalidOperationException("Unable to close chat tab that isn't a PM tab"); - _parentPanel.SelectTab(ChatTab.Local); + _closeButtonClicked = true; - Visible = false; + _parentPanel.SelectTab(ChatTab.Local); - _cachedChat.Clear(); - _label.Text = string.Empty; - _cachedScrollOffset = 0; + Visible = false; - OnClosed?.Invoke(this, EventArgs.Empty); - } + _cachedChat.Clear(); + _label.Text = string.Empty; + _cachedScrollOffset = 0; - protected override void OnUnconditionalUpdateControl(GameTime gameTime) - { - if (!Visible) - return; + OnClosed?.Invoke(this, EventArgs.Empty); + } - if (!_cachedChat.SetEquals(_chatProvider.AllChat[Tab])) + protected override void OnUnconditionalUpdateControl(GameTime gameTime) { - _cachedChat = _chatProvider.AllChat[Tab].ToHashSet(); - _renderables = _chatRenderableGenerator.GenerateChatRenderables(_cachedChat).ToList(); + if (!Visible) + return; - if (Active) - { - _scrollBar.UpdateDimensions(_renderables.Count); - _scrollBar.ScrollToEnd(); - } - else + if (!_cachedChat.SetEquals(_chatProvider.AllChat[Tab])) { - _cachedScrollOffset = Math.Max(0, _renderables.Count - 7); - _label.ForeColor = Color.White; + _cachedChat = _chatProvider.AllChat[Tab].ToHashSet(); + _renderables = _chatRenderableGenerator.GenerateChatRenderables(_cachedChat).ToList(); + + if (Active) + { + _scrollBar.UpdateDimensions(_renderables.Count); + _scrollBar.ScrollToEnd(); + } + else + { + _cachedScrollOffset = Math.Max(0, _renderables.Count - 7); + _label.ForeColor = Color.White; + } } + + base.OnUnconditionalUpdateControl(gameTime); } - base.OnUnconditionalUpdateControl(gameTime); - } + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); + var sheet = Active ? _tabSheetSelected : _tabSheetUnselected; + _spriteBatch.Draw(sheet.SheetTexture, _tab.ClickArea.Location.ToVector2() + ImmediateParent.DrawPositionWithParentOffset, sheet.SourceRectangle, Color.White); - var sheet = Active ? _tabSheetSelected : _tabSheetUnselected; - _spriteBatch.Draw(sheet.SheetTexture, _tab.ClickArea.Location.ToVector2() + ImmediateParent.DrawPositionWithParentOffset, sheet.SourceRectangle, Color.White); + if (Active) + { + _spriteBatch.End(); - if (Active) - { - _spriteBatch.End(); + foreach (var (ndx, renderable) in _renderables.Skip(_scrollBar.ScrollOffset).Take(_scrollBar.LinesToRender).Select((r, i) => (i, r))) + { + renderable.DisplayIndex = ndx; + renderable.Render(_parentPanel, _spriteBatch, _chatFont); + } - foreach (var (ndx, renderable) in _renderables.Skip(_scrollBar.ScrollOffset).Take(_scrollBar.LinesToRender).Select((r, i) => (i, r))) - { - renderable.DisplayIndex = ndx; - renderable.Render(_parentPanel, _spriteBatch, _chatFont); + _spriteBatch.Begin(); } - _spriteBatch.Begin(); - } - - _spriteBatch.End(); + _spriteBatch.End(); - base.OnDrawControl(gameTime); - } + base.OnDrawControl(gameTime); + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (eventArgs.Button == MouseButton.Right) + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) { - var clickedYRelativeToTopOfPanel = eventArgs.Position.Y - DrawAreaWithParentOffset.Y; - var clickedChatRow = (int)Math.Round(clickedYRelativeToTopOfPanel / 13.0) - 1; - - if (clickedChatRow >= 0 && _scrollBar.ScrollOffset + clickedChatRow < _cachedChat.Count) + if (eventArgs.Button == MouseButton.Right) { - var who = _chatProvider.AllChat[Tab][_scrollBar.ScrollOffset + clickedChatRow].Who; - _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{who} "; + var clickedYRelativeToTopOfPanel = eventArgs.Position.Y - DrawAreaWithParentOffset.Y; + var clickedChatRow = (int)Math.Round(clickedYRelativeToTopOfPanel / 13.0) - 1; + + if (clickedChatRow >= 0 && _scrollBar.ScrollOffset + clickedChatRow < _cachedChat.Count) + { + var who = _chatProvider.AllChat[Tab][_scrollBar.ScrollOffset + clickedChatRow].Who; + _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{who} "; + } + + return true; } - return true; + return false; } - return false; - } - - private void SelectThisTab() - { - if (!_closeButtonClicked) - _parentPanel.SelectTab(Tab); - _closeButtonClicked = false; - } + private void SelectThisTab() + { + if (!_closeButtonClicked) + _parentPanel.SelectTab(Tab); + _closeButtonClicked = false; + } - private Rectangle GetTabClickableArea() - { - return Tab switch + private Rectangle GetTabClickableArea() { - ChatTab.Private1 => new Rectangle(23, 102, 132, 16), - ChatTab.Private2 => new Rectangle(156, 102, 132, 16), - ChatTab.Local or - ChatTab.Global or - ChatTab.Group or - ChatTab.System => new Rectangle(289 + 44 * ((int)Tab - 2), 102, 43, 16), - _ => throw new ArgumentOutOfRangeException(nameof(Tab), Tab, null), - }; - } + return Tab switch + { + ChatTab.Private1 => new Rectangle(23, 102, 132, 16), + ChatTab.Private2 => new Rectangle(156, 102, 132, 16), + ChatTab.Local or + ChatTab.Global or + ChatTab.Group or + ChatTab.System => new Rectangle(289 + 44 * ((int)Tab - 2), 102, 43, 16), + _ => throw new ArgumentOutOfRangeException(nameof(Tab), Tab, null), + }; + } - private string GetTabTextLabel() - { - return Tab switch + private string GetTabTextLabel() { - ChatTab.Private1 or - ChatTab.Private2 => string.Empty, - ChatTab.Local => "scr", - ChatTab.Global => "glb", - ChatTab.Group => "grp", - ChatTab.System => "sys", - _ => throw new ArgumentOutOfRangeException(nameof(Tab), Tab, null), - }; + return Tab switch + { + ChatTab.Private1 or + ChatTab.Private2 => string.Empty, + ChatTab.Local => "scr", + ChatTab.Global => "glb", + ChatTab.Group => "grp", + ChatTab.System => "sys", + _ => throw new ArgumentOutOfRangeException(nameof(Tab), Tab, null), + }; + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ChatTextBoxActions.cs b/EndlessClient/HUD/Chat/ChatTextBoxActions.cs index 15d2fcf44..3a18f863a 100644 --- a/EndlessClient/HUD/Chat/ChatTextBoxActions.cs +++ b/EndlessClient/HUD/Chat/ChatTextBoxActions.cs @@ -3,31 +3,32 @@ using EndlessClient.HUD.Controls; using EndlessClient.UIControls; -namespace EndlessClient.HUD.Chat; - -[AutoMappedType] -public class ChatTextBoxActions : IChatTextBoxActions +namespace EndlessClient.HUD.Chat { - private readonly IHudControlProvider _hudControlProvider; - - public ChatTextBoxActions(IHudControlProvider hudControlProvider) + [AutoMappedType] + public class ChatTextBoxActions : IChatTextBoxActions { - _hudControlProvider = hudControlProvider; - } + private readonly IHudControlProvider _hudControlProvider; - public void ClearChatText() - { - var chatTextBox = GetChatTextBox(); - chatTextBox.Text = ""; - } + public ChatTextBoxActions(IHudControlProvider hudControlProvider) + { + _hudControlProvider = hudControlProvider; + } - public void FocusChatTextBox() - { - GetChatTextBox().Selected = true; - } + public void ClearChatText() + { + var chatTextBox = GetChatTextBox(); + chatTextBox.Text = ""; + } - private ChatTextBox GetChatTextBox() - { - return _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); + public void FocusChatTextBox() + { + GetChatTextBox().Selected = true; + } + + private ChatTextBox GetChatTextBox() + { + return _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/IChatModeCalculator.cs b/EndlessClient/HUD/Chat/IChatModeCalculator.cs index e7cacaec9..5ae7f3286 100644 --- a/EndlessClient/HUD/Chat/IChatModeCalculator.cs +++ b/EndlessClient/HUD/Chat/IChatModeCalculator.cs @@ -1,8 +1,9 @@ using EndlessClient.UIControls; -namespace EndlessClient.HUD.Chat; - -public interface IChatModeCalculator +namespace EndlessClient.HUD.Chat { - ChatModePictureBox.ChatMode CalculateMode(string fullTextString); + public interface IChatModeCalculator + { + ChatModePictureBox.ChatMode CalculateMode(string fullTextString); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/IChatTextBoxActions.cs b/EndlessClient/HUD/Chat/IChatTextBoxActions.cs index 4dcbe52cf..e5c61e4ec 100644 --- a/EndlessClient/HUD/Chat/IChatTextBoxActions.cs +++ b/EndlessClient/HUD/Chat/IChatTextBoxActions.cs @@ -1,8 +1,9 @@ -namespace EndlessClient.HUD.Chat; - -public interface IChatTextBoxActions +namespace EndlessClient.HUD.Chat { - void ClearChatText(); + public interface IChatTextBoxActions + { + void ClearChatText(); - void FocusChatTextBox(); + void FocusChatTextBox(); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/PrivateMessageActions.cs b/EndlessClient/HUD/Chat/PrivateMessageActions.cs index be60ea47b..6b57fe969 100644 --- a/EndlessClient/HUD/Chat/PrivateMessageActions.cs +++ b/EndlessClient/HUD/Chat/PrivateMessageActions.cs @@ -7,72 +7,73 @@ using EOLib.Localization; using System; -namespace EndlessClient.HUD.Chat; - -[MappedType(BaseType = typeof(IPrivateMessageActions))] -public class PrivateMessageActions : IPrivateMessageActions +namespace EndlessClient.HUD.Chat { - private readonly IHudControlProvider _hudControlProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IChatProvider _chatProvider; - private readonly IChatTypeCalculator _chatTypeCalculator; - private readonly IStatusLabelSetter _statusLabelSetter; - - public PrivateMessageActions(IHudControlProvider hudControlProvider, - ICharacterProvider characterProvider, - IChatProvider chatProvider, - IChatTypeCalculator chatTypeCalculator, - IStatusLabelSetter statusLabelSetter) + [MappedType(BaseType = typeof(IPrivateMessageActions))] + public class PrivateMessageActions : IPrivateMessageActions { - _hudControlProvider = hudControlProvider; - _characterProvider = characterProvider; - _chatProvider = chatProvider; - _chatTypeCalculator = chatTypeCalculator; - _statusLabelSetter = statusLabelSetter; - } + private readonly IHudControlProvider _hudControlProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IChatProvider _chatProvider; + private readonly IChatTypeCalculator _chatTypeCalculator; + private readonly IStatusLabelSetter _statusLabelSetter; - public (bool, string) GetTargetCharacter(string localTypedText) - { - if (_chatTypeCalculator.CalculateChatType(localTypedText) != ChatType.PM) + public PrivateMessageActions(IHudControlProvider hudControlProvider, + ICharacterProvider characterProvider, + IChatProvider chatProvider, + IChatTypeCalculator chatTypeCalculator, + IStatusLabelSetter statusLabelSetter) { - return (true, string.Empty); + _hudControlProvider = hudControlProvider; + _characterProvider = characterProvider; + _chatProvider = chatProvider; + _chatTypeCalculator = chatTypeCalculator; + _statusLabelSetter = statusLabelSetter; } - if (localTypedText.Length < 2 || localTypedText[1] == ' ') + public (bool, string) GetTargetCharacter(string localTypedText) { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_INVALID_INPUT_TRY); - return (false, string.Empty); - } + if (_chatTypeCalculator.CalculateChatType(localTypedText) != ChatType.PM) + { + return (true, string.Empty); + } - if (CurrentTab == ChatTab.Private1) - { - return (true, _chatProvider.PMTarget1); - } - else if (CurrentTab == ChatTab.Private2) - { - return (true, _chatProvider.PMTarget2); - } + if (localTypedText.Length < 2 || localTypedText[1] == ' ') + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_INVALID_INPUT_TRY); + return (false, string.Empty); + } - var messageParts = localTypedText[1..].Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - if (messageParts.Length <= 1) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_INVALID_INPUT_TRY); - return (false, string.Empty); - } + if (CurrentTab == ChatTab.Private1) + { + return (true, _chatProvider.PMTarget1); + } + else if (CurrentTab == ChatTab.Private2) + { + return (true, _chatProvider.PMTarget2); + } - if (string.Equals(messageParts[0], _characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase)) - return (false, string.Empty); + var messageParts = localTypedText[1..].Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (messageParts.Length <= 1) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_INVALID_INPUT_TRY); + return (false, string.Empty); + } - ChatPanel.TryStartNewPrivateChat(messageParts[0]); - return (true, messageParts[0]); - } + if (string.Equals(messageParts[0], _characterProvider.MainCharacter.Name, StringComparison.OrdinalIgnoreCase)) + return (false, string.Empty); - private ChatPanel ChatPanel => _hudControlProvider.GetComponent(HudControlIdentifier.ChatPanel); + ChatPanel.TryStartNewPrivateChat(messageParts[0]); + return (true, messageParts[0]); + } - private ChatTab CurrentTab => ChatPanel.CurrentTab; -} + private ChatPanel ChatPanel => _hudControlProvider.GetComponent(HudControlIdentifier.ChatPanel); -public interface IPrivateMessageActions -{ - (bool Ok, string TargetCharacter) GetTargetCharacter(string localTypedText); + private ChatTab CurrentTab => ChatPanel.CurrentTab; + } + + public interface IPrivateMessageActions + { + (bool Ok, string TargetCharacter) GetTargetCharacter(string localTypedText); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Chat/ServerMessageHandler.cs b/EndlessClient/HUD/Chat/ServerMessageHandler.cs index 7fc337348..89e66123c 100644 --- a/EndlessClient/HUD/Chat/ServerMessageHandler.cs +++ b/EndlessClient/HUD/Chat/ServerMessageHandler.cs @@ -3,41 +3,42 @@ using EOLib.Domain.Chat; using EOLib.Localization; -namespace EndlessClient.HUD.Chat; - -[AutoMappedType] -public class ServerMessageHandler : IServerMessageHandler +namespace EndlessClient.HUD.Chat { - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ISfxPlayer _sfxPlayer; - - public ServerMessageHandler(IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class ServerMessageHandler : IServerMessageHandler { - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _sfxPlayer = sfxPlayer; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ISfxPlayer _sfxPlayer; + + public ServerMessageHandler(IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + ISfxPlayer sfxPlayer) + { + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _sfxPlayer = sfxPlayer; + } + + public void AddServerMessage(string serverMessage, SoundEffectID soundEffect = SoundEffectID.Login, ChatIcon icon = ChatIcon.Exclamation) + { + var server = _localizedStringFinder.GetString(EOResourceID.STRING_SERVER); + + var localData = new ChatData(ChatTab.Local, server, serverMessage, icon, ChatColor.Server, log: false, filter: false); + var globalData = new ChatData(ChatTab.Global, server, serverMessage, icon, ChatColor.ServerGlobal, log: false, filter: false); + var systemData = new ChatData(ChatTab.System, string.Empty, serverMessage, icon, ChatColor.Server, filter: false); + + _chatRepository.AllChat[ChatTab.Local].Add(localData); + _chatRepository.AllChat[ChatTab.Global].Add(globalData); + _chatRepository.AllChat[ChatTab.System].Add(systemData); + + _sfxPlayer.PlaySfx(soundEffect); + } } - public void AddServerMessage(string serverMessage, SoundEffectID soundEffect = SoundEffectID.Login, ChatIcon icon = ChatIcon.Exclamation) + public interface IServerMessageHandler { - var server = _localizedStringFinder.GetString(EOResourceID.STRING_SERVER); - - var localData = new ChatData(ChatTab.Local, server, serverMessage, icon, ChatColor.Server, log: false, filter: false); - var globalData = new ChatData(ChatTab.Global, server, serverMessage, icon, ChatColor.ServerGlobal, log: false, filter: false); - var systemData = new ChatData(ChatTab.System, string.Empty, serverMessage, icon, ChatColor.Server, filter: false); - - _chatRepository.AllChat[ChatTab.Local].Add(localData); - _chatRepository.AllChat[ChatTab.Global].Add(globalData); - _chatRepository.AllChat[ChatTab.System].Add(systemData); - - _sfxPlayer.PlaySfx(soundEffect); + void AddServerMessage(string message, SoundEffectID soundEffect = SoundEffectID.ServerMessage, ChatIcon icon = ChatIcon.Exclamation); } -} - -public interface IServerMessageHandler -{ - void AddServerMessage(string message, SoundEffectID soundEffect = SoundEffectID.ServerMessage, ChatIcon icon = ChatIcon.Exclamation); } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs b/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs index fc7da93ed..741bbb32f 100644 --- a/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs +++ b/EndlessClient/HUD/Controls/DragCompletedEventArgs.cs @@ -1,22 +1,23 @@ using EOLib.IO.Pub; -namespace EndlessClient.HUD.Controls; - -public class DragCompletedEventArgs +namespace EndlessClient.HUD.Controls { - public bool ContinueDrag { get; set; } = false; + public class DragCompletedEventArgs + { + public bool ContinueDrag { get; set; } = false; - public bool RestoreOriginalSlot { get; set; } = false; + public bool RestoreOriginalSlot { get; set; } = false; - public bool DragOutOfBounds { get; set; } = false; + public bool DragOutOfBounds { get; set; } = false; - public TRecord Data { get; } + public TRecord Data { get; } - public bool IsChainedDrag { get; } + public bool IsChainedDrag { get; } - public DragCompletedEventArgs(TRecord data, bool isChainedDrag) - { - Data = data; - IsChainedDrag = isChainedDrag; + public DragCompletedEventArgs(TRecord data, bool isChainedDrag) + { + Data = data; + IsChainedDrag = isChainedDrag; + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/DraggablePanelItem.cs b/EndlessClient/HUD/Controls/DraggablePanelItem.cs index dcc587f14..7632e5fce 100644 --- a/EndlessClient/HUD/Controls/DraggablePanelItem.cs +++ b/EndlessClient/HUD/Controls/DraggablePanelItem.cs @@ -4,131 +4,132 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Controls; - -public abstract class DraggablePanelItem : XNAControl +namespace EndlessClient.HUD.Controls { - protected readonly IDraggableItemContainer _parentContainer; - - // true when a single-click drag is in progress and the icon should follow the mouse - // otherwise, drag event handles following the mouse - private bool _followMouse; - - // true when dragging and the drag was chained from another item - private bool _isChainedDrag; - - // the top-left of the parent inventory panel when the drag started - protected Vector2 OldOffset { get; private set; } - - // true when a drag is in progress (either single click or click + drag) - public bool IsDragging { get; private set; } - - public TRecord Data { get; protected set; } + public abstract class DraggablePanelItem : XNAControl + { + protected readonly IDraggableItemContainer _parentContainer; - public event EventHandler DraggingStarted; - public event EventHandler> DraggingFinishing; - public event EventHandler> DraggingFinished; + // true when a single-click drag is in progress and the icon should follow the mouse + // otherwise, drag event handles following the mouse + private bool _followMouse; - // assumes absolute coordinates (not based on parent position) - protected abstract Rectangle GridArea { get; } + // true when dragging and the drag was chained from another item + private bool _isChainedDrag; - protected DraggablePanelItem(IDraggableItemContainer parentContainer) - { - _parentContainer = parentContainer; - } + // the top-left of the parent inventory panel when the drag started + protected Vector2 OldOffset { get; private set; } - public void StartDragging(bool isChainedDrag) - { - if (!isChainedDrag && !_parentContainer.NoItemsDragging()) - return; + // true when a drag is in progress (either single click or click + drag) + public bool IsDragging { get; private set; } - IsDragging = true; - _followMouse = _isChainedDrag = isChainedDrag; + public TRecord Data { get; protected set; } - OldOffset = ImmediateParent.DrawPositionWithParentOffset; - DrawPosition = MouseExtended.GetState().Position.ToVector2(); + public event EventHandler DraggingStarted; + public event EventHandler> DraggingFinishing; + public event EventHandler> DraggingFinished; - SetControlUnparented(); - Game.Components.Add(this); - DrawOrder = 1000; + // assumes absolute coordinates (not based on parent position) + protected abstract Rectangle GridArea { get; } - DraggingStarted?.Invoke(this, EventArgs.Empty); - } - - protected override void OnUpdateControl(GameTime gameTime) - { - if (_followMouse) + protected DraggablePanelItem(IDraggableItemContainer parentContainer) { - DrawPosition = MouseExtended.GetState().Position.ToVector2() - new Vector2(DrawArea.Width / 2, DrawArea.Height / 2); + _parentContainer = parentContainer; } - base.OnUpdateControl(gameTime); - } + public void StartDragging(bool isChainedDrag) + { + if (!isChainedDrag && !_parentContainer.NoItemsDragging()) + return; - protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) - { - StartDragging(isChainedDrag: false); - return true; - } + IsDragging = true; + _followMouse = _isChainedDrag = isChainedDrag; - protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) - { - DrawPosition = eventArgs.Position.ToVector2() - new Vector2(DrawArea.Width / 2, DrawArea.Height / 2); - return true; - } + OldOffset = ImmediateParent.DrawPositionWithParentOffset; + DrawPosition = MouseExtended.GetState().Position.ToVector2(); - protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) - { - StopDragging(eventArgs); - return true; - } + SetControlUnparented(); + Game.Components.Add(this); + DrawOrder = 1000; - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (_followMouse) + DraggingStarted?.Invoke(this, EventArgs.Empty); + } + + protected override void OnUpdateControl(GameTime gameTime) { - StopDragging(eventArgs); + if (_followMouse) + { + DrawPosition = MouseExtended.GetState().Position.ToVector2() - new Vector2(DrawArea.Width / 2, DrawArea.Height / 2); + } + + base.OnUpdateControl(gameTime); } - else + + protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) { StartDragging(isChainedDrag: false); - _followMouse = true; + return true; } - return true; - } - - /// - /// Called when dragging is finished after the DraggingFinished event has been invoked - /// - protected virtual void OnDraggingFinished(DragCompletedEventArgs args) - { - } - - private void StopDragging(MouseEventArgs mouseEventArgs) - { - var args = new DragCompletedEventArgs(Data, _isChainedDrag) + protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) { - DragOutOfBounds = !GridArea.Contains(mouseEventArgs.Position) - }; - - DraggingFinishing?.Invoke(this, args); - OnDraggingFinished(args); + DrawPosition = eventArgs.Position.ToVector2() - new Vector2(DrawArea.Width / 2, DrawArea.Height / 2); + return true; + } - if (!args.ContinueDrag) + protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) { - IsDragging = false; - OldOffset = Vector2.Zero; - _followMouse = false; + StopDragging(eventArgs); + return true; + } - Game.Components.Remove(this); - SetParentControl(_parentContainer); + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (_followMouse) + { + StopDragging(eventArgs); + } + else + { + StartDragging(isChainedDrag: false); + _followMouse = true; + } + + return true; + } - DraggingFinished?.Invoke(this, args); + /// + /// Called when dragging is finished after the DraggingFinished event has been invoked + /// + protected virtual void OnDraggingFinished(DragCompletedEventArgs args) + { } - else + + private void StopDragging(MouseEventArgs mouseEventArgs) { - _followMouse = true; + var args = new DragCompletedEventArgs(Data, _isChainedDrag) + { + DragOutOfBounds = !GridArea.Contains(mouseEventArgs.Position) + }; + + DraggingFinishing?.Invoke(this, args); + OnDraggingFinished(args); + + if (!args.ContinueDrag) + { + IsDragging = false; + OldOffset = Vector2.Zero; + _followMouse = false; + + Game.Components.Remove(this); + SetParentControl(_parentContainer); + + DraggingFinished?.Invoke(this, args); + } + else + { + _followMouse = true; + } } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/HudBackgroundFrame.cs b/EndlessClient/HUD/Controls/HudBackgroundFrame.cs index 1d021a622..c9dde9fd6 100644 --- a/EndlessClient/HUD/Controls/HudBackgroundFrame.cs +++ b/EndlessClient/HUD/Controls/HudBackgroundFrame.cs @@ -3,68 +3,69 @@ using Microsoft.Xna.Framework.Graphics; using XNAControls; -namespace EndlessClient.HUD.Controls; - -public class HudBackgroundFrame : XNAControl +namespace EndlessClient.HUD.Controls { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; + public class HudBackgroundFrame : XNAControl + { + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; - private Texture2D _mainFrame; - private Texture2D _topLeft; - private Texture2D _sidebar; - private Texture2D _topBar; - private Texture2D _filler; + private Texture2D _mainFrame; + private Texture2D _topLeft; + private Texture2D _sidebar; + private Texture2D _topBar; + private Texture2D _filler; - public HudBackgroundFrame(INativeGraphicsManager nativeGraphicsManager, - IGraphicsDeviceProvider graphicsDeviceProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _graphicsDeviceProvider = graphicsDeviceProvider; - } + public HudBackgroundFrame(INativeGraphicsManager nativeGraphicsManager, + IGraphicsDeviceProvider graphicsDeviceProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _graphicsDeviceProvider = graphicsDeviceProvider; + } - protected override void LoadContent() - { - _mainFrame = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, true); - _topLeft = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 21, true); - _sidebar = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 22, true); - _topBar = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 23, true); + protected override void LoadContent() + { + _mainFrame = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, true); + _topLeft = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 21, true); + _sidebar = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 22, true); + _topBar = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 23, true); - _filler = new Texture2D(_graphicsDeviceProvider.GraphicsDevice, 1, 1); - _filler.SetData(new[] { Color.FromNonPremultiplied(8, 8, 8, 255) }); + _filler = new Texture2D(_graphicsDeviceProvider.GraphicsDevice, 1, 1); + _filler.SetData(new[] { Color.FromNonPremultiplied(8, 8, 8, 255) }); - base.LoadContent(); - } + base.LoadContent(); + } - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); - _spriteBatch.Draw(_filler, new Rectangle(0, 400, 640, 80), Color.White); + _spriteBatch.Draw(_filler, new Rectangle(0, 400, 640, 80), Color.White); - _spriteBatch.Draw(_topBar, new Vector2(49, 7), Color.White); - _spriteBatch.Draw(_mainFrame, Vector2.Zero, Color.White); - _spriteBatch.Draw(_topLeft, Vector2.Zero, Color.White); - _spriteBatch.Draw(_sidebar, new Vector2(7, 53), Color.White); - _spriteBatch.Draw(_sidebar, new Vector2(629, 53), new Rectangle(3, 0, 1, _sidebar.Height), Color.White); + _spriteBatch.Draw(_topBar, new Vector2(49, 7), Color.White); + _spriteBatch.Draw(_mainFrame, Vector2.Zero, Color.White); + _spriteBatch.Draw(_topLeft, Vector2.Zero, Color.White); + _spriteBatch.Draw(_sidebar, new Vector2(7, 53), Color.White); + _spriteBatch.Draw(_sidebar, new Vector2(629, 53), new Rectangle(3, 0, 1, _sidebar.Height), Color.White); - //fill in some extra holes with black lines - _spriteBatch.Draw(_filler, new Rectangle(542, 0, 1, 8), Color.White); - _spriteBatch.Draw(_filler, new Rectangle(14, 329, 1, 142), Color.White); - _spriteBatch.Draw(_filler, new Rectangle(98, 479, 445, 1), Color.White); + //fill in some extra holes with black lines + _spriteBatch.Draw(_filler, new Rectangle(542, 0, 1, 8), Color.White); + _spriteBatch.Draw(_filler, new Rectangle(14, 329, 1, 142), Color.White); + _spriteBatch.Draw(_filler, new Rectangle(98, 479, 445, 1), Color.White); - _spriteBatch.End(); + _spriteBatch.End(); - base.OnDrawControl(gameTime); - } + base.OnDrawControl(gameTime); + } - protected override void Dispose(bool disposing) - { - if (disposing) + protected override void Dispose(bool disposing) { - _filler.Dispose(); - } + if (disposing) + { + _filler.Dispose(); + } - base.Dispose(disposing); + base.Dispose(disposing); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/HudControlIdentifier.cs b/EndlessClient/HUD/Controls/HudControlIdentifier.cs index 35b646a2a..19824f396 100644 --- a/EndlessClient/HUD/Controls/HudControlIdentifier.cs +++ b/EndlessClient/HUD/Controls/HudControlIdentifier.cs @@ -1,80 +1,81 @@ using System; -namespace EndlessClient.HUD.Controls; - -public enum HudControlIdentifier +namespace EndlessClient.HUD.Controls { - CurrentUserInputTracker = int.MinValue, //this should always be first! + public enum HudControlIdentifier + { + CurrentUserInputTracker = int.MinValue, //this should always be first! - MapRenderer = 0, - StatusIcons, - MiniMapRenderer, + MapRenderer = 0, + StatusIcons, + MiniMapRenderer, - ClickDispatcher, + ClickDispatcher, - HudBackground, + HudBackground, - //buttons and panels - InventoryButton, - InventoryPanel, + //buttons and panels + InventoryButton, + InventoryPanel, - ViewMapButton, + ViewMapButton, - ActiveSpellsButton, - ActiveSpellsPanel, + ActiveSpellsButton, + ActiveSpellsPanel, - PassiveSpellsButton, - PassiveSpellsPanel, + PassiveSpellsButton, + PassiveSpellsPanel, - ChatButton, - ChatPanel, + ChatButton, + ChatPanel, - StatsButton, - StatsPanel, + StatsButton, + StatsPanel, - OnlineListButton, - OnlineListPanel, + OnlineListButton, + OnlineListPanel, - PartyButton, - PartyPanel, + PartyButton, + PartyPanel, - MacroButton, + MacroButton, - SettingsButton, - SettingsPanel, + SettingsButton, + SettingsPanel, - HelpButton, - HelpPanel, + HelpButton, + HelpPanel, - NewsPanel, + NewsPanel, - //top bar - SessionExpButton, - QuestsButton, + //top bar + SessionExpButton, + QuestsButton, - HPStatusBar, - TPStatusBar, - SPStatusBar, - TNLStatusBar, + HPStatusBar, + TPStatusBar, + SPStatusBar, + TNLStatusBar, - //mid stuff - ChatModePictureBox, - ChatTextBox, + //mid stuff + ChatModePictureBox, + ChatTextBox, - FriendList, - IgnoreList, + FriendList, + IgnoreList, - //lower stuff - StatusLabel, - ClockLabel, + //lower stuff + StatusLabel, + ClockLabel, - //not displayed - PeriodicStatUpdater, - UserInputHandler, - CharacterAnimator, - NPCAnimator, - UnknownEntitiesRequester, - PeriodicEmoteHandler, + //not displayed + PeriodicStatUpdater, + UserInputHandler, + CharacterAnimator, + NPCAnimator, + UnknownEntitiesRequester, + PeriodicEmoteHandler, - PreviousUserInputTracker = Int32.MaxValue, //this should always be last! + PreviousUserInputTracker = Int32.MaxValue, //this should always be last! + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/HudControlsFactory.cs b/EndlessClient/HUD/Controls/HudControlsFactory.cs index 38d9f6c18..793f450de 100644 --- a/EndlessClient/HUD/Controls/HudControlsFactory.cs +++ b/EndlessClient/HUD/Controls/HudControlsFactory.cs @@ -31,575 +31,576 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Controls; - -[AutoMappedType(IsSingleton = true)] -public class HudControlsFactory : IHudControlsFactory +namespace EndlessClient.HUD.Controls { - private const int HUD_BASE_LAYER = 100; - private const int HUD_CONTROL_LAYER = 130; - - private readonly IHudButtonController _hudButtonController; - private readonly IHudPanelFactory _hudPanelFactory; - private readonly IMapRendererFactory _mapRendererFactory; - private readonly IUserInputHandlerFactory _userInputHandlerFactory; - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly ICharacterRepository _characterRepository; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IUserInputRepository _userInputRepository; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IStatusLabelTextProvider _statusLabelTextProvider; - private readonly IContentProvider _contentProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IChatModeCalculator _chatModeCalculator; - private readonly IExperienceTableProvider _experienceTableProvider; - private readonly IPathFinder _pathFinder; - private readonly ICharacterActions _characterActions; - private readonly IWalkValidationActions _walkValidationActions; - private readonly IChatBubbleActions _chatBubbleActions; - private readonly IUnknownEntitiesRequestActions _unknownEntitiesRequestActions; - private readonly IUserInputTimeProvider _userInputTimeProvider; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly ISfxPlayer _sfxPlayer; - private readonly IMiniMapRendererFactory _miniMapRendererFactory; - private readonly INewsProvider _newsProvider; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - private readonly IClickDispatcherFactory _clickDispatcherFactory; - private readonly IMetadataProvider _weaponMetadataProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly INPCRendererProvider _npcRendererProvider; - private IChatController _chatController; - private IMainButtonController _mainButtonController; - - public HudControlsFactory(IHudButtonController hudButtonController, - IHudPanelFactory hudPanelFactory, - IMapRendererFactory mapRendererFactory, - IUserInputHandlerFactory userInputHandlerFactory, - INativeGraphicsManager nativeGraphicsManager, - IGraphicsDeviceProvider graphicsDeviceProvider, - IClientWindowSizeRepository clientWindowSizeRepository, - IEndlessGameProvider endlessGameProvider, - ICharacterRepository characterRepository, - ICurrentMapStateRepository currentMapStateRepository, - IUserInputRepository userInputRepository, - IStatusLabelSetter statusLabelSetter, - IStatusLabelTextProvider statusLabelTextProvider, - IContentProvider contentProvider, - IHudControlProvider hudControlProvider, - ICurrentMapProvider currentMapProvider, - IChatModeCalculator chatModeCalculator, - IExperienceTableProvider experienceTableProvider, - IPathFinder pathFinder, - ICharacterActions characterActions, - IWalkValidationActions walkValidationActions, - IChatBubbleActions chatBubbleActions, - IUnknownEntitiesRequestActions unknownEntitiesRequestActions, - IUserInputTimeProvider userInputTimeProvider, - ISpellSlotDataRepository spellSlotDataRepository, - ISfxPlayer sfxPlayer, - IMiniMapRendererFactory miniMapRendererFactory, - INewsProvider newsProvider, - IFixedTimeStepRepository fixedTimeStepRepository, - IClickDispatcherFactory clickDispatcherFactory, - IMetadataProvider weaponMetadataProvider, - ILocalizedStringFinder localizedStringFinder, - ICharacterRendererProvider characterRendererProvider, - INPCRendererProvider npcRendererProvider) + [AutoMappedType(IsSingleton = true)] + public class HudControlsFactory : IHudControlsFactory { - _hudButtonController = hudButtonController; - _hudPanelFactory = hudPanelFactory; - _mapRendererFactory = mapRendererFactory; - _userInputHandlerFactory = userInputHandlerFactory; - _nativeGraphicsManager = nativeGraphicsManager; - _graphicsDeviceProvider = graphicsDeviceProvider; - _clientWindowSizeRepository = clientWindowSizeRepository; - _endlessGameProvider = endlessGameProvider; - _characterRepository = characterRepository; - _currentMapStateRepository = currentMapStateRepository; - _userInputRepository = userInputRepository; - _statusLabelSetter = statusLabelSetter; - _statusLabelTextProvider = statusLabelTextProvider; - _contentProvider = contentProvider; - _hudControlProvider = hudControlProvider; - _currentMapProvider = currentMapProvider; - _chatModeCalculator = chatModeCalculator; - _experienceTableProvider = experienceTableProvider; - _pathFinder = pathFinder; - _characterActions = characterActions; - _walkValidationActions = walkValidationActions; - _chatBubbleActions = chatBubbleActions; - _unknownEntitiesRequestActions = unknownEntitiesRequestActions; - _userInputTimeProvider = userInputTimeProvider; - _spellSlotDataRepository = spellSlotDataRepository; - _sfxPlayer = sfxPlayer; - _miniMapRendererFactory = miniMapRendererFactory; - _newsProvider = newsProvider; - _fixedTimeStepRepository = fixedTimeStepRepository; - _clickDispatcherFactory = clickDispatcherFactory; - _weaponMetadataProvider = weaponMetadataProvider; - _localizedStringFinder = localizedStringFinder; - _characterRendererProvider = characterRendererProvider; - _npcRendererProvider = npcRendererProvider; - } - - public void InjectChatController(IChatController chatController, - IMainButtonController mainButtonController) - { - _chatController = chatController; - _mainButtonController = mainButtonController; - } + private const int HUD_BASE_LAYER = 100; + private const int HUD_CONTROL_LAYER = 130; + + private readonly IHudButtonController _hudButtonController; + private readonly IHudPanelFactory _hudPanelFactory; + private readonly IMapRendererFactory _mapRendererFactory; + private readonly IUserInputHandlerFactory _userInputHandlerFactory; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly ICharacterRepository _characterRepository; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IUserInputRepository _userInputRepository; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IStatusLabelTextProvider _statusLabelTextProvider; + private readonly IContentProvider _contentProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IChatModeCalculator _chatModeCalculator; + private readonly IExperienceTableProvider _experienceTableProvider; + private readonly IPathFinder _pathFinder; + private readonly ICharacterActions _characterActions; + private readonly IWalkValidationActions _walkValidationActions; + private readonly IChatBubbleActions _chatBubbleActions; + private readonly IUnknownEntitiesRequestActions _unknownEntitiesRequestActions; + private readonly IUserInputTimeProvider _userInputTimeProvider; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly ISfxPlayer _sfxPlayer; + private readonly IMiniMapRendererFactory _miniMapRendererFactory; + private readonly INewsProvider _newsProvider; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + private readonly IClickDispatcherFactory _clickDispatcherFactory; + private readonly IMetadataProvider _weaponMetadataProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly INPCRendererProvider _npcRendererProvider; + private IChatController _chatController; + private IMainButtonController _mainButtonController; + + public HudControlsFactory(IHudButtonController hudButtonController, + IHudPanelFactory hudPanelFactory, + IMapRendererFactory mapRendererFactory, + IUserInputHandlerFactory userInputHandlerFactory, + INativeGraphicsManager nativeGraphicsManager, + IGraphicsDeviceProvider graphicsDeviceProvider, + IClientWindowSizeRepository clientWindowSizeRepository, + IEndlessGameProvider endlessGameProvider, + ICharacterRepository characterRepository, + ICurrentMapStateRepository currentMapStateRepository, + IUserInputRepository userInputRepository, + IStatusLabelSetter statusLabelSetter, + IStatusLabelTextProvider statusLabelTextProvider, + IContentProvider contentProvider, + IHudControlProvider hudControlProvider, + ICurrentMapProvider currentMapProvider, + IChatModeCalculator chatModeCalculator, + IExperienceTableProvider experienceTableProvider, + IPathFinder pathFinder, + ICharacterActions characterActions, + IWalkValidationActions walkValidationActions, + IChatBubbleActions chatBubbleActions, + IUnknownEntitiesRequestActions unknownEntitiesRequestActions, + IUserInputTimeProvider userInputTimeProvider, + ISpellSlotDataRepository spellSlotDataRepository, + ISfxPlayer sfxPlayer, + IMiniMapRendererFactory miniMapRendererFactory, + INewsProvider newsProvider, + IFixedTimeStepRepository fixedTimeStepRepository, + IClickDispatcherFactory clickDispatcherFactory, + IMetadataProvider weaponMetadataProvider, + ILocalizedStringFinder localizedStringFinder, + ICharacterRendererProvider characterRendererProvider, + INPCRendererProvider npcRendererProvider) + { + _hudButtonController = hudButtonController; + _hudPanelFactory = hudPanelFactory; + _mapRendererFactory = mapRendererFactory; + _userInputHandlerFactory = userInputHandlerFactory; + _nativeGraphicsManager = nativeGraphicsManager; + _graphicsDeviceProvider = graphicsDeviceProvider; + _clientWindowSizeRepository = clientWindowSizeRepository; + _endlessGameProvider = endlessGameProvider; + _characterRepository = characterRepository; + _currentMapStateRepository = currentMapStateRepository; + _userInputRepository = userInputRepository; + _statusLabelSetter = statusLabelSetter; + _statusLabelTextProvider = statusLabelTextProvider; + _contentProvider = contentProvider; + _hudControlProvider = hudControlProvider; + _currentMapProvider = currentMapProvider; + _chatModeCalculator = chatModeCalculator; + _experienceTableProvider = experienceTableProvider; + _pathFinder = pathFinder; + _characterActions = characterActions; + _walkValidationActions = walkValidationActions; + _chatBubbleActions = chatBubbleActions; + _unknownEntitiesRequestActions = unknownEntitiesRequestActions; + _userInputTimeProvider = userInputTimeProvider; + _spellSlotDataRepository = spellSlotDataRepository; + _sfxPlayer = sfxPlayer; + _miniMapRendererFactory = miniMapRendererFactory; + _newsProvider = newsProvider; + _fixedTimeStepRepository = fixedTimeStepRepository; + _clickDispatcherFactory = clickDispatcherFactory; + _weaponMetadataProvider = weaponMetadataProvider; + _localizedStringFinder = localizedStringFinder; + _characterRendererProvider = characterRendererProvider; + _npcRendererProvider = npcRendererProvider; + } - public IReadOnlyDictionary CreateHud() - { - var characterAnimator = CreateCharacterAnimator(); - var mapRenderer = _mapRendererFactory.CreateMapRenderer(); + public void InjectChatController(IChatController chatController, + IMainButtonController mainButtonController) + { + _chatController = chatController; + _mainButtonController = mainButtonController; + } - var controls = new Dictionary + public IReadOnlyDictionary CreateHud() { - {HudControlIdentifier.CurrentUserInputTracker, CreateCurrentUserInputTracker()}, - - {HudControlIdentifier.CharacterAnimator, characterAnimator}, - {HudControlIdentifier.NPCAnimator, CreateNPCAnimator()}, - {HudControlIdentifier.MapRenderer, mapRenderer}, - {HudControlIdentifier.StatusIcons, CreatePlayerStatusIconRenderer()}, - {HudControlIdentifier.MiniMapRenderer, _miniMapRendererFactory.Create()}, - - {HudControlIdentifier.ClickDispatcher, CreateClickDispatcher(mapRenderer)}, - - {HudControlIdentifier.HudBackground, CreateHudBackground()}, - - {HudControlIdentifier.InventoryButton, CreateStateChangeButton(InGameStates.Inventory)}, - {HudControlIdentifier.ViewMapButton, CreateStateChangeButton(InGameStates.ViewMapToggle)}, - {HudControlIdentifier.ActiveSpellsButton, CreateStateChangeButton(InGameStates.ActiveSpells)}, - {HudControlIdentifier.PassiveSpellsButton, CreateStateChangeButton(InGameStates.PassiveSpells)}, - {HudControlIdentifier.ChatButton, CreateStateChangeButton(InGameStates.Chat)}, - {HudControlIdentifier.StatsButton, CreateStateChangeButton(InGameStates.Stats)}, - {HudControlIdentifier.OnlineListButton, CreateStateChangeButton(InGameStates.OnlineList)}, - {HudControlIdentifier.PartyButton, CreateStateChangeButton(InGameStates.Party)}, - {HudControlIdentifier.MacroButton, CreateStateChangeButton(InGameStates.Macro)}, - {HudControlIdentifier.SettingsButton, CreateStateChangeButton(InGameStates.Settings)}, - {HudControlIdentifier.HelpButton, CreateStateChangeButton(InGameStates.Help)}, - - {HudControlIdentifier.FriendList, CreateFriendListButton()}, - {HudControlIdentifier.IgnoreList, CreateIgnoreListButton()}, - - {HudControlIdentifier.NewsPanel, CreateStatePanel(InGameStates.News)}, - {HudControlIdentifier.InventoryPanel, CreateStatePanel(InGameStates.Inventory)}, - {HudControlIdentifier.ActiveSpellsPanel, CreateStatePanel(InGameStates.ActiveSpells)}, - {HudControlIdentifier.PassiveSpellsPanel, CreateStatePanel(InGameStates.PassiveSpells)}, - {HudControlIdentifier.ChatPanel, CreateStatePanel(InGameStates.Chat)}, - {HudControlIdentifier.StatsPanel, CreateStatePanel(InGameStates.Stats)}, - {HudControlIdentifier.OnlineListPanel, CreateStatePanel(InGameStates.OnlineList)}, - {HudControlIdentifier.PartyPanel, CreateStatePanel(InGameStates.Party)}, - //macro panel - {HudControlIdentifier.SettingsPanel, CreateStatePanel(InGameStates.Settings)}, - {HudControlIdentifier.HelpPanel, CreateStatePanel(InGameStates.Help)}, - - {HudControlIdentifier.SessionExpButton, CreateSessionExpButton()}, - {HudControlIdentifier.QuestsButton, CreateQuestButton()}, - - {HudControlIdentifier.HPStatusBar, CreateHPStatusBar()}, - {HudControlIdentifier.TPStatusBar, CreateTPStatusBar()}, - {HudControlIdentifier.SPStatusBar, CreateSPStatusBar()}, - {HudControlIdentifier.TNLStatusBar, CreateTNLStatusBar()}, - - {HudControlIdentifier.ChatModePictureBox, CreateChatModePictureBox()}, - {HudControlIdentifier.ChatTextBox, CreateChatTextBox()}, - {HudControlIdentifier.ClockLabel, CreateClockLabel()}, - {HudControlIdentifier.StatusLabel, CreateStatusLabel()}, - - {HudControlIdentifier.PeriodicStatUpdater, CreatePeriodicStatUpdater()}, - {HudControlIdentifier.UserInputHandler, CreateUserInputHandler()}, - {HudControlIdentifier.UnknownEntitiesRequester, CreateUnknownEntitiesRequester()}, - {HudControlIdentifier.PeriodicEmoteHandler, CreatePeriodicEmoteHandler(characterAnimator)}, - - {HudControlIdentifier.PreviousUserInputTracker, CreatePreviousUserInputTracker()} - }; - - return controls; - } + var characterAnimator = CreateCharacterAnimator(); + var mapRenderer = _mapRendererFactory.CreateMapRenderer(); - private PlayerStatusIconRenderer CreatePlayerStatusIconRenderer() - { - return new PlayerStatusIconRenderer( - _nativeGraphicsManager, - (ICharacterProvider)_characterRepository, - (ISpellSlotDataProvider)_spellSlotDataRepository, - _currentMapProvider, _clientWindowSizeRepository); - } + var controls = new Dictionary + { + {HudControlIdentifier.CurrentUserInputTracker, CreateCurrentUserInputTracker()}, + + {HudControlIdentifier.CharacterAnimator, characterAnimator}, + {HudControlIdentifier.NPCAnimator, CreateNPCAnimator()}, + {HudControlIdentifier.MapRenderer, mapRenderer}, + {HudControlIdentifier.StatusIcons, CreatePlayerStatusIconRenderer()}, + {HudControlIdentifier.MiniMapRenderer, _miniMapRendererFactory.Create()}, + + {HudControlIdentifier.ClickDispatcher, CreateClickDispatcher(mapRenderer)}, + + {HudControlIdentifier.HudBackground, CreateHudBackground()}, + + {HudControlIdentifier.InventoryButton, CreateStateChangeButton(InGameStates.Inventory)}, + {HudControlIdentifier.ViewMapButton, CreateStateChangeButton(InGameStates.ViewMapToggle)}, + {HudControlIdentifier.ActiveSpellsButton, CreateStateChangeButton(InGameStates.ActiveSpells)}, + {HudControlIdentifier.PassiveSpellsButton, CreateStateChangeButton(InGameStates.PassiveSpells)}, + {HudControlIdentifier.ChatButton, CreateStateChangeButton(InGameStates.Chat)}, + {HudControlIdentifier.StatsButton, CreateStateChangeButton(InGameStates.Stats)}, + {HudControlIdentifier.OnlineListButton, CreateStateChangeButton(InGameStates.OnlineList)}, + {HudControlIdentifier.PartyButton, CreateStateChangeButton(InGameStates.Party)}, + {HudControlIdentifier.MacroButton, CreateStateChangeButton(InGameStates.Macro)}, + {HudControlIdentifier.SettingsButton, CreateStateChangeButton(InGameStates.Settings)}, + {HudControlIdentifier.HelpButton, CreateStateChangeButton(InGameStates.Help)}, + + {HudControlIdentifier.FriendList, CreateFriendListButton()}, + {HudControlIdentifier.IgnoreList, CreateIgnoreListButton()}, + + {HudControlIdentifier.NewsPanel, CreateStatePanel(InGameStates.News)}, + {HudControlIdentifier.InventoryPanel, CreateStatePanel(InGameStates.Inventory)}, + {HudControlIdentifier.ActiveSpellsPanel, CreateStatePanel(InGameStates.ActiveSpells)}, + {HudControlIdentifier.PassiveSpellsPanel, CreateStatePanel(InGameStates.PassiveSpells)}, + {HudControlIdentifier.ChatPanel, CreateStatePanel(InGameStates.Chat)}, + {HudControlIdentifier.StatsPanel, CreateStatePanel(InGameStates.Stats)}, + {HudControlIdentifier.OnlineListPanel, CreateStatePanel(InGameStates.OnlineList)}, + {HudControlIdentifier.PartyPanel, CreateStatePanel(InGameStates.Party)}, + //macro panel + {HudControlIdentifier.SettingsPanel, CreateStatePanel(InGameStates.Settings)}, + {HudControlIdentifier.HelpPanel, CreateStatePanel(InGameStates.Help)}, + + {HudControlIdentifier.SessionExpButton, CreateSessionExpButton()}, + {HudControlIdentifier.QuestsButton, CreateQuestButton()}, + + {HudControlIdentifier.HPStatusBar, CreateHPStatusBar()}, + {HudControlIdentifier.TPStatusBar, CreateTPStatusBar()}, + {HudControlIdentifier.SPStatusBar, CreateSPStatusBar()}, + {HudControlIdentifier.TNLStatusBar, CreateTNLStatusBar()}, + + {HudControlIdentifier.ChatModePictureBox, CreateChatModePictureBox()}, + {HudControlIdentifier.ChatTextBox, CreateChatTextBox()}, + {HudControlIdentifier.ClockLabel, CreateClockLabel()}, + {HudControlIdentifier.StatusLabel, CreateStatusLabel()}, + + {HudControlIdentifier.PeriodicStatUpdater, CreatePeriodicStatUpdater()}, + {HudControlIdentifier.UserInputHandler, CreateUserInputHandler()}, + {HudControlIdentifier.UnknownEntitiesRequester, CreateUnknownEntitiesRequester()}, + {HudControlIdentifier.PeriodicEmoteHandler, CreatePeriodicEmoteHandler(characterAnimator)}, + + {HudControlIdentifier.PreviousUserInputTracker, CreatePreviousUserInputTracker()} + }; - private IClickDispatcher CreateClickDispatcher(IMapRenderer mapRenderer) - { - var dispatcher = _clickDispatcherFactory.Create(); - dispatcher.DrawOrder = mapRenderer.DrawOrder; - return dispatcher; - } + return controls; + } - private HudBackgroundFrame CreateHudBackground() - { - return new HudBackgroundFrame(_nativeGraphicsManager, _graphicsDeviceProvider) + private PlayerStatusIconRenderer CreatePlayerStatusIconRenderer() { - DrawOrder = HUD_BASE_LAYER, - Visible = !_clientWindowSizeRepository.Resizable, - }; - } - - private IXNAButton CreateStateChangeButton(InGameStates whichState) - { - if (whichState == InGameStates.News) - throw new ArgumentOutOfRangeException(nameof(whichState), "News state does not have a button associated with it"); - var buttonIndex = (int)whichState; + return new PlayerStatusIconRenderer( + _nativeGraphicsManager, + (ICharacterProvider)_characterRepository, + (ISpellSlotDataProvider)_spellSlotDataRepository, + _currentMapProvider, _clientWindowSizeRepository); + } - var mainButtonTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 25); - var widthDelta = mainButtonTexture.Width / 2; - var heightDelta = mainButtonTexture.Height / 11; + private IClickDispatcher CreateClickDispatcher(IMapRenderer mapRenderer) + { + var dispatcher = _clickDispatcherFactory.Create(); + dispatcher.DrawOrder = mapRenderer.DrawOrder; + return dispatcher; + } - IXNAButton retButton; - if (!_clientWindowSizeRepository.Resizable) + private HudBackgroundFrame CreateHudBackground() { - var xPosition = buttonIndex < 6 ? 62 : 590; - var yPosition = (buttonIndex < 6 ? 330 : 350) + (buttonIndex < 6 ? buttonIndex : buttonIndex - 6) * 20; - - retButton = new XNAButton( - mainButtonTexture, - new Vector2(xPosition, yPosition), - new Rectangle(0, heightDelta * buttonIndex, widthDelta, heightDelta), - new Rectangle(widthDelta, heightDelta * buttonIndex, widthDelta, heightDelta)) + return new HudBackgroundFrame(_nativeGraphicsManager, _graphicsDeviceProvider) { - DrawOrder = HUD_CONTROL_LAYER + DrawOrder = HUD_BASE_LAYER, + Visible = !_clientWindowSizeRepository.Resizable, }; } - else + + private IXNAButton CreateStateChangeButton(InGameStates whichState) { - var yIndex = buttonIndex % 6 - 3; + if (whichState == InGameStates.News) + throw new ArgumentOutOfRangeException(nameof(whichState), "News state does not have a button associated with it"); + var buttonIndex = (int)whichState; - var xPosition = buttonIndex < 6 ? 0 : _clientWindowSizeRepository.Width - widthDelta; - var yPosition = (_clientWindowSizeRepository.Height / 2 + heightDelta * yIndex); + var mainButtonTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 25); + var widthDelta = mainButtonTexture.Width / 2; + var heightDelta = mainButtonTexture.Height / 11; - retButton = new XNAButton( - mainButtonTexture, - new Vector2(xPosition, yPosition), - new Rectangle(0, heightDelta * buttonIndex, widthDelta, heightDelta), - new Rectangle(widthDelta, heightDelta * buttonIndex, widthDelta, heightDelta)) + IXNAButton retButton; + if (!_clientWindowSizeRepository.Resizable) { - DrawOrder = HUD_CONTROL_LAYER - }; - - _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => + var xPosition = buttonIndex < 6 ? 62 : 590; + var yPosition = (buttonIndex < 6 ? 330 : 350) + (buttonIndex < 6 ? buttonIndex : buttonIndex - 6) * 20; + + retButton = new XNAButton( + mainButtonTexture, + new Vector2(xPosition, yPosition), + new Rectangle(0, heightDelta * buttonIndex, widthDelta, heightDelta), + new Rectangle(widthDelta, heightDelta * buttonIndex, widthDelta, heightDelta)) + { + DrawOrder = HUD_CONTROL_LAYER + }; + } + else { - var capturedXPos = buttonIndex < 6 ? 0 : _clientWindowSizeRepository.Width - widthDelta; - var capturedYPos = (_clientWindowSizeRepository.Height / 2 + heightDelta * yIndex); - retButton.DrawPosition = new Vector2(capturedXPos, capturedYPos); - }; - } + var yIndex = buttonIndex % 6 - 3; - retButton.OnClick += (_, _) => DoHudStateChangeClick(whichState); - retButton.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel( - EOResourceID.STATUS_LABEL_TYPE_BUTTON, - EOResourceID.STATUS_LABEL_HUD_BUTTON_HOVER_FIRST + buttonIndex); - return retButton; - } + var xPosition = buttonIndex < 6 ? 0 : _clientWindowSizeRepository.Width - widthDelta; + var yPosition = (_clientWindowSizeRepository.Height / 2 + heightDelta * yIndex); - private IXNAButton CreateFriendListButton() - { - Func getFriendListDrawPosition = () => new Vector2(_clientWindowSizeRepository.Width - 48, _clientWindowSizeRepository.Height - 37); - var button = new XNAButton( - _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, false), - _clientWindowSizeRepository.Resizable ? getFriendListDrawPosition() : new Vector2(592, 312), - new Rectangle(0, 260, 17, 15), - new Rectangle(0, 276, 17, 15)) - { - DrawOrder = HUD_CONTROL_LAYER + 10 - }; - button.OnClick += (_, _) => _hudButtonController.ClickFriendList(); - button.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); - button.OnMouseOver += (o, e) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_FRIEND_LIST); + retButton = new XNAButton( + mainButtonTexture, + new Vector2(xPosition, yPosition), + new Rectangle(0, heightDelta * buttonIndex, widthDelta, heightDelta), + new Rectangle(widthDelta, heightDelta * buttonIndex, widthDelta, heightDelta)) + { + DrawOrder = HUD_CONTROL_LAYER + }; - if (_clientWindowSizeRepository.Resizable) - { - _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => button.DrawPosition = getFriendListDrawPosition(); - } + _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => + { + var capturedXPos = buttonIndex < 6 ? 0 : _clientWindowSizeRepository.Width - widthDelta; + var capturedYPos = (_clientWindowSizeRepository.Height / 2 + heightDelta * yIndex); + retButton.DrawPosition = new Vector2(capturedXPos, capturedYPos); + }; + } - return button; - } + retButton.OnClick += (_, _) => DoHudStateChangeClick(whichState); + retButton.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel( + EOResourceID.STATUS_LABEL_TYPE_BUTTON, + EOResourceID.STATUS_LABEL_HUD_BUTTON_HOVER_FIRST + buttonIndex); + return retButton; + } - private IXNAButton CreateIgnoreListButton() - { - Func getIgnoreListDrawPosition = () => new Vector2(_clientWindowSizeRepository.Width - 31, _clientWindowSizeRepository.Height - 37); - var button = new XNAButton( - _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, false), - _clientWindowSizeRepository.Resizable ? getIgnoreListDrawPosition() : new Vector2(609, 312), - new Rectangle(17, 260, 17, 15), - new Rectangle(17, 276, 17, 15)) + private IXNAButton CreateFriendListButton() { - DrawOrder = HUD_CONTROL_LAYER + 10 - }; - button.OnClick += (_, _) => _hudButtonController.ClickIgnoreList(); - button.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); - button.OnMouseOver += (o, e) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_IGNORE_LIST); + Func getFriendListDrawPosition = () => new Vector2(_clientWindowSizeRepository.Width - 48, _clientWindowSizeRepository.Height - 37); + var button = new XNAButton( + _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, false), + _clientWindowSizeRepository.Resizable ? getFriendListDrawPosition() : new Vector2(592, 312), + new Rectangle(0, 260, 17, 15), + new Rectangle(0, 276, 17, 15)) + { + DrawOrder = HUD_CONTROL_LAYER + 10 + }; + button.OnClick += (_, _) => _hudButtonController.ClickFriendList(); + button.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + button.OnMouseOver += (o, e) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_FRIEND_LIST); - if (_clientWindowSizeRepository.Resizable) - { - _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => button.DrawPosition = getIgnoreListDrawPosition(); - } + if (_clientWindowSizeRepository.Resizable) + { + _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => button.DrawPosition = getFriendListDrawPosition(); + } - return button; - } + return button; + } - private void DoHudStateChangeClick(InGameStates whichState) - { - switch (whichState) + private IXNAButton CreateIgnoreListButton() { - case InGameStates.Inventory: _hudButtonController.ClickInventory(); break; - case InGameStates.ViewMapToggle: _hudButtonController.ClickViewMapToggle(); break; - case InGameStates.ActiveSpells: _hudButtonController.ClickActiveSpells(); break; - case InGameStates.PassiveSpells: _hudButtonController.ClickPassiveSpells(); break; - case InGameStates.Chat: - _hudButtonController.ClickChat(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_CHAT_PANEL_NOW_VIEWED); - break; - case InGameStates.Stats: - _hudButtonController.ClickStats(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_STATS_PANEL_NOW_VIEWED); - break; - case InGameStates.OnlineList: - _hudButtonController.ClickOnlineList(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_ONLINE_PLAYERS_NOW_VIEWED); - break; - case InGameStates.Party: _hudButtonController.ClickParty(); break; - case InGameStates.Macro: break; - case InGameStates.Settings: _hudButtonController.ClickSettings(); break; - case InGameStates.Help: - _hudButtonController.ClickHelp(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_HUD_BUTTON_HOVER_LAST); - break; - default: throw new ArgumentOutOfRangeException(nameof(whichState), whichState, null); - } + Func getIgnoreListDrawPosition = () => new Vector2(_clientWindowSizeRepository.Width - 31, _clientWindowSizeRepository.Height - 37); + var button = new XNAButton( + _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, false), + _clientWindowSizeRepository.Resizable ? getIgnoreListDrawPosition() : new Vector2(609, 312), + new Rectangle(17, 260, 17, 15), + new Rectangle(17, 276, 17, 15)) + { + DrawOrder = HUD_CONTROL_LAYER + 10 + }; + button.OnClick += (_, _) => _hudButtonController.ClickIgnoreList(); + button.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + button.OnMouseOver += (o, e) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_IGNORE_LIST); - _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); - } + if (_clientWindowSizeRepository.Resizable) + { + _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => button.DrawPosition = getIgnoreListDrawPosition(); + } - private IGameComponent CreateStatePanel(InGameStates whichState) - { - DraggableHudPanel retPanel; + return button; + } - switch (whichState) + private void DoHudStateChangeClick(InGameStates whichState) { - case InGameStates.Inventory: retPanel = _hudPanelFactory.CreateInventoryPanel(); break; - case InGameStates.ActiveSpells: retPanel = _hudPanelFactory.CreateActiveSpellsPanel(); break; - case InGameStates.PassiveSpells: retPanel = _hudPanelFactory.CreatePassiveSpellsPanel(); break; - case InGameStates.Chat: retPanel = _hudPanelFactory.CreateChatPanel(); break; - case InGameStates.Stats: retPanel = _hudPanelFactory.CreateStatsPanel(); break; - case InGameStates.OnlineList: retPanel = _hudPanelFactory.CreateOnlineListPanel(); break; - case InGameStates.Party: retPanel = _hudPanelFactory.CreatePartyPanel(); break; - case InGameStates.Settings: retPanel = _hudPanelFactory.CreateSettingsPanel(); break; - case InGameStates.Help: retPanel = _hudPanelFactory.CreateHelpPanel(); break; - case InGameStates.News: retPanel = _hudPanelFactory.CreateNewsPanel(); break; - default: throw new ArgumentOutOfRangeException(nameof(whichState), whichState, "Panel specification is out of range."); + switch (whichState) + { + case InGameStates.Inventory: _hudButtonController.ClickInventory(); break; + case InGameStates.ViewMapToggle: _hudButtonController.ClickViewMapToggle(); break; + case InGameStates.ActiveSpells: _hudButtonController.ClickActiveSpells(); break; + case InGameStates.PassiveSpells: _hudButtonController.ClickPassiveSpells(); break; + case InGameStates.Chat: + _hudButtonController.ClickChat(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_CHAT_PANEL_NOW_VIEWED); + break; + case InGameStates.Stats: + _hudButtonController.ClickStats(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_STATS_PANEL_NOW_VIEWED); + break; + case InGameStates.OnlineList: + _hudButtonController.ClickOnlineList(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_ONLINE_PLAYERS_NOW_VIEWED); + break; + case InGameStates.Party: _hudButtonController.ClickParty(); break; + case InGameStates.Macro: break; + case InGameStates.Settings: _hudButtonController.ClickSettings(); break; + case InGameStates.Help: + _hudButtonController.ClickHelp(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_HUD_BUTTON_HOVER_LAST); + break; + default: throw new ArgumentOutOfRangeException(nameof(whichState), whichState, null); + } + + _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); } - retPanel.Activated += () => retPanel.DrawOrder = _hudControlProvider.HudPanels.Select(x => x.DrawOrder).Max() + 1; + private IGameComponent CreateStatePanel(InGameStates whichState) + { + DraggableHudPanel retPanel; - //news is visible by default when loading the game if news text is set - retPanel.Visible = (_newsProvider.NewsText.Any() && whichState == InGameStates.News) || - (!_newsProvider.NewsText.Any() && whichState == InGameStates.Chat); + switch (whichState) + { + case InGameStates.Inventory: retPanel = _hudPanelFactory.CreateInventoryPanel(); break; + case InGameStates.ActiveSpells: retPanel = _hudPanelFactory.CreateActiveSpellsPanel(); break; + case InGameStates.PassiveSpells: retPanel = _hudPanelFactory.CreatePassiveSpellsPanel(); break; + case InGameStates.Chat: retPanel = _hudPanelFactory.CreateChatPanel(); break; + case InGameStates.Stats: retPanel = _hudPanelFactory.CreateStatsPanel(); break; + case InGameStates.OnlineList: retPanel = _hudPanelFactory.CreateOnlineListPanel(); break; + case InGameStates.Party: retPanel = _hudPanelFactory.CreatePartyPanel(); break; + case InGameStates.Settings: retPanel = _hudPanelFactory.CreateSettingsPanel(); break; + case InGameStates.Help: retPanel = _hudPanelFactory.CreateHelpPanel(); break; + case InGameStates.News: retPanel = _hudPanelFactory.CreateNewsPanel(); break; + default: throw new ArgumentOutOfRangeException(nameof(whichState), whichState, "Panel specification is out of range."); + } - if (_clientWindowSizeRepository.Resizable) - { - retPanel.UpdateOrder = -1; + retPanel.Activated += () => retPanel.DrawOrder = _hudControlProvider.HudPanels.Select(x => x.DrawOrder).Max() + 1; - UpdatePanelDrawPosition(initialPosition: true); - _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => UpdatePanelDrawPosition(initialPosition: false); + //news is visible by default when loading the game if news text is set + retPanel.Visible = (_newsProvider.NewsText.Any() && whichState == InGameStates.News) || + (!_newsProvider.NewsText.Any() && whichState == InGameStates.Chat); - var panelConfig = new IniReader(Constants.PanelLayoutFile); - if (panelConfig.Load()) + if (_clientWindowSizeRepository.Resizable) { - if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:X", out int x) && - panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:Y", out int y)) + retPanel.UpdateOrder = -1; + + UpdatePanelDrawPosition(initialPosition: true); + _clientWindowSizeRepository.GameWindowSizeChanged += (_, _) => UpdatePanelDrawPosition(initialPosition: false); + + var panelConfig = new IniReader(Constants.PanelLayoutFile); + if (panelConfig.Load()) { - retPanel.DrawPosition = new Vector2(x, y); + if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:X", out int x) && + panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:Y", out int y)) + { + retPanel.DrawPosition = new Vector2(x, y); + } + + if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:Visible", out bool visible)) + { + retPanel.Visible = visible; + } + + if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:DrawOrder", out int drawOrder)) + { + retPanel.DrawOrder = drawOrder; + } } + } - if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:Visible", out bool visible)) + return retPanel; + + void UpdatePanelDrawPosition(bool initialPosition) + { + if (initialPosition) { - retPanel.Visible = visible; + retPanel.DrawArea = retPanel.DrawArea.WithPosition(new Vector2( + (_clientWindowSizeRepository.Width - retPanel.DrawArea.Width) / 2, + _clientWindowSizeRepository.Height - 45 - retPanel.DrawArea.Height)); } - - if (panelConfig.GetValue("PANELS", $"{retPanel.GetType().Name}:DrawOrder", out int drawOrder)) + else { - retPanel.DrawOrder = drawOrder; + if (_clientWindowSizeRepository.Width < retPanel.DrawPosition.X + retPanel.DrawArea.Width) + retPanel.DrawPosition = new Vector2(_clientWindowSizeRepository.Width - retPanel.DrawArea.Width, retPanel.DrawPosition.Y); + + if (_clientWindowSizeRepository.Height < retPanel.DrawPosition.Y + retPanel.DrawArea.Height) + retPanel.DrawPosition = new Vector2(retPanel.DrawPosition.X, _clientWindowSizeRepository.Height - retPanel.DrawArea.Height); } } } - return retPanel; - - void UpdatePanelDrawPosition(bool initialPosition) + private IGameComponent CreateSessionExpButton() { - if (initialPosition) + var btn = new XNAButton( + _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, transparent: true), + new Vector2(55, 0), + new Rectangle(331, 30, 22, 14), + new Rectangle(331, 30, 22, 14)) { - retPanel.DrawArea = retPanel.DrawArea.WithPosition(new Vector2( - (_clientWindowSizeRepository.Width - retPanel.DrawArea.Width) / 2, - _clientWindowSizeRepository.Height - 45 - retPanel.DrawArea.Height)); - } - else + DrawOrder = HUD_CONTROL_LAYER + }; + btn.OnClick += (_, _) => _hudButtonController.ClickSessionExp(); + btn.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return btn; + } + + private IGameComponent CreateQuestButton() + { + var btn = new XNAButton( + _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, transparent: true), + new Vector2(77, 0), + new Rectangle(353, 30, 22, 14), + new Rectangle(353, 30, 22, 14)) { - if (_clientWindowSizeRepository.Width < retPanel.DrawPosition.X + retPanel.DrawArea.Width) - retPanel.DrawPosition = new Vector2(_clientWindowSizeRepository.Width - retPanel.DrawArea.Width, retPanel.DrawPosition.Y); + DrawOrder = HUD_CONTROL_LAYER + }; + btn.OnClick += (_, _) => _hudButtonController.ClickQuestStatus(); + btn.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return btn; + } - if (_clientWindowSizeRepository.Height < retPanel.DrawPosition.Y + retPanel.DrawArea.Height) - retPanel.DrawPosition = new Vector2(retPanel.DrawPosition.X, _clientWindowSizeRepository.Height - retPanel.DrawArea.Height); - } + private IGameComponent CreateHPStatusBar() + { + var statusBar = new HPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; + statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return statusBar; } - } - private IGameComponent CreateSessionExpButton() - { - var btn = new XNAButton( - _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, transparent: true), - new Vector2(55, 0), - new Rectangle(331, 30, 22, 14), - new Rectangle(331, 30, 22, 14)) + private IGameComponent CreateTPStatusBar() { - DrawOrder = HUD_CONTROL_LAYER - }; - btn.OnClick += (_, _) => _hudButtonController.ClickSessionExp(); - btn.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return btn; - } + var statusBar = new TPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; + statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return statusBar; + } - private IGameComponent CreateQuestButton() - { - var btn = new XNAButton( - _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, transparent: true), - new Vector2(77, 0), - new Rectangle(353, 30, 22, 14), - new Rectangle(353, 30, 22, 14)) + private IGameComponent CreateSPStatusBar() { - DrawOrder = HUD_CONTROL_LAYER - }; - btn.OnClick += (_, _) => _hudButtonController.ClickQuestStatus(); - btn.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return btn; - } + var statusBar = new SPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; + statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return statusBar; + } - private IGameComponent CreateHPStatusBar() - { - var statusBar = new HPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; - statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return statusBar; - } + private IGameComponent CreateTNLStatusBar() + { + var statusBar = new TNLStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository, _experienceTableProvider) { DrawOrder = HUD_CONTROL_LAYER }; + statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); + return statusBar; + } - private IGameComponent CreateTPStatusBar() - { - var statusBar = new TPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; - statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return statusBar; - } + private ChatModePictureBox CreateChatModePictureBox() + { + return new ChatModePictureBox(_nativeGraphicsManager, _clientWindowSizeRepository, _chatModeCalculator, _hudControlProvider) + { + DrawOrder = HUD_CONTROL_LAYER + 1 + }; + } - private IGameComponent CreateSPStatusBar() - { - var statusBar = new SPStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository) { DrawOrder = HUD_CONTROL_LAYER }; - statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return statusBar; - } + private ChatTextBox CreateChatTextBox() + { + var chatTextBox = new ChatTextBox(_nativeGraphicsManager, _clientWindowSizeRepository, _contentProvider) + { + Text = "", + Selected = true, + Visible = true, + DrawOrder = HUD_CONTROL_LAYER, + }; + chatTextBox.OnEnterPressed += (_, _) => _chatController.SendChatAndClearTextBox(); + chatTextBox.OnClicked += (_, _) => _chatController.SelectChatTextBox(); + chatTextBox.OnTextChanged += (_, _) => _chatController.ClearAndWarnIfJailAndGlobal(); - private IGameComponent CreateTNLStatusBar() - { - var statusBar = new TNLStatusBar(_nativeGraphicsManager, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository, _experienceTableProvider) { DrawOrder = HUD_CONTROL_LAYER }; - statusBar.StatusBarClicked += () => _sfxPlayer.PlaySfx(SoundEffectID.HudStatusBarClick); - return statusBar; - } + return chatTextBox; + } - private ChatModePictureBox CreateChatModePictureBox() - { - return new ChatModePictureBox(_nativeGraphicsManager, _clientWindowSizeRepository, _chatModeCalculator, _hudControlProvider) + private TimeLabel CreateClockLabel() { - DrawOrder = HUD_CONTROL_LAYER + 1 - }; - } + return new TimeLabel(_clientWindowSizeRepository) { DrawOrder = HUD_CONTROL_LAYER + 1 }; + } - private ChatTextBox CreateChatTextBox() - { - var chatTextBox = new ChatTextBox(_nativeGraphicsManager, _clientWindowSizeRepository, _contentProvider) + private PeriodicStatUpdaterComponent CreatePeriodicStatUpdater() { - Text = "", - Selected = true, - Visible = true, - DrawOrder = HUD_CONTROL_LAYER, - }; - chatTextBox.OnEnterPressed += (_, _) => _chatController.SendChatAndClearTextBox(); - chatTextBox.OnClicked += (_, _) => _chatController.SelectChatTextBox(); - chatTextBox.OnTextChanged += (_, _) => _chatController.ClearAndWarnIfJailAndGlobal(); - - return chatTextBox; - } - - private TimeLabel CreateClockLabel() - { - return new TimeLabel(_clientWindowSizeRepository) { DrawOrder = HUD_CONTROL_LAYER + 1 }; - } - - private PeriodicStatUpdaterComponent CreatePeriodicStatUpdater() - { - return new PeriodicStatUpdaterComponent(_endlessGameProvider, _characterRepository); - } + return new PeriodicStatUpdaterComponent(_endlessGameProvider, _characterRepository); + } - private UnknownEntitiesRequester CreateUnknownEntitiesRequester() - { - return new UnknownEntitiesRequester(_endlessGameProvider, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository, _currentMapStateRepository, - _npcRendererProvider, _characterRendererProvider, _unknownEntitiesRequestActions); - } + private UnknownEntitiesRequester CreateUnknownEntitiesRequester() + { + return new UnknownEntitiesRequester(_endlessGameProvider, _clientWindowSizeRepository, (ICharacterProvider)_characterRepository, _currentMapStateRepository, + _npcRendererProvider, _characterRendererProvider, _unknownEntitiesRequestActions); + } - private StatusBarLabel CreateStatusLabel() - { - return new StatusBarLabel(_nativeGraphicsManager, _clientWindowSizeRepository, _statusLabelTextProvider) + private StatusBarLabel CreateStatusLabel() { - Visible = true, - DrawOrder = HUD_CONTROL_LAYER, - }; - } + return new StatusBarLabel(_nativeGraphicsManager, _clientWindowSizeRepository, _statusLabelTextProvider) + { + Visible = true, + DrawOrder = HUD_CONTROL_LAYER, + }; + } - private CurrentUserInputTracker CreateCurrentUserInputTracker() - { - return new CurrentUserInputTracker(_endlessGameProvider, _userInputRepository); - } + private CurrentUserInputTracker CreateCurrentUserInputTracker() + { + return new CurrentUserInputTracker(_endlessGameProvider, _userInputRepository); + } - private IUserInputHandler CreateUserInputHandler() - { - return _userInputHandlerFactory.CreateUserInputHandler(); - } + private IUserInputHandler CreateUserInputHandler() + { + return _userInputHandlerFactory.CreateUserInputHandler(); + } - private ICharacterAnimator CreateCharacterAnimator() - { - return new CharacterAnimator( - _endlessGameProvider, _characterRepository, _currentMapStateRepository, - _currentMapProvider, _spellSlotDataRepository, _characterActions, - _walkValidationActions, _pathFinder, _fixedTimeStepRepository, - _weaponMetadataProvider); - } + private ICharacterAnimator CreateCharacterAnimator() + { + return new CharacterAnimator( + _endlessGameProvider, _characterRepository, _currentMapStateRepository, + _currentMapProvider, _spellSlotDataRepository, _characterActions, + _walkValidationActions, _pathFinder, _fixedTimeStepRepository, + _weaponMetadataProvider); + } - private INPCAnimator CreateNPCAnimator() - { - return new NPCAnimator(_endlessGameProvider, _currentMapStateRepository, _fixedTimeStepRepository); - } + private INPCAnimator CreateNPCAnimator() + { + return new NPCAnimator(_endlessGameProvider, _currentMapStateRepository, _fixedTimeStepRepository); + } - private IPeriodicEmoteHandler CreatePeriodicEmoteHandler(ICharacterAnimator characterAnimator) - { - return new PeriodicEmoteHandler( - _endlessGameProvider, _characterActions, _chatBubbleActions, - _userInputTimeProvider, _characterRepository, characterAnimator, - _statusLabelSetter, _mainButtonController, _localizedStringFinder, - _sfxPlayer); - } + private IPeriodicEmoteHandler CreatePeriodicEmoteHandler(ICharacterAnimator characterAnimator) + { + return new PeriodicEmoteHandler( + _endlessGameProvider, _characterActions, _chatBubbleActions, + _userInputTimeProvider, _characterRepository, characterAnimator, + _statusLabelSetter, _mainButtonController, _localizedStringFinder, + _sfxPlayer); + } - private PreviousUserInputTracker CreatePreviousUserInputTracker() - { - return new PreviousUserInputTracker(_endlessGameProvider, _userInputRepository); + private PreviousUserInputTracker CreatePreviousUserInputTracker() + { + return new PreviousUserInputTracker(_endlessGameProvider, _userInputRepository); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/IDraggableItemContainer.cs b/EndlessClient/HUD/Controls/IDraggableItemContainer.cs index b5df38b41..39713bef4 100644 --- a/EndlessClient/HUD/Controls/IDraggableItemContainer.cs +++ b/EndlessClient/HUD/Controls/IDraggableItemContainer.cs @@ -1,8 +1,9 @@ using XNAControls; -namespace EndlessClient.HUD.Controls; - -public interface IDraggableItemContainer : IXNAControl +namespace EndlessClient.HUD.Controls { - bool NoItemsDragging(); + public interface IDraggableItemContainer : IXNAControl + { + bool NoItemsDragging(); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/IHudControlsFactory.cs b/EndlessClient/HUD/Controls/IHudControlsFactory.cs index ba6938641..dc788bcdb 100644 --- a/EndlessClient/HUD/Controls/IHudControlsFactory.cs +++ b/EndlessClient/HUD/Controls/IHudControlsFactory.cs @@ -2,11 +2,12 @@ using Microsoft.Xna.Framework; using System.Collections.Generic; -namespace EndlessClient.HUD.Controls; - -public interface IHudControlsFactory +namespace EndlessClient.HUD.Controls { - void InjectChatController(IChatController chatController, IMainButtonController mainButtonController); + public interface IHudControlsFactory + { + void InjectChatController(IChatController chatController, IMainButtonController mainButtonController); - IReadOnlyDictionary CreateHud(); + IReadOnlyDictionary CreateHud(); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs b/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs index 70e13b2fa..02baaf161 100644 --- a/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs +++ b/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs @@ -5,67 +5,68 @@ using System; using System.Diagnostics; -namespace EndlessClient.HUD.Controls; - -public class PeriodicStatUpdaterComponent : GameComponent +namespace EndlessClient.HUD.Controls { - private readonly IEndlessGameProvider _gameProvider; - private readonly ICharacterRepository _characterRepository; - - private DateTime _lastUsageUpdateTime; - private Option _lastSpUpdateTime; - - public PeriodicStatUpdaterComponent(IEndlessGameProvider gameProvider, - ICharacterRepository characterRepository) - : base((Game)gameProvider.Game) + public class PeriodicStatUpdaterComponent : GameComponent { - _gameProvider = gameProvider; - _characterRepository = characterRepository; - _lastUsageUpdateTime = DateTime.Now; - _lastSpUpdateTime = Option.None(); - } + private readonly IEndlessGameProvider _gameProvider; + private readonly ICharacterRepository _characterRepository; - public override void Initialize() - { - if (!_gameProvider.Game.Components.Contains(this)) - _gameProvider.Game.Components.Add(this); - - base.Initialize(); - } - - public override void Update(GameTime gameTime) - { - var stats = _characterRepository.MainCharacter.Stats; + private DateTime _lastUsageUpdateTime; + private Option _lastSpUpdateTime; - if ((DateTime.Now - _lastUsageUpdateTime).TotalMinutes >= 1) + public PeriodicStatUpdaterComponent(IEndlessGameProvider gameProvider, + ICharacterRepository characterRepository) + : base((Game)gameProvider.Game) { - stats = stats.WithNewStat(CharacterStat.Usage, stats.Stats[CharacterStat.Usage] + 1); - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithStats(stats); + _gameProvider = gameProvider; + _characterRepository = characterRepository; _lastUsageUpdateTime = DateTime.Now; + _lastSpUpdateTime = Option.None(); } - if (stats[CharacterStat.SP] < stats[CharacterStat.MaxSP] - 1) + public override void Initialize() { - _lastSpUpdateTime.Match( - some: t => - { - // this seems close to 2 but is probably based on level and/or one of the stats - if (t.ElapsedMilliseconds > 2000 - Math.Max(800, _characterRepository.MainCharacter.Stats[CharacterStat.Level] * 80)) - { - var spUpdate = _characterRepository.MainCharacter.RenderProperties.SitState != SitState.Standing ? 4 : 2; - var sp = Math.Min(stats[CharacterStat.SP] + spUpdate, stats[CharacterStat.MaxSP]); - stats = stats.WithNewStat(CharacterStat.SP, sp); - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithStats(stats); + if (!_gameProvider.Game.Components.Contains(this)) + _gameProvider.Game.Components.Add(this); - if (stats[CharacterStat.SP] == stats[CharacterStat.MaxSP]) - _lastSpUpdateTime = Option.None(); - else - _lastSpUpdateTime = Option.Some(Stopwatch.StartNew()); - } - }, - none: () => _lastSpUpdateTime = Option.Some(Stopwatch.StartNew())); + base.Initialize(); } - base.Update(gameTime); + public override void Update(GameTime gameTime) + { + var stats = _characterRepository.MainCharacter.Stats; + + if ((DateTime.Now - _lastUsageUpdateTime).TotalMinutes >= 1) + { + stats = stats.WithNewStat(CharacterStat.Usage, stats.Stats[CharacterStat.Usage] + 1); + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithStats(stats); + _lastUsageUpdateTime = DateTime.Now; + } + + if (stats[CharacterStat.SP] < stats[CharacterStat.MaxSP] - 1) + { + _lastSpUpdateTime.Match( + some: t => + { + // this seems close to 2 but is probably based on level and/or one of the stats + if (t.ElapsedMilliseconds > 2000 - Math.Max(800, _characterRepository.MainCharacter.Stats[CharacterStat.Level] * 80)) + { + var spUpdate = _characterRepository.MainCharacter.RenderProperties.SitState != SitState.Standing ? 4 : 2; + var sp = Math.Min(stats[CharacterStat.SP] + spUpdate, stats[CharacterStat.MaxSP]); + stats = stats.WithNewStat(CharacterStat.SP, sp); + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithStats(stats); + + if (stats[CharacterStat.SP] == stats[CharacterStat.MaxSP]) + _lastSpUpdateTime = Option.None(); + else + _lastSpUpdateTime = Option.Some(Stopwatch.StartNew()); + } + }, + none: () => _lastSpUpdateTime = Option.Some(Stopwatch.StartNew())); + } + + base.Update(gameTime); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/HudButtonController.cs b/EndlessClient/HUD/HudButtonController.cs index 7c4d45808..bc7947a3a 100644 --- a/EndlessClient/HUD/HudButtonController.cs +++ b/EndlessClient/HUD/HudButtonController.cs @@ -5,119 +5,120 @@ using EOLib.Localization; using Moffat.EndlessOnline.SDK.Protocol.Net; -namespace EndlessClient.HUD; - -[AutoMappedType] -public class HudButtonController : IHudButtonController +namespace EndlessClient.HUD { - private readonly IHudStateActions _hudStateActions; - private readonly IOnlinePlayerActions _onlinePlayerActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IQuestActions _questActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - - public HudButtonController(IHudStateActions hudStateActions, - IOnlinePlayerActions onlinePlayerActions, - IInGameDialogActions inGameDialogActions, - IQuestActions questActions, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder) - { - _hudStateActions = hudStateActions; - _onlinePlayerActions = onlinePlayerActions; - _inGameDialogActions = inGameDialogActions; - _questActions = questActions; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - } - - public void ShowNews() - { - _hudStateActions.SwitchToState(InGameStates.News); - } - - public void ClickInventory() - { - _hudStateActions.SwitchToState(InGameStates.Inventory); - } - - public void ClickViewMapToggle() - { - _hudStateActions.ToggleMapView(); - } - - public void ClickActiveSpells() - { - _hudStateActions.SwitchToState(InGameStates.ActiveSpells); - } - - public void ClickPassiveSpells() - { - _hudStateActions.SwitchToState(InGameStates.PassiveSpells); - } - - public void ClickChat() - { - _hudStateActions.SwitchToState(InGameStates.Chat); - } - - public void ClickStats() - { - _hudStateActions.SwitchToState(InGameStates.Stats); - } - - public void ClickOnlineList() - { - _onlinePlayerActions.RequestOnlinePlayers(fullList: true); - _hudStateActions.SwitchToState(InGameStates.OnlineList); - } - - public void ClickParty() - { - _hudStateActions.SwitchToState(InGameStates.Party); - } - - public void ClickSettings() - { - _hudStateActions.SwitchToState(InGameStates.Settings); - } - - public void ClickHelp() - { - _hudStateActions.SwitchToState(InGameStates.Help); - _inGameDialogActions.ShowHelpDialog(); - } - - public void ClickFriendList() - { - _inGameDialogActions.ShowFriendListDialog(); - _onlinePlayerActions.RequestOnlinePlayers(fullList: false); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - EOResourceID.STATUS_LABEL_FRIEND_LIST, - _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_USE_RIGHT_MOUSE_CLICK_DELETE)); - } - - public void ClickIgnoreList() - { - _inGameDialogActions.ShowIgnoreListDialog(); - _onlinePlayerActions.RequestOnlinePlayers(fullList: false); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, - EOResourceID.STATUS_LABEL_IGNORE_LIST, - _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_USE_RIGHT_MOUSE_CLICK_DELETE)); - } - - public void ClickSessionExp() - { - _inGameDialogActions.ShowSessionExpDialog(); - } - - public void ClickQuestStatus() - { - _questActions.RequestQuestHistory(QuestPage.Progress); - _questActions.RequestQuestHistory(QuestPage.History); - _inGameDialogActions.ShowQuestStatusDialog(); + [AutoMappedType] + public class HudButtonController : IHudButtonController + { + private readonly IHudStateActions _hudStateActions; + private readonly IOnlinePlayerActions _onlinePlayerActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IQuestActions _questActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + + public HudButtonController(IHudStateActions hudStateActions, + IOnlinePlayerActions onlinePlayerActions, + IInGameDialogActions inGameDialogActions, + IQuestActions questActions, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder) + { + _hudStateActions = hudStateActions; + _onlinePlayerActions = onlinePlayerActions; + _inGameDialogActions = inGameDialogActions; + _questActions = questActions; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + } + + public void ShowNews() + { + _hudStateActions.SwitchToState(InGameStates.News); + } + + public void ClickInventory() + { + _hudStateActions.SwitchToState(InGameStates.Inventory); + } + + public void ClickViewMapToggle() + { + _hudStateActions.ToggleMapView(); + } + + public void ClickActiveSpells() + { + _hudStateActions.SwitchToState(InGameStates.ActiveSpells); + } + + public void ClickPassiveSpells() + { + _hudStateActions.SwitchToState(InGameStates.PassiveSpells); + } + + public void ClickChat() + { + _hudStateActions.SwitchToState(InGameStates.Chat); + } + + public void ClickStats() + { + _hudStateActions.SwitchToState(InGameStates.Stats); + } + + public void ClickOnlineList() + { + _onlinePlayerActions.RequestOnlinePlayers(fullList: true); + _hudStateActions.SwitchToState(InGameStates.OnlineList); + } + + public void ClickParty() + { + _hudStateActions.SwitchToState(InGameStates.Party); + } + + public void ClickSettings() + { + _hudStateActions.SwitchToState(InGameStates.Settings); + } + + public void ClickHelp() + { + _hudStateActions.SwitchToState(InGameStates.Help); + _inGameDialogActions.ShowHelpDialog(); + } + + public void ClickFriendList() + { + _inGameDialogActions.ShowFriendListDialog(); + _onlinePlayerActions.RequestOnlinePlayers(fullList: false); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + EOResourceID.STATUS_LABEL_FRIEND_LIST, + _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_USE_RIGHT_MOUSE_CLICK_DELETE)); + } + + public void ClickIgnoreList() + { + _inGameDialogActions.ShowIgnoreListDialog(); + _onlinePlayerActions.RequestOnlinePlayers(fullList: false); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, + EOResourceID.STATUS_LABEL_IGNORE_LIST, + _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_USE_RIGHT_MOUSE_CLICK_DELETE)); + } + + public void ClickSessionExp() + { + _inGameDialogActions.ShowSessionExpDialog(); + } + + public void ClickQuestStatus() + { + _questActions.RequestQuestHistory(QuestPage.Progress); + _questActions.RequestQuestHistory(QuestPage.History); + _inGameDialogActions.ShowQuestStatusDialog(); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/HudStateActions.cs b/EndlessClient/HUD/HudStateActions.cs index 73c9466a8..1b2d78473 100644 --- a/EndlessClient/HUD/HudStateActions.cs +++ b/EndlessClient/HUD/HudStateActions.cs @@ -8,77 +8,78 @@ using System; using System.Linq; -namespace EndlessClient.HUD; - -[AutoMappedType] -public class HudStateActions : IHudStateActions +namespace EndlessClient.HUD { - private const int HUD_CONTROL_LAYER = 130; + [AutoMappedType] + public class HudStateActions : IHudStateActions + { + private const int HUD_CONTROL_LAYER = 130; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IHudControlProvider _hudControlProvider; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IMapFileProvider _mapFileProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IHudControlProvider _hudControlProvider; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IMapFileProvider _mapFileProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - public HudStateActions(IStatusLabelSetter statusLabelSetter, - IHudControlProvider hudControlProvider, - ICurrentMapStateRepository currentMapStateRepository, - IMapFileProvider mapFileProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _statusLabelSetter = statusLabelSetter; - _hudControlProvider = hudControlProvider; - _currentMapStateRepository = currentMapStateRepository; - _mapFileProvider = mapFileProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - } + public HudStateActions(IStatusLabelSetter statusLabelSetter, + IHudControlProvider hudControlProvider, + ICurrentMapStateRepository currentMapStateRepository, + IMapFileProvider mapFileProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _statusLabelSetter = statusLabelSetter; + _hudControlProvider = hudControlProvider; + _currentMapStateRepository = currentMapStateRepository; + _mapFileProvider = mapFileProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + } - public void SwitchToState(InGameStates newState) - { - if (!_hudControlProvider.IsInGame) - return; + public void SwitchToState(InGameStates newState) + { + if (!_hudControlProvider.IsInGame) + return; - if (newState != InGameStates.News) - _hudControlProvider.GetComponent(Controls.HudControlIdentifier.NewsPanel).Visible = false; + if (newState != InGameStates.News) + _hudControlProvider.GetComponent(Controls.HudControlIdentifier.NewsPanel).Visible = false; - foreach (var panel in _hudControlProvider.HudPanels.Where(x => x.Visible)) - panel.Visible = _clientWindowSizeProvider.Resizable; + foreach (var panel in _hudControlProvider.HudPanels.Where(x => x.Visible)) + panel.Visible = _clientWindowSizeProvider.Resizable; - var targetPanel = _hudControlProvider.HudPanels.Single(x => IsPanelForRequestedState(x, newState)); - targetPanel.Visible = !targetPanel.Visible; + var targetPanel = _hudControlProvider.HudPanels.Single(x => IsPanelForRequestedState(x, newState)); + targetPanel.Visible = !targetPanel.Visible; - if (targetPanel.Visible && _clientWindowSizeProvider.Resizable) - targetPanel.DrawOrder = _hudControlProvider.HudPanels.Select(x => x.DrawOrder).Max() + 1; - } + if (targetPanel.Visible && _clientWindowSizeProvider.Resizable) + targetPanel.DrawOrder = _hudControlProvider.HudPanels.Select(x => x.DrawOrder).Max() + 1; + } - public void ToggleMapView() - { - var mapFile = _mapFileProvider.MapFiles[_currentMapStateRepository.CurrentMapID]; - if (!mapFile.Properties.MapAvailable) + public void ToggleMapView() { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_NO_MAP_OF_AREA); - return; - } + var mapFile = _mapFileProvider.MapFiles[_currentMapStateRepository.CurrentMapID]; + if (!mapFile.Properties.MapAvailable) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_NO_MAP_OF_AREA); + return; + } - _currentMapStateRepository.ShowMiniMap = !_currentMapStateRepository.ShowMiniMap; - } + _currentMapStateRepository.ShowMiniMap = !_currentMapStateRepository.ShowMiniMap; + } - private bool IsPanelForRequestedState(IHudPanel hudPanel, InGameStates newState) - { - switch (newState) + private bool IsPanelForRequestedState(IHudPanel hudPanel, InGameStates newState) { - case InGameStates.News: return hudPanel is NewsPanel; - case InGameStates.Inventory: return hudPanel is InventoryPanel; - case InGameStates.ActiveSpells: return hudPanel is ActiveSpellsPanel; - case InGameStates.PassiveSpells: return hudPanel is PassiveSpellsPanel; - case InGameStates.Chat: return hudPanel is ChatPanel; - case InGameStates.Stats: return hudPanel is StatsPanel; - case InGameStates.OnlineList: return hudPanel is OnlineListPanel; - case InGameStates.Party: return hudPanel is PartyPanel; - case InGameStates.Settings: return hudPanel is SettingsPanel; - case InGameStates.Help: return hudPanel is HelpPanel; - default: throw new ArgumentOutOfRangeException(nameof(newState), newState, null); + switch (newState) + { + case InGameStates.News: return hudPanel is NewsPanel; + case InGameStates.Inventory: return hudPanel is InventoryPanel; + case InGameStates.ActiveSpells: return hudPanel is ActiveSpellsPanel; + case InGameStates.PassiveSpells: return hudPanel is PassiveSpellsPanel; + case InGameStates.Chat: return hudPanel is ChatPanel; + case InGameStates.Stats: return hudPanel is StatsPanel; + case InGameStates.OnlineList: return hudPanel is OnlineListPanel; + case InGameStates.Party: return hudPanel is PartyPanel; + case InGameStates.Settings: return hudPanel is SettingsPanel; + case InGameStates.Help: return hudPanel is HelpPanel; + default: throw new ArgumentOutOfRangeException(nameof(newState), newState, null); + } } } } \ No newline at end of file diff --git a/EndlessClient/HUD/IHudButtonController.cs b/EndlessClient/HUD/IHudButtonController.cs index bba953064..47a5e8ad8 100644 --- a/EndlessClient/HUD/IHudButtonController.cs +++ b/EndlessClient/HUD/IHudButtonController.cs @@ -1,34 +1,35 @@ -namespace EndlessClient.HUD; - -public interface IHudButtonController +namespace EndlessClient.HUD { - void ShowNews(); + public interface IHudButtonController + { + void ShowNews(); - void ClickInventory(); + void ClickInventory(); - void ClickViewMapToggle(); + void ClickViewMapToggle(); - void ClickActiveSpells(); + void ClickActiveSpells(); - void ClickPassiveSpells(); + void ClickPassiveSpells(); - void ClickChat(); + void ClickChat(); - void ClickStats(); + void ClickStats(); - void ClickOnlineList(); + void ClickOnlineList(); - void ClickParty(); + void ClickParty(); - void ClickSettings(); + void ClickSettings(); - void ClickHelp(); + void ClickHelp(); - void ClickFriendList(); + void ClickFriendList(); - void ClickIgnoreList(); + void ClickIgnoreList(); - void ClickSessionExp(); + void ClickSessionExp(); - void ClickQuestStatus(); + void ClickQuestStatus(); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/IHudStateActions.cs b/EndlessClient/HUD/IHudStateActions.cs index e7e7906c5..83e06dba3 100644 --- a/EndlessClient/HUD/IHudStateActions.cs +++ b/EndlessClient/HUD/IHudStateActions.cs @@ -1,8 +1,9 @@ -namespace EndlessClient.HUD; - -public interface IHudStateActions +namespace EndlessClient.HUD { - void SwitchToState(InGameStates newState); + public interface IHudStateActions + { + void SwitchToState(InGameStates newState); - void ToggleMapView(); + void ToggleMapView(); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/IStatusLabelSetter.cs b/EndlessClient/HUD/IStatusLabelSetter.cs index a65bb682b..b28839090 100644 --- a/EndlessClient/HUD/IStatusLabelSetter.cs +++ b/EndlessClient/HUD/IStatusLabelSetter.cs @@ -1,15 +1,16 @@ using EOLib.Domain.Interact.Quest; using EOLib.Localization; -namespace EndlessClient.HUD; - -public interface IStatusLabelSetter : IStatusLabelNotifier +namespace EndlessClient.HUD { - void SetStatusLabel(EOResourceID type, EOResourceID text, string appended = "", bool showChatError = false); + public interface IStatusLabelSetter : IStatusLabelNotifier + { + void SetStatusLabel(EOResourceID type, EOResourceID text, string appended = "", bool showChatError = false); - void SetStatusLabel(EOResourceID type, string prepended, EOResourceID text, bool showChatError = false); + void SetStatusLabel(EOResourceID type, string prepended, EOResourceID text, bool showChatError = false); - void SetStatusLabel(EOResourceID type, string text); + void SetStatusLabel(EOResourceID type, string text); - void SetStatusLabel(string text); + void SetStatusLabel(string text); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/IStatusLabelTextRepository.cs b/EndlessClient/HUD/IStatusLabelTextRepository.cs index f8b7dd2de..59eb2d9ca 100644 --- a/EndlessClient/HUD/IStatusLabelTextRepository.cs +++ b/EndlessClient/HUD/IStatusLabelTextRepository.cs @@ -1,33 +1,34 @@ using AutomaticTypeMapper; using System; -namespace EndlessClient.HUD; - -public interface IStatusLabelTextRepository +namespace EndlessClient.HUD { - string StatusText { get; set; } + public interface IStatusLabelTextRepository + { + string StatusText { get; set; } - DateTime SetTime { get; set; } -} + DateTime SetTime { get; set; } + } -public interface IStatusLabelTextProvider -{ - string StatusText { get; } + public interface IStatusLabelTextProvider + { + string StatusText { get; } - DateTime SetTime { get; } -} + DateTime SetTime { get; } + } -[MappedType(BaseType = typeof(IStatusLabelTextRepository), IsSingleton = true)] -[MappedType(BaseType = typeof(IStatusLabelTextProvider), IsSingleton = true)] -public class StatusLabelTextRepository : IStatusLabelTextRepository, IStatusLabelTextProvider -{ - public string StatusText { get; set; } + [MappedType(BaseType = typeof(IStatusLabelTextRepository), IsSingleton = true)] + [MappedType(BaseType = typeof(IStatusLabelTextProvider), IsSingleton = true)] + public class StatusLabelTextRepository : IStatusLabelTextRepository, IStatusLabelTextProvider + { + public string StatusText { get; set; } - public DateTime SetTime { get; set; } + public DateTime SetTime { get; set; } - public StatusLabelTextRepository() - { - StatusText = ""; - SetTime = DateTime.Now; + public StatusLabelTextRepository() + { + StatusText = ""; + SetTime = DateTime.Now; + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/InGameStates.cs b/EndlessClient/HUD/InGameStates.cs index 20573374e..22d67676f 100644 --- a/EndlessClient/HUD/InGameStates.cs +++ b/EndlessClient/HUD/InGameStates.cs @@ -1,17 +1,18 @@ -namespace EndlessClient.HUD; - -public enum InGameStates +namespace EndlessClient.HUD { - Inventory, - ViewMapToggle, - ActiveSpells, - PassiveSpells, - Chat, - Stats, - OnlineList, - Party, - Macro, - Settings, - Help, - News + public enum InGameStates + { + Inventory, + ViewMapToggle, + ActiveSpells, + PassiveSpells, + Chat, + Stats, + OnlineList, + Party, + Macro, + Settings, + Help, + News + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventoryPanelItem.cs b/EndlessClient/HUD/Inventory/InventoryPanelItem.cs index ef9745c31..10400ca73 100644 --- a/EndlessClient/HUD/Inventory/InventoryPanelItem.cs +++ b/EndlessClient/HUD/Inventory/InventoryPanelItem.cs @@ -15,220 +15,221 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Inventory; - -public class InventoryPanelItem : DraggablePanelItem +namespace EndlessClient.HUD.Inventory { - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly Texture2D _itemGraphic; - private readonly Texture2D _highlightBackground; - private readonly XNALabel _nameLabel; + public class InventoryPanelItem : DraggablePanelItem + { + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly Texture2D _itemGraphic; + private readonly Texture2D _highlightBackground; + private readonly XNALabel _nameLabel; - private int _slot; + private int _slot; - private Option _highlightDrawPosition; + private Option _highlightDrawPosition; - public int Slot - { - get => _slot; - set + public int Slot { - _slot = value; - DrawPosition = GetPosition(_slot); - UpdateNameLabelPosition(); + get => _slot; + set + { + _slot = value; + DrawPosition = GetPosition(_slot); + UpdateNameLabelPosition(); + } } - } - public InventoryItem InventoryItem { get; set; } + public InventoryItem InventoryItem { get; set; } - public string Text - { - get => _nameLabel.Text; - set + public string Text { - _nameLabel.Text = value; - _nameLabel.ResizeBasedOnText(16, 9); - UpdateNameLabelPosition(); + get => _nameLabel.Text; + set + { + _nameLabel.Text = value; + _nameLabel.ResizeBasedOnText(16, 9); + UpdateNameLabelPosition(); + } } - } - - public event EventHandler DoubleClick; - - public override Rectangle EventArea => IsDragging ? DrawArea : DrawAreaWithParentOffset; - - // uses absolute coordinates - protected override Rectangle GridArea => new Rectangle( - _parentContainer.DrawPositionWithParentOffset.ToPoint() + new Point(12, 8), - new Point(363, 102)); - public InventoryPanelItem(IItemNameColorService itemNameColorService, - InventoryPanel inventoryPanel, - IActiveDialogProvider activeDialogProvider, - ISfxPlayer sfxPlayer, - int slot, - InventoryItem inventoryItem, - EIFRecord data) - : base(inventoryPanel) - { - _activeDialogProvider = activeDialogProvider; - _sfxPlayer = sfxPlayer; + public event EventHandler DoubleClick; - Slot = slot; - InventoryItem = inventoryItem; - Data = data; + public override Rectangle EventArea => IsDragging ? DrawArea : DrawAreaWithParentOffset; - _itemGraphic = inventoryPanel.NativeGraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic, transparent: true); - _highlightBackground = new Texture2D(Game.GraphicsDevice, 1, 1); - _highlightBackground.SetData(new[] { Color.FromNonPremultiplied(200, 200, 200, 60) }); + // uses absolute coordinates + protected override Rectangle GridArea => new Rectangle( + _parentContainer.DrawPositionWithParentOffset.ToPoint() + new Point(12, 8), + new Point(363, 102)); - _nameLabel = new XNALabel(Constants.FontSize08) - { - Visible = false, - AutoSize = false, - TextAlign = LabelAlignment.MiddleCenter, - ForeColor = itemNameColorService.GetColorForInventoryDisplay(Data), - BackColor = Color.FromNonPremultiplied(30, 30, 30, 160), - Text = string.Empty - }; - - OnMouseEnter += (_, _) => _nameLabel.Visible = _parentContainer.NoItemsDragging() && _activeDialogProvider.PaperdollDialog.Match(d => d.NoItemsDragging(), () => true); - OnMouseOver += InventoryPanelItem_OnMouseOver; - OnMouseLeave += (_, _) => + public InventoryPanelItem(IItemNameColorService itemNameColorService, + InventoryPanel inventoryPanel, + IActiveDialogProvider activeDialogProvider, + ISfxPlayer sfxPlayer, + int slot, + InventoryItem inventoryItem, + EIFRecord data) + : base(inventoryPanel) { - _nameLabel.Visible = false; - _highlightDrawPosition = Option.None(); - }; + _activeDialogProvider = activeDialogProvider; + _sfxPlayer = sfxPlayer; + + Slot = slot; + InventoryItem = inventoryItem; + Data = data; + + _itemGraphic = inventoryPanel.NativeGraphicsManager.TextureFromResource(GFXTypes.Items, 2 * data.Graphic, transparent: true); + _highlightBackground = new Texture2D(Game.GraphicsDevice, 1, 1); + _highlightBackground.SetData(new[] { Color.FromNonPremultiplied(200, 200, 200, 60) }); + + _nameLabel = new XNALabel(Constants.FontSize08) + { + Visible = false, + AutoSize = false, + TextAlign = LabelAlignment.MiddleCenter, + ForeColor = itemNameColorService.GetColorForInventoryDisplay(Data), + BackColor = Color.FromNonPremultiplied(30, 30, 30, 160), + Text = string.Empty + }; + + OnMouseEnter += (_, _) => _nameLabel.Visible = _parentContainer.NoItemsDragging() && _activeDialogProvider.PaperdollDialog.Match(d => d.NoItemsDragging(), () => true); + OnMouseOver += InventoryPanelItem_OnMouseOver; + OnMouseLeave += (_, _) => + { + _nameLabel.Visible = false; + _highlightDrawPosition = Option.None(); + }; + + DraggingStarted += (_, _) => + { + _nameLabel.Visible = false; + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + }; + + var (slotWidth, slotHeight) = Data.Size.GetDimensions(); + SetSize(slotWidth * 26 - 3, slotHeight * 26 - 3); + } - DraggingStarted += (_, _) => + public int GetCurrentSlotBasedOnPosition() { - _nameLabel.Visible = false; - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - }; - - var (slotWidth, slotHeight) = Data.Size.GetDimensions(); - SetSize(slotWidth * 26 - 3, slotHeight * 26 - 3); - } - - public int GetCurrentSlotBasedOnPosition() - { - if (!IsDragging) - return Slot; - - return (int)((DrawPosition.X - OldOffset.X) / 26) + InventoryPanel.InventoryRowSlots * (int)((DrawPosition.Y - OldOffset.Y) / 26); - } + if (!IsDragging) + return Slot; - public override void Initialize() - { - _nameLabel.Initialize(); - _nameLabel.SetParentControl(_parentContainer); - _nameLabel.ResizeBasedOnText(16, 9); - //_nameLabel.DrawOrderChanged += (_, e) => - //{ - // _nameLabel.DrawOrder = _parentContainer.DrawOrder + 200 - //}; - - base.Initialize(); - } - - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); + return (int)((DrawPosition.X - OldOffset.X) / 26) + InventoryPanel.InventoryRowSlots * (int)((DrawPosition.Y - OldOffset.Y) / 26); + } - _highlightDrawPosition.MatchSome(drawPosition => + public override void Initialize() { - if (GridArea.Contains(DrawArea.WithPosition(drawPosition))) - _spriteBatch.Draw(_highlightBackground, DrawArea.WithPosition(drawPosition), Color.White); - }); + _nameLabel.Initialize(); + _nameLabel.SetParentControl(_parentContainer); + _nameLabel.ResizeBasedOnText(16, 9); + //_nameLabel.DrawOrderChanged += (_, e) => + //{ + // _nameLabel.DrawOrder = _parentContainer.DrawOrder + 200 + //}; - if (IsDragging) - { - _spriteBatch.Draw(_itemGraphic, DrawPosition, Color.FromNonPremultiplied(255, 255, 255, 128)); + base.Initialize(); } - else - { - _spriteBatch.Draw(_itemGraphic, DrawPositionWithParentOffset, Color.FromNonPremultiplied(255, 255, 255, 255)); - } - - _spriteBatch.End(); - base.OnDrawControl(gameTime); - } - - private void InventoryPanelItem_OnMouseOver(object sender, MouseStateExtended e) - { - if (!GridArea.Contains(e.Position)) - return; - - var currentSlot = GetCurrentSlotBasedOnPosition(); - _highlightDrawPosition = Option.Some(GetPosition(currentSlot) + (IsDragging ? OldOffset : ImmediateParent.DrawPositionWithParentOffset)); - } - protected override bool HandleDoubleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (IsDragging) + protected override void OnDrawControl(GameTime gameTime) { - // roll back the first click in the double click - base.HandleClick(control, eventArgs); + _spriteBatch.Begin(); + + _highlightDrawPosition.MatchSome(drawPosition => + { + if (GridArea.Contains(DrawArea.WithPosition(drawPosition))) + _spriteBatch.Draw(_highlightBackground, DrawArea.WithPosition(drawPosition), Color.White); + }); + + if (IsDragging) + { + _spriteBatch.Draw(_itemGraphic, DrawPosition, Color.FromNonPremultiplied(255, 255, 255, 128)); + } + else + { + _spriteBatch.Draw(_itemGraphic, DrawPositionWithParentOffset, Color.FromNonPremultiplied(255, 255, 255, 255)); + } + + _spriteBatch.End(); + base.OnDrawControl(gameTime); } - DoubleClick?.Invoke(control, Data); - - return true; - } - - protected override void Dispose(bool disposing) - { - if (disposing) + private void InventoryPanelItem_OnMouseOver(object sender, MouseStateExtended e) { - _nameLabel.Dispose(); - _highlightBackground.Dispose(); + if (!GridArea.Contains(e.Position)) + return; + + var currentSlot = GetCurrentSlotBasedOnPosition(); + _highlightDrawPosition = Option.Some(GetPosition(currentSlot) + (IsDragging ? OldOffset : ImmediateParent.DrawPositionWithParentOffset)); } - base.Dispose(disposing); - } + protected override bool HandleDoubleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (IsDragging) + { + // roll back the first click in the double click + base.HandleClick(control, eventArgs); + } - private void UpdateNameLabelPosition() - { - if (_nameLabel == null) - return; + DoubleClick?.Invoke(control, Data); - // the name label is parented to the inventory panel so that all name labels draw over all items (see draw orders below) - // the actual position of the name label needs to be set to this control's draw position - var actualPosition = DrawPosition; + return true; + } - if (actualPosition.X + _nameLabel.DrawAreaWithParentOffset.Width + DrawArea.Width > GridArea.Width) + protected override void Dispose(bool disposing) { - _nameLabel.DrawPosition = new Vector2(actualPosition.X - _nameLabel.DrawArea.Width, actualPosition.Y); + if (disposing) + { + _nameLabel.Dispose(); + _highlightBackground.Dispose(); + } + + base.Dispose(disposing); } - else + + private void UpdateNameLabelPosition() { - _nameLabel.DrawPosition = new Vector2(actualPosition.X + DrawArea.Width, actualPosition.Y); + if (_nameLabel == null) + return; + + // the name label is parented to the inventory panel so that all name labels draw over all items (see draw orders below) + // the actual position of the name label needs to be set to this control's draw position + var actualPosition = DrawPosition; + + if (actualPosition.X + _nameLabel.DrawAreaWithParentOffset.Width + DrawArea.Width > GridArea.Width) + { + _nameLabel.DrawPosition = new Vector2(actualPosition.X - _nameLabel.DrawArea.Width, actualPosition.Y); + } + else + { + _nameLabel.DrawPosition = new Vector2(actualPosition.X + DrawArea.Width, actualPosition.Y); + } + + DrawOrder = _parentContainer.DrawOrder + 2; + _nameLabel.DrawOrder = _parentContainer.DrawOrder + 200; } - DrawOrder = _parentContainer.DrawOrder + 2; - _nameLabel.DrawOrder = _parentContainer.DrawOrder + 200; - } - - protected override void OnDraggingFinished(DragCompletedEventArgs args) - { - base.OnDraggingFinished(args); + protected override void OnDraggingFinished(DragCompletedEventArgs args) + { + base.OnDraggingFinished(args); - if (args.ContinueDrag) - return; + if (args.ContinueDrag) + return; - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - if (!args.RestoreOriginalSlot) - Slot = GetCurrentSlotBasedOnPosition(); - else - DrawPosition = GetPosition(Slot); + if (!args.RestoreOriginalSlot) + Slot = GetCurrentSlotBasedOnPosition(); + else + DrawPosition = GetPosition(Slot); - _nameLabel.Visible = false; - UpdateNameLabelPosition(); - } + _nameLabel.Visible = false; + UpdateNameLabelPosition(); + } - private static Vector2 GetPosition(int slot) - { - return new Vector2(13 + 26 * (slot % InventoryPanel.InventoryRowSlots), 9 + 26 * (slot / InventoryPanel.InventoryRowSlots)); + private static Vector2 GetPosition(int slot) + { + return new Vector2(13 + 26 * (slot % InventoryPanel.InventoryRowSlots), 9 + 26 * (slot / InventoryPanel.InventoryRowSlots)); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventoryService.cs b/EndlessClient/HUD/Inventory/InventoryService.cs index 8bf113bee..c1b43937a 100644 --- a/EndlessClient/HUD/Inventory/InventoryService.cs +++ b/EndlessClient/HUD/Inventory/InventoryService.cs @@ -5,108 +5,109 @@ using Optional; using System.Collections.Generic; -namespace EndlessClient.HUD.Inventory; - -[AutoMappedType] -public class InventoryService : IInventoryService +namespace EndlessClient.HUD.Inventory { - public Option GetNextOpenSlot(bool[,] usedSlots, ItemSize size, Option preferredSlot) + [AutoMappedType] + public class InventoryService : IInventoryService { - var (sizeWidth, sizeHeight) = size.GetDimensions(); + public Option GetNextOpenSlot(bool[,] usedSlots, ItemSize size, Option preferredSlot) + { + var (sizeWidth, sizeHeight) = size.GetDimensions(); - var preferredSlotIsValid = preferredSlot.Match( - some: slot => IsSlotOpen(usedSlots, Option.None(), slot, size), - none: () => false); + var preferredSlotIsValid = preferredSlot.Match( + some: slot => IsSlotOpen(usedSlots, Option.None(), slot, size), + none: () => false); - if (preferredSlotIsValid) - return preferredSlot; + if (preferredSlotIsValid) + return preferredSlot; - for (int r = 0; r < usedSlots.GetLength(0); r++) - { - for (int c = 0; c < usedSlots.GetLength(1); c++) + for (int r = 0; r < usedSlots.GetLength(0); r++) { - var slot = r * InventoryPanel.InventoryRowSlots + c; - if (!usedSlots[r, c] && IsSlotOpen(usedSlots, Option.None(), slot, size)) - return Option.Some(slot); + for (int c = 0; c < usedSlots.GetLength(1); c++) + { + var slot = r * InventoryPanel.InventoryRowSlots + c; + if (!usedSlots[r, c] && IsSlotOpen(usedSlots, Option.None(), slot, size)) + return Option.Some(slot); + } } - } - return Option.None(); - } - - public void SetSlots(bool[,] usedSlots, int slot, ItemSize size) - { - SetSlotValue(usedSlots, slot, size, value: true); - } + return Option.None(); + } - public void ClearSlots(bool[,] usedSlots, int slot, ItemSize size) - { - SetSlotValue(usedSlots, slot, size, value: false); - } + public void SetSlots(bool[,] usedSlots, int slot, ItemSize size) + { + SetSlotValue(usedSlots, slot, size, value: true); + } - public bool FitsInSlot(bool[,] usedSlots, int oldSlot, int newSlot, ItemSize size) => - IsSlotOpen(usedSlots, Option.Some(oldSlot), newSlot, size); + public void ClearSlots(bool[,] usedSlots, int slot, ItemSize size) + { + SetSlotValue(usedSlots, slot, size, value: false); + } - public bool FitsInSlot(bool[,] usedSlots, int newSlot, ItemSize size) => - IsSlotOpen(usedSlots, Option.None(), newSlot, size); + public bool FitsInSlot(bool[,] usedSlots, int oldSlot, int newSlot, ItemSize size) => + IsSlotOpen(usedSlots, Option.Some(oldSlot), newSlot, size); - private bool IsSlotOpen(bool[,] usedSlots, Option oldSlot, int slot, ItemSize size) - { - var (sizeWidth, sizeHeight) = size.GetDimensions(); + public bool FitsInSlot(bool[,] usedSlots, int newSlot, ItemSize size) => + IsSlotOpen(usedSlots, Option.None(), newSlot, size); - var ignorePoints = new List<(int X, int Y)>(); - oldSlot.MatchSome(s => + private bool IsSlotOpen(bool[,] usedSlots, Option oldSlot, int slot, ItemSize size) { - var oldCol = s % InventoryPanel.InventoryRowSlots; - var oldRow = s / InventoryPanel.InventoryRowSlots; + var (sizeWidth, sizeHeight) = size.GetDimensions(); - for (int r = oldRow; r < oldRow + sizeHeight; r++) - for (int c = oldCol; c < oldCol + sizeWidth; c++) - ignorePoints.Add((c, r)); - }); + var ignorePoints = new List<(int X, int Y)>(); + oldSlot.MatchSome(s => + { + var oldCol = s % InventoryPanel.InventoryRowSlots; + var oldRow = s / InventoryPanel.InventoryRowSlots; - var col = slot % InventoryPanel.InventoryRowSlots; - var row = slot / InventoryPanel.InventoryRowSlots; - for (int r = row; r < row + sizeHeight; r++) - { - for (int c = col; c < col + sizeWidth; c++) + for (int r = oldRow; r < oldRow + sizeHeight; r++) + for (int c = oldCol; c < oldCol + sizeWidth; c++) + ignorePoints.Add((c, r)); + }); + + var col = slot % InventoryPanel.InventoryRowSlots; + var row = slot / InventoryPanel.InventoryRowSlots; + for (int r = row; r < row + sizeHeight; r++) { - if (r >= usedSlots.GetLength(0) || c >= usedSlots.GetLength(1) || - r < 0 || c < 0 || - (!ignorePoints.Contains((c, r)) && usedSlots[r, c])) - return false; + for (int c = col; c < col + sizeWidth; c++) + { + if (r >= usedSlots.GetLength(0) || c >= usedSlots.GetLength(1) || + r < 0 || c < 0 || + (!ignorePoints.Contains((c, r)) && usedSlots[r, c])) + return false; + } } - } - return true; - } + return true; + } - private void SetSlotValue(bool[,] usedSlots, int slot, ItemSize size, bool value) - { - var (sizeWidth, sizeHeight) = size.GetDimensions(); + private void SetSlotValue(bool[,] usedSlots, int slot, ItemSize size, bool value) + { + var (sizeWidth, sizeHeight) = size.GetDimensions(); - var slotCol = slot % InventoryPanel.InventoryRowSlots; - var slotRow = slot / InventoryPanel.InventoryRowSlots; + var slotCol = slot % InventoryPanel.InventoryRowSlots; + var slotRow = slot / InventoryPanel.InventoryRowSlots; - for (int r = slotRow; r < slotRow + sizeHeight; r++) - { - for (int c = slotCol; c < slotCol + sizeWidth; c++) + for (int r = slotRow; r < slotRow + sizeHeight; r++) { - if (r < usedSlots.GetLength(0) && c < usedSlots.GetLength(1)) - usedSlots[r, c] = value; + for (int c = slotCol; c < slotCol + sizeWidth; c++) + { + if (r < usedSlots.GetLength(0) && c < usedSlots.GetLength(1)) + usedSlots[r, c] = value; + } } } } -} -public interface IInventoryService -{ - Option GetNextOpenSlot(bool[,] usedSlots, ItemSize size, Option preferredSlot); - void SetSlots(bool[,] usedSlots, int slot, ItemSize size); + public interface IInventoryService + { + Option GetNextOpenSlot(bool[,] usedSlots, ItemSize size, Option preferredSlot); + void SetSlots(bool[,] usedSlots, int slot, ItemSize size); - void ClearSlots(bool[,] usedSlots, int slot, ItemSize size); + void ClearSlots(bool[,] usedSlots, int slot, ItemSize size); - bool FitsInSlot(bool[,] usedSlots, int oldSlot, int newSlot, ItemSize size); + bool FitsInSlot(bool[,] usedSlots, int oldSlot, int newSlot, ItemSize size); - bool FitsInSlot(bool[,] usedSlots, int newSlot, ItemSize size); + bool FitsInSlot(bool[,] usedSlots, int newSlot, ItemSize size); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventorySlotRepository.cs b/EndlessClient/HUD/Inventory/InventorySlotRepository.cs index 5cf65074a..aa4be9371 100644 --- a/EndlessClient/HUD/Inventory/InventorySlotRepository.cs +++ b/EndlessClient/HUD/Inventory/InventorySlotRepository.cs @@ -4,41 +4,42 @@ using EOLib.IO.Map; using System.Collections.Generic; -namespace EndlessClient.HUD.Inventory; - -public interface IInventorySlotRepository +namespace EndlessClient.HUD.Inventory { - Matrix FilledSlots { get; set; } + public interface IInventorySlotRepository + { + Matrix FilledSlots { get; set; } - Dictionary SlotMap { get; set; } -} + Dictionary SlotMap { get; set; } + } -public interface IInventorySlotProvider -{ - IReadOnlyMatrix FilledSlots { get; } + public interface IInventorySlotProvider + { + IReadOnlyMatrix FilledSlots { get; } - IReadOnlyDictionary SlotMap { get; } -} + IReadOnlyDictionary SlotMap { get; } + } -[AutoMappedType(IsSingleton = true)] -public class InventorySlotRepository : IInventorySlotProvider, IInventorySlotRepository, IResettable -{ - public Matrix FilledSlots { get; set; } + [AutoMappedType(IsSingleton = true)] + public class InventorySlotRepository : IInventorySlotProvider, IInventorySlotRepository, IResettable + { + public Matrix FilledSlots { get; set; } - public Dictionary SlotMap { get; set; } + public Dictionary SlotMap { get; set; } - IReadOnlyMatrix IInventorySlotProvider.FilledSlots => FilledSlots; + IReadOnlyMatrix IInventorySlotProvider.FilledSlots => FilledSlots; - IReadOnlyDictionary IInventorySlotProvider.SlotMap => SlotMap; + IReadOnlyDictionary IInventorySlotProvider.SlotMap => SlotMap; - public InventorySlotRepository() - { - ResetState(); - } + public InventorySlotRepository() + { + ResetState(); + } - public void ResetState() - { - FilledSlots = new Matrix(InventoryPanel.InventoryRows, InventoryPanel.InventoryRowSlots, false); - SlotMap = new Dictionary(); + public void ResetState() + { + FilledSlots = new Matrix(InventoryPanel.InventoryRows, InventoryPanel.InventoryRowSlots, false); + SlotMap = new Dictionary(); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs b/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs index 4eec02bdd..4cbeac495 100644 --- a/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs +++ b/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs @@ -9,80 +9,81 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.HUD.Inventory; - -[AutoMappedType] -public class InventorySpaceValidator : IInventorySpaceValidator +namespace EndlessClient.HUD.Inventory { - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IInventorySlotProvider _inventorySlotProvider; - private readonly IInventoryService _inventoryService; - - public InventorySpaceValidator(IEIFFileProvider eifFileProvider, - ICharacterInventoryProvider characterInventoryProvider, - IInventorySlotProvider inventorySlotProvider, - IInventoryService inventoryService) - { - _eifFileProvider = eifFileProvider; - _characterInventoryProvider = characterInventoryProvider; - _inventorySlotProvider = inventorySlotProvider; - _inventoryService = inventoryService; - } - - public bool ItemFits(MapItem item) + [AutoMappedType] + public class InventorySpaceValidator : IInventorySpaceValidator { - return _characterInventoryProvider.ItemInventory.Any(x => x.ItemID == item.ItemID) || ItemFits(item.ItemID); - } + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IInventorySlotProvider _inventorySlotProvider; + private readonly IInventoryService _inventoryService; - public bool ItemFits(int itemId) - { - return _characterInventoryProvider.ItemInventory.Any(x => x.ItemID == itemId) || ItemFits(_eifFileProvider.EIFFile[itemId].Size); - } + public InventorySpaceValidator(IEIFFileProvider eifFileProvider, + ICharacterInventoryProvider characterInventoryProvider, + IInventorySlotProvider inventorySlotProvider, + IInventoryService inventoryService) + { + _eifFileProvider = eifFileProvider; + _characterInventoryProvider = characterInventoryProvider; + _inventorySlotProvider = inventorySlotProvider; + _inventoryService = inventoryService; + } - public bool ItemsFit(IReadOnlyList outItems, IReadOnlyList inItems) - { - var slotsCopy = new Matrix(_inventorySlotProvider.FilledSlots); + public bool ItemFits(MapItem item) + { + return _characterInventoryProvider.ItemInventory.Any(x => x.ItemID == item.ItemID) || ItemFits(item.ItemID); + } - foreach (var item in outItems) + public bool ItemFits(int itemId) { - var itemData = _eifFileProvider.EIFFile[item.ItemID]; - _inventorySlotProvider.SlotMap.SingleOrNone(x => x.Value == item.ItemID) - .Map(x => x.Key) - .MatchSome(x => _inventoryService.ClearSlots(slotsCopy, x, itemData.Size)); + return _characterInventoryProvider.ItemInventory.Any(x => x.ItemID == itemId) || ItemFits(_eifFileProvider.EIFFile[itemId].Size); } - foreach (var item in inItems) + public bool ItemsFit(IReadOnlyList outItems, IReadOnlyList inItems) { - var itemData = _eifFileProvider.EIFFile[item.ItemID]; - var itemFits = _inventoryService - .GetNextOpenSlot(slotsCopy, itemData.Size, Option.None()) - .Match(some: slot => - { - _inventoryService.SetSlots(slotsCopy, slot, itemData.Size); - return true; - }, - none: () => false); - if (!itemFits) - return false; + var slotsCopy = new Matrix(_inventorySlotProvider.FilledSlots); + + foreach (var item in outItems) + { + var itemData = _eifFileProvider.EIFFile[item.ItemID]; + _inventorySlotProvider.SlotMap.SingleOrNone(x => x.Value == item.ItemID) + .Map(x => x.Key) + .MatchSome(x => _inventoryService.ClearSlots(slotsCopy, x, itemData.Size)); + } + + foreach (var item in inItems) + { + var itemData = _eifFileProvider.EIFFile[item.ItemID]; + var itemFits = _inventoryService + .GetNextOpenSlot(slotsCopy, itemData.Size, Option.None()) + .Match(some: slot => + { + _inventoryService.SetSlots(slotsCopy, slot, itemData.Size); + return true; + }, + none: () => false); + if (!itemFits) + return false; + } + + return true; } - return true; + private bool ItemFits(ItemSize itemSize) + { + return _inventoryService + .GetNextOpenSlot((Matrix)_inventorySlotProvider.FilledSlots, itemSize, Option.None()) + .HasValue; + } } - private bool ItemFits(ItemSize itemSize) + public interface IInventorySpaceValidator { - return _inventoryService - .GetNextOpenSlot((Matrix)_inventorySlotProvider.FilledSlots, itemSize, Option.None()) - .HasValue; - } -} + bool ItemFits(MapItem item); -public interface IInventorySpaceValidator -{ - bool ItemFits(MapItem item); + bool ItemFits(int itemId); - bool ItemFits(int itemId); - - bool ItemsFit(IReadOnlyList outItems, IReadOnlyList inItems); + bool ItemsFit(IReadOnlyList outItems, IReadOnlyList inItems); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/ItemNameColorService.cs b/EndlessClient/HUD/ItemNameColorService.cs index 371951261..c41fe4a20 100644 --- a/EndlessClient/HUD/ItemNameColorService.cs +++ b/EndlessClient/HUD/ItemNameColorService.cs @@ -4,33 +4,34 @@ using EOLib.IO.Pub; using Microsoft.Xna.Framework; -namespace EndlessClient.HUD; - -[AutoMappedType] -public class ItemNameColorService : IItemNameColorService +namespace EndlessClient.HUD { - public Color GetColorForInventoryDisplay(EIFRecord itemData) => GetColor(itemData, ColorConstants.LightGrayText); + [AutoMappedType] + public class ItemNameColorService : IItemNameColorService + { + public Color GetColorForInventoryDisplay(EIFRecord itemData) => GetColor(itemData, ColorConstants.LightGrayText); - public Color GetColorForMapDisplay(EIFRecord itemData) => GetColor(itemData, Color.White); + public Color GetColorForMapDisplay(EIFRecord itemData) => GetColor(itemData, Color.White); - private static Color GetColor(EIFRecord itemData, Color defaultColor) - { - switch (itemData.Special) + private static Color GetColor(EIFRecord itemData, Color defaultColor) { - case ItemSpecial.Lore: - case ItemSpecial.Unique: - return Color.FromNonPremultiplied(0xff, 0xf0, 0xa5, 0xff); - case ItemSpecial.Rare: - return Color.FromNonPremultiplied(0xf5, 0xc8, 0x9c, 0xff); - } + switch (itemData.Special) + { + case ItemSpecial.Lore: + case ItemSpecial.Unique: + return Color.FromNonPremultiplied(0xff, 0xf0, 0xa5, 0xff); + case ItemSpecial.Rare: + return Color.FromNonPremultiplied(0xf5, 0xc8, 0x9c, 0xff); + } - return defaultColor; + return defaultColor; + } } -} -public interface IItemNameColorService -{ - Color GetColorForMapDisplay(EIFRecord itemData); + public interface IItemNameColorService + { + Color GetColorForMapDisplay(EIFRecord itemData); - Color GetColorForInventoryDisplay(EIFRecord itemData); + Color GetColorForInventoryDisplay(EIFRecord itemData); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs b/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs index 44e4c340e..0178d79ef 100644 --- a/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs +++ b/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs @@ -32,593 +32,594 @@ using static EndlessClient.HUD.Spells.SpellPanelItem; -namespace EndlessClient.HUD.Panels; - -public class ActiveSpellsPanel : DraggableHudPanel, IHudPanel, IDraggableItemContainer +namespace EndlessClient.HUD.Panels { - public const int SpellRows = 4; - public const int SpellRowLength = 8; - - private readonly ITrainingController _trainingController; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IESFFileProvider _esfFileProvider; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly IHudControlProvider _hudControlProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IConfigurationProvider _configProvider; - - private readonly Dictionary _spellSlotMap; - private readonly List _childItems; - - private readonly Texture2D _functionKeyLabelSheet; - private Rectangle _functionKeyRow1Source, _functionKeyRow2Source; - - private readonly XNALabel _selectedSpellName, _selectedSpellLevel, _totalSkillPoints; - private readonly XNAButton _levelUpButton1, _levelUpButton2; - private readonly ScrollBar _scrollBar; - - private HashSet _cachedSpells; - private CharacterStats _cachedStats; - private Option _cachedSelectedSpell; - - private bool _confirmedTraining; - private int _lastScrollOffset; - private Texture2D _activeSpellIcon; - - public INativeGraphicsManager NativeGraphicsManager { get; } - - public ActiveSpellsPanel(INativeGraphicsManager nativeGraphicsManager, - ITrainingController trainingController, - IEOMessageBoxFactory messageBoxFactory, - IStatusLabelSetter statusLabelSetter, - IPlayerInfoProvider playerInfoProvider, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IESFFileProvider esfFileProvider, - ISpellSlotDataRepository spellSlotDataRepository, - IHudControlProvider hudControlProvider, - ISfxPlayer sfxPlayer, - IConfigurationProvider configProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + public class ActiveSpellsPanel : DraggableHudPanel, IHudPanel, IDraggableItemContainer { - NativeGraphicsManager = nativeGraphicsManager; - _trainingController = trainingController; - _messageBoxFactory = messageBoxFactory; - _statusLabelSetter = statusLabelSetter; - _playerInfoProvider = playerInfoProvider; - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _esfFileProvider = esfFileProvider; - _spellSlotDataRepository = spellSlotDataRepository; - _hudControlProvider = hudControlProvider; - _sfxPlayer = sfxPlayer; - _configProvider = configProvider; - - _spellSlotMap = GetSpellSlotMap(_playerInfoProvider.LoggedInAccountName, _characterProvider.MainCharacter.Name, _configProvider.Host); - _childItems = new List(); - - _cachedSpells = new HashSet(); - - _functionKeyLabelSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); - _functionKeyRow1Source = new Rectangle(148, 51, 18, 13); - _functionKeyRow2Source = new Rectangle(148 + 18 * 8, 51, 18, 13); - - _selectedSpellName = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(9, 50, 81, 13), - Visible = false, - Text = "", - AutoSize = false, - TextAlign = LabelAlignment.MiddleCenter, - ForeColor = ColorConstants.LightGrayText, - }; - - _selectedSpellLevel = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = new Rectangle(32, 78, 42, 15), - Visible = true, - Text = "0", - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText, - }; - - _totalSkillPoints = new XNALabel(Constants.FontSize08pt5) + public const int SpellRows = 4; + public const int SpellRowLength = 8; + + private readonly ITrainingController _trainingController; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IESFFileProvider _esfFileProvider; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly IHudControlProvider _hudControlProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IConfigurationProvider _configProvider; + + private readonly Dictionary _spellSlotMap; + private readonly List _childItems; + + private readonly Texture2D _functionKeyLabelSheet; + private Rectangle _functionKeyRow1Source, _functionKeyRow2Source; + + private readonly XNALabel _selectedSpellName, _selectedSpellLevel, _totalSkillPoints; + private readonly XNAButton _levelUpButton1, _levelUpButton2; + private readonly ScrollBar _scrollBar; + + private HashSet _cachedSpells; + private CharacterStats _cachedStats; + private Option _cachedSelectedSpell; + + private bool _confirmedTraining; + private int _lastScrollOffset; + private Texture2D _activeSpellIcon; + + public INativeGraphicsManager NativeGraphicsManager { get; } + + public ActiveSpellsPanel(INativeGraphicsManager nativeGraphicsManager, + ITrainingController trainingController, + IEOMessageBoxFactory messageBoxFactory, + IStatusLabelSetter statusLabelSetter, + IPlayerInfoProvider playerInfoProvider, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IESFFileProvider esfFileProvider, + ISpellSlotDataRepository spellSlotDataRepository, + IHudControlProvider hudControlProvider, + ISfxPlayer sfxPlayer, + IConfigurationProvider configProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - DrawArea = new Rectangle(32, 96, 42, 15), - Visible = true, - Text = _characterProvider.MainCharacter.Stats[CharacterStat.SkillPoints].ToString(), - AutoSize = false, - TextAlign = LabelAlignment.MiddleLeft, - ForeColor = ColorConstants.LightGrayText, - }; - - var buttonSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); - _levelUpButton1 = new XNAButton(buttonSheet, new Vector2(71, 77), new Rectangle(215, 386, 19, 15), new Rectangle(234, 386, 19, 15)) - { - FlashSpeed = 500, - Visible = false - }; - _levelUpButton1.OnClick += LevelUp_Click; + NativeGraphicsManager = nativeGraphicsManager; + _trainingController = trainingController; + _messageBoxFactory = messageBoxFactory; + _statusLabelSetter = statusLabelSetter; + _playerInfoProvider = playerInfoProvider; + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _esfFileProvider = esfFileProvider; + _spellSlotDataRepository = spellSlotDataRepository; + _hudControlProvider = hudControlProvider; + _sfxPlayer = sfxPlayer; + _configProvider = configProvider; + + _spellSlotMap = GetSpellSlotMap(_playerInfoProvider.LoggedInAccountName, _characterProvider.MainCharacter.Name, _configProvider.Host); + _childItems = new List(); + + _cachedSpells = new HashSet(); + + _functionKeyLabelSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); + _functionKeyRow1Source = new Rectangle(148, 51, 18, 13); + _functionKeyRow2Source = new Rectangle(148 + 18 * 8, 51, 18, 13); + + _selectedSpellName = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(9, 50, 81, 13), + Visible = false, + Text = "", + AutoSize = false, + TextAlign = LabelAlignment.MiddleCenter, + ForeColor = ColorConstants.LightGrayText, + }; - _levelUpButton2 = new XNAButton(buttonSheet, new Vector2(71, 95), new Rectangle(215, 386, 19, 15), new Rectangle(234, 386, 19, 15)) - { - FlashSpeed = 500, - Visible = false - }; - _levelUpButton2.OnClick += LevelUp_Click; + _selectedSpellLevel = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(32, 78, 42, 15), + Visible = true, + Text = "0", + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText, + }; - _scrollBar = new ScrollBar(new Vector2(467, 2), new Vector2(16, 115), ScrollBarColors.LightOnMed, NativeGraphicsManager) - { - LinesToRender = 2 - }; - _scrollBar.UpdateDimensions(4); - SetScrollWheelHandler(_scrollBar); + _totalSkillPoints = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(32, 96, 42, 15), + Visible = true, + Text = _characterProvider.MainCharacter.Stats[CharacterStat.SkillPoints].ToString(), + AutoSize = false, + TextAlign = LabelAlignment.MiddleLeft, + ForeColor = ColorConstants.LightGrayText, + }; - BackgroundImage = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 62); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + var buttonSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); + _levelUpButton1 = new XNAButton(buttonSheet, new Vector2(71, 77), new Rectangle(215, 386, 19, 15), new Rectangle(234, 386, 19, 15)) + { + FlashSpeed = 500, + Visible = false + }; + _levelUpButton1.OnClick += LevelUp_Click; - Game.Exiting += SaveSpellsFile; - } + _levelUpButton2 = new XNAButton(buttonSheet, new Vector2(71, 95), new Rectangle(215, 386, 19, 15), new Rectangle(234, 386, 19, 15)) + { + FlashSpeed = 500, + Visible = false + }; + _levelUpButton2.OnClick += LevelUp_Click; - public bool NoItemsDragging() => _childItems.All(x => !x.IsDragging); + _scrollBar = new ScrollBar(new Vector2(467, 2), new Vector2(16, 115), ScrollBarColors.LightOnMed, NativeGraphicsManager) + { + LinesToRender = 2 + }; + _scrollBar.UpdateDimensions(4); + SetScrollWheelHandler(_scrollBar); - public override void Initialize() - { - _selectedSpellName.Initialize(); - _selectedSpellName.SetParentControl(this); + BackgroundImage = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 62); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - _selectedSpellLevel.Initialize(); - _selectedSpellLevel.SetParentControl(this); + Game.Exiting += SaveSpellsFile; + } - _totalSkillPoints.Initialize(); - _totalSkillPoints.SetParentControl(this); + public bool NoItemsDragging() => _childItems.All(x => !x.IsDragging); - _levelUpButton1.Initialize(); - _levelUpButton1.SetParentControl(this); + public override void Initialize() + { + _selectedSpellName.Initialize(); + _selectedSpellName.SetParentControl(this); - _levelUpButton2.Initialize(); - _levelUpButton2.SetParentControl(this); + _selectedSpellLevel.Initialize(); + _selectedSpellLevel.SetParentControl(this); - _scrollBar.Initialize(); - _scrollBar.SetParentControl(this); + _totalSkillPoints.Initialize(); + _totalSkillPoints.SetParentControl(this); - base.Initialize(); - } + _levelUpButton1.Initialize(); + _levelUpButton1.SetParentControl(this); - protected override void OnUnconditionalUpdateControl(GameTime gameTime) - { - if (!_cachedSpells.SetEquals(_characterInventoryProvider.SpellInventory)) - { - var added = _characterInventoryProvider.SpellInventory.Where(i => !_cachedSpells.Any(j => i.ID == j.ID)); - var removed = _cachedSpells.Where(i => !_characterInventoryProvider.SpellInventory.Any(j => i.ID == j.ID)); - var updated = _characterInventoryProvider.SpellInventory.Except(added) - .Where(i => _cachedSpells.Any(j => i.ID == j.ID && i.Level != j.Level)); + _levelUpButton2.Initialize(); + _levelUpButton2.SetParentControl(this); - foreach (var spell in removed) - { - var matchedSpell = _childItems.SingleOrNone(x => x.InventorySpell.ID == spell.ID); - matchedSpell.MatchSome(childControl => - { - childControl.SetControlUnparented(); - childControl.Dispose(); - _childItems.Remove(childControl); + _scrollBar.Initialize(); + _scrollBar.SetParentControl(this); - _spellSlotDataRepository.SpellSlots[childControl.Slot] = Option.None(); - }); - } + base.Initialize(); + } - foreach (var spell in updated) + protected override void OnUnconditionalUpdateControl(GameTime gameTime) + { + if (!_cachedSpells.SetEquals(_characterInventoryProvider.SpellInventory)) { - var matchedSpell = _childItems.SingleOrNone(x => x.InventorySpell.ID == spell.ID); - matchedSpell.MatchSome(childControl => + var added = _characterInventoryProvider.SpellInventory.Where(i => !_cachedSpells.Any(j => i.ID == j.ID)); + var removed = _cachedSpells.Where(i => !_characterInventoryProvider.SpellInventory.Any(j => i.ID == j.ID)); + var updated = _characterInventoryProvider.SpellInventory.Except(added) + .Where(i => _cachedSpells.Any(j => i.ID == j.ID && i.Level != j.Level)); + + foreach (var spell in removed) { - childControl.InventorySpell = spell; - _spellSlotDataRepository.SelectedSpellSlot.MatchSome(s => + var matchedSpell = _childItems.SingleOrNone(x => x.InventorySpell.ID == spell.ID); + matchedSpell.MatchSome(childControl => { - if (childControl.Slot == s) - _selectedSpellLevel.Text = spell.Level.ToString(); - }); - }); - } + childControl.SetControlUnparented(); + childControl.Dispose(); + _childItems.Remove(childControl); - foreach (var spell in added) - { - var spellData = _esfFileProvider.ESFFile[spell.ID]; + _spellSlotDataRepository.SpellSlots[childControl.Slot] = Option.None(); + }); + } - var preferredSlot = _spellSlotMap.SingleOrNone(x => x.Value == spell.ID).Map(x => x.Key); - var actualSlot = preferredSlot.Match( - some: x => + foreach (var spell in updated) + { + var matchedSpell = _childItems.SingleOrNone(x => x.InventorySpell.ID == spell.ID); + matchedSpell.MatchSome(childControl => { - return _childItems.OfType().Any(ci => ci.Slot == x) - ? GetNextOpenSlot(_childItems) - : Option.Some(x); - }, - none: () => GetNextOpenSlot(_childItems)); + childControl.InventorySpell = spell; + _spellSlotDataRepository.SelectedSpellSlot.MatchSome(s => + { + if (childControl.Slot == s) + _selectedSpellLevel.Text = spell.Level.ToString(); + }); + }); + } - actualSlot.MatchSome(slot => + foreach (var spell in added) { - var newChild = new SpellPanelItem(this, _sfxPlayer, slot, spell, spellData); - newChild.Initialize(); - newChild.SetParentControl(this); - - // this is required so scroll works while click+dragging when the control becomes unparented - newChild.SetScrollWheelHandler(_scrollBar); + var spellData = _esfFileProvider.ESFFile[spell.ID]; + + var preferredSlot = _spellSlotMap.SingleOrNone(x => x.Value == spell.ID).Map(x => x.Key); + var actualSlot = preferredSlot.Match( + some: x => + { + return _childItems.OfType().Any(ci => ci.Slot == x) + ? GetNextOpenSlot(_childItems) + : Option.Some(x); + }, + none: () => GetNextOpenSlot(_childItems)); + + actualSlot.MatchSome(slot => + { + var newChild = new SpellPanelItem(this, _sfxPlayer, slot, spell, spellData); + newChild.Initialize(); + newChild.SetParentControl(this); - newChild.Click += (sender, _) => _spellSlotDataRepository.SelectedSpellSlot = Option.Some(((SpellPanelItem)sender).Slot); - newChild.OnMouseOver += SetSpellStatusLabelHover; - newChild.DraggingFinishing += HandleItemDoneDragging; + // this is required so scroll works while click+dragging when the control becomes unparented + newChild.SetScrollWheelHandler(_scrollBar); - _childItems.Add(newChild); - _spellSlotDataRepository.SpellSlots[slot] = Option.Some(spell); - }); - } + newChild.Click += (sender, _) => _spellSlotDataRepository.SelectedSpellSlot = Option.Some(((SpellPanelItem)sender).Slot); + newChild.OnMouseOver += SetSpellStatusLabelHover; + newChild.DraggingFinishing += HandleItemDoneDragging; - if (added.Any()) - UpdateSpellItemsForScroll(); + _childItems.Add(newChild); + _spellSlotDataRepository.SpellSlots[slot] = Option.Some(spell); + }); + } - _cachedSpells = _characterInventoryProvider.SpellInventory.ToHashSet(); - } + if (added.Any()) + UpdateSpellItemsForScroll(); - base.OnUnconditionalUpdateControl(gameTime); - } + _cachedSpells = _characterInventoryProvider.SpellInventory.ToHashSet(); + } - protected override void OnUpdateControl(GameTime gameTime) - { - var kbd = KeyboardExtended.GetState(); - if (kbd.WasKeyJustUp(Keys.RightShift) || kbd.WasKeyJustDown(Keys.RightShift) || - kbd.WasKeyJustUp(Keys.LeftShift) || kbd.WasKeyJustDown(Keys.LeftShift)) - { - SwapFunctionKeySourceRectangles(); + base.OnUnconditionalUpdateControl(gameTime); } - if (_lastScrollOffset != _scrollBar.ScrollOffset) + protected override void OnUpdateControl(GameTime gameTime) { - UpdateSpellItemsForScroll(); - } + var kbd = KeyboardExtended.GetState(); + if (kbd.WasKeyJustUp(Keys.RightShift) || kbd.WasKeyJustDown(Keys.RightShift) || + kbd.WasKeyJustUp(Keys.LeftShift) || kbd.WasKeyJustDown(Keys.LeftShift)) + { + SwapFunctionKeySourceRectangles(); + } - if (_cachedStats != _characterProvider.MainCharacter.Stats && _activeSpellIcon != null) - { - _cachedStats = _characterProvider.MainCharacter.Stats; - var skillPoints = _cachedStats[CharacterStat.SkillPoints]; - _totalSkillPoints.Text = skillPoints.ToString(); + if (_lastScrollOffset != _scrollBar.ScrollOffset) + { + UpdateSpellItemsForScroll(); + } - _levelUpButton1.Visible = skillPoints > 0; - _levelUpButton2.Visible = skillPoints > 0; - } + if (_cachedStats != _characterProvider.MainCharacter.Stats && _activeSpellIcon != null) + { + _cachedStats = _characterProvider.MainCharacter.Stats; + var skillPoints = _cachedStats[CharacterStat.SkillPoints]; + _totalSkillPoints.Text = skillPoints.ToString(); - _cachedSelectedSpell.Match( - some: cached => _spellSlotDataRepository.SelectedSpellSlot.Match( - some: repoSlot => - { - if (cached != repoSlot) + _levelUpButton1.Visible = skillPoints > 0; + _levelUpButton2.Visible = skillPoints > 0; + } + + _cachedSelectedSpell.Match( + some: cached => _spellSlotDataRepository.SelectedSpellSlot.Match( + some: repoSlot => + { + if (cached != repoSlot) + { + SetSelectedSpell(repoSlot); + _cachedSelectedSpell = _spellSlotDataRepository.SelectedSpellSlot; + } + }, + none: () => + { + ClearSelectedSpell(); + _cachedSelectedSpell = Option.None(); + }), + none: () => _spellSlotDataRepository.SelectedSpellSlot.MatchSome( + some: repoSlot => { SetSelectedSpell(repoSlot); _cachedSelectedSpell = _spellSlotDataRepository.SelectedSpellSlot; - } - }, - none: () => - { - ClearSelectedSpell(); - _cachedSelectedSpell = Option.None(); - }), - none: () => _spellSlotDataRepository.SelectedSpellSlot.MatchSome( - some: repoSlot => - { - SetSelectedSpell(repoSlot); - _cachedSelectedSpell = _spellSlotDataRepository.SelectedSpellSlot; - })); - - base.OnUpdateControl(gameTime); - } + })); - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + base.OnUpdateControl(gameTime); + } - _spriteBatch.Begin(); + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - DrawFunctionKeyLabels(); - DrawActiveSpell(); + _spriteBatch.Begin(); - _spriteBatch.End(); - } + DrawFunctionKeyLabels(); + DrawActiveSpell(); - private void DrawFunctionKeyLabels() - { - if (_scrollBar.ScrollOffset >= 2) - return; + _spriteBatch.End(); + } - for (int i = 0; i < 8; ++i) + private void DrawFunctionKeyLabels() { - var offset = _functionKeyRow1Source.Width * i; + if (_scrollBar.ScrollOffset >= 2) + return; - if (_scrollBar.ScrollOffset == 0) + for (int i = 0; i < 8; ++i) { - _spriteBatch.Draw(_functionKeyLabelSheet, - DrawPosition + new Vector2(100 + 45 * i, 8), - _functionKeyRow1Source.WithPosition((_functionKeyRow1Source.Location + new Point(offset, 0)).ToVector2()), - Color.White); - } + var offset = _functionKeyRow1Source.Width * i; - if (_scrollBar.ScrollOffset < 2) - { - var yCoord = _scrollBar.ScrollOffset == 0 ? 90 : 38; - _spriteBatch.Draw(_functionKeyLabelSheet, - DrawPosition + new Vector2(100 + 45 * i, yCoord), - _functionKeyRow2Source.WithPosition((_functionKeyRow2Source.Location + new Point(offset, 0)).ToVector2()), - Color.White); + if (_scrollBar.ScrollOffset == 0) + { + _spriteBatch.Draw(_functionKeyLabelSheet, + DrawPosition + new Vector2(100 + 45 * i, 8), + _functionKeyRow1Source.WithPosition((_functionKeyRow1Source.Location + new Point(offset, 0)).ToVector2()), + Color.White); + } + + if (_scrollBar.ScrollOffset < 2) + { + var yCoord = _scrollBar.ScrollOffset == 0 ? 90 : 38; + _spriteBatch.Draw(_functionKeyLabelSheet, + DrawPosition + new Vector2(100 + 45 * i, yCoord), + _functionKeyRow2Source.WithPosition((_functionKeyRow2Source.Location + new Point(offset, 0)).ToVector2()), + Color.White); + } } } - } - private void DrawActiveSpell() - { - if (_activeSpellIcon == null) - return; + private void DrawActiveSpell() + { + if (_activeSpellIcon == null) + return; - var srcRect = new Rectangle(0, 0, _activeSpellIcon.Width / 2, _activeSpellIcon.Height); - var dstRect = new Rectangle(DrawAreaWithParentOffset.X + 32, DrawAreaWithParentOffset.Y + 14, srcRect.Width, srcRect.Height); - _spriteBatch.Draw(_activeSpellIcon, dstRect, srcRect, Color.White); - } + var srcRect = new Rectangle(0, 0, _activeSpellIcon.Width / 2, _activeSpellIcon.Height); + var dstRect = new Rectangle(DrawAreaWithParentOffset.X + 32, DrawAreaWithParentOffset.Y + 14, srcRect.Width, srcRect.Height); + _spriteBatch.Draw(_activeSpellIcon, dstRect, srcRect, Color.White); + } - private void LevelUp_Click(object sender, EventArgs args) - { - if (!_confirmedTraining) + private void LevelUp_Click(object sender, EventArgs args) { - //apparently this is NOT stored in the edf files... - //NOTE: copy-pasted from EOCharacterStats button event handler. Should probably be in some shared function somewhere. - var dialog = _messageBoxFactory.CreateMessageBox("Do you want to train?", - "Skill training", - EODialogButtons.OkCancel); - dialog.DialogClosing += (_, e) => + if (!_confirmedTraining) { - if (e.Result == XNADialogResult.OK) - _confirmedTraining = true; - }; - dialog.ShowDialog(); - } - else - { - _cachedSelectedSpell.MatchSome(slot => + //apparently this is NOT stored in the edf files... + //NOTE: copy-pasted from EOCharacterStats button event handler. Should probably be in some shared function somewhere. + var dialog = _messageBoxFactory.CreateMessageBox("Do you want to train?", + "Skill training", + EODialogButtons.OkCancel); + dialog.DialogClosing += (_, e) => + { + if (e.Result == XNADialogResult.OK) + _confirmedTraining = true; + }; + dialog.ShowDialog(); + } + else { - _childItems.SingleOrNone(x => x.Slot == slot) - .MatchSome(x => _trainingController.AddSkillPoint(x.Data.ID)); - }); + _cachedSelectedSpell.MatchSome(slot => + { + _childItems.SingleOrNone(x => x.Slot == slot) + .MatchSome(x => _trainingController.AddSkillPoint(x.Data.ID)); + }); + } } - } - private void SetSelectedSpell(int slot) - { - _childItems.OfType().SingleOrNone(x => x.Slot == slot) - .MatchSome(spell => - { - var spellData = spell.Data; - - _activeSpellIcon = NativeGraphicsManager.TextureFromResource(GFXTypes.SpellIcons, spellData.Icon); - - _selectedSpellName.Text = spellData.Name; - _selectedSpellName.Visible = true; - - _selectedSpellLevel.Text = spell.InventorySpell.Level.ToString(); + private void SetSelectedSpell(int slot) + { + _childItems.OfType().SingleOrNone(x => x.Slot == slot) + .MatchSome(spell => + { + var spellData = spell.Data; - _levelUpButton1.Visible = _levelUpButton2.Visible = _characterProvider.MainCharacter.Stats[CharacterStat.SkillPoints] > 0; - }); - } + _activeSpellIcon = NativeGraphicsManager.TextureFromResource(GFXTypes.SpellIcons, spellData.Icon); - private void ClearSelectedSpell() - { - _activeSpellIcon = null; + _selectedSpellName.Text = spellData.Name; + _selectedSpellName.Visible = true; - _selectedSpellName.Text = string.Empty; - _selectedSpellName.Visible = false; + _selectedSpellLevel.Text = spell.InventorySpell.Level.ToString(); - _selectedSpellLevel.Text = "0"; + _levelUpButton1.Visible = _levelUpButton2.Visible = _characterProvider.MainCharacter.Stats[CharacterStat.SkillPoints] > 0; + }); + } - _levelUpButton1.Visible = _levelUpButton2.Visible = false; - } + private void ClearSelectedSpell() + { + _activeSpellIcon = null; - private void SetSpellStatusLabelHover(object sender, MouseStateExtended e) - { - var spellPanelItem = sender as SpellPanelItem; - if (spellPanelItem == null || spellPanelItem.IsDragging) - return; + _selectedSpellName.Text = string.Empty; + _selectedSpellName.Visible = false; - _statusLabelSetter.SetStatusLabel(EOResourceID.SKILLMASTER_WORD_SPELL, spellPanelItem.Data.Name); - } + _selectedSpellLevel.Text = "0"; - private void HandleItemDoneDragging(object sender, DragCompletedEventArgs e) - { - var item = sender as SpellPanelItem; - if (item == null) - return; + _levelUpButton1.Visible = _levelUpButton2.Visible = false; + } - if (e.DragOutOfBounds) + private void SetSpellStatusLabelHover(object sender, MouseStateExtended e) { - e.RestoreOriginalSlot = true; - return; - } + var spellPanelItem = sender as SpellPanelItem; + if (spellPanelItem == null || spellPanelItem.IsDragging) + return; - var oldSlot = item.Slot; - var newSlot = item.GetCurrentSlotBasedOnPosition(_scrollBar.ScrollOffset); + _statusLabelSetter.SetStatusLabel(EOResourceID.SKILLMASTER_WORD_SPELL, spellPanelItem.Data.Name); + } - if (oldSlot != newSlot && - newSlot < (_scrollBar.ScrollOffset + _scrollBar.LinesToRender) * SpellRowLength && - newSlot >= _scrollBar.ScrollOffset * SpellRowLength) + private void HandleItemDoneDragging(object sender, DragCompletedEventArgs e) { - _childItems.SingleOrNone(x => x.Slot == newSlot) - .Match(child => - { - var oldDisplaySlot = item.DisplaySlot; - var newDisplaySlot = child.DisplaySlot; + var item = sender as SpellPanelItem; + if (item == null) + return; - item.Slot = newSlot; - item.DisplaySlot = newDisplaySlot; + if (e.DragOutOfBounds) + { + e.RestoreOriginalSlot = true; + return; + } - child.Slot = oldSlot; - child.DisplaySlot = oldDisplaySlot; + var oldSlot = item.Slot; + var newSlot = item.GetCurrentSlotBasedOnPosition(_scrollBar.ScrollOffset); - _spellSlotDataRepository.SpellSlots[oldSlot] = Option.Some(child.InventorySpell); - _spellSlotDataRepository.SpellSlots[newSlot] = Option.Some(item.InventorySpell); - _spellSlotDataRepository.SelectedSpellSlot = Option.Some(newSlot); - _spellSlotDataRepository.SpellIsPrepared = false; - }, - () => - { - item.Slot = newSlot; - item.DisplaySlot = newSlot - (SpellRowLength * _scrollBar.ScrollOffset); + if (oldSlot != newSlot && + newSlot < (_scrollBar.ScrollOffset + _scrollBar.LinesToRender) * SpellRowLength && + newSlot >= _scrollBar.ScrollOffset * SpellRowLength) + { + _childItems.SingleOrNone(x => x.Slot == newSlot) + .Match(child => + { + var oldDisplaySlot = item.DisplaySlot; + var newDisplaySlot = child.DisplaySlot; - _spellSlotDataRepository.SpellSlots[oldSlot] = Option.None(); - _spellSlotDataRepository.SpellSlots[newSlot] = Option.Some(item.InventorySpell); - _spellSlotDataRepository.SelectedSpellSlot = Option.Some(newSlot); - _spellSlotDataRepository.SpellIsPrepared = false; - }); + item.Slot = newSlot; + item.DisplaySlot = newDisplaySlot; - UpdateSpellItemsForScroll(); - } - } + child.Slot = oldSlot; + child.DisplaySlot = oldDisplaySlot; - private Option GetNextOpenSlot(IEnumerable childItems) - { - return _spellSlotDataRepository.SpellSlots - .Select((spellItem, slot) => (SpellItem: spellItem, Slot: slot)) - .Where(pair => !pair.SpellItem.HasValue && childItems.All(x => x.Slot != pair.Slot)) - .FirstOrNone() - .Map(x => x.Slot); - } + _spellSlotDataRepository.SpellSlots[oldSlot] = Option.Some(child.InventorySpell); + _spellSlotDataRepository.SpellSlots[newSlot] = Option.Some(item.InventorySpell); + _spellSlotDataRepository.SelectedSpellSlot = Option.Some(newSlot); + _spellSlotDataRepository.SpellIsPrepared = false; + }, + () => + { + item.Slot = newSlot; + item.DisplaySlot = newSlot - (SpellRowLength * _scrollBar.ScrollOffset); - private void SwapFunctionKeySourceRectangles() - { - var tmpRect = _functionKeyRow2Source; - _functionKeyRow2Source = _functionKeyRow1Source; - _functionKeyRow1Source = tmpRect; - } + _spellSlotDataRepository.SpellSlots[oldSlot] = Option.None(); + _spellSlotDataRepository.SpellSlots[newSlot] = Option.Some(item.InventorySpell); + _spellSlotDataRepository.SelectedSpellSlot = Option.Some(newSlot); + _spellSlotDataRepository.SpellIsPrepared = false; + }); - private void UpdateSpellItemsForScroll() - { - var firstValidSlot = _scrollBar.ScrollOffset * SpellRowLength; - var lastValidSlot = firstValidSlot + 2 * SpellRowLength; + UpdateSpellItemsForScroll(); + } + } - var itemsToHide = _childItems.Where(x => x.Slot < firstValidSlot || x.Slot >= lastValidSlot).ToList(); - foreach (var item in itemsToHide) + private Option GetNextOpenSlot(IEnumerable childItems) { - if (!item.IsDragging) - item.Visible = false; - - item.DisplaySlot = GetDisplaySlotFromSlot(item.Slot); + return _spellSlotDataRepository.SpellSlots + .Select((spellItem, slot) => (SpellItem: spellItem, Slot: slot)) + .Where(pair => !pair.SpellItem.HasValue && childItems.All(x => x.Slot != pair.Slot)) + .FirstOrNone() + .Map(x => x.Slot); } - foreach (var item in _childItems.Except(itemsToHide)) + private void SwapFunctionKeySourceRectangles() { - item.Visible = true; - item.DisplaySlot = item.Slot - firstValidSlot; + var tmpRect = _functionKeyRow2Source; + _functionKeyRow2Source = _functionKeyRow1Source; + _functionKeyRow1Source = tmpRect; } - _lastScrollOffset = _scrollBar.ScrollOffset; - } + private void UpdateSpellItemsForScroll() + { + var firstValidSlot = _scrollBar.ScrollOffset * SpellRowLength; + var lastValidSlot = firstValidSlot + 2 * SpellRowLength; - private int GetDisplaySlotFromSlot(int newSlot) - { - var offset = _scrollBar.ScrollOffset; - return newSlot - SpellRowLength * offset; - } + var itemsToHide = _childItems.Where(x => x.Slot < firstValidSlot || x.Slot >= lastValidSlot).ToList(); + foreach (var item in itemsToHide) + { + if (!item.IsDragging) + item.Visible = false; - protected override void Dispose(bool disposing) - { - if (disposing) + item.DisplaySlot = GetDisplaySlotFromSlot(item.Slot); + } + + foreach (var item in _childItems.Except(itemsToHide)) + { + item.Visible = true; + item.DisplaySlot = item.Slot - firstValidSlot; + } + + _lastScrollOffset = _scrollBar.ScrollOffset; + } + + private int GetDisplaySlotFromSlot(int newSlot) { - Game.Exiting -= SaveSpellsFile; - SaveSpellsFile(null, EventArgs.Empty); + var offset = _scrollBar.ScrollOffset; + return newSlot - SpellRowLength * offset; } - base.Dispose(disposing); - } + protected override void Dispose(bool disposing) + { + if (disposing) + { + Game.Exiting -= SaveSpellsFile; + SaveSpellsFile(null, EventArgs.Empty); + } - #region Slot loading + base.Dispose(disposing); + } - private static Dictionary GetSpellSlotMap(string accountName, string characterName, string host) - { - var map = new Dictionary(); + #region Slot loading - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !File.Exists(Constants.SpellsFile)) + private static Dictionary GetSpellSlotMap(string accountName, string characterName, string host) { - using var registrySpellsKey = TryGetCharacterRegistryKey(accountName, characterName); - if (registrySpellsKey != null) + var map = new Dictionary(); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !File.Exists(Constants.SpellsFile)) { - for (int i = 0; i < SpellRowLength * SpellRows; ++i) + using var registrySpellsKey = TryGetCharacterRegistryKey(accountName, characterName); + if (registrySpellsKey != null) { - if (int.TryParse(registrySpellsKey.GetValue($"item{i}")?.ToString() ?? string.Empty, out var id)) - map[i] = id; + for (int i = 0; i < SpellRowLength * SpellRows; ++i) + { + if (int.TryParse(registrySpellsKey.GetValue($"item{i}")?.ToString() ?? string.Empty, out var id)) + map[i] = id; + } } } - } - var spells = new IniReader(Constants.SpellsFile); - var spellsKey = $"{host}:{accountName}"; - if (spells.Load() && spells.Sections.ContainsKey(spellsKey)) - { - var section = spells.Sections[spellsKey]; - foreach (var key in section.Keys.Where(x => x.Contains(characterName, StringComparison.OrdinalIgnoreCase))) + var spells = new IniReader(Constants.SpellsFile); + var spellsKey = $"{host}:{accountName}"; + if (spells.Load() && spells.Sections.ContainsKey(spellsKey)) { - if (!key.Contains(".")) - continue; + var section = spells.Sections[spellsKey]; + foreach (var key in section.Keys.Where(x => x.Contains(characterName, StringComparison.OrdinalIgnoreCase))) + { + if (!key.Contains(".")) + continue; - var slot = key.Split(".")[1]; - if (!int.TryParse(slot, out var slotIndex)) - continue; + var slot = key.Split(".")[1]; + if (!int.TryParse(slot, out var slotIndex)) + continue; - if (int.TryParse(section[key], out var id)) - map[slotIndex] = id; + if (int.TryParse(section[key], out var id)) + map[slotIndex] = id; + } } + + return map; } - return map; - } + [SupportedOSPlatform("Windows")] + private static RegistryKey TryGetCharacterRegistryKey(string accountName, string characterName) + { + using RegistryKey currentUser = Registry.CurrentUser; - [SupportedOSPlatform("Windows")] - private static RegistryKey TryGetCharacterRegistryKey(string accountName, string characterName) - { - using RegistryKey currentUser = Registry.CurrentUser; + var pathSegments = $"Software\\EndlessClient\\{accountName}\\{characterName}\\spells".Split('\\'); + var currentPath = string.Empty; - var pathSegments = $"Software\\EndlessClient\\{accountName}\\{characterName}\\spells".Split('\\'); - var currentPath = string.Empty; + RegistryKey retKey = null; + foreach (var segment in pathSegments) + { + retKey?.Dispose(); - RegistryKey retKey = null; - foreach (var segment in pathSegments) - { - retKey?.Dispose(); + currentPath = Path.Combine(currentPath, segment); + retKey = currentUser.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadSubTree); + } - currentPath = Path.Combine(currentPath, segment); - retKey = currentUser.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadSubTree); + return retKey; } - return retKey; - } + private void SaveSpellsFile(object sender, EventArgs e) + { + var spells = new IniReader(Constants.SpellsFile); - private void SaveSpellsFile(object sender, EventArgs e) - { - var spells = new IniReader(Constants.SpellsFile); + var section = spells.Load() && spells.Sections.ContainsKey(_playerInfoProvider.LoggedInAccountName) + ? spells.Sections[_playerInfoProvider.LoggedInAccountName] + : new SortedList(); - var section = spells.Load() && spells.Sections.ContainsKey(_playerInfoProvider.LoggedInAccountName) - ? spells.Sections[_playerInfoProvider.LoggedInAccountName] - : new SortedList(); + var existing = section.Where(x => x.Key.Contains(_characterProvider.MainCharacter.Name)).Select(x => x.Key).ToList(); + foreach (var key in existing) + section.Remove(key); - var existing = section.Where(x => x.Key.Contains(_characterProvider.MainCharacter.Name)).Select(x => x.Key).ToList(); - foreach (var key in existing) - section.Remove(key); + foreach (var item in _childItems.OfType()) + section[$"{_characterProvider.MainCharacter.Name}.{item.Slot}"] = $"{item.InventorySpell.ID}"; - foreach (var item in _childItems.OfType()) - section[$"{_characterProvider.MainCharacter.Name}.{item.Slot}"] = $"{item.InventorySpell.ID}"; + spells.Sections[_playerInfoProvider.LoggedInAccountName] = section; - spells.Sections[_playerInfoProvider.LoggedInAccountName] = section; + spells.Save(); + } - spells.Save(); + #endregion } - - #endregion } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/ChatPanel.cs b/EndlessClient/HUD/Panels/ChatPanel.cs index 7747c7cf5..856db4f09 100644 --- a/EndlessClient/HUD/Panels/ChatPanel.cs +++ b/EndlessClient/HUD/Panels/ChatPanel.cs @@ -13,123 +13,124 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels; - -public class ChatPanel : DraggableHudPanel +namespace EndlessClient.HUD.Panels { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatActions _chatActions; - private readonly IChatRenderableGenerator _chatRenderableGenerator; - private readonly IChatProvider _chatProvider; - private readonly IHudControlProvider _hudControlProvider; - - private readonly ScrollBar _scrollBar; - private readonly Dictionary _tabs; - - public ChatTab CurrentTab => _tabs.Single(x => x.Value.Active).Key; - - public ChatPanel(INativeGraphicsManager nativeGraphicsManager, - IChatActions chatActions, - IChatRenderableGenerator chatRenderableGenerator, - IChatProvider chatProvider, - IHudControlProvider hudControlProvider, - BitmapFont chatFont, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + public class ChatPanel : DraggableHudPanel { - _nativeGraphicsManager = nativeGraphicsManager; - _chatActions = chatActions; - _chatRenderableGenerator = chatRenderableGenerator; - _chatProvider = chatProvider; - _hudControlProvider = hudControlProvider; - - //abs coordiantes: 568 309 - _scrollBar = new ScrollBar(new Vector2(467, 2), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) - { - LinesToRender = 7, - Visible = true - }; - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); - - var tabTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 35); - var smallSelected = new SpriteSheet(tabTexture, new Rectangle(307, 16, 43, 16)); - var smallUnselected = new SpriteSheet(tabTexture, new Rectangle(264, 16, 43, 16)); - var largeSelected = new SpriteSheet(tabTexture, new Rectangle(132, 16, 132, 16)); - var largeUnselected = new SpriteSheet(tabTexture, new Rectangle(0, 16, 132, 16)); - - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 28); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - - _tabs = new Dictionary + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatActions _chatActions; + private readonly IChatRenderableGenerator _chatRenderableGenerator; + private readonly IChatProvider _chatProvider; + private readonly IHudControlProvider _hudControlProvider; + + private readonly ScrollBar _scrollBar; + private readonly Dictionary _tabs; + + public ChatTab CurrentTab => _tabs.Single(x => x.Value.Active).Key; + + public ChatPanel(INativeGraphicsManager nativeGraphicsManager, + IChatActions chatActions, + IChatRenderableGenerator chatRenderableGenerator, + IChatProvider chatProvider, + IHudControlProvider hudControlProvider, + BitmapFont chatFont, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - {ChatTab.Local, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Local, smallSelected, smallUnselected, chatFont) { Visible = true, Active = true } }, - {ChatTab.Global, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Global, smallSelected, smallUnselected, chatFont) { Visible = true, } }, - {ChatTab.Group, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Group, smallSelected, smallUnselected, chatFont) { Visible = true, } }, - {ChatTab.System, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.System, smallSelected, smallUnselected, chatFont) { Visible = true, } }, - {ChatTab.Private1, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Private1, largeSelected, largeUnselected, chatFont) {Visible = false} }, - {ChatTab.Private2, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Private2, largeSelected, largeUnselected, chatFont) {Visible = false } }, - }; - - foreach (var tab in _tabs.Values) - { - tab.SetParentControl(this); - tab.OnClosed += (s, _) => _chatActions.ClosePMTab(((ChatPanelTab)s).Tab); + _nativeGraphicsManager = nativeGraphicsManager; + _chatActions = chatActions; + _chatRenderableGenerator = chatRenderableGenerator; + _chatProvider = chatProvider; + _hudControlProvider = hudControlProvider; + + //abs coordiantes: 568 309 + _scrollBar = new ScrollBar(new Vector2(467, 2), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) + { + LinesToRender = 7, + Visible = true + }; + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); + + var tabTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 35); + var smallSelected = new SpriteSheet(tabTexture, new Rectangle(307, 16, 43, 16)); + var smallUnselected = new SpriteSheet(tabTexture, new Rectangle(264, 16, 43, 16)); + var largeSelected = new SpriteSheet(tabTexture, new Rectangle(132, 16, 132, 16)); + var largeUnselected = new SpriteSheet(tabTexture, new Rectangle(0, 16, 132, 16)); + + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 28); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + + _tabs = new Dictionary + { + {ChatTab.Local, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Local, smallSelected, smallUnselected, chatFont) { Visible = true, Active = true } }, + {ChatTab.Global, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Global, smallSelected, smallUnselected, chatFont) { Visible = true, } }, + {ChatTab.Group, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Group, smallSelected, smallUnselected, chatFont) { Visible = true, } }, + {ChatTab.System, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.System, smallSelected, smallUnselected, chatFont) { Visible = true, } }, + {ChatTab.Private1, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Private1, largeSelected, largeUnselected, chatFont) {Visible = false} }, + {ChatTab.Private2, new ChatPanelTab(_chatProvider, _hudControlProvider, _chatRenderableGenerator, this, _scrollBar, ChatTab.Private2, largeSelected, largeUnselected, chatFont) {Visible = false } }, + }; + + foreach (var tab in _tabs.Values) + { + tab.SetParentControl(this); + tab.OnClosed += (s, _) => _chatActions.ClosePMTab(((ChatPanelTab)s).Tab); + } } - } - public override void Initialize() - { - _scrollBar.Initialize(); - - foreach (var tab in _tabs.Values) - tab.Initialize(); + public override void Initialize() + { + _scrollBar.Initialize(); - base.Initialize(); - } + foreach (var tab in _tabs.Values) + tab.Initialize(); - public void TryStartNewPrivateChat(string targetCharacter) - { - if (_tabs[ChatTab.Private1].Visible && _tabs[ChatTab.Private2].Visible) - return; + base.Initialize(); + } - if (!string.Equals(_chatProvider.PMTarget1, targetCharacter, StringComparison.OrdinalIgnoreCase) && - !string.Equals(_chatProvider.PMTarget2, targetCharacter, StringComparison.OrdinalIgnoreCase)) + public void TryStartNewPrivateChat(string targetCharacter) { - if (_tabs[ChatTab.Private1].Visible) - { - SelectTab(ChatTab.Private2); - _tabs[ChatTab.Private2].Text = char.ToUpper(targetCharacter[0]) + targetCharacter[1..]; - } - else + if (_tabs[ChatTab.Private1].Visible && _tabs[ChatTab.Private2].Visible) + return; + + if (!string.Equals(_chatProvider.PMTarget1, targetCharacter, StringComparison.OrdinalIgnoreCase) && + !string.Equals(_chatProvider.PMTarget2, targetCharacter, StringComparison.OrdinalIgnoreCase)) { - SelectTab(ChatTab.Private1); - _tabs[ChatTab.Private1].Text = char.ToUpper(targetCharacter[0]) + targetCharacter[1..]; + if (_tabs[ChatTab.Private1].Visible) + { + SelectTab(ChatTab.Private2); + _tabs[ChatTab.Private2].Text = char.ToUpper(targetCharacter[0]) + targetCharacter[1..]; + } + else + { + SelectTab(ChatTab.Private1); + _tabs[ChatTab.Private1].Text = char.ToUpper(targetCharacter[0]) + targetCharacter[1..]; + } } } - } - public void SelectTab(ChatTab clickedTab) - { - if (CurrentTab == ChatTab.Global && clickedTab != ChatTab.Global) - { - _chatActions.SetGlobalActive(false); - } - else if (CurrentTab != ChatTab.Global && clickedTab == ChatTab.Global) + public void SelectTab(ChatTab clickedTab) { - _chatActions.SetGlobalActive(true); - } + if (CurrentTab == ChatTab.Global && clickedTab != ChatTab.Global) + { + _chatActions.SetGlobalActive(false); + } + else if (CurrentTab != ChatTab.Global && clickedTab == ChatTab.Global) + { + _chatActions.SetGlobalActive(true); + } - _tabs[CurrentTab].Active = false; + _tabs[CurrentTab].Active = false; - _tabs[clickedTab].Visible = true; - _tabs[clickedTab].Active = true; + _tabs[clickedTab].Visible = true; + _tabs[clickedTab].Active = true; - _scrollBar.UpdateDimensions(_chatProvider.AllChat[clickedTab].Count); - } + _scrollBar.UpdateDimensions(_chatProvider.AllChat[clickedTab].Count); + } - public void ClosePMTab(ChatTab whichTab) - { - _tabs[whichTab].CloseTab(); + public void ClosePMTab(ChatTab whichTab) + { + _tabs[whichTab].CloseTab(); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/DraggableHudPanel.cs b/EndlessClient/HUD/Panels/DraggableHudPanel.cs index e7ee305b6..3a3316c3e 100644 --- a/EndlessClient/HUD/Panels/DraggableHudPanel.cs +++ b/EndlessClient/HUD/Panels/DraggableHudPanel.cs @@ -4,62 +4,63 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Panels; - -public class DraggableHudPanel : XNAPanel, IHudPanel +namespace EndlessClient.HUD.Panels { - public event Action Activated; - public event Action DragCompleted; + public class DraggableHudPanel : XNAPanel, IHudPanel + { + public event Action Activated; + public event Action DragCompleted; - private static Option _dragging; - private bool _enableDragging; + private static Option _dragging; + private bool _enableDragging; - public bool IsBeingDragged => _dragging.HasValue; + public bool IsBeingDragged => _dragging.HasValue; - public DraggableHudPanel(bool enableDragging) - { - _enableDragging = enableDragging; - } + public DraggableHudPanel(bool enableDragging) + { + _enableDragging = enableDragging; + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - Activated?.Invoke(); - return true; - } + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + Activated?.Invoke(); + return true; + } - protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_enableDragging) - return false; + protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_enableDragging) + return false; - Activated?.Invoke(); - return true; - } + Activated?.Invoke(); + return true; + } - protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_enableDragging) - return false; + protected override bool HandleDrag(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_enableDragging) + return false; - _dragging - .FlatMap(p => p.NoneWhen(q => p == this)) - .MatchNone(() => - { - _dragging = Option.Some(this); - DrawPosition = DrawPositionWithParentOffset + eventArgs.DistanceMoved; - }); + _dragging + .FlatMap(p => p.NoneWhen(q => p == this)) + .MatchNone(() => + { + _dragging = Option.Some(this); + DrawPosition = DrawPositionWithParentOffset + eventArgs.DistanceMoved; + }); - return true; - } + return true; + } - protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) - { - if (!_enableDragging) - return false; + protected override bool HandleDragEnd(IXNAControl control, MouseEventArgs eventArgs) + { + if (!_enableDragging) + return false; - _dragging = Option.None(); - DragCompleted?.Invoke(); + _dragging = Option.None(); + DragCompleted?.Invoke(); - return true; + return true; + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/HelpPanel.cs b/EndlessClient/HUD/Panels/HelpPanel.cs index 4f05576da..3ac20c7cb 100644 --- a/EndlessClient/HUD/Panels/HelpPanel.cs +++ b/EndlessClient/HUD/Panels/HelpPanel.cs @@ -3,19 +3,20 @@ using Microsoft.Xna.Framework; using XNAControls; -namespace EndlessClient.HUD.Panels; - -public class HelpPanel : DraggableHudPanel +namespace EndlessClient.HUD.Panels { - private readonly INativeGraphicsManager _nativeGraphicsManager; - - public HelpPanel(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + public class HelpPanel : DraggableHudPanel { - _nativeGraphicsManager = nativeGraphicsManager; + private readonly INativeGraphicsManager _nativeGraphicsManager; + + public HelpPanel(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) + { + _nativeGraphicsManager = nativeGraphicsManager; - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 63); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 63); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/HudPanelFactory.cs b/EndlessClient/HUD/Panels/HudPanelFactory.cs index e3f10ed35..0a1f045de 100644 --- a/EndlessClient/HUD/Panels/HudPanelFactory.cs +++ b/EndlessClient/HUD/Panels/HudPanelFactory.cs @@ -22,219 +22,220 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.HUD.Panels; - -[MappedType(BaseType = typeof(IHudPanelFactory))] -public class HudPanelFactory : IHudPanelFactory +namespace EndlessClient.HUD.Panels { - private const int HUD_CONTROL_LAYER = 130; - - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IInventoryController _inventoryController; - private readonly IChatActions _chatActions; - private readonly IContentProvider _contentProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly INewsProvider _newsProvider; - private readonly IChatProvider _chatProvider; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IExperienceTableProvider _experienceTableProvider; - private readonly IPubFileProvider _pubFileProvider; - private readonly IInventorySlotRepository _inventorySlotRepository; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITrainingController _trainingController; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IItemStringService _itemStringService; - private readonly IItemNameColorService _itemNameColorService; - private readonly IInventoryService _inventoryService; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly IConfigurationRepository _configurationRepository; - private readonly IOnlinePlayerProvider _onlinePlayerProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IAudioActions _audioActions; - private readonly ISfxPlayer _sfxPlayer; - private readonly IPartyActions _partyActions; - private readonly IPartyDataProvider _partyDataProvider; - private readonly IConfigurationProvider _configurationProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - - public HudPanelFactory(INativeGraphicsManager nativeGraphicsManager, - IInventoryController inventoryController, - IChatActions chatActions, - IContentProvider contentProvider, - IHudControlProvider hudControlProvider, - INewsProvider newsProvider, - IChatProvider chatProvider, - IPlayerInfoProvider playerInfoProvider, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IExperienceTableProvider experienceTableProvider, - IPubFileProvider pubFileProvider, - IInventorySlotRepository inventorySlotRepository, - IEOMessageBoxFactory messageBoxFactory, - ITrainingController trainingController, - IFriendIgnoreListService friendIgnoreListService, - IStatusLabelSetter statusLabelSetter, - IItemStringService itemStringService, - IItemNameColorService itemNameColorService, - IInventoryService inventoryService, - IActiveDialogProvider activeDialogProvider, - ISpellSlotDataRepository spellSlotDataRepository, - IConfigurationRepository configurationRepository, - IOnlinePlayerProvider onlinePlayerProvider, - ILocalizedStringFinder localizedStringFinder, - IAudioActions audioActions, - ISfxPlayer sfxPlayer, - IPartyActions partyActions, - IPartyDataProvider partyDataProvider, - IConfigurationProvider configurationProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _inventoryController = inventoryController; - _chatActions = chatActions; - _contentProvider = contentProvider; - _hudControlProvider = hudControlProvider; - _newsProvider = newsProvider; - _chatProvider = chatProvider; - _playerInfoProvider = playerInfoProvider; - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _experienceTableProvider = experienceTableProvider; - _pubFileProvider = pubFileProvider; - _inventorySlotRepository = inventorySlotRepository; - _messageBoxFactory = messageBoxFactory; - _trainingController = trainingController; - _friendIgnoreListService = friendIgnoreListService; - _statusLabelSetter = statusLabelSetter; - _itemStringService = itemStringService; - _itemNameColorService = itemNameColorService; - _inventoryService = inventoryService; - _activeDialogProvider = activeDialogProvider; - _spellSlotDataRepository = spellSlotDataRepository; - _configurationRepository = configurationRepository; - _onlinePlayerProvider = onlinePlayerProvider; - _localizedStringFinder = localizedStringFinder; - _audioActions = audioActions; - _sfxPlayer = sfxPlayer; - _partyActions = partyActions; - _partyDataProvider = partyDataProvider; - _configurationProvider = configurationProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - } - - public NewsPanel CreateNewsPanel() - { - var chatFont = _contentProvider.Fonts[Constants.FontSize08]; - - return new NewsPanel(_nativeGraphicsManager, - new ChatRenderableGenerator(_nativeGraphicsManager, _friendIgnoreListService, chatFont), - _newsProvider, - chatFont, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public InventoryPanel CreateInventoryPanel() - { - return new InventoryPanel(_nativeGraphicsManager, - _inventoryController, - _statusLabelSetter, - _itemStringService, - _itemNameColorService, - _inventoryService, - _inventorySlotRepository, - _playerInfoProvider, - _characterProvider, - _characterInventoryProvider, - _pubFileProvider, - _hudControlProvider, - _activeDialogProvider, - _sfxPlayer, - _configurationProvider, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public ActiveSpellsPanel CreateActiveSpellsPanel() - { - return new ActiveSpellsPanel(_nativeGraphicsManager, - _trainingController, - _messageBoxFactory, - _statusLabelSetter, - _playerInfoProvider, - _characterProvider, - _characterInventoryProvider, - _pubFileProvider, - _spellSlotDataRepository, - _hudControlProvider, - _sfxPlayer, - _configurationProvider, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public PassiveSpellsPanel CreatePassiveSpellsPanel() - { - return new PassiveSpellsPanel(_nativeGraphicsManager, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; - } - - public ChatPanel CreateChatPanel() - { - var chatFont = _contentProvider.Fonts[Constants.FontSize08]; - - return new ChatPanel(_nativeGraphicsManager, - _chatActions, - new ChatRenderableGenerator(_nativeGraphicsManager, _friendIgnoreListService, chatFont), - _chatProvider, - _hudControlProvider, - chatFont, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public StatsPanel CreateStatsPanel() - { - return new StatsPanel(_nativeGraphicsManager, - _characterProvider, - _characterInventoryProvider, - _experienceTableProvider, - _messageBoxFactory, - _trainingController, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public OnlineListPanel CreateOnlineListPanel() - { - var chatFont = _contentProvider.Fonts[Constants.FontSize08]; - return new OnlineListPanel(_nativeGraphicsManager, _hudControlProvider, _onlinePlayerProvider, _partyDataProvider, _friendIgnoreListService, _sfxPlayer, chatFont, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; - } - - public PartyPanel CreatePartyPanel() - { - return new PartyPanel(_nativeGraphicsManager, _partyActions, _contentProvider, _partyDataProvider, _characterProvider, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; - } - - public SettingsPanel CreateSettingsPanel() - { - return new SettingsPanel(_nativeGraphicsManager, - _chatActions, - _audioActions, - _statusLabelSetter, - _localizedStringFinder, - _messageBoxFactory, - _configurationRepository, - _sfxPlayer, - _clientWindowSizeProvider) - { DrawOrder = HUD_CONTROL_LAYER }; - } - - public HelpPanel CreateHelpPanel() + [MappedType(BaseType = typeof(IHudPanelFactory))] + public class HudPanelFactory : IHudPanelFactory { - return new HelpPanel(_nativeGraphicsManager, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + private const int HUD_CONTROL_LAYER = 130; + + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IInventoryController _inventoryController; + private readonly IChatActions _chatActions; + private readonly IContentProvider _contentProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly INewsProvider _newsProvider; + private readonly IChatProvider _chatProvider; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IExperienceTableProvider _experienceTableProvider; + private readonly IPubFileProvider _pubFileProvider; + private readonly IInventorySlotRepository _inventorySlotRepository; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITrainingController _trainingController; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IItemStringService _itemStringService; + private readonly IItemNameColorService _itemNameColorService; + private readonly IInventoryService _inventoryService; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly IConfigurationRepository _configurationRepository; + private readonly IOnlinePlayerProvider _onlinePlayerProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IAudioActions _audioActions; + private readonly ISfxPlayer _sfxPlayer; + private readonly IPartyActions _partyActions; + private readonly IPartyDataProvider _partyDataProvider; + private readonly IConfigurationProvider _configurationProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + + public HudPanelFactory(INativeGraphicsManager nativeGraphicsManager, + IInventoryController inventoryController, + IChatActions chatActions, + IContentProvider contentProvider, + IHudControlProvider hudControlProvider, + INewsProvider newsProvider, + IChatProvider chatProvider, + IPlayerInfoProvider playerInfoProvider, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IExperienceTableProvider experienceTableProvider, + IPubFileProvider pubFileProvider, + IInventorySlotRepository inventorySlotRepository, + IEOMessageBoxFactory messageBoxFactory, + ITrainingController trainingController, + IFriendIgnoreListService friendIgnoreListService, + IStatusLabelSetter statusLabelSetter, + IItemStringService itemStringService, + IItemNameColorService itemNameColorService, + IInventoryService inventoryService, + IActiveDialogProvider activeDialogProvider, + ISpellSlotDataRepository spellSlotDataRepository, + IConfigurationRepository configurationRepository, + IOnlinePlayerProvider onlinePlayerProvider, + ILocalizedStringFinder localizedStringFinder, + IAudioActions audioActions, + ISfxPlayer sfxPlayer, + IPartyActions partyActions, + IPartyDataProvider partyDataProvider, + IConfigurationProvider configurationProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _inventoryController = inventoryController; + _chatActions = chatActions; + _contentProvider = contentProvider; + _hudControlProvider = hudControlProvider; + _newsProvider = newsProvider; + _chatProvider = chatProvider; + _playerInfoProvider = playerInfoProvider; + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _experienceTableProvider = experienceTableProvider; + _pubFileProvider = pubFileProvider; + _inventorySlotRepository = inventorySlotRepository; + _messageBoxFactory = messageBoxFactory; + _trainingController = trainingController; + _friendIgnoreListService = friendIgnoreListService; + _statusLabelSetter = statusLabelSetter; + _itemStringService = itemStringService; + _itemNameColorService = itemNameColorService; + _inventoryService = inventoryService; + _activeDialogProvider = activeDialogProvider; + _spellSlotDataRepository = spellSlotDataRepository; + _configurationRepository = configurationRepository; + _onlinePlayerProvider = onlinePlayerProvider; + _localizedStringFinder = localizedStringFinder; + _audioActions = audioActions; + _sfxPlayer = sfxPlayer; + _partyActions = partyActions; + _partyDataProvider = partyDataProvider; + _configurationProvider = configurationProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + } + + public NewsPanel CreateNewsPanel() + { + var chatFont = _contentProvider.Fonts[Constants.FontSize08]; + + return new NewsPanel(_nativeGraphicsManager, + new ChatRenderableGenerator(_nativeGraphicsManager, _friendIgnoreListService, chatFont), + _newsProvider, + chatFont, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public InventoryPanel CreateInventoryPanel() + { + return new InventoryPanel(_nativeGraphicsManager, + _inventoryController, + _statusLabelSetter, + _itemStringService, + _itemNameColorService, + _inventoryService, + _inventorySlotRepository, + _playerInfoProvider, + _characterProvider, + _characterInventoryProvider, + _pubFileProvider, + _hudControlProvider, + _activeDialogProvider, + _sfxPlayer, + _configurationProvider, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public ActiveSpellsPanel CreateActiveSpellsPanel() + { + return new ActiveSpellsPanel(_nativeGraphicsManager, + _trainingController, + _messageBoxFactory, + _statusLabelSetter, + _playerInfoProvider, + _characterProvider, + _characterInventoryProvider, + _pubFileProvider, + _spellSlotDataRepository, + _hudControlProvider, + _sfxPlayer, + _configurationProvider, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public PassiveSpellsPanel CreatePassiveSpellsPanel() + { + return new PassiveSpellsPanel(_nativeGraphicsManager, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + } + + public ChatPanel CreateChatPanel() + { + var chatFont = _contentProvider.Fonts[Constants.FontSize08]; + + return new ChatPanel(_nativeGraphicsManager, + _chatActions, + new ChatRenderableGenerator(_nativeGraphicsManager, _friendIgnoreListService, chatFont), + _chatProvider, + _hudControlProvider, + chatFont, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public StatsPanel CreateStatsPanel() + { + return new StatsPanel(_nativeGraphicsManager, + _characterProvider, + _characterInventoryProvider, + _experienceTableProvider, + _messageBoxFactory, + _trainingController, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public OnlineListPanel CreateOnlineListPanel() + { + var chatFont = _contentProvider.Fonts[Constants.FontSize08]; + return new OnlineListPanel(_nativeGraphicsManager, _hudControlProvider, _onlinePlayerProvider, _partyDataProvider, _friendIgnoreListService, _sfxPlayer, chatFont, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + } + + public PartyPanel CreatePartyPanel() + { + return new PartyPanel(_nativeGraphicsManager, _partyActions, _contentProvider, _partyDataProvider, _characterProvider, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + } + + public SettingsPanel CreateSettingsPanel() + { + return new SettingsPanel(_nativeGraphicsManager, + _chatActions, + _audioActions, + _statusLabelSetter, + _localizedStringFinder, + _messageBoxFactory, + _configurationRepository, + _sfxPlayer, + _clientWindowSizeProvider) + { DrawOrder = HUD_CONTROL_LAYER }; + } + + public HelpPanel CreateHelpPanel() + { + return new HelpPanel(_nativeGraphicsManager, _clientWindowSizeProvider) { DrawOrder = HUD_CONTROL_LAYER }; + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/IHudPanel.cs b/EndlessClient/HUD/Panels/IHudPanel.cs index be4cdb34b..e380c4618 100644 --- a/EndlessClient/HUD/Panels/IHudPanel.cs +++ b/EndlessClient/HUD/Panels/IHudPanel.cs @@ -2,21 +2,22 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Panels; - -public interface IHudPanel : IGameComponent +namespace EndlessClient.HUD.Panels { - bool Visible { get; set; } + public interface IHudPanel : IGameComponent + { + bool Visible { get; set; } - int UpdateOrder { get; set; } + int UpdateOrder { get; set; } - int DrawOrder { get; set; } + int DrawOrder { get; set; } - Vector2 DrawPosition { get; set; } + Vector2 DrawPosition { get; set; } - Rectangle DrawArea { get; set; } + Rectangle DrawArea { get; set; } - bool IsBeingDragged { get; } + bool IsBeingDragged { get; } - event Action DragCompleted; + event Action DragCompleted; + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/IHudPanelFactory.cs b/EndlessClient/HUD/Panels/IHudPanelFactory.cs index bc7208317..eec471e9d 100644 --- a/EndlessClient/HUD/Panels/IHudPanelFactory.cs +++ b/EndlessClient/HUD/Panels/IHudPanelFactory.cs @@ -1,24 +1,25 @@ -namespace EndlessClient.HUD.Panels; - -public interface IHudPanelFactory +namespace EndlessClient.HUD.Panels { - NewsPanel CreateNewsPanel(); + public interface IHudPanelFactory + { + NewsPanel CreateNewsPanel(); - InventoryPanel CreateInventoryPanel(); + InventoryPanel CreateInventoryPanel(); - ActiveSpellsPanel CreateActiveSpellsPanel(); + ActiveSpellsPanel CreateActiveSpellsPanel(); - PassiveSpellsPanel CreatePassiveSpellsPanel(); + PassiveSpellsPanel CreatePassiveSpellsPanel(); - ChatPanel CreateChatPanel(); + ChatPanel CreateChatPanel(); - StatsPanel CreateStatsPanel(); + StatsPanel CreateStatsPanel(); - OnlineListPanel CreateOnlineListPanel(); + OnlineListPanel CreateOnlineListPanel(); - PartyPanel CreatePartyPanel(); + PartyPanel CreatePartyPanel(); - SettingsPanel CreateSettingsPanel(); + SettingsPanel CreateSettingsPanel(); - HelpPanel CreateHelpPanel(); + HelpPanel CreateHelpPanel(); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/InventoryPanel.cs b/EndlessClient/HUD/Panels/InventoryPanel.cs index 45fe1b3e7..aa3abf31d 100644 --- a/EndlessClient/HUD/Panels/InventoryPanel.cs +++ b/EndlessClient/HUD/Panels/InventoryPanel.cs @@ -32,533 +32,534 @@ using System.Runtime.Versioning; using XNAControls; -namespace EndlessClient.HUD.Panels; - -public class InventoryPanel : DraggableHudPanel, IHudPanel, IDraggableItemContainer +namespace EndlessClient.HUD.Panels { - public const int InventoryRows = 4; - public const int InventoryRowSlots = 14; - - private readonly IInventoryController _inventoryController; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IItemStringService _itemStringService; - private readonly IItemNameColorService _itemNameColorService; - private readonly IInventoryService _inventoryService; - private readonly IInventorySlotRepository _inventorySlotRepository; - private readonly IPlayerInfoProvider _playerInfoProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IPubFileProvider _pubFileProvider; // todo: this can probably become EIFFileProvider - private readonly IHudControlProvider _hudControlProvider; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IConfigurationProvider _configProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly List _childItems = new List(); - - private readonly IXNALabel _weightLabel; - private readonly IXNAButton _drop, _junk, _paperdoll; - //private readonly ScrollBar _scrollBar; - - private Option _cachedStats; - private HashSet _cachedInventory; - - public INativeGraphicsManager NativeGraphicsManager { get; } - - public InventoryPanel(INativeGraphicsManager nativeGraphicsManager, - IInventoryController inventoryController, - IStatusLabelSetter statusLabelSetter, - IItemStringService itemStringService, - IItemNameColorService itemNameColorService, - IInventoryService inventoryService, - IInventorySlotRepository inventorySlotRepository, - IPlayerInfoProvider playerInfoProvider, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IPubFileProvider pubFileProvider, - IHudControlProvider hudControlProvider, - IActiveDialogProvider activeDialogProvider, - ISfxPlayer sfxPlayer, - IConfigurationProvider configProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + public class InventoryPanel : DraggableHudPanel, IHudPanel, IDraggableItemContainer { - NativeGraphicsManager = nativeGraphicsManager; - _inventoryController = inventoryController; - _statusLabelSetter = statusLabelSetter; - _itemStringService = itemStringService; - _itemNameColorService = itemNameColorService; - _inventoryService = inventoryService; - _inventorySlotRepository = inventorySlotRepository; - _playerInfoProvider = playerInfoProvider; - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _pubFileProvider = pubFileProvider; - _hudControlProvider = hudControlProvider; - _activeDialogProvider = activeDialogProvider; - _sfxPlayer = sfxPlayer; - _configProvider = configProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - - _weightLabel = new XNALabel(Constants.FontSize08pt5) + public const int InventoryRows = 4; + public const int InventoryRowSlots = 14; + + private readonly IInventoryController _inventoryController; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IItemStringService _itemStringService; + private readonly IItemNameColorService _itemNameColorService; + private readonly IInventoryService _inventoryService; + private readonly IInventorySlotRepository _inventorySlotRepository; + private readonly IPlayerInfoProvider _playerInfoProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IPubFileProvider _pubFileProvider; // todo: this can probably become EIFFileProvider + private readonly IHudControlProvider _hudControlProvider; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IConfigurationProvider _configProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly List _childItems = new List(); + + private readonly IXNALabel _weightLabel; + private readonly IXNAButton _drop, _junk, _paperdoll; + //private readonly ScrollBar _scrollBar; + + private Option _cachedStats; + private HashSet _cachedInventory; + + public INativeGraphicsManager NativeGraphicsManager { get; } + + public InventoryPanel(INativeGraphicsManager nativeGraphicsManager, + IInventoryController inventoryController, + IStatusLabelSetter statusLabelSetter, + IItemStringService itemStringService, + IItemNameColorService itemNameColorService, + IInventoryService inventoryService, + IInventorySlotRepository inventorySlotRepository, + IPlayerInfoProvider playerInfoProvider, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IPubFileProvider pubFileProvider, + IHudControlProvider hudControlProvider, + IActiveDialogProvider activeDialogProvider, + ISfxPlayer sfxPlayer, + IConfigurationProvider configProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - DrawArea = new Rectangle(385, 37, 88, 18), - ForeColor = ColorConstants.LightGrayText, - TextAlign = LabelAlignment.MiddleCenter, - Visible = true, - AutoSize = false - }; - - _inventorySlotRepository.SlotMap = GetItemSlotMap(_playerInfoProvider.LoggedInAccountName, _characterProvider.MainCharacter.Name, _configProvider.Host); + NativeGraphicsManager = nativeGraphicsManager; + _inventoryController = inventoryController; + _statusLabelSetter = statusLabelSetter; + _itemStringService = itemStringService; + _itemNameColorService = itemNameColorService; + _inventoryService = inventoryService; + _inventorySlotRepository = inventorySlotRepository; + _playerInfoProvider = playerInfoProvider; + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _pubFileProvider = pubFileProvider; + _hudControlProvider = hudControlProvider; + _activeDialogProvider = activeDialogProvider; + _sfxPlayer = sfxPlayer; + _configProvider = configProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + + _weightLabel = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = new Rectangle(385, 37, 88, 18), + ForeColor = ColorConstants.LightGrayText, + TextAlign = LabelAlignment.MiddleCenter, + Visible = true, + AutoSize = false + }; - var weirdOffsetSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); + _inventorySlotRepository.SlotMap = GetItemSlotMap(_playerInfoProvider.LoggedInAccountName, _characterProvider.MainCharacter.Name, _configProvider.Host); - _paperdoll = new XNAButton(weirdOffsetSheet, new Vector2(385, 9), new Rectangle(39, 385, 88, 19), new Rectangle(126, 385, 88, 19)); - _paperdoll.OnMouseEnter += MouseOverButton; - _paperdoll.OnClick += (_, _) => - { - _inventoryController.ShowPaperdollDialog(); - _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); - }; + var weirdOffsetSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27); - _drop = new XNAButton(weirdOffsetSheet, new Vector2(389, 68), new Rectangle(0, 15, 38, 37), new Rectangle(0, 52, 38, 37)); - _drop.OnMouseEnter += MouseOverButton; - _drop.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + _paperdoll = new XNAButton(weirdOffsetSheet, new Vector2(385, 9), new Rectangle(39, 385, 88, 19), new Rectangle(126, 385, 88, 19)); + _paperdoll.OnMouseEnter += MouseOverButton; + _paperdoll.OnClick += (_, _) => + { + _inventoryController.ShowPaperdollDialog(); + _sfxPlayer.PlaySfx(SoundEffectID.ButtonClick); + }; - _junk = new XNAButton(weirdOffsetSheet, new Vector2(431, 68), new Rectangle(0, 89, 38, 37), new Rectangle(0, 126, 38, 37)); - _junk.OnMouseEnter += MouseOverButton; - _junk.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + _drop = new XNAButton(weirdOffsetSheet, new Vector2(389, 68), new Rectangle(0, 15, 38, 37), new Rectangle(0, 52, 38, 37)); + _drop.OnMouseEnter += MouseOverButton; + _drop.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - _cachedStats = Option.None(); - _cachedInventory = new HashSet(); + _junk = new XNAButton(weirdOffsetSheet, new Vector2(431, 68), new Rectangle(0, 89, 38, 37), new Rectangle(0, 126, 38, 37)); + _junk.OnMouseEnter += MouseOverButton; + _junk.OnClick += (_, _) => _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - BackgroundImage = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 44); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + _cachedStats = Option.None(); + _cachedInventory = new HashSet(); - Game.Exiting += SaveInventoryFile; - } + BackgroundImage = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 44); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - public bool NoItemsDragging() => _childItems.All(x => !x.IsDragging); + Game.Exiting += SaveInventoryFile; + } - public override void Initialize() - { - _weightLabel.Initialize(); - _weightLabel.SetParentControl(this); + public bool NoItemsDragging() => _childItems.All(x => !x.IsDragging); - _paperdoll.Initialize(); - _paperdoll.SetParentControl(this); + public override void Initialize() + { + _weightLabel.Initialize(); + _weightLabel.SetParentControl(this); - _drop.Initialize(); - _drop.SetParentControl(this); + _paperdoll.Initialize(); + _paperdoll.SetParentControl(this); - _junk.Initialize(); - _junk.SetParentControl(this); + _drop.Initialize(); + _drop.SetParentControl(this); - OnUpdateControl(new GameTime()); - _inventorySlotRepository.SlotMap.Clear(); + _junk.Initialize(); + _junk.SetParentControl(this); - base.Initialize(); - } + OnUpdateControl(new GameTime()); + _inventorySlotRepository.SlotMap.Clear(); - protected override void OnDrawOrderChanged(object sender, EventArgs args) - { - base.OnDrawOrderChanged(sender, args); + base.Initialize(); + } - if (_clientWindowSizeProvider.Resizable) + protected override void OnDrawOrderChanged(object sender, EventArgs args) { - // ensure labels have a high enough draw order when in resizable mode - // this is because draw order is updated when panels are opened in resizable mode - foreach (var label in ChildControls.OfType()) - label.DrawOrder = DrawOrder + 70; - } - } + base.OnDrawOrderChanged(sender, args); - protected override void OnUnconditionalUpdateControl(GameTime gameTime) - { - _cachedStats.Match( - some: stats => - { - stats.SomeWhen(s => s != _characterProvider.MainCharacter.Stats) - .MatchSome(_ => - { - var newStats = _characterProvider.MainCharacter.Stats; - _cachedStats = Option.Some(newStats); - _weightLabel.Text = $"{newStats[CharacterStat.Weight]} / {newStats[CharacterStat.MaxWeight]}"; - }); - }, - none: () => + if (_clientWindowSizeProvider.Resizable) { - var stats = _characterProvider.MainCharacter.Stats; - _cachedStats = Option.Some(stats); - _weightLabel.Text = $"{stats[CharacterStat.Weight]} / {stats[CharacterStat.MaxWeight]}"; - }); + // ensure labels have a high enough draw order when in resizable mode + // this is because draw order is updated when panels are opened in resizable mode + foreach (var label in ChildControls.OfType()) + label.DrawOrder = DrawOrder + 70; + } + } - if (!_cachedInventory.SetEquals(_characterInventoryProvider.ItemInventory)) + protected override void OnUnconditionalUpdateControl(GameTime gameTime) { - var added = _characterInventoryProvider.ItemInventory.Where(i => !_cachedInventory.Any(j => i.ItemID == j.ItemID)); - var removed = _cachedInventory.Where(i => !_characterInventoryProvider.ItemInventory.Any(j => i.ItemID == j.ItemID)); - var updated = _characterInventoryProvider.ItemInventory.Except(added) - .Where(i => _cachedInventory.Any(j => i.ItemID == j.ItemID && i.Amount != j.Amount)); - - foreach (var item in removed) - { - var matchedItem = _childItems.SingleOrNone(x => x.InventoryItem.ItemID == item.ItemID); - matchedItem.MatchSome(childItem => + _cachedStats.Match( + some: stats => { - childItem.SetControlUnparented(); - childItem.Dispose(); - _childItems.Remove(childItem); - - var itemData = _pubFileProvider.EIFFile[item.ItemID]; - _inventoryService.ClearSlots(_inventorySlotRepository.FilledSlots, childItem.Slot, itemData.Size); + stats.SomeWhen(s => s != _characterProvider.MainCharacter.Stats) + .MatchSome(_ => + { + var newStats = _characterProvider.MainCharacter.Stats; + _cachedStats = Option.Some(newStats); + _weightLabel.Text = $"{newStats[CharacterStat.Weight]} / {newStats[CharacterStat.MaxWeight]}"; + }); + }, + none: () => + { + var stats = _characterProvider.MainCharacter.Stats; + _cachedStats = Option.Some(stats); + _weightLabel.Text = $"{stats[CharacterStat.Weight]} / {stats[CharacterStat.MaxWeight]}"; }); - } - foreach (var item in updated) + if (!_cachedInventory.SetEquals(_characterInventoryProvider.ItemInventory)) { - var itemData = _pubFileProvider.EIFFile[item.ItemID]; + var added = _characterInventoryProvider.ItemInventory.Where(i => !_cachedInventory.Any(j => i.ItemID == j.ItemID)); + var removed = _cachedInventory.Where(i => !_characterInventoryProvider.ItemInventory.Any(j => i.ItemID == j.ItemID)); + var updated = _characterInventoryProvider.ItemInventory.Except(added) + .Where(i => _cachedInventory.Any(j => i.ItemID == j.ItemID && i.Amount != j.Amount)); - var matchedItem = _childItems.SingleOrNone(x => x.InventoryItem.ItemID == item.ItemID); - matchedItem.MatchSome(childItem => + foreach (var item in removed) { - childItem.InventoryItem = item; - childItem.Text = _itemStringService.GetStringForInventoryDisplay(itemData, item.Amount); - }); - } + var matchedItem = _childItems.SingleOrNone(x => x.InventoryItem.ItemID == item.ItemID); + matchedItem.MatchSome(childItem => + { + childItem.SetControlUnparented(); + childItem.Dispose(); + _childItems.Remove(childItem); - foreach (var item in added) - { - var itemData = _pubFileProvider.EIFFile[item.ItemID]; + var itemData = _pubFileProvider.EIFFile[item.ItemID]; + _inventoryService.ClearSlots(_inventorySlotRepository.FilledSlots, childItem.Slot, itemData.Size); + }); + } - var preferredSlot = _inventorySlotRepository.SlotMap.SingleOrNone(x => x.Value == item.ItemID).Map(x => x.Key); - var actualSlot = _inventoryService.GetNextOpenSlot(_inventorySlotRepository.FilledSlots, itemData.Size, preferredSlot); + foreach (var item in updated) + { + var itemData = _pubFileProvider.EIFFile[item.ItemID]; + + var matchedItem = _childItems.SingleOrNone(x => x.InventoryItem.ItemID == item.ItemID); + matchedItem.MatchSome(childItem => + { + childItem.InventoryItem = item; + childItem.Text = _itemStringService.GetStringForInventoryDisplay(itemData, item.Amount); + }); + } - actualSlot.MatchSome(slot => + foreach (var item in added) { - _inventoryService.SetSlots(_inventorySlotRepository.FilledSlots, slot, itemData.Size); + var itemData = _pubFileProvider.EIFFile[item.ItemID]; - var newItem = new InventoryPanelItem(_itemNameColorService, this, _activeDialogProvider, _sfxPlayer, slot, item, itemData); - newItem.Initialize(); - newItem.SetParentControl(this); - newItem.Text = _itemStringService.GetStringForInventoryDisplay(itemData, item.Amount); + var preferredSlot = _inventorySlotRepository.SlotMap.SingleOrNone(x => x.Value == item.ItemID).Map(x => x.Key); + var actualSlot = _inventoryService.GetNextOpenSlot(_inventorySlotRepository.FilledSlots, itemData.Size, preferredSlot); - newItem.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ITEM, newItem.Text); - newItem.DoubleClick += HandleItemDoubleClick; - newItem.DraggingFinishing += HandleItemDoneDragging; - newItem.DraggingFinished += (_, _) => ResetSlotMap(_childItems.Where(x => !x.IsDragging)); + actualSlot.MatchSome(slot => + { + _inventoryService.SetSlots(_inventorySlotRepository.FilledSlots, slot, itemData.Size); - // side-effect of calling newItem.SetParentControl(this) is that the draw order gets reset - // setting the slot manually here resets it so the item labels render appropriately - newItem.Slot = slot; + var newItem = new InventoryPanelItem(_itemNameColorService, this, _activeDialogProvider, _sfxPlayer, slot, item, itemData); + newItem.Initialize(); + newItem.SetParentControl(this); + newItem.Text = _itemStringService.GetStringForInventoryDisplay(itemData, item.Amount); - _childItems.Add(newItem); - }); - } + newItem.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ITEM, newItem.Text); + newItem.DoubleClick += HandleItemDoubleClick; + newItem.DraggingFinishing += HandleItemDoneDragging; + newItem.DraggingFinished += (_, _) => ResetSlotMap(_childItems.Where(x => !x.IsDragging)); - _cachedInventory = _characterInventoryProvider.ItemInventory.ToHashSet(); + // side-effect of calling newItem.SetParentControl(this) is that the draw order gets reset + // setting the slot manually here resets it so the item labels render appropriately + newItem.Slot = slot; - if (removed.Any()) - { - RemoveHiddenItemsFromCachedInventory(); + _childItems.Add(newItem); + }); + } + + _cachedInventory = _characterInventoryProvider.ItemInventory.ToHashSet(); + + if (removed.Any()) + { + RemoveHiddenItemsFromCachedInventory(); + } } - } - base.OnUpdateControl(gameTime); - } + base.OnUpdateControl(gameTime); + } - protected override void Dispose(bool disposing) - { - if (disposing) + protected override void Dispose(bool disposing) { - _paperdoll.OnMouseEnter -= MouseOverButton; - _drop.OnMouseEnter -= MouseOverButton; - _junk.OnMouseEnter -= MouseOverButton; - Game.Exiting -= SaveInventoryFile; + if (disposing) + { + _paperdoll.OnMouseEnter -= MouseOverButton; + _drop.OnMouseEnter -= MouseOverButton; + _junk.OnMouseEnter -= MouseOverButton; + Game.Exiting -= SaveInventoryFile; - // todo: IResettable should work but it doesn't - _inventorySlotRepository.FilledSlots = new Matrix(InventoryRows, InventoryRowSlots, false); + // todo: IResettable should work but it doesn't + _inventorySlotRepository.FilledSlots = new Matrix(InventoryRows, InventoryRowSlots, false); - SaveInventoryFile(null, EventArgs.Empty); - } - - base.Dispose(disposing); - } + SaveInventoryFile(null, EventArgs.Empty); + } - private void MouseOverButton(object sender, MouseStateExtended e) - { - var id = sender == _paperdoll - ? EOResourceID.STATUS_LABEL_INVENTORY_SHOW_YOUR_PAPERDOLL - : sender == _drop - ? EOResourceID.STATUS_LABEL_INVENTORY_DROP_BUTTON - : EOResourceID.STATUS_LABEL_INVENTORY_JUNK_BUTTON; - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, id); - } + base.Dispose(disposing); + } - private static Dictionary GetItemSlotMap(string accountName, string characterName, string host) - { - var map = new Dictionary(); + private void MouseOverButton(object sender, MouseStateExtended e) + { + var id = sender == _paperdoll + ? EOResourceID.STATUS_LABEL_INVENTORY_SHOW_YOUR_PAPERDOLL + : sender == _drop + ? EOResourceID.STATUS_LABEL_INVENTORY_DROP_BUTTON + : EOResourceID.STATUS_LABEL_INVENTORY_JUNK_BUTTON; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, id); + } - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !File.Exists(Constants.InventoryFile)) + private static Dictionary GetItemSlotMap(string accountName, string characterName, string host) { - using var registryInventoryKey = TryGetCharacterRegistryKey(accountName, characterName); - if (registryInventoryKey != null) + var map = new Dictionary(); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !File.Exists(Constants.InventoryFile)) { - for (int i = 0; i < InventoryRowSlots * 4; ++i) + using var registryInventoryKey = TryGetCharacterRegistryKey(accountName, characterName); + if (registryInventoryKey != null) { - if (int.TryParse(registryInventoryKey.GetValue($"item{i}")?.ToString() ?? string.Empty, out var id)) - map[i] = id; + for (int i = 0; i < InventoryRowSlots * 4; ++i) + { + if (int.TryParse(registryInventoryKey.GetValue($"item{i}")?.ToString() ?? string.Empty, out var id)) + map[i] = id; + } } } - } - var inventory = new IniReader(Constants.InventoryFile); - var inventoryKey = $"{host}:{accountName}"; - if (inventory.Load() && inventory.Sections.ContainsKey(inventoryKey)) - { - var section = inventory.Sections[inventoryKey]; - foreach (var key in section.Keys.Where(x => x.Contains(characterName, StringComparison.OrdinalIgnoreCase))) + var inventory = new IniReader(Constants.InventoryFile); + var inventoryKey = $"{host}:{accountName}"; + if (inventory.Load() && inventory.Sections.ContainsKey(inventoryKey)) { - if (!key.Contains(".")) - continue; + var section = inventory.Sections[inventoryKey]; + foreach (var key in section.Keys.Where(x => x.Contains(characterName, StringComparison.OrdinalIgnoreCase))) + { + if (!key.Contains(".")) + continue; - var slot = key.Split(".")[1]; - if (!int.TryParse(slot, out var slotIndex)) - continue; + var slot = key.Split(".")[1]; + if (!int.TryParse(slot, out var slotIndex)) + continue; - if (int.TryParse(section[key], out var id)) - map[slotIndex] = id; + if (int.TryParse(section[key], out var id)) + map[slotIndex] = id; + } } + + return map; } - return map; - } + [SupportedOSPlatform("Windows")] + private static RegistryKey TryGetCharacterRegistryKey(string accountName, string characterName) + { + using RegistryKey currentUser = Registry.CurrentUser; - [SupportedOSPlatform("Windows")] - private static RegistryKey TryGetCharacterRegistryKey(string accountName, string characterName) - { - using RegistryKey currentUser = Registry.CurrentUser; + var pathSegments = $"Software\\EndlessClient\\{accountName}\\{characterName}\\inventory".Split('\\'); + var currentPath = string.Empty; - var pathSegments = $"Software\\EndlessClient\\{accountName}\\{characterName}\\inventory".Split('\\'); - var currentPath = string.Empty; + RegistryKey retKey = null; + foreach (var segment in pathSegments) + { + retKey?.Dispose(); - RegistryKey retKey = null; - foreach (var segment in pathSegments) - { - retKey?.Dispose(); + currentPath = Path.Combine(currentPath, segment); + retKey = currentUser.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadSubTree); + } - currentPath = Path.Combine(currentPath, segment); - retKey = currentUser.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadSubTree); + return retKey; } - return retKey; - } - - private void SaveInventoryFile(object sender, EventArgs e) - { - var inventory = new IniReader(Constants.InventoryFile); - var inventoryKey = $"{_configProvider.Host}:{_playerInfoProvider.LoggedInAccountName}"; + private void SaveInventoryFile(object sender, EventArgs e) + { + var inventory = new IniReader(Constants.InventoryFile); + var inventoryKey = $"{_configProvider.Host}:{_playerInfoProvider.LoggedInAccountName}"; - var section = inventory.Load() && inventory.Sections.ContainsKey(inventoryKey) - ? inventory.Sections[inventoryKey] - : new SortedList(); + var section = inventory.Load() && inventory.Sections.ContainsKey(inventoryKey) + ? inventory.Sections[inventoryKey] + : new SortedList(); - var existing = section.Where(x => x.Key.Contains(_characterProvider.MainCharacter.Name)).Select(x => x.Key).ToList(); - foreach (var key in existing) - section.Remove(key); + var existing = section.Where(x => x.Key.Contains(_characterProvider.MainCharacter.Name)).Select(x => x.Key).ToList(); + foreach (var key in existing) + section.Remove(key); - foreach (var item in _childItems) - section[$"{_characterProvider.MainCharacter.Name}.{item.Slot}"] = $"{item.InventoryItem.ItemID}"; + foreach (var item in _childItems) + section[$"{_characterProvider.MainCharacter.Name}.{item.Slot}"] = $"{item.InventoryItem.ItemID}"; - inventory.Sections[inventoryKey] = section; + inventory.Sections[inventoryKey] = section; - inventory.Save(); - } + inventory.Save(); + } - private void HandleItemDoubleClick(object sender, EIFRecord itemData) - { - if (itemData.Type >= ItemType.Weapon && itemData.Type <= ItemType.Bracer) + private void HandleItemDoubleClick(object sender, EIFRecord itemData) { - _inventoryController.EquipItem(itemData); + if (itemData.Type >= ItemType.Weapon && itemData.Type <= ItemType.Bracer) + { + _inventoryController.EquipItem(itemData); + } + else + { + _inventoryController.UseItem(itemData); + } + + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); } - else + + private void HandleItemDoneDragging(object sender, DragCompletedEventArgs e) { - _inventoryController.UseItem(itemData); - } + var item = sender as InventoryPanelItem; + if (item == null) + return; - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - } + ResetSlotMap(_childItems.Where(x => !x.IsDragging)); - private void HandleItemDoneDragging(object sender, DragCompletedEventArgs e) - { - var item = sender as InventoryPanelItem; - if (item == null) - return; + var oldSlot = item.Slot; + var fitsInOldSlot = _inventoryService.FitsInSlot(_inventorySlotRepository.FilledSlots, oldSlot, e.Data.Size); - ResetSlotMap(_childItems.Where(x => !x.IsDragging)); + if (_activeDialogProvider.ActiveDialogs.All(x => !x.HasValue)) + { + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + if (mapRenderer.MouseOver && !MouseOver) + { + e.ContinueDrag = !fitsInOldSlot; + e.RestoreOriginalSlot = fitsInOldSlot; - var oldSlot = item.Slot; - var fitsInOldSlot = _inventoryService.FitsInSlot(_inventorySlotRepository.FilledSlots, oldSlot, e.Data.Size); + _inventoryController.DropItem(item.Data, item.InventoryItem, mapRenderer.GridCoordinates); + return; + } + } - if (_activeDialogProvider.ActiveDialogs.All(x => !x.HasValue)) - { - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - if (mapRenderer.MouseOver && !MouseOver) + if (_drop.MouseOver) { e.ContinueDrag = !fitsInOldSlot; e.RestoreOriginalSlot = fitsInOldSlot; - _inventoryController.DropItem(item.Data, item.InventoryItem, mapRenderer.GridCoordinates); + _inventoryController.DropItem(item.Data, item.InventoryItem, MapCoordinate.Max); return; } - } - - if (_drop.MouseOver) - { - e.ContinueDrag = !fitsInOldSlot; - e.RestoreOriginalSlot = fitsInOldSlot; - - _inventoryController.DropItem(item.Data, item.InventoryItem, MapCoordinate.Max); - return; - } - else if (_junk.MouseOver) - { - e.ContinueDrag = !fitsInOldSlot; - e.RestoreOriginalSlot = fitsInOldSlot; - - _inventoryController.JunkItem(item.Data, item.InventoryItem); - return; - } + else if (_junk.MouseOver) + { + e.ContinueDrag = !fitsInOldSlot; + e.RestoreOriginalSlot = fitsInOldSlot; - var dialogDrop = false; - foreach (var dlg in _activeDialogProvider.ActiveDialogs) - { - dialogDrop |= dlg.Match( - activeDialog => - { - if (!activeDialog.MouseOver && !activeDialog.MouseOverPreviously) - return false; + _inventoryController.JunkItem(item.Data, item.InventoryItem); + return; + } - switch (activeDialog) + var dialogDrop = false; + foreach (var dlg in _activeDialogProvider.ActiveDialogs) + { + dialogDrop |= dlg.Match( + activeDialog => { - case PaperdollDialog: - if (item.Data.GetEquipLocation() != EquipLocation.PAPERDOLL_MAX) - _inventoryController.EquipItem(item.Data); - break; - case ChestDialog: _inventoryController.DropItemInChest(item.Data, item.InventoryItem); break; - case LockerDialog: _inventoryController.DropItemInLocker(item.Data, item.InventoryItem); break; - case BankAccountDialog: - if (item.Data.ID == 1) - _inventoryController.DropItemInBank(item.Data, item.InventoryItem); - break; - case TradeDialog: _inventoryController.TradeItem(item.Data, item.InventoryItem); break; - default: return false; - }; - - return true; - }, - () => false); - } - - if (e.DragOutOfBounds || dialogDrop) - { - e.ContinueDrag = !fitsInOldSlot; - e.RestoreOriginalSlot = fitsInOldSlot; - return; - } + if (!activeDialog.MouseOver && !activeDialog.MouseOverPreviously) + return false; + + switch (activeDialog) + { + case PaperdollDialog: + if (item.Data.GetEquipLocation() != EquipLocation.PAPERDOLL_MAX) + _inventoryController.EquipItem(item.Data); + break; + case ChestDialog: _inventoryController.DropItemInChest(item.Data, item.InventoryItem); break; + case LockerDialog: _inventoryController.DropItemInLocker(item.Data, item.InventoryItem); break; + case BankAccountDialog: + if (item.Data.ID == 1) + _inventoryController.DropItemInBank(item.Data, item.InventoryItem); + break; + case TradeDialog: _inventoryController.TradeItem(item.Data, item.InventoryItem); break; + default: return false; + }; + + return true; + }, + () => false); + } - var newSlot = item.GetCurrentSlotBasedOnPosition(); + if (e.DragOutOfBounds || dialogDrop) + { + e.ContinueDrag = !fitsInOldSlot; + e.RestoreOriginalSlot = fitsInOldSlot; + return; + } - // check overlapping items: - // 1. If there's multiple items under it, snap it back to the original slot if iti fits, otherwise continue dragging - // 2. If there's only one item under it, "chain" the drag operation to that item - // 3. If there's nothing under it, make sure it fits in the inventory, otherwise snap back to original slot + var newSlot = item.GetCurrentSlotBasedOnPosition(); - var overlapped = GetOverlappingTakenSlots(newSlot, e.Data.Size, _childItems.Except(new[] { item }).Select(x => (x.Slot, x.Data.Size))) - .ToList(); + // check overlapping items: + // 1. If there's multiple items under it, snap it back to the original slot if iti fits, otherwise continue dragging + // 2. If there's only one item under it, "chain" the drag operation to that item + // 3. If there's nothing under it, make sure it fits in the inventory, otherwise snap back to original slot - if (overlapped.Count > 1) - { - e.RestoreOriginalSlot = true; + var overlapped = GetOverlappingTakenSlots(newSlot, e.Data.Size, _childItems.Except(new[] { item }).Select(x => (x.Slot, x.Data.Size))) + .ToList(); - if (!fitsInOldSlot) - e.ContinueDrag = true; - } - else if (overlapped.Count == 1) - { - var nextItem = _childItems.Single(x => x.Slot == overlapped[0] && !x.IsDragging); - nextItem.Slot = oldSlot; - nextItem.StartDragging(isChainedDrag: true); - } - else if (oldSlot != newSlot) - { - if (!_inventoryService.FitsInSlot(_inventorySlotRepository.FilledSlots, oldSlot, newSlot, e.Data.Size)) + if (overlapped.Count > 1) { - // if the original slot no longer fits (because this is a chained drag), don't stop dragging this item + e.RestoreOriginalSlot = true; + if (!fitsInOldSlot) - { e.ContinueDrag = true; + } + else if (overlapped.Count == 1) + { + var nextItem = _childItems.Single(x => x.Slot == overlapped[0] && !x.IsDragging); + nextItem.Slot = oldSlot; + nextItem.StartDragging(isChainedDrag: true); + } + else if (oldSlot != newSlot) + { + if (!_inventoryService.FitsInSlot(_inventorySlotRepository.FilledSlots, oldSlot, newSlot, e.Data.Size)) + { + // if the original slot no longer fits (because this is a chained drag), don't stop dragging this item + if (!fitsInOldSlot) + { + e.ContinueDrag = true; + } + else + { + e.RestoreOriginalSlot = true; + } } else { - e.RestoreOriginalSlot = true; + RemoveHiddenItemsFromCachedInventory(); } } - else - { - RemoveHiddenItemsFromCachedInventory(); - } } - } - private void ResetSlotMap(IEnumerable childItems) - { - // reset the slot map based on the current state of the inventory - // avoids issues due to chained drags + variable item sizes - _inventorySlotRepository.FilledSlots.Fill(false); - foreach (var childItem in childItems) - _inventoryService.SetSlots(_inventorySlotRepository.FilledSlots, childItem.Slot, childItem.Data.Size); - } - - private void RemoveHiddenItemsFromCachedInventory() - { - // the item fits in the new slot, and there is no chained drag, snapback, or continued drag - // under these conditions, check if there are any items that don't have a matching childItem and remove them from the cached list - // the next update loop will detect these items as 'added' and attempt to show them in the empty space - - var notDisplayedItems = _cachedInventory.Where(x => _childItems.All(ci => x != ci.InventoryItem)); - _cachedInventory.RemoveWhere(notDisplayedItems.Contains); - } + private void ResetSlotMap(IEnumerable childItems) + { + // reset the slot map based on the current state of the inventory + // avoids issues due to chained drags + variable item sizes + _inventorySlotRepository.FilledSlots.Fill(false); + foreach (var childItem in childItems) + _inventoryService.SetSlots(_inventorySlotRepository.FilledSlots, childItem.Slot, childItem.Data.Size); + } - private static IEnumerable GetOverlappingTakenSlots(int newSlot, ItemSize size, IEnumerable<(int Slot, ItemSize Size)> items) - { - var slotX = newSlot % InventoryRowSlots; - var slotY = newSlot / InventoryRowSlots; - var slotItemDim = size.GetDimensions(); + private void RemoveHiddenItemsFromCachedInventory() + { + // the item fits in the new slot, and there is no chained drag, snapback, or continued drag + // under these conditions, check if there are any items that don't have a matching childItem and remove them from the cached list + // the next update loop will detect these items as 'added' and attempt to show them in the empty space - var newSlotCoords = new List<(int X, int Y)>(); - for (int r = slotY; r < slotY + slotItemDim.Height; r++) - for (int c = slotX; c < slotX + slotItemDim.Width; c++) - newSlotCoords.Add((c, r)); + var notDisplayedItems = _cachedInventory.Where(x => _childItems.All(ci => x != ci.InventoryItem)); + _cachedInventory.RemoveWhere(notDisplayedItems.Contains); + } - foreach (var item in items) + private static IEnumerable GetOverlappingTakenSlots(int newSlot, ItemSize size, IEnumerable<(int Slot, ItemSize Size)> items) { - var itemX = item.Slot % InventoryRowSlots; - var itemY = item.Slot / InventoryRowSlots; - var itemDim = item.Size.GetDimensions(); + var slotX = newSlot % InventoryRowSlots; + var slotY = newSlot / InventoryRowSlots; + var slotItemDim = size.GetDimensions(); - var @break = false; - for (int r = itemY; r < itemY + itemDim.Height; r++) + var newSlotCoords = new List<(int X, int Y)>(); + for (int r = slotY; r < slotY + slotItemDim.Height; r++) + for (int c = slotX; c < slotX + slotItemDim.Width; c++) + newSlotCoords.Add((c, r)); + + foreach (var item in items) { - if (@break) - break; + var itemX = item.Slot % InventoryRowSlots; + var itemY = item.Slot / InventoryRowSlots; + var itemDim = item.Size.GetDimensions(); - for (int c = itemX; c < itemX + itemDim.Width; c++) + var @break = false; + for (int r = itemY; r < itemY + itemDim.Height; r++) { - if (newSlotCoords.Contains((c, r))) - { - yield return item.Slot; - @break = true; + if (@break) break; + + for (int c = itemX; c < itemX + itemDim.Width; c++) + { + if (newSlotCoords.Contains((c, r))) + { + yield return item.Slot; + @break = true; + break; + } } } } diff --git a/EndlessClient/HUD/Panels/NewsPanel.cs b/EndlessClient/HUD/Panels/NewsPanel.cs index dc5976243..ad983b417 100644 --- a/EndlessClient/HUD/Panels/NewsPanel.cs +++ b/EndlessClient/HUD/Panels/NewsPanel.cs @@ -10,122 +10,123 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels; - -public class NewsPanel : DraggableHudPanel +namespace EndlessClient.HUD.Panels { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatRenderableGenerator _chatRenderableGenerator; - private readonly INewsProvider _newsProvider; - private readonly ScrollBar _scrollBar; - private readonly List _chatRenderables; - private readonly BitmapFont _chatFont; - - //cached data fields - private readonly List _cachedNewsStrings; - private int _cachedScrollOffset; - private int _cachedLinesToRender; - - private bool _firstTime = true; - - public NewsPanel(INativeGraphicsManager nativeGraphicsManager, - IChatRenderableGenerator chatRenderableGenerator, - INewsProvider newsProvider, - BitmapFont chatFont, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + public class NewsPanel : DraggableHudPanel { - _nativeGraphicsManager = nativeGraphicsManager; - _chatRenderableGenerator = chatRenderableGenerator; - _newsProvider = newsProvider; - - //abs coordiantes: 568 331 - _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatRenderableGenerator _chatRenderableGenerator; + private readonly INewsProvider _newsProvider; + private readonly ScrollBar _scrollBar; + private readonly List _chatRenderables; + private readonly BitmapFont _chatFont; + + //cached data fields + private readonly List _cachedNewsStrings; + private int _cachedScrollOffset; + private int _cachedLinesToRender; + + private bool _firstTime = true; + + public NewsPanel(INativeGraphicsManager nativeGraphicsManager, + IChatRenderableGenerator chatRenderableGenerator, + INewsProvider newsProvider, + BitmapFont chatFont, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - LinesToRender = 7, - Visible = true - }; - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); + _nativeGraphicsManager = nativeGraphicsManager; + _chatRenderableGenerator = chatRenderableGenerator; + _newsProvider = newsProvider; - _chatRenderables = new List(); - _chatFont = chatFont; + //abs coordiantes: 568 331 + _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) + { + LinesToRender = 7, + Visible = true + }; + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); - _cachedNewsStrings = new List(); - _cachedScrollOffset = -1; - _cachedLinesToRender = -1; + _chatRenderables = new List(); + _chatFont = chatFont; - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 48); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - } + _cachedNewsStrings = new List(); + _cachedScrollOffset = -1; + _cachedLinesToRender = -1; - public override void Initialize() - { - _scrollBar.Initialize(); - base.Initialize(); - } + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 48); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + } - protected override void OnUpdateControl(GameTime gameTime) - { - var newsChanged = false; - if (!_cachedNewsStrings.SequenceEqual(_newsProvider.NewsText)) + public override void Initialize() { - UpdateCachedNewsStrings(); - newsChanged = true; + _scrollBar.Initialize(); + base.Initialize(); } - if (newsChanged || - _cachedScrollOffset != _scrollBar.ScrollOffset || - _cachedLinesToRender != _scrollBar.LinesToRender) + protected override void OnUpdateControl(GameTime gameTime) { - var renderables = _chatRenderableGenerator.GenerateNewsRenderables(_cachedNewsStrings); - - UpdateCachedScrollProperties(); - SetupRenderablesFromCachedValues(renderables); + var newsChanged = false; + if (!_cachedNewsStrings.SequenceEqual(_newsProvider.NewsText)) + { + UpdateCachedNewsStrings(); + newsChanged = true; + } - if (_firstTime && renderables.Count > _scrollBar.LinesToRender) + if (newsChanged || + _cachedScrollOffset != _scrollBar.ScrollOffset || + _cachedLinesToRender != _scrollBar.LinesToRender) { - _scrollBar.SetDownArrowFlashSpeed(500); - _firstTime = false; + var renderables = _chatRenderableGenerator.GenerateNewsRenderables(_cachedNewsStrings); + + UpdateCachedScrollProperties(); + SetupRenderablesFromCachedValues(renderables); + + if (_firstTime && renderables.Count > _scrollBar.LinesToRender) + { + _scrollBar.SetDownArrowFlashSpeed(500); + _firstTime = false; + } } - } - base.OnUpdateControl(gameTime); - } + base.OnUpdateControl(gameTime); + } - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - if (_chatRenderables == null) - return; + if (_chatRenderables == null) + return; - foreach (var renderable in _chatRenderables) - renderable.Render(this, _spriteBatch, _chatFont); - } + foreach (var renderable in _chatRenderables) + renderable.Render(this, _spriteBatch, _chatFont); + } - private void UpdateCachedNewsStrings() - { - _cachedNewsStrings.Clear(); - _cachedNewsStrings.AddRange(_newsProvider.NewsText); - } + private void UpdateCachedNewsStrings() + { + _cachedNewsStrings.Clear(); + _cachedNewsStrings.AddRange(_newsProvider.NewsText); + } - private void UpdateCachedScrollProperties() - { - _cachedScrollOffset = _scrollBar.ScrollOffset; - _cachedLinesToRender = _scrollBar.LinesToRender; - } + private void UpdateCachedScrollProperties() + { + _cachedScrollOffset = _scrollBar.ScrollOffset; + _cachedLinesToRender = _scrollBar.LinesToRender; + } - private void SetupRenderablesFromCachedValues(IReadOnlyList renderables) - { - _chatRenderables.Clear(); + private void SetupRenderablesFromCachedValues(IReadOnlyList renderables) + { + _chatRenderables.Clear(); - //only render based on what the scroll bar's position is - _chatRenderables.AddRange(renderables.Skip(_cachedScrollOffset).Take(_cachedLinesToRender)); - for (int i = 0; i < _chatRenderables.Count; ++i) - _chatRenderables[i].DisplayIndex = i; + //only render based on what the scroll bar's position is + _chatRenderables.AddRange(renderables.Skip(_cachedScrollOffset).Take(_cachedLinesToRender)); + for (int i = 0; i < _chatRenderables.Count; ++i) + _chatRenderables[i].DisplayIndex = i; - //update scrollbar with total number of renderables - _scrollBar.UpdateDimensions(renderables.Count); + //update scrollbar with total number of renderables + _scrollBar.UpdateDimensions(renderables.Count); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/OnlineListPanel.cs b/EndlessClient/HUD/Panels/OnlineListPanel.cs index 2a9b50f00..6f892ebb2 100644 --- a/EndlessClient/HUD/Panels/OnlineListPanel.cs +++ b/EndlessClient/HUD/Panels/OnlineListPanel.cs @@ -21,222 +21,223 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels; - -public class OnlineListPanel : DraggableHudPanel +namespace EndlessClient.HUD.Panels { - private enum Filter - { - All, - Friends, - Admins, - Party, - Max - } - - private const int DRAW_NAME_X = 18, - DRAW_OFFSET_Y = 23; - - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IHudControlProvider _hudControlProvider; - private readonly IOnlinePlayerProvider _onlinePlayerProvider; - private readonly IPartyDataProvider _partyDataProvider; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly ISfxPlayer _sfxPlayer; - - private readonly BitmapFont _chatFont; - - private readonly List _onlineList; - private readonly IXNALabel _totalNumberOfPlayers; - private readonly ScrollBar _scrollBar; - private readonly ClickableArea _filterClickArea; - - private readonly Texture2D _weirdOffsetTextureSheet, _chatIconsTexture; - private readonly Rectangle[] _filterTextureSources; - - private HashSet _cachedList; - - private Filter _filter; - private List _filteredList; - private IReadOnlyList _friendList; - - public OnlineListPanel(INativeGraphicsManager nativeGraphicsManager, - IHudControlProvider hudControlProvider, - IOnlinePlayerProvider onlinePlayerProvider, - IPartyDataProvider partyDataProvider, - IFriendIgnoreListService friendIgnoreListService, - ISfxPlayer sfxPlayer, - BitmapFont chatFont, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + public class OnlineListPanel : DraggableHudPanel { - _nativeGraphicsManager = nativeGraphicsManager; - _hudControlProvider = hudControlProvider; - _onlinePlayerProvider = onlinePlayerProvider; - _partyDataProvider = partyDataProvider; - _friendIgnoreListService = friendIgnoreListService; - _sfxPlayer = sfxPlayer; - _chatFont = chatFont; - _onlineList = new List(); - - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 36); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - - _totalNumberOfPlayers = new XNALabel(Constants.FontSize09) + private enum Filter { - AutoSize = false, - ForeColor = ColorConstants.LightGrayText, - TextAlign = LabelAlignment.MiddleRight, - DrawArea = new Rectangle(454, 1, 27, 14), - BackColor = Color.Transparent, - }; - _totalNumberOfPlayers.SetParentControl(this); - - _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) + All, + Friends, + Admins, + Party, + Max + } + + private const int DRAW_NAME_X = 18, + DRAW_OFFSET_Y = 23; + + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IHudControlProvider _hudControlProvider; + private readonly IOnlinePlayerProvider _onlinePlayerProvider; + private readonly IPartyDataProvider _partyDataProvider; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly ISfxPlayer _sfxPlayer; + + private readonly BitmapFont _chatFont; + + private readonly List _onlineList; + private readonly IXNALabel _totalNumberOfPlayers; + private readonly ScrollBar _scrollBar; + private readonly ClickableArea _filterClickArea; + + private readonly Texture2D _weirdOffsetTextureSheet, _chatIconsTexture; + private readonly Rectangle[] _filterTextureSources; + + private HashSet _cachedList; + + private Filter _filter; + private List _filteredList; + private IReadOnlyList _friendList; + + public OnlineListPanel(INativeGraphicsManager nativeGraphicsManager, + IHudControlProvider hudControlProvider, + IOnlinePlayerProvider onlinePlayerProvider, + IPartyDataProvider partyDataProvider, + IFriendIgnoreListService friendIgnoreListService, + ISfxPlayer sfxPlayer, + BitmapFont chatFont, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - LinesToRender = 7, - Visible = true - }; - _scrollBar.SetParentControl(this); - SetScrollWheelHandler(_scrollBar); - - _filterClickArea = new ClickableArea(new Rectangle(2, 2, 14, 14)); - _filterClickArea.SetParentControl(this); - _filterClickArea.OnClick += FilterClickArea_Click; - - _weirdOffsetTextureSheet = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); - _chatIconsTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); - - _filterTextureSources = new Rectangle[4]; - for (int i = 0; i < _filterTextureSources.Length; ++i) - _filterTextureSources[i] = new Rectangle(i % 2 == 0 ? 0 : 12, i >= 2 ? 246 : 233, 12, 13); - - _cachedList = new HashSet(); - _filter = Filter.All; - _filteredList = new List(); - } + _nativeGraphicsManager = nativeGraphicsManager; + _hudControlProvider = hudControlProvider; + _onlinePlayerProvider = onlinePlayerProvider; + _partyDataProvider = partyDataProvider; + _friendIgnoreListService = friendIgnoreListService; + _sfxPlayer = sfxPlayer; + _chatFont = chatFont; + _onlineList = new List(); + + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 36); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + + _totalNumberOfPlayers = new XNALabel(Constants.FontSize09) + { + AutoSize = false, + ForeColor = ColorConstants.LightGrayText, + TextAlign = LabelAlignment.MiddleRight, + DrawArea = new Rectangle(454, 1, 27, 14), + BackColor = Color.Transparent, + }; + _totalNumberOfPlayers.SetParentControl(this); + + _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) + { + LinesToRender = 7, + Visible = true + }; + _scrollBar.SetParentControl(this); + SetScrollWheelHandler(_scrollBar); + + _filterClickArea = new ClickableArea(new Rectangle(2, 2, 14, 14)); + _filterClickArea.SetParentControl(this); + _filterClickArea.OnClick += FilterClickArea_Click; + + _weirdOffsetTextureSheet = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); + _chatIconsTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); + + _filterTextureSources = new Rectangle[4]; + for (int i = 0; i < _filterTextureSources.Length; ++i) + _filterTextureSources[i] = new Rectangle(i % 2 == 0 ? 0 : 12, i >= 2 ? 246 : 233, 12, 13); + + _cachedList = new HashSet(); + _filter = Filter.All; + _filteredList = new List(); + } - public override void Initialize() - { - _totalNumberOfPlayers.Initialize(); - _scrollBar.Initialize(); - _filterClickArea.Initialize(); + public override void Initialize() + { + _totalNumberOfPlayers.Initialize(); + _scrollBar.Initialize(); + _filterClickArea.Initialize(); - base.Initialize(); - } + base.Initialize(); + } - protected override void OnUpdateControl(GameTime gameTime) - { - if (!_cachedList.SetEquals(_onlinePlayerProvider.OnlinePlayers)) + protected override void OnUpdateControl(GameTime gameTime) { - _cachedList = _onlinePlayerProvider.OnlinePlayers.ToHashSet(); - - // keep the friends list data from overriding the displayed data in this panel - // it will be friends list data if all titles (or any field other than name) are empty - if (!_cachedList.All(x => x.Title == string.Empty)) + if (!_cachedList.SetEquals(_onlinePlayerProvider.OnlinePlayers)) { - _onlineList.Clear(); - _onlineList.AddRange(_cachedList); + _cachedList = _onlinePlayerProvider.OnlinePlayers.ToHashSet(); - _onlineList.Sort((a, b) => a.Name.CompareTo(b.Name)); - _filteredList = new List(_onlineList); + // keep the friends list data from overriding the displayed data in this panel + // it will be friends list data if all titles (or any field other than name) are empty + if (!_cachedList.All(x => x.Title == string.Empty)) + { + _onlineList.Clear(); + _onlineList.AddRange(_cachedList); - _totalNumberOfPlayers.Text = $"{_onlineList.Count}"; - _scrollBar.UpdateDimensions(_onlineList.Count); - _scrollBar.ScrollToTop(); + _onlineList.Sort((a, b) => a.Name.CompareTo(b.Name)); + _filteredList = new List(_onlineList); - _friendList = _friendIgnoreListService.LoadList(Constants.FriendListFile); + _totalNumberOfPlayers.Text = $"{_onlineList.Count}"; + _scrollBar.UpdateDimensions(_onlineList.Count); + _scrollBar.ScrollToTop(); - ApplyFilter(); + _friendList = _friendIgnoreListService.LoadList(Constants.FriendListFile); + + ApplyFilter(); + } } + + base.OnUpdateControl(gameTime); } - base.OnUpdateControl(gameTime); - } + protected override void OnDrawControl(GameTime gameTime) + { + base.OnDrawControl(gameTime); - protected override void OnDrawControl(GameTime gameTime) - { - base.OnDrawControl(gameTime); + const int DRAW_ICON_X = 4, + DRAW_TITLE_X = 133, + DRAW_GUILD_X = 245, + DRAW_CLASS_X = 359; - const int DRAW_ICON_X = 4, - DRAW_TITLE_X = 133, - DRAW_GUILD_X = 245, - DRAW_CLASS_X = 359; + _spriteBatch.Begin(); - _spriteBatch.Begin(); + _spriteBatch.Draw(_weirdOffsetTextureSheet, new Vector2(DrawAreaWithParentOffset.X + 4, DrawAreaWithParentOffset.Y + 2), _filterTextureSources[(int)_filter], Color.White); - _spriteBatch.Draw(_weirdOffsetTextureSheet, new Vector2(DrawAreaWithParentOffset.X + 4, DrawAreaWithParentOffset.Y + 2), _filterTextureSources[(int)_filter], Color.White); + // todo: either a) use renderable approach like Chat/News or b) remove renderable approach in favor of this simpler method + for (int i = _scrollBar.ScrollOffset; i < _scrollBar.ScrollOffset + _scrollBar.LinesToRender && i < _filteredList.Count; ++i) + { + int yCoord = DRAW_OFFSET_Y + DrawAreaWithParentOffset.Y + (i - _scrollBar.ScrollOffset) * 13; + _spriteBatch.Draw(_chatIconsTexture, new Vector2(DrawAreaWithParentOffset.X + DRAW_ICON_X, yCoord), GetChatIconSourceRectangle(_filteredList[i].Icon), Color.White); + _spriteBatch.DrawString(_chatFont, _filteredList[i].Name, new Vector2(DrawAreaWithParentOffset.X + DRAW_NAME_X, yCoord), Color.Black); + _spriteBatch.DrawString(_chatFont, _filteredList[i].Title, new Vector2(DrawAreaWithParentOffset.X + DRAW_TITLE_X, yCoord), Color.Black); + _spriteBatch.DrawString(_chatFont, _filteredList[i].Guild, new Vector2(DrawAreaWithParentOffset.X + DRAW_GUILD_X, yCoord), Color.Black); + _spriteBatch.DrawString(_chatFont, _filteredList[i].Class, new Vector2(DrawAreaWithParentOffset.X + DRAW_CLASS_X, yCoord), Color.Black); + } - // todo: either a) use renderable approach like Chat/News or b) remove renderable approach in favor of this simpler method - for (int i = _scrollBar.ScrollOffset; i < _scrollBar.ScrollOffset + _scrollBar.LinesToRender && i < _filteredList.Count; ++i) - { - int yCoord = DRAW_OFFSET_Y + DrawAreaWithParentOffset.Y + (i - _scrollBar.ScrollOffset) * 13; - _spriteBatch.Draw(_chatIconsTexture, new Vector2(DrawAreaWithParentOffset.X + DRAW_ICON_X, yCoord), GetChatIconSourceRectangle(_filteredList[i].Icon), Color.White); - _spriteBatch.DrawString(_chatFont, _filteredList[i].Name, new Vector2(DrawAreaWithParentOffset.X + DRAW_NAME_X, yCoord), Color.Black); - _spriteBatch.DrawString(_chatFont, _filteredList[i].Title, new Vector2(DrawAreaWithParentOffset.X + DRAW_TITLE_X, yCoord), Color.Black); - _spriteBatch.DrawString(_chatFont, _filteredList[i].Guild, new Vector2(DrawAreaWithParentOffset.X + DRAW_GUILD_X, yCoord), Color.Black); - _spriteBatch.DrawString(_chatFont, _filteredList[i].Class, new Vector2(DrawAreaWithParentOffset.X + DRAW_CLASS_X, yCoord), Color.Black); + _spriteBatch.End(); } - _spriteBatch.End(); - } - - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (eventArgs.Button != MouseButton.Right) - return false; - - var mousePos = eventArgs.Position; - if (mousePos.X >= DrawAreaWithParentOffset.X + DRAW_NAME_X && mousePos.X <= _scrollBar.DrawAreaWithParentOffset.X && - mousePos.Y >= DrawAreaWithParentOffset.Y + DRAW_OFFSET_Y && mousePos.Y <= DrawAreaWithParentOffset.Y + DrawAreaWithParentOffset.Height) + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) { - var index = (mousePos.Y - (DrawAreaWithParentOffset.Y + DRAW_OFFSET_Y)) / 13; - if (index >= 0 && index <= _filteredList.Count) + if (eventArgs.Button != MouseButton.Right) + return false; + + var mousePos = eventArgs.Position; + if (mousePos.X >= DrawAreaWithParentOffset.X + DRAW_NAME_X && mousePos.X <= _scrollBar.DrawAreaWithParentOffset.X && + mousePos.Y >= DrawAreaWithParentOffset.Y + DRAW_OFFSET_Y && mousePos.Y <= DrawAreaWithParentOffset.Y + DrawAreaWithParentOffset.Height) { - var name = _filteredList[_scrollBar.ScrollOffset + index].Name; - _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{name} "; + var index = (mousePos.Y - (DrawAreaWithParentOffset.Y + DRAW_OFFSET_Y)) / 13; + if (index >= 0 && index <= _filteredList.Count) + { + var name = _filteredList[_scrollBar.ScrollOffset + index].Name; + _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{name} "; + } } - } - return true; - } + return true; + } - private void FilterClickArea_Click(object sender, EventArgs e) - { - _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - _filter = (Filter)(((int)_filter + 1) % (int)Filter.Max); - _scrollBar.ScrollToTop(); + private void FilterClickArea_Click(object sender, EventArgs e) + { + _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + _filter = (Filter)(((int)_filter + 1) % (int)Filter.Max); + _scrollBar.ScrollToTop(); - ApplyFilter(); - } + ApplyFilter(); + } - private void ApplyFilter() - { - switch (_filter) + private void ApplyFilter() { - case Filter.Friends: _filteredList = _onlineList.Where(x => _friendList.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase)).ToList(); break; - case Filter.Admins: _filteredList = _onlineList.Where(IsAdminIcon).ToList(); break; - case Filter.Party: _filteredList = _onlineList.Where(x => _partyDataProvider.Members.Any(y => string.Equals(y.Name, x.Name, StringComparison.InvariantCultureIgnoreCase))).ToList(); break; - case Filter.All: - default: _filteredList = new List(_onlineList); break; - } + switch (_filter) + { + case Filter.Friends: _filteredList = _onlineList.Where(x => _friendList.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase)).ToList(); break; + case Filter.Admins: _filteredList = _onlineList.Where(IsAdminIcon).ToList(); break; + case Filter.Party: _filteredList = _onlineList.Where(x => _partyDataProvider.Members.Any(y => string.Equals(y.Name, x.Name, StringComparison.InvariantCultureIgnoreCase))).ToList(); break; + case Filter.All: + default: _filteredList = new List(_onlineList); break; + } - _scrollBar.UpdateDimensions(_filteredList.Count); - } + _scrollBar.UpdateDimensions(_filteredList.Count); + } - private static bool IsAdminIcon(OnlinePlayerInfo onlineInfo) - { - return onlineInfo.Icon switch + private static bool IsAdminIcon(OnlinePlayerInfo onlineInfo) { - CharacterIcon.Gm or CharacterIcon.Hgm or CharacterIcon.GmParty or CharacterIcon.HgmParty => true, - _ => false, - }; - } + return onlineInfo.Icon switch + { + CharacterIcon.Gm or CharacterIcon.Hgm or CharacterIcon.GmParty or CharacterIcon.HgmParty => true, + _ => false, + }; + } - private static Rectangle? GetChatIconSourceRectangle(CharacterIcon icon) - { - var (x, y, width, height) = icon.ToChatIcon().GetChatIconRectangleBounds().ValueOrDefault(); - return new Rectangle(x, y, width, height); + private static Rectangle? GetChatIconSourceRectangle(CharacterIcon icon) + { + var (x, y, width, height) = icon.ToChatIcon().GetChatIconRectangleBounds().ValueOrDefault(); + return new Rectangle(x, y, width, height); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/PartyPanel.cs b/EndlessClient/HUD/Panels/PartyPanel.cs index e5f22a316..40bc1a4ea 100644 --- a/EndlessClient/HUD/Panels/PartyPanel.cs +++ b/EndlessClient/HUD/Panels/PartyPanel.cs @@ -12,151 +12,152 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels; - -public class PartyPanel : DraggableHudPanel +namespace EndlessClient.HUD.Panels { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IPartyActions _partyActions; - private readonly IContentProvider _contentProvider; - private readonly IPartyDataProvider _partyDataProvider; - private readonly ICharacterProvider _characterProvider; - - private readonly ScrollBar _scrollBar; - private readonly IXNALabel _numMembers; - private readonly List _children; - - private HashSet _cachedParty; - private int _cachedScrollOffset; - - public PartyPanel(INativeGraphicsManager nativeGraphicsManager, - IPartyActions partyActions, - IContentProvider contentProvider, - IPartyDataProvider partyDataProvider, - ICharacterProvider characterProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + public class PartyPanel : DraggableHudPanel { - _nativeGraphicsManager = nativeGraphicsManager; - _partyActions = partyActions; - _contentProvider = contentProvider; - _partyDataProvider = partyDataProvider; - _characterProvider = characterProvider; - _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) - { - LinesToRender = 7, - Visible = true, - }; - _scrollBar.SetParentControl(this); - _scrollBar.UpdateDimensions(0); - SetScrollWheelHandler(_scrollBar); - - _numMembers = new XNALabel(Constants.FontSize09) + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IPartyActions _partyActions; + private readonly IContentProvider _contentProvider; + private readonly IPartyDataProvider _partyDataProvider; + private readonly ICharacterProvider _characterProvider; + + private readonly ScrollBar _scrollBar; + private readonly IXNALabel _numMembers; + private readonly List _children; + + private HashSet _cachedParty; + private int _cachedScrollOffset; + + public PartyPanel(INativeGraphicsManager nativeGraphicsManager, + IPartyActions partyActions, + IContentProvider contentProvider, + IPartyDataProvider partyDataProvider, + ICharacterProvider characterProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - AutoSize = false, - DrawArea = new Rectangle(455, 0, 27, 14), - ForeColor = ColorConstants.LightGrayText, - TextAlign = LabelAlignment.MiddleRight - }; - _numMembers.SetParentControl(this); + _nativeGraphicsManager = nativeGraphicsManager; + _partyActions = partyActions; + _contentProvider = contentProvider; + _partyDataProvider = partyDataProvider; + _characterProvider = characterProvider; + _scrollBar = new ScrollBar(new Vector2(467, 20), new Vector2(16, 97), ScrollBarColors.LightOnMed, _nativeGraphicsManager) + { + LinesToRender = 7, + Visible = true, + }; + _scrollBar.SetParentControl(this); + _scrollBar.UpdateDimensions(0); + SetScrollWheelHandler(_scrollBar); + + _numMembers = new XNALabel(Constants.FontSize09) + { + AutoSize = false, + DrawArea = new Rectangle(455, 0, 27, 14), + ForeColor = ColorConstants.LightGrayText, + TextAlign = LabelAlignment.MiddleRight + }; + _numMembers.SetParentControl(this); - _children = new List(); + _children = new List(); - _cachedParty = new HashSet(); + _cachedParty = new HashSet(); - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 42); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - } + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 42); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + } - public override void Initialize() - { - _scrollBar.Initialize(); - _numMembers.Initialize(); + public override void Initialize() + { + _scrollBar.Initialize(); + _numMembers.Initialize(); - base.Initialize(); - } + base.Initialize(); + } - protected override void OnUpdateControl(GameTime gameTime) - { - if (!_cachedParty.SetEquals(_partyDataProvider.Members)) + protected override void OnUpdateControl(GameTime gameTime) { - var added = _partyDataProvider.Members.Where(x => !_cachedParty.Any(y => y.CharacterID == x.CharacterID)).ToList(); - var removed = _cachedParty.Where(x => !_partyDataProvider.Members.Any(y => y.CharacterID == x.CharacterID)).ToList(); - var updated = _partyDataProvider.Members.Where(x => _cachedParty.Any(y => y.CharacterID == x.CharacterID && !y.Equals(x))).ToList(); - _cachedParty = _partyDataProvider.Members.ToHashSet(); + if (!_cachedParty.SetEquals(_partyDataProvider.Members)) + { + var added = _partyDataProvider.Members.Where(x => !_cachedParty.Any(y => y.CharacterID == x.CharacterID)).ToList(); + var removed = _cachedParty.Where(x => !_partyDataProvider.Members.Any(y => y.CharacterID == x.CharacterID)).ToList(); + var updated = _partyDataProvider.Members.Where(x => _cachedParty.Any(y => y.CharacterID == x.CharacterID && !y.Equals(x))).ToList(); + _cachedParty = _partyDataProvider.Members.ToHashSet(); - var mainCharacterIsLeader = _cachedParty.Any(x => x.IsLeader && x.CharacterID == _characterProvider.MainCharacter.ID); + var mainCharacterIsLeader = _cachedParty.Any(x => x.IsLeader && x.CharacterID == _characterProvider.MainCharacter.ID); - foreach (var member in added) - { - var next = new PartyPanelMember( - _nativeGraphicsManager, - _contentProvider, - mainCharacterIsLeader || member.CharacterID == _characterProvider.MainCharacter.ID) + foreach (var member in added) { - PartyMember = member, - }; - next.RemoveAction += (_, _) => _partyActions.RemovePartyMember(member.CharacterID); - next.SetParentControl(this); - next.Initialize(); + var next = new PartyPanelMember( + _nativeGraphicsManager, + _contentProvider, + mainCharacterIsLeader || member.CharacterID == _characterProvider.MainCharacter.ID) + { + PartyMember = member, + }; + next.RemoveAction += (_, _) => _partyActions.RemovePartyMember(member.CharacterID); + next.SetParentControl(this); + next.Initialize(); - _children.Add(next); - } + _children.Add(next); + } - foreach (var member in removed) - { - _children.SingleOrNone(x => x.PartyMember.CharacterID == member.CharacterID) - .MatchSome(x => - { - x.SetControlUnparented(); - x.Dispose(); - _children.Remove(x); - }); + foreach (var member in removed) + { + _children.SingleOrNone(x => x.PartyMember.CharacterID == member.CharacterID) + .MatchSome(x => + { + x.SetControlUnparented(); + x.Dispose(); + _children.Remove(x); + }); + } + + foreach (var member in updated) + { + _children.SingleOrNone(x => x.PartyMember.CharacterID == member.CharacterID) + .MatchSome(x => x.PartyMember = member); + } + + _numMembers.Text = $"{_cachedParty.Count}"; + _scrollBar.UpdateDimensions(_cachedParty.Count); + + UpdateChildMemberVisibility(); } - foreach (var member in updated) + if (_cachedScrollOffset != _scrollBar.ScrollOffset) { - _children.SingleOrNone(x => x.PartyMember.CharacterID == member.CharacterID) - .MatchSome(x => x.PartyMember = member); + _cachedScrollOffset = _scrollBar.ScrollOffset; + UpdateChildMemberVisibility(); } - _numMembers.Text = $"{_cachedParty.Count}"; - _scrollBar.UpdateDimensions(_cachedParty.Count); - - UpdateChildMemberVisibility(); + base.OnUpdateControl(gameTime); } - if (_cachedScrollOffset != _scrollBar.ScrollOffset) + protected override void OnVisibleChanged(object sender, System.EventArgs args) { - _cachedScrollOffset = _scrollBar.ScrollOffset; - UpdateChildMemberVisibility(); - } - - base.OnUpdateControl(gameTime); - } + if (Visible) + { + // request party list when viewing the party panel + _partyActions.ListParty(); + } - protected override void OnVisibleChanged(object sender, System.EventArgs args) - { - if (Visible) - { - // request party list when viewing the party panel - _partyActions.ListParty(); + base.OnVisibleChanged(sender, args); } - base.OnVisibleChanged(sender, args); - } - - private void UpdateChildMemberVisibility() - { - foreach (var child in _children) - child.Visible = false; - - for (int i = 0; i < _scrollBar.LinesToRender; i++) + private void UpdateChildMemberVisibility() { - if (_scrollBar.ScrollOffset + i >= _children.Count) - break; - _children[_scrollBar.ScrollOffset + i].DisplayIndex = i; - _children[_scrollBar.ScrollOffset + i].Visible = true; + foreach (var child in _children) + child.Visible = false; + + for (int i = 0; i < _scrollBar.LinesToRender; i++) + { + if (_scrollBar.ScrollOffset + i >= _children.Count) + break; + _children[_scrollBar.ScrollOffset + i].DisplayIndex = i; + _children[_scrollBar.ScrollOffset + i].Visible = true; + } } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/PassiveSpellsPanel.cs b/EndlessClient/HUD/Panels/PassiveSpellsPanel.cs index bcb0b765b..aeadd38a3 100644 --- a/EndlessClient/HUD/Panels/PassiveSpellsPanel.cs +++ b/EndlessClient/HUD/Panels/PassiveSpellsPanel.cs @@ -2,19 +2,20 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; -namespace EndlessClient.HUD.Panels; - -public class PassiveSpellsPanel : DraggableHudPanel +namespace EndlessClient.HUD.Panels { - private readonly INativeGraphicsManager _nativeGraphicsManager; - - public PassiveSpellsPanel(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + public class PassiveSpellsPanel : DraggableHudPanel { - _nativeGraphicsManager = nativeGraphicsManager; + private readonly INativeGraphicsManager _nativeGraphicsManager; + + public PassiveSpellsPanel(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) + { + _nativeGraphicsManager = nativeGraphicsManager; - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 62); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 62); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/SettingsPanel.cs b/EndlessClient/HUD/Panels/SettingsPanel.cs index c27284a03..c459144dc 100644 --- a/EndlessClient/HUD/Panels/SettingsPanel.cs +++ b/EndlessClient/HUD/Panels/SettingsPanel.cs @@ -13,254 +13,255 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels; - -public class SettingsPanel : DraggableHudPanel +namespace EndlessClient.HUD.Panels { - private enum KeyboardLayout + public class SettingsPanel : DraggableHudPanel { - English, - Dutch, - Swedish, - Azerty - } + private enum KeyboardLayout + { + English, + Dutch, + Swedish, + Azerty + } - private enum WhichSetting - { - Sfx, - Mfx, - Keyboard, - Language, - HearWhispers, - ShowBalloons, - ShowShadows, - CurseFilter, - LogChat, - Interaction, - } + private enum WhichSetting + { + Sfx, + Mfx, + Keyboard, + Language, + HearWhispers, + ShowBalloons, + ShowShadows, + CurseFilter, + LogChat, + Interaction, + } - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IChatActions _chatActions; - private readonly IAudioActions _audioActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IConfigurationRepository _configurationRepository; - private readonly ISfxPlayer _sfxPlayer; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IChatActions _chatActions; + private readonly IAudioActions _audioActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IConfigurationRepository _configurationRepository; + private readonly ISfxPlayer _sfxPlayer; - private readonly Dictionary _labels; - private readonly Dictionary _buttons; + private readonly Dictionary _labels; + private readonly Dictionary _buttons; - private bool _soundChanged, _musicChanged; - private KeyboardLayout _keyboardLayout; + private bool _soundChanged, _musicChanged; + private KeyboardLayout _keyboardLayout; - public SettingsPanel(INativeGraphicsManager nativeGraphicsManager, - IChatActions chatActions, - IAudioActions audioActions, - IStatusLabelSetter statusLabelSetter, - ILocalizedStringFinder localizedStringFinder, - IEOMessageBoxFactory messageBoxFactory, - IConfigurationRepository configurationRepository, - ISfxPlayer sfxPlayer, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) - { - _nativeGraphicsManager = nativeGraphicsManager; - _chatActions = chatActions; - _audioActions = audioActions; - _statusLabelSetter = statusLabelSetter; - _localizedStringFinder = localizedStringFinder; - _messageBoxFactory = messageBoxFactory; - _configurationRepository = configurationRepository; - _sfxPlayer = sfxPlayer; + public SettingsPanel(INativeGraphicsManager nativeGraphicsManager, + IChatActions chatActions, + IAudioActions audioActions, + IStatusLabelSetter statusLabelSetter, + ILocalizedStringFinder localizedStringFinder, + IEOMessageBoxFactory messageBoxFactory, + IConfigurationRepository configurationRepository, + ISfxPlayer sfxPlayer, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) + { + _nativeGraphicsManager = nativeGraphicsManager; + _chatActions = chatActions; + _audioActions = audioActions; + _statusLabelSetter = statusLabelSetter; + _localizedStringFinder = localizedStringFinder; + _messageBoxFactory = messageBoxFactory; + _configurationRepository = configurationRepository; + _sfxPlayer = sfxPlayer; - BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 47); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + BackgroundImage = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 47); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - var values = Enum.GetValues(); - _labels = values.ToDictionary(k => k, - v => - { - var ndx = (int)v; - return (IXNALabel)new XNALabel(Constants.FontSize09) + var values = Enum.GetValues(); + _labels = values.ToDictionary(k => k, + v => { - DrawArea = new Rectangle(117 + (ndx / 5) * 239, 25 + 18 * (ndx % 5), 100, 15), - AutoSize = false, - ForeColor = ColorConstants.LightGrayText, - }; - }); + var ndx = (int)v; + return (IXNALabel)new XNALabel(Constants.FontSize09) + { + DrawArea = new Rectangle(117 + (ndx / 5) * 239, 25 + 18 * (ndx % 5), 100, 15), + AutoSize = false, + ForeColor = ColorConstants.LightGrayText, + }; + }); - UpdateDisplayText(); + UpdateDisplayText(); - _buttons = values.ToDictionary(k => k, - v => - { - var ndx = (int)v; - return (IXNAButton)new XNAButton( - _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true), - new Vector2(215 + (ndx / 5) * 239, 25 + 18 * (ndx % 5)), - new Rectangle(0, 0, 19, 15), - new Rectangle(19, 0, 19, 15)); - }); - } - - public override void Initialize() - { - foreach (var label in _labels.Values) - { - label.SetParentControl(this); - label.Initialize(); + _buttons = values.ToDictionary(k => k, + v => + { + var ndx = (int)v; + return (IXNAButton)new XNAButton( + _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true), + new Vector2(215 + (ndx / 5) * 239, 25 + 18 * (ndx % 5)), + new Rectangle(0, 0, 19, 15), + new Rectangle(19, 0, 19, 15)); + }); } - foreach (var pair in _buttons) + public override void Initialize() { - var button = pair.Value; - button.OnClick += (_, _) => SettingChange(pair.Key); - button.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_SETTINGS_CLICK_TO_CHANGE); - button.SetParentControl(this); - button.Initialize(); - } + foreach (var label in _labels.Values) + { + label.SetParentControl(this); + label.Initialize(); + } - if (!_configurationRepository.HearWhispers) - _chatActions.SetHearWhispers(_configurationRepository.HearWhispers); + foreach (var pair in _buttons) + { + var button = pair.Value; + button.OnClick += (_, _) => SettingChange(pair.Key); + button.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, EOResourceID.STATUS_LABEL_SETTINGS_CLICK_TO_CHANGE); + button.SetParentControl(this); + button.Initialize(); + } - base.Initialize(); - } + if (!_configurationRepository.HearWhispers) + _chatActions.SetHearWhispers(_configurationRepository.HearWhispers); - private void SettingChange(WhichSetting setting) - { - _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + base.Initialize(); + } - switch (setting) + private void SettingChange(WhichSetting setting) { - case WhichSetting.Sfx: - { - // this alert is emulated even though it isn't needed - if (!_soundChanged && !_configurationRepository.SoundEnabled) + _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + + switch (setting) + { + case WhichSetting.Sfx: { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SETTINGS_SOUND_DISABLED, EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => + // this alert is emulated even though it isn't needed + if (!_soundChanged && !_configurationRepository.SoundEnabled) { - if (e.Result != XNADialogResult.OK) - return; + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SETTINGS_SOUND_DISABLED, EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => + { + if (e.Result != XNADialogResult.OK) + return; + + _soundChanged = true; + _configurationRepository.SoundEnabled = !_configurationRepository.SoundEnabled; + _audioActions.ToggleSound(); + UpdateDisplayText(); + }; + dlg.ShowDialog(); + } + else + { _soundChanged = true; _configurationRepository.SoundEnabled = !_configurationRepository.SoundEnabled; _audioActions.ToggleSound(); - - UpdateDisplayText(); - }; - dlg.ShowDialog(); - } - else - { - _soundChanged = true; - _configurationRepository.SoundEnabled = !_configurationRepository.SoundEnabled; - _audioActions.ToggleSound(); + } } - } - break; - case WhichSetting.Mfx: - { - // this alert is emulated even though it isn't needed - if (!_musicChanged && !_configurationRepository.MusicEnabled) + break; + case WhichSetting.Mfx: { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SETTINGS_MUSIC_DISABLED, EODialogButtons.OkCancel); - dlg.DialogClosing += (_, e) => + // this alert is emulated even though it isn't needed + if (!_musicChanged && !_configurationRepository.MusicEnabled) { - if (e.Result != XNADialogResult.OK) - return; + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.SETTINGS_MUSIC_DISABLED, EODialogButtons.OkCancel); + dlg.DialogClosing += (_, e) => + { + if (e.Result != XNADialogResult.OK) + return; + + _musicChanged = true; + _configurationRepository.MusicEnabled = !_configurationRepository.MusicEnabled; + _audioActions.ToggleBackgroundMusic(); + UpdateDisplayText(); + }; + dlg.ShowDialog(); + } + else + { _musicChanged = true; _configurationRepository.MusicEnabled = !_configurationRepository.MusicEnabled; _audioActions.ToggleBackgroundMusic(); - - UpdateDisplayText(); - }; - dlg.ShowDialog(); + } } - else + break; + case WhichSetting.Keyboard: { - _musicChanged = true; - _configurationRepository.MusicEnabled = !_configurationRepository.MusicEnabled; - _audioActions.ToggleBackgroundMusic(); + // this doesn't actually change anything... + _keyboardLayout++; + if (_keyboardLayout > KeyboardLayout.Azerty) + _keyboardLayout = 0; } - } - break; - case WhichSetting.Keyboard: - { - // this doesn't actually change anything... - _keyboardLayout++; - if (_keyboardLayout > KeyboardLayout.Azerty) - _keyboardLayout = 0; - } - break; - case WhichSetting.Language: - { - _configurationRepository.Language++; - if (_configurationRepository.Language > EOLanguage.Portuguese) - _configurationRepository.Language = 0; - } - break; - case WhichSetting.HearWhispers: - { - _configurationRepository.HearWhispers = !_configurationRepository.HearWhispers; - _chatActions.SetHearWhispers(_configurationRepository.HearWhispers); - } - break; - case WhichSetting.ShowBalloons: - _configurationRepository.ShowChatBubbles = !_configurationRepository.ShowChatBubbles; - break; - case WhichSetting.ShowShadows: - _configurationRepository.ShowShadows = !_configurationRepository.ShowShadows; - break; - case WhichSetting.CurseFilter: - { - if (_configurationRepository.StrictFilterEnabled) + break; + case WhichSetting.Language: { - _configurationRepository.StrictFilterEnabled = false; + _configurationRepository.Language++; + if (_configurationRepository.Language > EOLanguage.Portuguese) + _configurationRepository.Language = 0; } - else if (_configurationRepository.CurseFilterEnabled) + break; + case WhichSetting.HearWhispers: { - _configurationRepository.CurseFilterEnabled = false; - _configurationRepository.StrictFilterEnabled = true; + _configurationRepository.HearWhispers = !_configurationRepository.HearWhispers; + _chatActions.SetHearWhispers(_configurationRepository.HearWhispers); } - else + break; + case WhichSetting.ShowBalloons: + _configurationRepository.ShowChatBubbles = !_configurationRepository.ShowChatBubbles; + break; + case WhichSetting.ShowShadows: + _configurationRepository.ShowShadows = !_configurationRepository.ShowShadows; + break; + case WhichSetting.CurseFilter: { - _configurationRepository.CurseFilterEnabled = true; + if (_configurationRepository.StrictFilterEnabled) + { + _configurationRepository.StrictFilterEnabled = false; + } + else if (_configurationRepository.CurseFilterEnabled) + { + _configurationRepository.CurseFilterEnabled = false; + _configurationRepository.StrictFilterEnabled = true; + } + else + { + _configurationRepository.CurseFilterEnabled = true; + } } - } - break; - case WhichSetting.LogChat: - _configurationRepository.LogChatToFile = !_configurationRepository.LogChatToFile; - break; - case WhichSetting.Interaction: - // todo: block trade requests when this is true - _configurationRepository.Interaction = !_configurationRepository.Interaction; - break; - } + break; + case WhichSetting.LogChat: + _configurationRepository.LogChatToFile = !_configurationRepository.LogChatToFile; + break; + case WhichSetting.Interaction: + // todo: block trade requests when this is true + _configurationRepository.Interaction = !_configurationRepository.Interaction; + break; + } - UpdateDisplayText(); - } + UpdateDisplayText(); + } - private void UpdateDisplayText() - { - _labels[WhichSetting.Sfx].Text = _localizedStringFinder.GetString(_configurationRepository.SoundEnabled ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.Mfx].Text = _localizedStringFinder.GetString(_configurationRepository.MusicEnabled ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.Keyboard].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_KEYBOARD_ENGLISH); - _labels[WhichSetting.Language].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_LANG_CURRENT); - _labels[WhichSetting.HearWhispers].Text = _localizedStringFinder.GetString(_configurationRepository.HearWhispers ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + private void UpdateDisplayText() + { + _labels[WhichSetting.Sfx].Text = _localizedStringFinder.GetString(_configurationRepository.SoundEnabled ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + _labels[WhichSetting.Mfx].Text = _localizedStringFinder.GetString(_configurationRepository.MusicEnabled ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + _labels[WhichSetting.Keyboard].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_KEYBOARD_ENGLISH); + _labels[WhichSetting.Language].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_LANG_CURRENT); + _labels[WhichSetting.HearWhispers].Text = _localizedStringFinder.GetString(_configurationRepository.HearWhispers ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.ShowBalloons].Text = _localizedStringFinder.GetString(_configurationRepository.ShowChatBubbles ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.ShowShadows].Text = _localizedStringFinder.GetString(_configurationRepository.ShowShadows ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - if (_configurationRepository.StrictFilterEnabled) - _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_EXCLUSIVE); - else if (_configurationRepository.CurseFilterEnabled) - _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_NORMAL); - else - _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_DISABLED); + _labels[WhichSetting.ShowBalloons].Text = _localizedStringFinder.GetString(_configurationRepository.ShowChatBubbles ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + _labels[WhichSetting.ShowShadows].Text = _localizedStringFinder.GetString(_configurationRepository.ShowShadows ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + if (_configurationRepository.StrictFilterEnabled) + _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_EXCLUSIVE); + else if (_configurationRepository.CurseFilterEnabled) + _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_NORMAL); + else + _labels[WhichSetting.CurseFilter].Text = _localizedStringFinder.GetString(EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.LogChat].Text = _localizedStringFinder.GetString(_configurationRepository.LogChatToFile ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); - _labels[WhichSetting.Interaction].Text = _localizedStringFinder.GetString(_configurationRepository.Interaction ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + _labels[WhichSetting.LogChat].Text = _localizedStringFinder.GetString(_configurationRepository.LogChatToFile ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + _labels[WhichSetting.Interaction].Text = _localizedStringFinder.GetString(_configurationRepository.Interaction ? EOResourceID.SETTING_ENABLED : EOResourceID.SETTING_DISABLED); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Panels/StatsPanel.cs b/EndlessClient/HUD/Panels/StatsPanel.cs index 6fb734617..9106f5563 100644 --- a/EndlessClient/HUD/Panels/StatsPanel.cs +++ b/EndlessClient/HUD/Panels/StatsPanel.cs @@ -11,230 +11,231 @@ using System.Linq; using XNAControls; -namespace EndlessClient.HUD.Panels; - -public class StatsPanel : DraggableHudPanel +namespace EndlessClient.HUD.Panels { - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterInventoryProvider _characterInventoryProvider; - private readonly IExperienceTableProvider _experienceTableProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ITrainingController _trainingController; - private const int STR = 0, INT = 1, WIS = 2, AGI = 3, CON = 4, CHA = 5; - private readonly IXNALabel[] _basicStats; - private readonly IXNAButton[] _arrowButtons; - - private const int HP = 0, TP = 1, DAM = 2, ACC = 3, ARM = 4, EVA = 5; - private readonly IXNALabel[] _characterStats; - - private const int NAME = 0, LEVEL = 1, GUILD = 2; - private readonly IXNALabel[] _characterInfo; - - private const int WEIGHT = 0, STATPTS = 1, SKILLPTS = 2, ELEM = 3, - GOLD = 4, EXP = 5, TNL = 6, KARMA = 7; - private readonly IXNALabel[] _otherInfo; - - private CharacterStats _lastCharacterStats; - private InventoryItem _lastCharacterGold; - private bool _confirmedTraining; - - public StatsPanel(INativeGraphicsManager nativeGraphicsManager, - ICharacterProvider characterProvider, - ICharacterInventoryProvider characterInventoryProvider, - IExperienceTableProvider experienceTableProvider, - IEOMessageBoxFactory messageBoxFactory, - ITrainingController trainingController, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(clientWindowSizeProvider.Resizable) + public class StatsPanel : DraggableHudPanel { - _characterProvider = characterProvider; - _characterInventoryProvider = characterInventoryProvider; - _experienceTableProvider = experienceTableProvider; - _messageBoxFactory = messageBoxFactory; - _trainingController = trainingController; - - BackgroundImage = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 34); - DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); - - _basicStats = new IXNALabel[6]; - _arrowButtons = new IXNAButton[6]; - _characterStats = new IXNALabel[6]; - _characterInfo = new IXNALabel[3]; - _otherInfo = new IXNALabel[8]; - - var buttonTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); - var outTextureArea = new Rectangle(215, 386, 19, 15); - var overTextureArea = new Rectangle(234, 386, 19, 15); - - for (int i = 0; i < _basicStats.Length; ++i) + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterInventoryProvider _characterInventoryProvider; + private readonly IExperienceTableProvider _experienceTableProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ITrainingController _trainingController; + private const int STR = 0, INT = 1, WIS = 2, AGI = 3, CON = 4, CHA = 5; + private readonly IXNALabel[] _basicStats; + private readonly IXNAButton[] _arrowButtons; + + private const int HP = 0, TP = 1, DAM = 2, ACC = 3, ARM = 4, EVA = 5; + private readonly IXNALabel[] _characterStats; + + private const int NAME = 0, LEVEL = 1, GUILD = 2; + private readonly IXNALabel[] _characterInfo; + + private const int WEIGHT = 0, STATPTS = 1, SKILLPTS = 2, ELEM = 3, + GOLD = 4, EXP = 5, TNL = 6, KARMA = 7; + private readonly IXNALabel[] _otherInfo; + + private CharacterStats _lastCharacterStats; + private InventoryItem _lastCharacterGold; + private bool _confirmedTraining; + + public StatsPanel(INativeGraphicsManager nativeGraphicsManager, + ICharacterProvider characterProvider, + ICharacterInventoryProvider characterInventoryProvider, + IExperienceTableProvider experienceTableProvider, + IEOMessageBoxFactory messageBoxFactory, + ITrainingController trainingController, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(clientWindowSizeProvider.Resizable) { - _basicStats[i] = new XNALabel(Constants.FontSize08pt5) + _characterProvider = characterProvider; + _characterInventoryProvider = characterInventoryProvider; + _experienceTableProvider = experienceTableProvider; + _messageBoxFactory = messageBoxFactory; + _trainingController = trainingController; + + BackgroundImage = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 34); + DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height); + + _basicStats = new IXNALabel[6]; + _arrowButtons = new IXNAButton[6]; + _characterStats = new IXNALabel[6]; + _characterInfo = new IXNALabel[3]; + _otherInfo = new IXNALabel[8]; + + var buttonTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true); + var outTextureArea = new Rectangle(215, 386, 19, 15); + var overTextureArea = new Rectangle(234, 386, 19, 15); + + for (int i = 0; i < _basicStats.Length; ++i) + { + _basicStats[i] = new XNALabel(Constants.FontSize08pt5) + { + ForeColor = ColorConstants.LightGrayText, + AutoSize = false, + Text = "", + DrawArea = new Rectangle(50, 8 + i * 18, 73, 13) + }; + + _arrowButtons[i] = new XNAButton(buttonTexture, + new Vector2(106, 7 + i * 18), + outTextureArea, + overTextureArea) + { + Visible = false, + FlashSpeed = 500 + }; + } + + for (int i = 0; i < _characterStats.Length; ++i) + { + _characterStats[i] = new XNALabel(Constants.FontSize08pt5) + { + ForeColor = ColorConstants.LightGrayText, + AutoSize = false, + Text = "", + DrawArea = new Rectangle(158, 8 + i * 18, 73, 13) + }; + } + + for (int i = 0; i < _otherInfo.Length; ++i) + { + var drawArea = i < 4 + ? new Rectangle(280, 44 + i % 4 * 18, 60, 13) + : new Rectangle(379, 44 + i % 4 * 18, 94, 13); + + _otherInfo[i] = new XNALabel(Constants.FontSize08pt5) + { + ForeColor = ColorConstants.LightGrayText, + AutoSize = false, + Text = "", + DrawArea = drawArea + }; + } + + _characterInfo[NAME] = new XNALabel(Constants.FontSize08pt5) { ForeColor = ColorConstants.LightGrayText, AutoSize = false, Text = "", - DrawArea = new Rectangle(50, 8 + i * 18, 73, 13) - }; - - _arrowButtons[i] = new XNAButton(buttonTexture, - new Vector2(106, 7 + i * 18), - outTextureArea, - overTextureArea) - { - Visible = false, - FlashSpeed = 500 + DrawArea = new Rectangle(280, 8, 144, 13) }; - } - - for (int i = 0; i < _characterStats.Length; ++i) - { - _characterStats[i] = new XNALabel(Constants.FontSize08pt5) + _characterInfo[GUILD] = new XNALabel(Constants.FontSize08pt5) { ForeColor = ColorConstants.LightGrayText, AutoSize = false, Text = "", - DrawArea = new Rectangle(158, 8 + i * 18, 73, 13) + DrawArea = new Rectangle(280, 26, 193, 13) }; - } - - for (int i = 0; i < _otherInfo.Length; ++i) - { - var drawArea = i < 4 - ? new Rectangle(280, 44 + i % 4 * 18, 60, 13) - : new Rectangle(379, 44 + i % 4 * 18, 94, 13); - - _otherInfo[i] = new XNALabel(Constants.FontSize08pt5) + _characterInfo[LEVEL] = new XNALabel(Constants.FontSize08pt5) { ForeColor = ColorConstants.LightGrayText, AutoSize = false, Text = "", - DrawArea = drawArea + DrawArea = new Rectangle(453, 8, 20, 13) }; } - _characterInfo[NAME] = new XNALabel(Constants.FontSize08pt5) - { - ForeColor = ColorConstants.LightGrayText, - AutoSize = false, - Text = "", - DrawArea = new Rectangle(280, 8, 144, 13) - }; - _characterInfo[GUILD] = new XNALabel(Constants.FontSize08pt5) + public override void Initialize() { - ForeColor = ColorConstants.LightGrayText, - AutoSize = false, - Text = "", - DrawArea = new Rectangle(280, 26, 193, 13) - }; - _characterInfo[LEVEL] = new XNALabel(Constants.FontSize08pt5) - { - ForeColor = ColorConstants.LightGrayText, - AutoSize = false, - Text = "", - DrawArea = new Rectangle(453, 8, 20, 13) - }; - } + foreach (var control in _arrowButtons) + control.OnClick += HandleArrowButtonClick; + + var controls = _basicStats.Concat(_characterStats) + .Concat(_arrowButtons) + .Concat(_characterInfo) + .Concat(_otherInfo); + foreach (var control in controls) + { + control.SetParentControl(this); + control.Initialize(); + } - public override void Initialize() - { - foreach (var control in _arrowButtons) - control.OnClick += HandleArrowButtonClick; - - var controls = _basicStats.Concat(_characterStats) - .Concat(_arrowButtons) - .Concat(_characterInfo) - .Concat(_otherInfo); - foreach (var control in controls) - { - control.SetParentControl(this); - control.Initialize(); + base.Initialize(); } - base.Initialize(); - } - - protected override void OnUpdateControl(GameTime gameTime) - { - if (_lastCharacterStats != _characterProvider.MainCharacter.Stats || - _lastCharacterGold != CurrentCharacterGold) + protected override void OnUpdateControl(GameTime gameTime) { - _lastCharacterStats = _characterProvider.MainCharacter.Stats; - _lastCharacterGold = CurrentCharacterGold; - - _basicStats[STR].Text = $"{_lastCharacterStats[CharacterStat.Strength]}"; - _basicStats[INT].Text = $"{_lastCharacterStats[CharacterStat.Intelligence]}"; - _basicStats[WIS].Text = $"{_lastCharacterStats[CharacterStat.Wisdom]}"; - _basicStats[AGI].Text = $"{_lastCharacterStats[CharacterStat.Agility]}"; - _basicStats[CON].Text = $"{_lastCharacterStats[CharacterStat.Constitution]}"; - _basicStats[CHA].Text = $"{_lastCharacterStats[CharacterStat.Charisma]}"; - - _characterStats[HP].Text = $"{_lastCharacterStats[CharacterStat.HP]}"; - _characterStats[TP].Text = $"{_lastCharacterStats[CharacterStat.TP]}"; - _characterStats[DAM].Text = $"{_lastCharacterStats[CharacterStat.MinDam]} - {_lastCharacterStats[CharacterStat.MaxDam]}"; - _characterStats[ACC].Text = $"{_lastCharacterStats[CharacterStat.Accuracy]}"; - _characterStats[EVA].Text = $"{_lastCharacterStats[CharacterStat.Evade]}"; - _characterStats[ARM].Text = $"{_lastCharacterStats[CharacterStat.Armor]}"; - - _otherInfo[WEIGHT].Text = $"{_lastCharacterStats[CharacterStat.Weight]} / {_lastCharacterStats[CharacterStat.MaxWeight]}"; - _otherInfo[STATPTS].Text = $"{_lastCharacterStats[CharacterStat.StatPoints]}"; - _otherInfo[SKILLPTS].Text = $"{_lastCharacterStats[CharacterStat.SkillPoints]}"; - _otherInfo[ELEM].Text = ""; //Elements are not supported by Endless Online :( - _otherInfo[GOLD].Text = $"{CurrentCharacterGold.Amount}"; - _otherInfo[EXP].Text = $"{_lastCharacterStats[CharacterStat.Experience]}"; - _otherInfo[TNL].Text = $"{ExperienceToNextLevel}"; - _otherInfo[KARMA].Text = $"{_lastCharacterStats.GetKarmaString()}"; - - _characterInfo[NAME].Text = $"{_characterProvider.MainCharacter.Name}"; - _characterInfo[GUILD].Text = $"{_characterProvider.MainCharacter.GuildName}"; - _characterInfo[LEVEL].Text = $"{_lastCharacterStats[CharacterStat.Level]}"; - - if (_lastCharacterStats.Stats[CharacterStat.StatPoints] > 0) + if (_lastCharacterStats != _characterProvider.MainCharacter.Stats || + _lastCharacterGold != CurrentCharacterGold) { - foreach (var button in _arrowButtons.OfType()) - button.Visible = true; + _lastCharacterStats = _characterProvider.MainCharacter.Stats; + _lastCharacterGold = CurrentCharacterGold; + + _basicStats[STR].Text = $"{_lastCharacterStats[CharacterStat.Strength]}"; + _basicStats[INT].Text = $"{_lastCharacterStats[CharacterStat.Intelligence]}"; + _basicStats[WIS].Text = $"{_lastCharacterStats[CharacterStat.Wisdom]}"; + _basicStats[AGI].Text = $"{_lastCharacterStats[CharacterStat.Agility]}"; + _basicStats[CON].Text = $"{_lastCharacterStats[CharacterStat.Constitution]}"; + _basicStats[CHA].Text = $"{_lastCharacterStats[CharacterStat.Charisma]}"; + + _characterStats[HP].Text = $"{_lastCharacterStats[CharacterStat.HP]}"; + _characterStats[TP].Text = $"{_lastCharacterStats[CharacterStat.TP]}"; + _characterStats[DAM].Text = $"{_lastCharacterStats[CharacterStat.MinDam]} - {_lastCharacterStats[CharacterStat.MaxDam]}"; + _characterStats[ACC].Text = $"{_lastCharacterStats[CharacterStat.Accuracy]}"; + _characterStats[EVA].Text = $"{_lastCharacterStats[CharacterStat.Evade]}"; + _characterStats[ARM].Text = $"{_lastCharacterStats[CharacterStat.Armor]}"; + + _otherInfo[WEIGHT].Text = $"{_lastCharacterStats[CharacterStat.Weight]} / {_lastCharacterStats[CharacterStat.MaxWeight]}"; + _otherInfo[STATPTS].Text = $"{_lastCharacterStats[CharacterStat.StatPoints]}"; + _otherInfo[SKILLPTS].Text = $"{_lastCharacterStats[CharacterStat.SkillPoints]}"; + _otherInfo[ELEM].Text = ""; //Elements are not supported by Endless Online :( + _otherInfo[GOLD].Text = $"{CurrentCharacterGold.Amount}"; + _otherInfo[EXP].Text = $"{_lastCharacterStats[CharacterStat.Experience]}"; + _otherInfo[TNL].Text = $"{ExperienceToNextLevel}"; + _otherInfo[KARMA].Text = $"{_lastCharacterStats.GetKarmaString()}"; + + _characterInfo[NAME].Text = $"{_characterProvider.MainCharacter.Name}"; + _characterInfo[GUILD].Text = $"{_characterProvider.MainCharacter.GuildName}"; + _characterInfo[LEVEL].Text = $"{_lastCharacterStats[CharacterStat.Level]}"; + + if (_lastCharacterStats.Stats[CharacterStat.StatPoints] > 0) + { + foreach (var button in _arrowButtons.OfType()) + button.Visible = true; + } + else + { + foreach (var button in _arrowButtons.OfType()) + button.Visible = false; + _confirmedTraining = false; + } } - else - { - foreach (var button in _arrowButtons.OfType()) - button.Visible = false; - _confirmedTraining = false; - } - } - base.OnUpdateControl(gameTime); - } + base.OnUpdateControl(gameTime); + } - private void HandleArrowButtonClick(object sender, EventArgs e) - { - if (!_confirmedTraining) + private void HandleArrowButtonClick(object sender, EventArgs e) { - var dialog = _messageBoxFactory.CreateMessageBox("Do you want to train?", - "Character training", - EODialogButtons.OkCancel); - - dialog.DialogClosing += (_, e) => + if (!_confirmedTraining) { + var dialog = _messageBoxFactory.CreateMessageBox("Do you want to train?", + "Character training", + EODialogButtons.OkCancel); - if (e.Result == XNADialogResult.OK) - _confirmedTraining = true; - }; + dialog.DialogClosing += (_, e) => + { - dialog.ShowDialog(); - } - else - { - var index = _arrowButtons.Select((btn, ndx) => new { btn, ndx }) - .Single(x => x.btn == sender).ndx; - var characterStat = CharacterStat.Strength + index; - _trainingController.AddStatPoint(characterStat); + if (e.Result == XNADialogResult.OK) + _confirmedTraining = true; + }; + + dialog.ShowDialog(); + } + else + { + var index = _arrowButtons.Select((btn, ndx) => new { btn, ndx }) + .Single(x => x.btn == sender).ndx; + var characterStat = CharacterStat.Strength + index; + _trainingController.AddStatPoint(characterStat); + } } - } - private InventoryItem CurrentCharacterGold - => _characterInventoryProvider.ItemInventory.Single(x => x.ItemID == 1); + private InventoryItem CurrentCharacterGold + => _characterInventoryProvider.ItemInventory.Single(x => x.ItemID == 1); - private int ExperienceToNextLevel => - _experienceTableProvider.ExperienceByLevel[ - _characterProvider.MainCharacter.Stats[CharacterStat.Level] + 1 - ] - _lastCharacterStats[CharacterStat.Experience]; + private int ExperienceToNextLevel => + _experienceTableProvider.ExperienceByLevel[ + _characterProvider.MainCharacter.Stats[CharacterStat.Level] + 1 + ] - _lastCharacterStats[CharacterStat.Experience]; + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Party/PartyPanelMember.cs b/EndlessClient/HUD/Party/PartyPanelMember.cs index abf6ba5b1..f37254f22 100644 --- a/EndlessClient/HUD/Party/PartyPanelMember.cs +++ b/EndlessClient/HUD/Party/PartyPanelMember.cs @@ -9,126 +9,127 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Party; - -public class PartyPanelMember : XNAControl +namespace EndlessClient.HUD.Party { - private readonly IContentProvider _contentProvider; - private readonly Texture2D _chatIconsTexture; + public class PartyPanelMember : XNAControl + { + private readonly IContentProvider _contentProvider; + private readonly Texture2D _chatIconsTexture; - private readonly IXNAButton _removeButton; - private readonly IXNALabel _nameLabel, _levelLabel, _hpLabel; + private readonly IXNAButton _removeButton; + private readonly IXNALabel _nameLabel, _levelLabel, _hpLabel; - private ChatIcon _playerIcon; - private Rectangle _iconSource; + private ChatIcon _playerIcon; + private Rectangle _iconSource; - private int _displayIndex; - public int DisplayIndex - { - get => _displayIndex; - set + private int _displayIndex; + public int DisplayIndex { - _displayIndex = value; + get => _displayIndex; + set + { + _displayIndex = value; - DrawArea = new Rectangle(0, 20 + _displayIndex * 13, ImmediateParent?.DrawArea.Width ?? 0, 13); + DrawArea = new Rectangle(0, 20 + _displayIndex * 13, ImmediateParent?.DrawArea.Width ?? 0, 13); + } } - } - private PartyMember _partyMember; - public PartyMember PartyMember - { - get => _partyMember; - set + private PartyMember _partyMember; + public PartyMember PartyMember { - _partyMember = value; - _nameLabel.Text = _partyMember.Name; - _levelLabel.Text = $"{_partyMember.Level}"; - - _playerIcon = _partyMember.IsLeader ? ChatIcon.Star : ChatIcon.Player; - var (X, Y, Width, Height) = _playerIcon.GetChatIconRectangleBounds().ValueOr((0, 0, 0, 0)); - _iconSource = new Rectangle(X, Y, Width, Height); + get => _partyMember; + set + { + _partyMember = value; + _nameLabel.Text = _partyMember.Name; + _levelLabel.Text = $"{_partyMember.Level}"; + + _playerIcon = _partyMember.IsLeader ? ChatIcon.Star : ChatIcon.Player; + var (X, Y, Width, Height) = _playerIcon.GetChatIconRectangleBounds().ValueOr((0, 0, 0, 0)); + _iconSource = new Rectangle(X, Y, Width, Height); + } } - } - - public event EventHandler RemoveAction; - public PartyPanelMember(INativeGraphicsManager nativeGraphicsManager, - IContentProvider contentProvider, - bool isRemovable) - { - _contentProvider = contentProvider; - _chatIconsTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); - - var removeTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 43); - var delta = removeTexture.Height / 3; - _removeButton = new XNAButton(removeTexture, - new Vector2(337, 0), - isRemovable - ? new Rectangle(0, 0, removeTexture.Width, delta) - : new Rectangle(0, delta, removeTexture.Width, delta), - isRemovable - ? new Rectangle(0, delta * 2, removeTexture.Width, delta) - : new Rectangle(0, delta, removeTexture.Width, delta)); - - if (isRemovable) - _removeButton.OnClick += (o, e) => RemoveAction?.Invoke(o, e); - _removeButton.SetParentControl(this); - - _nameLabel = new XNALabel(Constants.FontSize08) - { - DrawPosition = new Vector2(23, 0), - AutoSize = true, - ForeColor = Color.Black - }; - _nameLabel.SetParentControl(this); + public event EventHandler RemoveAction; - _levelLabel = new XNALabel(Constants.FontSize08) + public PartyPanelMember(INativeGraphicsManager nativeGraphicsManager, + IContentProvider contentProvider, + bool isRemovable) { - DrawPosition = new Vector2(138, 0), - AutoSize = true, - ForeColor = Color.Black - }; - _levelLabel.SetParentControl(this); + _contentProvider = contentProvider; + _chatIconsTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true); + + var removeTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 43); + var delta = removeTexture.Height / 3; + _removeButton = new XNAButton(removeTexture, + new Vector2(337, 0), + isRemovable + ? new Rectangle(0, 0, removeTexture.Width, delta) + : new Rectangle(0, delta, removeTexture.Width, delta), + isRemovable + ? new Rectangle(0, delta * 2, removeTexture.Width, delta) + : new Rectangle(0, delta, removeTexture.Width, delta)); + + if (isRemovable) + _removeButton.OnClick += (o, e) => RemoveAction?.Invoke(o, e); + _removeButton.SetParentControl(this); + + _nameLabel = new XNALabel(Constants.FontSize08) + { + DrawPosition = new Vector2(23, 0), + AutoSize = true, + ForeColor = Color.Black + }; + _nameLabel.SetParentControl(this); + + _levelLabel = new XNALabel(Constants.FontSize08) + { + DrawPosition = new Vector2(138, 0), + AutoSize = true, + ForeColor = Color.Black + }; + _levelLabel.SetParentControl(this); + + _hpLabel = new XNALabel(Constants.FontSize08) + { + DrawPosition = new Vector2(205, 0), + AutoSize = true, + ForeColor = Color.Black, + Text = "HP" + }; + _hpLabel.SetParentControl(this); + } - _hpLabel = new XNALabel(Constants.FontSize08) + public override void Initialize() { - DrawPosition = new Vector2(205, 0), - AutoSize = true, - ForeColor = Color.Black, - Text = "HP" - }; - _hpLabel.SetParentControl(this); - } + _removeButton.Initialize(); + _nameLabel.Initialize(); + _levelLabel.Initialize(); + _hpLabel.Initialize(); - public override void Initialize() - { - _removeButton.Initialize(); - _nameLabel.Initialize(); - _levelLabel.Initialize(); - _hpLabel.Initialize(); - - base.Initialize(); - } + base.Initialize(); + } - protected override void OnDrawControl(GameTime gameTime) - { - var iconDrawPosition = DrawPositionWithParentOffset + new Vector2(5, 1); - var healthBarDrawPosition = DrawPositionWithParentOffset + new Vector2(228, 1); + protected override void OnDrawControl(GameTime gameTime) + { + var iconDrawPosition = DrawPositionWithParentOffset + new Vector2(5, 1); + var healthBarDrawPosition = DrawPositionWithParentOffset + new Vector2(228, 1); - var barTexture = _partyMember.PercentHealth > 50 - ? _contentProvider.Textures[ContentProvider.HPGreen] - : _partyMember.PercentHealth > 25 - ? _contentProvider.Textures[ContentProvider.HPYellow] - : _contentProvider.Textures[ContentProvider.HPRed]; + var barTexture = _partyMember.PercentHealth > 50 + ? _contentProvider.Textures[ContentProvider.HPGreen] + : _partyMember.PercentHealth > 25 + ? _contentProvider.Textures[ContentProvider.HPYellow] + : _contentProvider.Textures[ContentProvider.HPRed]; - var barSource = new Rectangle(0, 0, (int)Math.Round(barTexture.Width * (_partyMember.PercentHealth / 100.0)), barTexture.Height); + var barSource = new Rectangle(0, 0, (int)Math.Round(barTexture.Width * (_partyMember.PercentHealth / 100.0)), barTexture.Height); - _spriteBatch.Begin(); - _spriteBatch.Draw(_chatIconsTexture, iconDrawPosition, _iconSource, Color.White); - _spriteBatch.Draw(_contentProvider.Textures[ContentProvider.HPOutline], healthBarDrawPosition, Color.White); - _spriteBatch.Draw(barTexture, healthBarDrawPosition, barSource, Color.White); - _spriteBatch.End(); + _spriteBatch.Begin(); + _spriteBatch.Draw(_chatIconsTexture, iconDrawPosition, _iconSource, Color.White); + _spriteBatch.Draw(_contentProvider.Textures[ContentProvider.HPOutline], healthBarDrawPosition, Color.White); + _spriteBatch.Draw(barTexture, healthBarDrawPosition, barSource, Color.White); + _spriteBatch.End(); - base.OnDrawControl(gameTime); + base.OnDrawControl(gameTime); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/Spells/SpellPanelItem.cs b/EndlessClient/HUD/Spells/SpellPanelItem.cs index d7c2b39b1..ad936f914 100644 --- a/EndlessClient/HUD/Spells/SpellPanelItem.cs +++ b/EndlessClient/HUD/Spells/SpellPanelItem.cs @@ -11,188 +11,189 @@ using System; using XNAControls; -namespace EndlessClient.HUD.Spells; - -public class SpellPanelItem : DraggablePanelItem +namespace EndlessClient.HUD.Spells { - private const int ICON_AREA_WIDTH = 42, ICON_AREA_HEIGHT = 36; + public class SpellPanelItem : DraggablePanelItem + { + private const int ICON_AREA_WIDTH = 42, ICON_AREA_HEIGHT = 36; - private readonly ISfxPlayer _sfxPlayer; + private readonly ISfxPlayer _sfxPlayer; - private readonly Texture2D _spellGraphic; - private Rectangle _spellGraphicSourceRect; + private readonly Texture2D _spellGraphic; + private Rectangle _spellGraphicSourceRect; - private readonly Texture2D _whitePixel; + private readonly Texture2D _whitePixel; - public int Slot { get; set; } + public int Slot { get; set; } - private int _displaySlot; - public int DisplaySlot - { - get => _displaySlot; - set + private int _displaySlot; + public int DisplaySlot { - _displaySlot = value; - DrawPosition = GetDisplayPosition(_displaySlot); + get => _displaySlot; + set + { + _displaySlot = value; + DrawPosition = GetDisplayPosition(_displaySlot); + } } - } - public InventorySpell InventorySpell { get; set; } + public InventorySpell InventorySpell { get; set; } - public override Rectangle EventArea => IsDragging ? DrawArea : DrawAreaWithParentOffset; + public override Rectangle EventArea => IsDragging ? DrawArea : DrawAreaWithParentOffset; - // uses absolute coordinates - protected override Rectangle GridArea => new Rectangle( - _parentContainer.DrawPositionWithParentOffset.ToPoint() + new Point(98, 6), - new Point(363, 102)); + // uses absolute coordinates + protected override Rectangle GridArea => new Rectangle( + _parentContainer.DrawPositionWithParentOffset.ToPoint() + new Point(98, 6), + new Point(363, 102)); - public event EventHandler Click; + public event EventHandler Click; - public SpellPanelItem(ActiveSpellsPanel spellPanel, - ISfxPlayer sfxPlayer, - int slot, - InventorySpell spell, - ESFRecord data) - : base(spellPanel) - { - _sfxPlayer = sfxPlayer; + public SpellPanelItem(ActiveSpellsPanel spellPanel, + ISfxPlayer sfxPlayer, + int slot, + InventorySpell spell, + ESFRecord data) + : base(spellPanel) + { + _sfxPlayer = sfxPlayer; - Slot = DisplaySlot = slot; - InventorySpell = spell; - Data = data; + Slot = DisplaySlot = slot; + InventorySpell = spell; + Data = data; - _spellGraphic = spellPanel.NativeGraphicsManager.TextureFromResource(GFXTypes.SpellIcons, Data.Icon); - _spellGraphicSourceRect = new Rectangle(0, 0, _spellGraphic.Width / 2, _spellGraphic.Height); + _spellGraphic = spellPanel.NativeGraphicsManager.TextureFromResource(GFXTypes.SpellIcons, Data.Icon); + _spellGraphicSourceRect = new Rectangle(0, 0, _spellGraphic.Width / 2, _spellGraphic.Height); - _whitePixel = new Texture2D(Game.GraphicsDevice, 1, 1); - _whitePixel.SetData(new[] { Color.White }); + _whitePixel = new Texture2D(Game.GraphicsDevice, 1, 1); + _whitePixel.SetData(new[] { Color.White }); - SetSize(ICON_AREA_WIDTH, ICON_AREA_HEIGHT); - } + SetSize(ICON_AREA_WIDTH, ICON_AREA_HEIGHT); + } - public int GetCurrentSlotBasedOnPosition(int scrollOffset) - { - if (!IsDragging) - return Slot; + public int GetCurrentSlotBasedOnPosition(int scrollOffset) + { + if (!IsDragging) + return Slot; - // old offset X needs to be adjusted since it assumes parent coordinates are the start of the slot grid - // this works for inventory without adjustment since the grid goes all the way to the parent panel coordinate - // however, spell panel has 2 slots worth of padding for the selected slot / level up controls - var adjustedOffsetX = OldOffset.X + (ICON_AREA_WIDTH * 2); + // old offset X needs to be adjusted since it assumes parent coordinates are the start of the slot grid + // this works for inventory without adjustment since the grid goes all the way to the parent panel coordinate + // however, spell panel has 2 slots worth of padding for the selected slot / level up controls + var adjustedOffsetX = OldOffset.X + (ICON_AREA_WIDTH * 2); - return scrollOffset * ActiveSpellsPanel.SpellRowLength + - (int)((DrawPosition.X - adjustedOffsetX) / ICON_AREA_WIDTH) + - ActiveSpellsPanel.SpellRowLength * (int)((DrawPosition.Y - OldOffset.Y) / ICON_AREA_HEIGHT); - } + return scrollOffset * ActiveSpellsPanel.SpellRowLength + + (int)((DrawPosition.X - adjustedOffsetX) / ICON_AREA_WIDTH) + + ActiveSpellsPanel.SpellRowLength * (int)((DrawPosition.Y - OldOffset.Y) / ICON_AREA_HEIGHT); + } - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); - DrawLevelAndHighlight(); - DrawSpellIcon(); + DrawLevelAndHighlight(); + DrawSpellIcon(); - _spriteBatch.End(); + _spriteBatch.End(); - base.OnDrawControl(gameTime); - } + base.OnDrawControl(gameTime); + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (_parentContainer.NoItemsDragging()) - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + if (_parentContainer.NoItemsDragging()) + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - Click?.Invoke(control, eventArgs); - return base.HandleClick(control, eventArgs); - } + Click?.Invoke(control, eventArgs); + return base.HandleClick(control, eventArgs); + } - protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) - { - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); + protected override bool HandleDragStart(IXNAControl control, MouseEventArgs eventArgs) + { + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPickup); - return base.HandleDragStart(control, eventArgs); - } + return base.HandleDragStart(control, eventArgs); + } - protected override void OnDraggingFinished(DragCompletedEventArgs args) - { - base.OnDraggingFinished(args); + protected override void OnDraggingFinished(DragCompletedEventArgs args) + { + base.OnDraggingFinished(args); - _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); - DrawPosition = GetDisplayPosition(DisplaySlot); - } + _sfxPlayer.PlaySfx(SoundEffectID.InventoryPlace); + DrawPosition = GetDisplayPosition(DisplaySlot); + } - protected override void Dispose(bool disposing) - { - if (disposing) + protected override void Dispose(bool disposing) { - _whitePixel.Dispose(); - } + if (disposing) + { + _whitePixel.Dispose(); + } - base.Dispose(disposing); - } + base.Dispose(disposing); + } - private void DrawLevelAndHighlight() - { - if (!IsDragging) + private void DrawLevelAndHighlight() { - var width = (int)(InventorySpell.Level / 100.0 * 36); - var levelDestinationRectangle = new Rectangle(DrawAreaWithParentOffset.X + 3, DrawAreaWithParentOffset.Y + 40, width, 6); - _spriteBatch.Draw(_whitePixel, levelDestinationRectangle, Color.FromNonPremultiplied(0xc9, 0xb8, 0x9b, 0xff)); + if (!IsDragging) + { + var width = (int)(InventorySpell.Level / 100.0 * 36); + var levelDestinationRectangle = new Rectangle(DrawAreaWithParentOffset.X + 3, DrawAreaWithParentOffset.Y + 40, width, 6); + _spriteBatch.Draw(_whitePixel, levelDestinationRectangle, Color.FromNonPremultiplied(0xc9, 0xb8, 0x9b, 0xff)); + } + + if (MouseOver) + { + if (!IsDragging) + { + _spriteBatch.Draw(_whitePixel, DrawAreaWithParentOffset, Color.FromNonPremultiplied(200, 200, 200, 60)); + } + else + { + var highlightPosition = GetDisplayPosition(DisplaySlot); + var highlightRectangle = new Rectangle((_parentContainer.DrawPositionWithParentOffset + highlightPosition).ToPoint(), DrawArea.Size); + + if (highlightRectangle.Contains(Mouse.GetState().Position)) + _spriteBatch.Draw(_whitePixel, highlightRectangle, Color.FromNonPremultiplied(200, 200, 200, 60)); + } + } } - if (MouseOver) + private void DrawSpellIcon() { + var halfWidth = _spellGraphic.Width / 2; + _spellGraphicSourceRect = new Rectangle(MouseOver ? halfWidth : 0, 0, halfWidth, _spellGraphic.Height); + + Rectangle targetDrawArea; if (!IsDragging) { - _spriteBatch.Draw(_whitePixel, DrawAreaWithParentOffset, Color.FromNonPremultiplied(200, 200, 200, 60)); + targetDrawArea = new Rectangle( + DrawAreaWithParentOffset.X + (DrawAreaWithParentOffset.Width - _spellGraphicSourceRect.Width) / 2, + DrawAreaWithParentOffset.Y + (DrawAreaWithParentOffset.Height - _spellGraphicSourceRect.Height) / 2, + _spellGraphicSourceRect.Width, + _spellGraphicSourceRect.Height); } else { - var highlightPosition = GetDisplayPosition(DisplaySlot); - var highlightRectangle = new Rectangle((_parentContainer.DrawPositionWithParentOffset + highlightPosition).ToPoint(), DrawArea.Size); - - if (highlightRectangle.Contains(Mouse.GetState().Position)) - _spriteBatch.Draw(_whitePixel, highlightRectangle, Color.FromNonPremultiplied(200, 200, 200, 60)); + targetDrawArea = new Rectangle( + Mouse.GetState().X - _spellGraphicSourceRect.Width / 2, + Mouse.GetState().Y - _spellGraphicSourceRect.Height / 2, + _spellGraphicSourceRect.Width, + _spellGraphicSourceRect.Height + ); } - } - } - - private void DrawSpellIcon() - { - var halfWidth = _spellGraphic.Width / 2; - _spellGraphicSourceRect = new Rectangle(MouseOver ? halfWidth : 0, 0, halfWidth, _spellGraphic.Height); - Rectangle targetDrawArea; - if (!IsDragging) - { - targetDrawArea = new Rectangle( - DrawAreaWithParentOffset.X + (DrawAreaWithParentOffset.Width - _spellGraphicSourceRect.Width) / 2, - DrawAreaWithParentOffset.Y + (DrawAreaWithParentOffset.Height - _spellGraphicSourceRect.Height) / 2, - _spellGraphicSourceRect.Width, - _spellGraphicSourceRect.Height); + _spriteBatch.Draw(_spellGraphic, + targetDrawArea, + _spellGraphicSourceRect, + Color.FromNonPremultiplied(255, 255, 255, IsDragging ? 127 : 255)); } - else + + private static Vector2 GetDisplayPosition(int slot) { - targetDrawArea = new Rectangle( - Mouse.GetState().X - _spellGraphicSourceRect.Width / 2, - Mouse.GetState().Y - _spellGraphicSourceRect.Height / 2, - _spellGraphicSourceRect.Width, - _spellGraphicSourceRect.Height - ); + //start pos: 101, 97 + //xdelta: 45; ydelta: 52 + var row = slot / ActiveSpellsPanel.SpellRowLength; + var col = slot % ActiveSpellsPanel.SpellRowLength; + return new Vector2(101 + col * 45, 9 + row * 52); } - - _spriteBatch.Draw(_spellGraphic, - targetDrawArea, - _spellGraphicSourceRect, - Color.FromNonPremultiplied(255, 255, 255, IsDragging ? 127 : 255)); - } - - private static Vector2 GetDisplayPosition(int slot) - { - //start pos: 101, 97 - //xdelta: 45; ydelta: 52 - var row = slot / ActiveSpellsPanel.SpellRowLength; - var col = slot % ActiveSpellsPanel.SpellRowLength; - return new Vector2(101 + col * 45, 9 + row * 52); } } \ No newline at end of file diff --git a/EndlessClient/HUD/Spells/SpellSelectActions.cs b/EndlessClient/HUD/Spells/SpellSelectActions.cs index 25e143f71..58a3035bf 100644 --- a/EndlessClient/HUD/Spells/SpellSelectActions.cs +++ b/EndlessClient/HUD/Spells/SpellSelectActions.cs @@ -5,56 +5,57 @@ using Optional; using System.Linq; -namespace EndlessClient.HUD.Spells; - -[AutoMappedType] -public class SpellSelectActions : ISpellSelectActions +namespace EndlessClient.HUD.Spells { - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly IPartyDataProvider _partyDataProvider; - private readonly IESFFileProvider _esfFileProvider; - - public SpellSelectActions(IStatusLabelSetter statusLabelSetter, - ISpellSlotDataRepository spellSlotDataRepository, - IPartyDataProvider partyDataProvider, - IESFFileProvider esfFileProvider) + [AutoMappedType] + public class SpellSelectActions : ISpellSelectActions { - _statusLabelSetter = statusLabelSetter; - _spellSlotDataRepository = spellSlotDataRepository; - _partyDataProvider = partyDataProvider; - _esfFileProvider = esfFileProvider; - } + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly IPartyDataProvider _partyDataProvider; + private readonly IESFFileProvider _esfFileProvider; - public void SelectSpellBySlot(int slot) - { - _spellSlotDataRepository.SpellSlots[slot].Match( - some: si => - { - var spellData = _esfFileProvider.ESFFile[si.ID]; + public SpellSelectActions(IStatusLabelSetter statusLabelSetter, + ISpellSlotDataRepository spellSlotDataRepository, + IPartyDataProvider partyDataProvider, + IESFFileProvider esfFileProvider) + { + _statusLabelSetter = statusLabelSetter; + _spellSlotDataRepository = spellSlotDataRepository; + _partyDataProvider = partyDataProvider; + _esfFileProvider = esfFileProvider; + } - if (spellData.Target == EOLib.IO.SpellTarget.Group && !_partyDataProvider.Members.Any()) + public void SelectSpellBySlot(int slot) + { + _spellSlotDataRepository.SpellSlots[slot].Match( + some: si => { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.SPELL_ONLY_WORKS_ON_GROUP); - } - else + var spellData = _esfFileProvider.ESFFile[si.ID]; + + if (spellData.Target == EOLib.IO.SpellTarget.Group && !_partyDataProvider.Members.Any()) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.SPELL_ONLY_WORKS_ON_GROUP); + } + else + { + _statusLabelSetter.SetStatusLabel(EOResourceID.SKILLMASTER_WORD_SPELL, $"{spellData.Name} ", EOResourceID.SPELL_WAS_SELECTED); + _spellSlotDataRepository.SelectedSpellSlot = Option.Some(slot); + _spellSlotDataRepository.SpellIsPrepared = true; + } + }, + none: () => { - _statusLabelSetter.SetStatusLabel(EOResourceID.SKILLMASTER_WORD_SPELL, $"{spellData.Name} ", EOResourceID.SPELL_WAS_SELECTED); - _spellSlotDataRepository.SelectedSpellSlot = Option.Some(slot); - _spellSlotDataRepository.SpellIsPrepared = true; - } - }, - none: () => - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.SPELL_NOTHING_WAS_SELECTED); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.SPELL_NOTHING_WAS_SELECTED); - _spellSlotDataRepository.SelectedSpellSlot = Option.None(); - _spellSlotDataRepository.SpellIsPrepared = false; - }); + _spellSlotDataRepository.SelectedSpellSlot = Option.None(); + _spellSlotDataRepository.SpellIsPrepared = false; + }); + } } -} -public interface ISpellSelectActions -{ - void SelectSpellBySlot(int slot); + public interface ISpellSelectActions + { + void SelectSpellBySlot(int slot); + } } \ No newline at end of file diff --git a/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs b/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs index 0243a224d..e6bae1c2e 100644 --- a/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs +++ b/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs @@ -4,62 +4,63 @@ using Optional; using System.Collections.Generic; -namespace EndlessClient.HUD.Spells; - -public interface ISpellSlotDataRepository +namespace EndlessClient.HUD.Spells { - /// - /// Slot for the selected spell displayed in the UI (or none if nothing is selected). A selected spell is not necessarily prepared for cast via hotkey selection. - /// - Option SelectedSpellSlot { get; set; } + public interface ISpellSlotDataRepository + { + /// + /// Slot for the selected spell displayed in the UI (or none if nothing is selected). A selected spell is not necessarily prepared for cast via hotkey selection. + /// + Option SelectedSpellSlot { get; set; } - /// - /// Spell info for the selected spell (based on SelectedSpellSlot value) - /// - Option SelectedSpellInfo { get; } + /// + /// Spell info for the selected spell (based on SelectedSpellSlot value) + /// + Option SelectedSpellInfo { get; } - /// - /// True if the selected spell slot has been prepared by using a hotkey. - /// - bool SpellIsPrepared { get; set; } + /// + /// True if the selected spell slot has been prepared by using a hotkey. + /// + bool SpellIsPrepared { get; set; } - /// - /// Array of inventory spells by their slot number. - /// - Option[] SpellSlots { get; set; } -} + /// + /// Array of inventory spells by their slot number. + /// + Option[] SpellSlots { get; set; } + } -public interface ISpellSlotDataProvider -{ - Option SelectedSpellSlot { get; } + public interface ISpellSlotDataProvider + { + Option SelectedSpellSlot { get; } - Option SelectedSpellInfo { get; } + Option SelectedSpellInfo { get; } - bool SpellIsPrepared { get; } + bool SpellIsPrepared { get; } - IReadOnlyList> SpellSlots { get; } -} + IReadOnlyList> SpellSlots { get; } + } -[AutoMappedType(IsSingleton = true)] -public class SpellSlotDataRepository : ISpellSlotDataRepository, ISpellSlotDataProvider -{ - public Option SelectedSpellSlot { get; set; } + [AutoMappedType(IsSingleton = true)] + public class SpellSlotDataRepository : ISpellSlotDataRepository, ISpellSlotDataProvider + { + public Option SelectedSpellSlot { get; set; } - public Option SelectedSpellInfo => - SelectedSpellSlot.Match( - x => SpellSlots[x].Match( - y => Option.Some(y), - () => Option.None()), - () => Option.None()); + public Option SelectedSpellInfo => + SelectedSpellSlot.Match( + x => SpellSlots[x].Match( + y => Option.Some(y), + () => Option.None()), + () => Option.None()); - public bool SpellIsPrepared { get; set; } + public bool SpellIsPrepared { get; set; } - public Option[] SpellSlots { get; set; } + public Option[] SpellSlots { get; set; } - IReadOnlyList> ISpellSlotDataProvider.SpellSlots => SpellSlots; + IReadOnlyList> ISpellSlotDataProvider.SpellSlots => SpellSlots; - public SpellSlotDataRepository() - { - SpellSlots = new Option[ActiveSpellsPanel.SpellRows * ActiveSpellsPanel.SpellRowLength]; + public SpellSlotDataRepository() + { + SpellSlots = new Option[ActiveSpellsPanel.SpellRows * ActiveSpellsPanel.SpellRowLength]; + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/HPStatusBar.cs b/EndlessClient/HUD/StatusBars/HPStatusBar.cs index 335c3171e..03150e25c 100644 --- a/EndlessClient/HUD/StatusBars/HPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/HPStatusBar.cs @@ -4,35 +4,36 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.HUD.StatusBars; - -public class HPStatusBar : StatusBarBase +namespace EndlessClient.HUD.StatusBars { - protected override int StatusBarIndex => -2; - - public HPStatusBar(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider) - : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + public class HPStatusBar : StatusBarBase { - DrawArea = new Rectangle(100, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); - ChangeStatusBarPosition(); - } + protected override int StatusBarIndex => -2; - protected override void UpdateLabelText() - { - _label.Text = $"{Stats[CharacterStat.HP]}/{Stats[CharacterStat.MaxHP]}"; - } + public HPStatusBar(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider) + : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + { + DrawArea = new Rectangle(100, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); + ChangeStatusBarPosition(); + } - protected override void DrawStatusBar() - { - //todo: figure out these magic numbers - var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.HP] / (double)Stats[CharacterStat.MaxHP] * 79); - var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); + protected override void UpdateLabelText() + { + _label.Text = $"{Stats[CharacterStat.HP]}/{Stats[CharacterStat.MaxHP]}"; + } + + protected override void DrawStatusBar() + { + //todo: figure out these magic numbers + var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.HP] / (double)Stats[CharacterStat.MaxHP] * 79); + var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); - _spriteBatch.Begin(); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); - _spriteBatch.End(); + _spriteBatch.Begin(); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); + _spriteBatch.End(); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/SPStatusBar.cs b/EndlessClient/HUD/StatusBars/SPStatusBar.cs index 95d281f19..cf2e2916a 100644 --- a/EndlessClient/HUD/StatusBars/SPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/SPStatusBar.cs @@ -4,36 +4,37 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.HUD.StatusBars; - -public class SPStatusBar : StatusBarBase +namespace EndlessClient.HUD.StatusBars { - protected override int StatusBarIndex => 0; - - public SPStatusBar(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider) - : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + public class SPStatusBar : StatusBarBase { - DrawArea = new Rectangle(320, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); - _sourceRectangleArea.Offset(_sourceRectangleArea.Width * 2, 0); - ChangeStatusBarPosition(); - } + protected override int StatusBarIndex => 0; - protected override void UpdateLabelText() - { - _label.Text = $"{Stats[CharacterStat.SP]}/{Stats[CharacterStat.MaxSP]}"; - } + public SPStatusBar(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider) + : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + { + DrawArea = new Rectangle(320, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); + _sourceRectangleArea.Offset(_sourceRectangleArea.Width * 2, 0); + ChangeStatusBarPosition(); + } - protected override void DrawStatusBar() - { - //todo: figure out these magic numbers - var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.SP] / (double)Stats[CharacterStat.MaxSP] * 79); - var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); + protected override void UpdateLabelText() + { + _label.Text = $"{Stats[CharacterStat.SP]}/{Stats[CharacterStat.MaxSP]}"; + } + + protected override void DrawStatusBar() + { + //todo: figure out these magic numbers + var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.SP] / (double)Stats[CharacterStat.MaxSP] * 79); + var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); - _spriteBatch.Begin(); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); - _spriteBatch.End(); + _spriteBatch.Begin(); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); + _spriteBatch.End(); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/StatusBarBase.cs b/EndlessClient/HUD/StatusBars/StatusBarBase.cs index 6f731f44b..aec449222 100644 --- a/EndlessClient/HUD/StatusBars/StatusBarBase.cs +++ b/EndlessClient/HUD/StatusBars/StatusBarBase.cs @@ -9,115 +9,116 @@ using System; using XNAControls; -namespace EndlessClient.HUD.StatusBars; - -public abstract class StatusBarBase : XNAControl +namespace EndlessClient.HUD.StatusBars { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICharacterProvider _characterProvider; - - protected readonly XNALabel _label; - protected readonly Texture2D _texture; - - protected CharacterStats Stats => _characterProvider.MainCharacter.Stats; - protected Rectangle _sourceRectangleArea; + public abstract class StatusBarBase : XNAControl + { + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICharacterProvider _characterProvider; - protected abstract int StatusBarIndex { get; } + protected readonly XNALabel _label; + protected readonly Texture2D _texture; - private Option _labelShowTime; + protected CharacterStats Stats => _characterProvider.MainCharacter.Stats; + protected Rectangle _sourceRectangleArea; - public event Action StatusBarClicked; - public event Action StatusBarClosed; + protected abstract int StatusBarIndex { get; } - protected StatusBarBase(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _clientWindowSizeProvider = clientWindowSizeProvider; - _characterProvider = characterProvider; + private Option _labelShowTime; - _texture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); + public event Action StatusBarClicked; + public event Action StatusBarClosed; - _label = new XNALabel(Constants.FontSize08) + protected StatusBarBase(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider) { - AutoSize = false, - BackColor = Color.Transparent, - DrawPosition = new Vector2(6, 15), - ForeColor = ColorConstants.LightGrayText, - Visible = false - }; - _label.SetParentControl(this); - - _sourceRectangleArea = new Rectangle(0, 0, 110, 14); - - if (_clientWindowSizeProvider.Resizable) - _clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => ChangeStatusBarPosition(); - } + _nativeGraphicsManager = nativeGraphicsManager; + _clientWindowSizeProvider = clientWindowSizeProvider; + _characterProvider = characterProvider; - protected abstract void UpdateLabelText(); - protected abstract void DrawStatusBar(); + _texture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); - public override void Initialize() - { - _label.Initialize(); - base.Initialize(); - } + _label = new XNALabel(Constants.FontSize08) + { + AutoSize = false, + BackColor = Color.Transparent, + DrawPosition = new Vector2(6, 15), + ForeColor = ColorConstants.LightGrayText, + Visible = false + }; + _label.SetParentControl(this); + + _sourceRectangleArea = new Rectangle(0, 0, 110, 14); + + if (_clientWindowSizeProvider.Resizable) + _clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => ChangeStatusBarPosition(); + } - protected override void OnUpdateControl(GameTime gameTime) - { - _labelShowTime.MatchSome(x => + protected abstract void UpdateLabelText(); + protected abstract void DrawStatusBar(); + + public override void Initialize() { - UpdateLabelText(); + _label.Initialize(); + base.Initialize(); + } - if ((DateTime.Now - x).TotalSeconds >= 4) + protected override void OnUpdateControl(GameTime gameTime) + { + _labelShowTime.MatchSome(x => { - _label.Visible = false; - _labelShowTime = Option.None(); + UpdateLabelText(); - StatusBarClosed?.Invoke(); - } - }); + if ((DateTime.Now - x).TotalSeconds >= 4) + { + _label.Visible = false; + _labelShowTime = Option.None(); - base.OnUpdateControl(gameTime); - } + StatusBarClosed?.Invoke(); + } + }); - protected override void OnDrawControl(GameTime gameTime) - { - DrawStatusBar(); + base.OnUpdateControl(gameTime); + } - if (_labelShowTime.HasValue) + protected override void OnDrawControl(GameTime gameTime) { - var dest = new Vector2(DrawAreaWithParentOffset.X, - DrawAreaWithParentOffset.Y + _sourceRectangleArea.Height - 3); + DrawStatusBar(); + + if (_labelShowTime.HasValue) + { + var dest = new Vector2(DrawAreaWithParentOffset.X, + DrawAreaWithParentOffset.Y + _sourceRectangleArea.Height - 3); - _spriteBatch.Begin(); - _spriteBatch.Draw(_texture, dest, DropDownSourceRectangle, Color.White); - _spriteBatch.End(); + _spriteBatch.Begin(); + _spriteBatch.Draw(_texture, dest, DropDownSourceRectangle, Color.White); + _spriteBatch.End(); + } + + base.OnDrawControl(gameTime); } - base.OnDrawControl(gameTime); - } + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + _label.Visible = !_label.Visible; + _labelShowTime = _label.SomeWhen(x => x.Visible).Map(_ => DateTime.Now); - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - _label.Visible = !_label.Visible; - _labelShowTime = _label.SomeWhen(x => x.Visible).Map(_ => DateTime.Now); + StatusBarClicked?.Invoke(); - StatusBarClicked?.Invoke(); + return true; + } - return true; - } + protected void ChangeStatusBarPosition() + { + var xCoord = (_clientWindowSizeProvider.Width / 2) + StatusBarIndex * DrawArea.Width; + DrawPosition = new Vector2(xCoord, 0); + } - protected void ChangeStatusBarPosition() - { - var xCoord = (_clientWindowSizeProvider.Width / 2) + StatusBarIndex * DrawArea.Width; - DrawPosition = new Vector2(xCoord, 0); + /// + /// Source rectangle for the drop-down box in the texture sprite sheet (shown when control is clicked) + /// + private static Rectangle DropDownSourceRectangle => new Rectangle(220, 30, 110, 21); } - - /// - /// Source rectangle for the drop-down box in the texture sprite sheet (shown when control is clicked) - /// - private static Rectangle DropDownSourceRectangle => new Rectangle(220, 30, 110, 21); } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/TNLStatusBar.cs b/EndlessClient/HUD/StatusBars/TNLStatusBar.cs index 31382c97f..9919e57a8 100644 --- a/EndlessClient/HUD/StatusBars/TNLStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/TNLStatusBar.cs @@ -6,48 +6,49 @@ using System; using System.Collections.Generic; -namespace EndlessClient.HUD.StatusBars; - -public class TNLStatusBar : StatusBarBase +namespace EndlessClient.HUD.StatusBars { - private readonly IExperienceTableProvider _experienceTableProvider; - - protected override int StatusBarIndex => 1; - - public TNLStatusBar(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider, - IExperienceTableProvider experienceTableProvider) - : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) - { - _experienceTableProvider = experienceTableProvider; - DrawArea = new Rectangle(430, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); - - _sourceRectangleArea = new Rectangle(_sourceRectangleArea.Width * 3 - 1, - 0, - _sourceRectangleArea.Width + 1, - _sourceRectangleArea.Height); - ChangeStatusBarPosition(); - } - - protected override void UpdateLabelText() + public class TNLStatusBar : StatusBarBase { - _label.Text = $"{ExpTable[Stats[CharacterStat.Level] + 1] - Stats[CharacterStat.Experience]}"; + private readonly IExperienceTableProvider _experienceTableProvider; + + protected override int StatusBarIndex => 1; + + public TNLStatusBar(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider, + IExperienceTableProvider experienceTableProvider) + : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + { + _experienceTableProvider = experienceTableProvider; + DrawArea = new Rectangle(430, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); + + _sourceRectangleArea = new Rectangle(_sourceRectangleArea.Width * 3 - 1, + 0, + _sourceRectangleArea.Width + 1, + _sourceRectangleArea.Height); + ChangeStatusBarPosition(); + } + + protected override void UpdateLabelText() + { + _label.Text = $"{ExpTable[Stats[CharacterStat.Level] + 1] - Stats[CharacterStat.Experience]}"; + } + + protected override void DrawStatusBar() + { + //todo: figure out these magic numbers + var thisLevelExp = ExpTable[Stats[CharacterStat.Level]]; + var nextLevelExp = ExpTable[Stats[CharacterStat.Level] + 1]; + var srcWidth = 25 + (int)Math.Round((Stats[CharacterStat.Experience] - thisLevelExp) / (double)(nextLevelExp - thisLevelExp) * 79); + var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); + + _spriteBatch.Begin(); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); + _spriteBatch.End(); + } + + private IReadOnlyList ExpTable => _experienceTableProvider.ExperienceByLevel; } - - protected override void DrawStatusBar() - { - //todo: figure out these magic numbers - var thisLevelExp = ExpTable[Stats[CharacterStat.Level]]; - var nextLevelExp = ExpTable[Stats[CharacterStat.Level] + 1]; - var srcWidth = 25 + (int)Math.Round((Stats[CharacterStat.Experience] - thisLevelExp) / (double)(nextLevelExp - thisLevelExp) * 79); - var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); - - _spriteBatch.Begin(); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); - _spriteBatch.End(); - } - - private IReadOnlyList ExpTable => _experienceTableProvider.ExperienceByLevel; } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusBars/TPStatusBar.cs b/EndlessClient/HUD/StatusBars/TPStatusBar.cs index 4803fb420..0d9c2705b 100644 --- a/EndlessClient/HUD/StatusBars/TPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/TPStatusBar.cs @@ -5,36 +5,37 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.HUD.StatusBars; - -public class TPStatusBar : StatusBarBase +namespace EndlessClient.HUD.StatusBars { - protected override int StatusBarIndex => -1; - - public TPStatusBar(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider) - : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + public class TPStatusBar : StatusBarBase { - DrawArea = new Rectangle(210, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); - _sourceRectangleArea.Offset(_sourceRectangleArea.Width, 0); - ChangeStatusBarPosition(); - } + protected override int StatusBarIndex => -1; - protected override void UpdateLabelText() - { - _label.Text = $"{Stats[CharacterStat.TP]}/{Stats[CharacterStat.MaxTP]}"; - } + public TPStatusBar(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider) + : base(nativeGraphicsManager, clientWindowSizeProvider, characterProvider) + { + DrawArea = new Rectangle(210, 0, _sourceRectangleArea.Width, _sourceRectangleArea.Height); + _sourceRectangleArea.Offset(_sourceRectangleArea.Width, 0); + ChangeStatusBarPosition(); + } - protected override void DrawStatusBar() - { - //todo: figure out these magic numbers - var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.TP] / (double)Stats[CharacterStat.MaxTP] * 79); - var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); + protected override void UpdateLabelText() + { + _label.Text = $"{Stats[CharacterStat.TP]}/{Stats[CharacterStat.MaxTP]}"; + } + + protected override void DrawStatusBar() + { + //todo: figure out these magic numbers + var srcWidth = 25 + (int)Math.Round(Stats[CharacterStat.TP] / (double)Stats[CharacterStat.MaxTP] * 79); + var maskSrc = new Rectangle(_sourceRectangleArea.X, _sourceRectangleArea.Height, srcWidth, _sourceRectangleArea.Height); - _spriteBatch.Begin(); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); - _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); - _spriteBatch.End(); + _spriteBatch.Begin(); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, _sourceRectangleArea, Color.White); + _spriteBatch.Draw(_texture, DrawPositionWithParentOffset, maskSrc, Color.White); + _spriteBatch.End(); + } } } \ No newline at end of file diff --git a/EndlessClient/HUD/StatusLabelSetter.cs b/EndlessClient/HUD/StatusLabelSetter.cs index 22518f043..547124824 100644 --- a/EndlessClient/HUD/StatusLabelSetter.cs +++ b/EndlessClient/HUD/StatusLabelSetter.cs @@ -3,84 +3,85 @@ using EOLib.Localization; using System; -namespace EndlessClient.HUD; - -[AutoMappedType] -public class StatusLabelSetter : IStatusLabelSetter +namespace EndlessClient.HUD { - private readonly IStatusLabelTextRepository _statusLabelTextRepository; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - - public StatusLabelSetter(IStatusLabelTextRepository statusLabelTextRepository, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder) + [AutoMappedType] + public class StatusLabelSetter : IStatusLabelSetter { - _statusLabelTextRepository = statusLabelTextRepository; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - } + private readonly IStatusLabelTextRepository _statusLabelTextRepository; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; - public void SetStatusLabel(EOResourceID type, EOResourceID text, string appended = "", bool showChatError = false) - { - CheckStatusLabelType(type); + public StatusLabelSetter(IStatusLabelTextRepository statusLabelTextRepository, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder) + { + _statusLabelTextRepository = statusLabelTextRepository; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + } - SetStatusLabelText(_localizedStringFinder.GetString(type), - _localizedStringFinder.GetString(text), - appended, - showChatError); - } + public void SetStatusLabel(EOResourceID type, EOResourceID text, string appended = "", bool showChatError = false) + { + CheckStatusLabelType(type); - public void SetStatusLabel(EOResourceID type, string prepended, EOResourceID text, bool showChatError = false) - { - CheckStatusLabelType(type); - SetStatusLabelText(_localizedStringFinder.GetString(type), - prepended, - _localizedStringFinder.GetString(text), - showChatError); - } + SetStatusLabelText(_localizedStringFinder.GetString(type), + _localizedStringFinder.GetString(text), + appended, + showChatError); + } - public void SetStatusLabel(EOResourceID type, string text) - { - CheckStatusLabelType(type); - SetStatusLabelText(_localizedStringFinder.GetString(type), text); - } + public void SetStatusLabel(EOResourceID type, string prepended, EOResourceID text, bool showChatError = false) + { + CheckStatusLabelType(type); + SetStatusLabelText(_localizedStringFinder.GetString(type), + prepended, + _localizedStringFinder.GetString(text), + showChatError); + } - public void SetStatusLabel(string text) - { - _statusLabelTextRepository.StatusText = text; - _statusLabelTextRepository.SetTime = DateTime.Now; - } + public void SetStatusLabel(EOResourceID type, string text) + { + CheckStatusLabelType(type); + SetStatusLabelText(_localizedStringFinder.GetString(type), text); + } - public void ShowWarning(string message) - { - SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, message); - } + public void SetStatusLabel(string text) + { + _statusLabelTextRepository.StatusText = text; + _statusLabelTextRepository.SetTime = DateTime.Now; + } - private void SetStatusLabelText(string type, string text, string extra = "", bool showChatError = false) - { - _statusLabelTextRepository.StatusText = $"[ {type} ] {text}{extra}"; - _statusLabelTextRepository.SetTime = DateTime.Now; + public void ShowWarning(string message) + { + SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, message); + } - if (showChatError) + private void SetStatusLabelText(string type, string text, string extra = "", bool showChatError = false) { - var chatData = new ChatData(ChatTab.System, string.Empty, $"{text}{extra}", ChatIcon.Error, ChatColor.Error); - _chatRepository.AllChat[ChatTab.System].Add(chatData); + _statusLabelTextRepository.StatusText = $"[ {type} ] {text}{extra}"; + _statusLabelTextRepository.SetTime = DateTime.Now; + + if (showChatError) + { + var chatData = new ChatData(ChatTab.System, string.Empty, $"{text}{extra}", ChatIcon.Error, ChatColor.Error); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } } - } - private void CheckStatusLabelType(EOResourceID type) - { - switch (type) + private void CheckStatusLabelType(EOResourceID type) { - case EOResourceID.STATUS_LABEL_TYPE_ACTION: - case EOResourceID.STATUS_LABEL_TYPE_BUTTON: - case EOResourceID.STATUS_LABEL_TYPE_INFORMATION: - case EOResourceID.STATUS_LABEL_TYPE_WARNING: - case EOResourceID.STATUS_LABEL_TYPE_ITEM: - case EOResourceID.SKILLMASTER_WORD_SPELL: - break; - default: throw new ArgumentOutOfRangeException(nameof(type), "Use either ACTION, BUTTION, INFORMATION, WARNING, ITEM, or SPELL for this."); + switch (type) + { + case EOResourceID.STATUS_LABEL_TYPE_ACTION: + case EOResourceID.STATUS_LABEL_TYPE_BUTTON: + case EOResourceID.STATUS_LABEL_TYPE_INFORMATION: + case EOResourceID.STATUS_LABEL_TYPE_WARNING: + case EOResourceID.STATUS_LABEL_TYPE_ITEM: + case EOResourceID.SKILLMASTER_WORD_SPELL: + break; + default: throw new ArgumentOutOfRangeException(nameof(type), "Use either ACTION, BUTTION, INFORMATION, WARNING, ITEM, or SPELL for this."); + } } } } \ No newline at end of file diff --git a/EndlessClient/HUD/UserInterfaceActions.cs b/EndlessClient/HUD/UserInterfaceActions.cs index ad8f9110c..46a0c2a3d 100644 --- a/EndlessClient/HUD/UserInterfaceActions.cs +++ b/EndlessClient/HUD/UserInterfaceActions.cs @@ -10,95 +10,96 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.HUD; - -[AutoMappedType] -public class UserInterfaceActions : IUserInterfaceNotifier +namespace EndlessClient.HUD { - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ILocalizedStringFinder _localizedStringFinder; - - public UserInterfaceActions(IInGameDialogActions inGameDialogActions, - IEIFFileProvider eifFileProvider, - ILocalizedStringFinder localizedStringFinder) + [AutoMappedType] + public class UserInterfaceActions : IUserInterfaceNotifier { - _inGameDialogActions = inGameDialogActions; - _eifFileProvider = eifFileProvider; - _localizedStringFinder = localizedStringFinder; - } + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ILocalizedStringFinder _localizedStringFinder; - public void NotifyPacketDialog(PacketFamily packetFamily) - { - switch (packetFamily) + public UserInterfaceActions(IInGameDialogActions inGameDialogActions, + IEIFFileProvider eifFileProvider, + ILocalizedStringFinder localizedStringFinder) { - case PacketFamily.Locker: _inGameDialogActions.ShowLockerDialog(); break; - case PacketFamily.Chest: _inGameDialogActions.ShowChestDialog(); break; - case PacketFamily.Board: _inGameDialogActions.ShowBoardDialog(); break; - case PacketFamily.Jukebox: _inGameDialogActions.ShowJukeboxDialog(); break; + _inGameDialogActions = inGameDialogActions; + _eifFileProvider = eifFileProvider; + _localizedStringFinder = localizedStringFinder; } - } - public void NotifyMessageDialog(string title, IReadOnlyList messages) - { - _inGameDialogActions.ShowMessageDialog(title, messages); - } + public void NotifyPacketDialog(PacketFamily packetFamily) + { + switch (packetFamily) + { + case PacketFamily.Locker: _inGameDialogActions.ShowLockerDialog(); break; + case PacketFamily.Chest: _inGameDialogActions.ShowChestDialog(); break; + case PacketFamily.Board: _inGameDialogActions.ShowBoardDialog(); break; + case PacketFamily.Jukebox: _inGameDialogActions.ShowJukeboxDialog(); break; + } + } - public void NotifyCharacterInfo(string name, int mapId, MapCoordinate mapCoords, CharacterStats stats) - { - var messages = new List<(string, string)> + public void NotifyMessageDialog(string title, IReadOnlyList messages) { - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEVEL), $"{stats[CharacterStat.Experience]} [{stats[CharacterStat.Level]}]"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_LOCATION), mapId.ToString()), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_COORDINATES), $"{mapCoords.X},{mapCoords.Y}"), - (string.Empty, string.Empty), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_HITPOINTS), $"{stats[CharacterStat.HP]}/{stats[CharacterStat.MaxHP]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_TECHPOINTS), $"{stats[CharacterStat.TP]}/{stats[CharacterStat.MaxTP]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WEIGHT), $"{stats[CharacterStat.Weight]}/{stats[CharacterStat.MaxWeight]}"), - (string.Empty, string.Empty), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DAMAGE), $"{stats[CharacterStat.MinDam]}-{stats[CharacterStat.MaxDam]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_HITRATE), $"{stats[CharacterStat.Accuracy]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_ARMOR), $"{stats[CharacterStat.Armor]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DODGE), $"{stats[CharacterStat.Evade]}"), - (string.Empty, string.Empty), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_STRENGTH), $"{stats[CharacterStat.Strength]}"), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_INTELLIGENCE), $"{stats[CharacterStat.Intelligence]}"), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_WISDOM), $"{stats[CharacterStat.Wisdom]}"), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_AGILITY), $"{stats[CharacterStat.Agility]}"), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CONSTITUTION), $"{stats[CharacterStat.Constitution]}"), - (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CHARISMA), $"{stats[CharacterStat.Charisma]}"), - (string.Empty, string.Empty), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_LIGHT), $"{stats[CharacterStat.Light]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DARK), $"{stats[CharacterStat.Dark]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_FIRE), $"{stats[CharacterStat.Fire]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WATER), $"{stats[CharacterStat.Water]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_EARTH), $"{stats[CharacterStat.Earth]}"), - (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WIND), $"{stats[CharacterStat.Wind]}"), - }; + _inGameDialogActions.ShowMessageDialog(title, messages); + } - var title = $"{name} - {(int)Math.Floor(stats[CharacterStat.Usage] / 60.0)}h.{stats[CharacterStat.Usage] % 60}m."; - _inGameDialogActions.ShowKeyValueMessageDialog(title, messages); - } + public void NotifyCharacterInfo(string name, int mapId, MapCoordinate mapCoords, CharacterStats stats) + { + var messages = new List<(string, string)> + { + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_LEVEL), $"{stats[CharacterStat.Experience]} [{stats[CharacterStat.Level]}]"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_LOCATION), mapId.ToString()), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_COORDINATES), $"{mapCoords.X},{mapCoords.Y}"), + (string.Empty, string.Empty), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_HITPOINTS), $"{stats[CharacterStat.HP]}/{stats[CharacterStat.MaxHP]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_TECHPOINTS), $"{stats[CharacterStat.TP]}/{stats[CharacterStat.MaxTP]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WEIGHT), $"{stats[CharacterStat.Weight]}/{stats[CharacterStat.MaxWeight]}"), + (string.Empty, string.Empty), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DAMAGE), $"{stats[CharacterStat.MinDam]}-{stats[CharacterStat.MaxDam]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_HITRATE), $"{stats[CharacterStat.Accuracy]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_ARMOR), $"{stats[CharacterStat.Armor]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DODGE), $"{stats[CharacterStat.Evade]}"), + (string.Empty, string.Empty), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_STRENGTH), $"{stats[CharacterStat.Strength]}"), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_INTELLIGENCE), $"{stats[CharacterStat.Intelligence]}"), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_WISDOM), $"{stats[CharacterStat.Wisdom]}"), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_AGILITY), $"{stats[CharacterStat.Agility]}"), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CONSTITUTION), $"{stats[CharacterStat.Constitution]}"), + (_localizedStringFinder.GetString(EOResourceID.SKILLMASTER_WORD_CHARISMA), $"{stats[CharacterStat.Charisma]}"), + (string.Empty, string.Empty), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_LIGHT), $"{stats[CharacterStat.Light]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_DARK), $"{stats[CharacterStat.Dark]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_FIRE), $"{stats[CharacterStat.Fire]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WATER), $"{stats[CharacterStat.Water]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_EARTH), $"{stats[CharacterStat.Earth]}"), + (_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_WIND), $"{stats[CharacterStat.Wind]}"), + }; - public void NotifyCharacterInventory(string name, int usage, int gold, IReadOnlyList inventory, IReadOnlyList bank) - { - var inventoryDisplay = inventory - .Select(x => ((string, string))(_eifFileProvider.EIFFile[x.ItemID].Name, x.Amount.ToString())) - .OrderBy(x => x.Item1); + var title = $"{name} - {(int)Math.Floor(stats[CharacterStat.Usage] / 60.0)}h.{stats[CharacterStat.Usage] % 60}m."; + _inGameDialogActions.ShowKeyValueMessageDialog(title, messages); + } + + public void NotifyCharacterInventory(string name, int usage, int gold, IReadOnlyList inventory, IReadOnlyList bank) + { + var inventoryDisplay = inventory + .Select(x => ((string, string))(_eifFileProvider.EIFFile[x.ItemID].Name, x.Amount.ToString())) + .OrderBy(x => x.Item1); - var bankDisplay = bank - .Select(x => ((string, string))(_eifFileProvider.EIFFile[x.ItemID].Name, x.Amount.ToString())) - .OrderBy(x => x.Item1); + var bankDisplay = bank + .Select(x => ((string, string))(_eifFileProvider.EIFFile[x.ItemID].Name, x.Amount.ToString())) + .OrderBy(x => x.Item1); - var messages = new List<(string, string)>(); - messages.AddRange(inventoryDisplay); - messages.Add((string.Empty, string.Empty)); - messages.AddRange(bankDisplay); - messages.Add((string.Empty, string.Empty)); - messages.Add((_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_BANK_ACCOUNT), gold.ToString())); - messages.Add((string.Empty, string.Empty)); + var messages = new List<(string, string)>(); + messages.AddRange(inventoryDisplay); + messages.Add((string.Empty, string.Empty)); + messages.AddRange(bankDisplay); + messages.Add((string.Empty, string.Empty)); + messages.Add((_localizedStringFinder.GetString(EOResourceID.ADMIN_INFO_WORD_BANK_ACCOUNT), gold.ToString())); + messages.Add((string.Empty, string.Empty)); - var title = $"{name} - {(int)Math.Floor(usage / 60.0)}h.{usage % 60}m."; - _inGameDialogActions.ShowKeyValueMessageDialog(title, messages); + var title = $"{name} - {(int)Math.Floor(usage / 60.0)}h.{usage % 60}m."; + _inGameDialogActions.ShowKeyValueMessageDialog(title, messages); + } } } \ No newline at end of file diff --git a/EndlessClient/Initialization/ConfigInitializer.cs b/EndlessClient/Initialization/ConfigInitializer.cs index e08064992..3610a8654 100644 --- a/EndlessClient/Initialization/ConfigInitializer.cs +++ b/EndlessClient/Initialization/ConfigInitializer.cs @@ -1,20 +1,21 @@ using AutomaticTypeMapper; using EOLib.Config; -namespace EndlessClient.Initialization; - -[MappedType(BaseType = typeof(IGameInitializer))] -public class ConfigInitializer : IGameInitializer +namespace EndlessClient.Initialization { - private readonly IConfigFileLoadActions _configFileLoadActions; - - public ConfigInitializer(IConfigFileLoadActions configFileLoadActions) + [MappedType(BaseType = typeof(IGameInitializer))] + public class ConfigInitializer : IGameInitializer { - _configFileLoadActions = configFileLoadActions; - } + private readonly IConfigFileLoadActions _configFileLoadActions; - public void Initialize() - { - _configFileLoadActions.LoadConfigFile(); + public ConfigInitializer(IConfigFileLoadActions configFileLoadActions) + { + _configFileLoadActions = configFileLoadActions; + } + + public void Initialize() + { + _configFileLoadActions.LoadConfigFile(); + } } } \ No newline at end of file diff --git a/EndlessClient/Initialization/EndlessClientInitializer.cs b/EndlessClient/Initialization/EndlessClientInitializer.cs index 1fb5e67bd..f4d90833d 100644 --- a/EndlessClient/Initialization/EndlessClientInitializer.cs +++ b/EndlessClient/Initialization/EndlessClientInitializer.cs @@ -12,87 +12,88 @@ using XNAControls; using XNAControls.Input; -namespace EndlessClient.Initialization; - -[AutoMappedType] -public class EndlessClientInitializer : IGameInitializer +namespace EndlessClient.Initialization { - private readonly IEndlessGame _game; - private readonly IEndlessGameRepository _endlessGameRepository; - private readonly IContentProvider _contentProvider; - private readonly List _persistentComponents; + [AutoMappedType] + public class EndlessClientInitializer : IGameInitializer + { + private readonly IEndlessGame _game; + private readonly IEndlessGameRepository _endlessGameRepository; + private readonly IContentProvider _contentProvider; + private readonly List _persistentComponents; - private readonly IMainButtonController _mainButtonController; - private readonly IAccountController _accountController; - private readonly ILoginController _loginController; - private readonly ICharacterManagementController _characterManagementController; - private readonly IChatController _chatController; - private readonly IInventoryController _inventoryController; - private readonly IControlSetFactory _controlSetFactory; - private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; - private readonly IHudControlsFactory _hudControlsFactory; - private readonly IPaperdollDialogFactory _paperdollDialogFactory; + private readonly IMainButtonController _mainButtonController; + private readonly IAccountController _accountController; + private readonly ILoginController _loginController; + private readonly ICharacterManagementController _characterManagementController; + private readonly IChatController _chatController; + private readonly IInventoryController _inventoryController; + private readonly IControlSetFactory _controlSetFactory; + private readonly ICharacterInfoPanelFactory _characterInfoPanelFactory; + private readonly IHudControlsFactory _hudControlsFactory; + private readonly IPaperdollDialogFactory _paperdollDialogFactory; - public EndlessClientInitializer(IEndlessGame game, - IEndlessGameRepository endlessGameRepository, - IContentProvider contentProvider, - List persistentComponents, + public EndlessClientInitializer(IEndlessGame game, + IEndlessGameRepository endlessGameRepository, + IContentProvider contentProvider, + List persistentComponents, - //Todo: refactor method injection to something like IEnumerable - IMainButtonController mainButtonController, - IAccountController accountController, - ILoginController loginController, - ICharacterManagementController characterManagementController, - IChatController chatController, - IInventoryController inventoryController, - //factories - IControlSetFactory controlSetFactory, - ICharacterInfoPanelFactory characterInfoPanelFactory, - IHudControlsFactory hudControlsFactory, - IPaperdollDialogFactory paperdollDialogFactory) - { - _game = game; - _endlessGameRepository = endlessGameRepository; - _contentProvider = contentProvider; - _persistentComponents = persistentComponents; - _mainButtonController = mainButtonController; - _accountController = accountController; - _loginController = loginController; - _characterManagementController = characterManagementController; - _chatController = chatController; - _inventoryController = inventoryController; - _controlSetFactory = controlSetFactory; - _characterInfoPanelFactory = characterInfoPanelFactory; - _hudControlsFactory = hudControlsFactory; - _paperdollDialogFactory = paperdollDialogFactory; - } + //Todo: refactor method injection to something like IEnumerable + IMainButtonController mainButtonController, + IAccountController accountController, + ILoginController loginController, + ICharacterManagementController characterManagementController, + IChatController chatController, + IInventoryController inventoryController, + //factories + IControlSetFactory controlSetFactory, + ICharacterInfoPanelFactory characterInfoPanelFactory, + IHudControlsFactory hudControlsFactory, + IPaperdollDialogFactory paperdollDialogFactory) + { + _game = game; + _endlessGameRepository = endlessGameRepository; + _contentProvider = contentProvider; + _persistentComponents = persistentComponents; + _mainButtonController = mainButtonController; + _accountController = accountController; + _loginController = loginController; + _characterManagementController = characterManagementController; + _chatController = chatController; + _inventoryController = inventoryController; + _controlSetFactory = controlSetFactory; + _characterInfoPanelFactory = characterInfoPanelFactory; + _hudControlsFactory = hudControlsFactory; + _paperdollDialogFactory = paperdollDialogFactory; + } - public void Initialize() - { - GameRepository.SetGame(_game as Game); + public void Initialize() + { + GameRepository.SetGame(_game as Game); - foreach (var component in _persistentComponents) - _game.Components.Add(component); + foreach (var component in _persistentComponents) + _game.Components.Add(component); - var mouseListenerSettings = new MouseListenerSettings - { - DoubleClickMilliseconds = 150, - DragThreshold = 1 - }; - _game.Components.Add(new InputManager(GameRepository.GetGame(), mouseListenerSettings)); + var mouseListenerSettings = new MouseListenerSettings + { + DoubleClickMilliseconds = 150, + DragThreshold = 1 + }; + _game.Components.Add(new InputManager(GameRepository.GetGame(), mouseListenerSettings)); - _endlessGameRepository.Game = _game; + _endlessGameRepository.Game = _game; - _game.Content.RootDirectory = "ContentPipeline"; - _contentProvider.SetContentManager(_game.Content); + _game.Content.RootDirectory = "ContentPipeline"; + _contentProvider.SetContentManager(_game.Content); - _controlSetFactory.InjectControllers(_mainButtonController, - _accountController, - _loginController, - _characterManagementController); - _characterInfoPanelFactory.InjectCharacterManagementController(_characterManagementController); - _characterInfoPanelFactory.InjectLoginController(_loginController); - _hudControlsFactory.InjectChatController(_chatController, _mainButtonController); - _paperdollDialogFactory.InjectInventoryController(_inventoryController); + _controlSetFactory.InjectControllers(_mainButtonController, + _accountController, + _loginController, + _characterManagementController); + _characterInfoPanelFactory.InjectCharacterManagementController(_characterManagementController); + _characterInfoPanelFactory.InjectLoginController(_loginController); + _hudControlsFactory.InjectChatController(_chatController, _mainButtonController); + _paperdollDialogFactory.InjectInventoryController(_inventoryController); + } } } \ No newline at end of file diff --git a/EndlessClient/Initialization/GraphicsInitializer.cs b/EndlessClient/Initialization/GraphicsInitializer.cs index c2bc82450..d39032ce5 100644 --- a/EndlessClient/Initialization/GraphicsInitializer.cs +++ b/EndlessClient/Initialization/GraphicsInitializer.cs @@ -3,40 +3,41 @@ using PELoaderLib; using System.IO; -namespace EndlessClient.Initialization; - -[MappedType(BaseType = typeof(IGameInitializer))] -public class GraphicsInitializer : IGameInitializer +namespace EndlessClient.Initialization { - private readonly IPEFileCollection _peFileCollection; - - public GraphicsInitializer(IPEFileCollection peFileCollection) + [MappedType(BaseType = typeof(IGameInitializer))] + public class GraphicsInitializer : IGameInitializer { - _peFileCollection = peFileCollection; - } - - public void Initialize() - { - _peFileCollection.PopulateCollectionWithStandardGFX(); - - foreach (var filePair in _peFileCollection) - TryInitializePEFiles(filePair.Key, filePair.Value); - } + private readonly IPEFileCollection _peFileCollection; - private static void TryInitializePEFiles(GFXTypes file, IPEFile peFile) - { - var number = ((int)file).ToString("D3"); - - try + public GraphicsInitializer(IPEFileCollection peFileCollection) { - peFile.Initialize(); + _peFileCollection = peFileCollection; } - catch (IOException) + + public void Initialize() { - throw new LibraryLoadException(number, file); + _peFileCollection.PopulateCollectionWithStandardGFX(); + + foreach (var filePair in _peFileCollection) + TryInitializePEFiles(filePair.Key, filePair.Value); } - if (!peFile.Initialized) - throw new LibraryLoadException(number, file); + private static void TryInitializePEFiles(GFXTypes file, IPEFile peFile) + { + var number = ((int)file).ToString("D3"); + + try + { + peFile.Initialize(); + } + catch (IOException) + { + throw new LibraryLoadException(number, file); + } + + if (!peFile.Initialized) + throw new LibraryLoadException(number, file); + } } } \ No newline at end of file diff --git a/EndlessClient/Initialization/IGameInitializer.cs b/EndlessClient/Initialization/IGameInitializer.cs index 1963b6c4c..7bddf1ae9 100644 --- a/EndlessClient/Initialization/IGameInitializer.cs +++ b/EndlessClient/Initialization/IGameInitializer.cs @@ -1,6 +1,7 @@ -namespace EndlessClient.Initialization; - -public interface IGameInitializer +namespace EndlessClient.Initialization { - void Initialize(); + public interface IGameInitializer + { + void Initialize(); + } } \ No newline at end of file diff --git a/EndlessClient/Initialization/LocalizationInitializer.cs b/EndlessClient/Initialization/LocalizationInitializer.cs index 6c8272b37..72f96ae48 100644 --- a/EndlessClient/Initialization/LocalizationInitializer.cs +++ b/EndlessClient/Initialization/LocalizationInitializer.cs @@ -1,20 +1,21 @@ using AutomaticTypeMapper; using EOLib.Localization; -namespace EndlessClient.Initialization; - -[MappedType(BaseType = typeof(IGameInitializer))] -public class LocalizationInitializer : IGameInitializer +namespace EndlessClient.Initialization { - private readonly IDataFileLoadActions _dataFileLoadActions; - - public LocalizationInitializer(IDataFileLoadActions dataFileLoadActions) + [MappedType(BaseType = typeof(IGameInitializer))] + public class LocalizationInitializer : IGameInitializer { - _dataFileLoadActions = dataFileLoadActions; - } + private readonly IDataFileLoadActions _dataFileLoadActions; - public void Initialize() - { - _dataFileLoadActions.LoadDataFiles(); + public LocalizationInitializer(IDataFileLoadActions dataFileLoadActions) + { + _dataFileLoadActions = dataFileLoadActions; + } + + public void Initialize() + { + _dataFileLoadActions.LoadDataFiles(); + } } } \ No newline at end of file diff --git a/EndlessClient/Input/ArrowKeyHandler.cs b/EndlessClient/Input/ArrowKeyHandler.cs index 6c5301a01..c4aac0903 100644 --- a/EndlessClient/Input/ArrowKeyHandler.cs +++ b/EndlessClient/Input/ArrowKeyHandler.cs @@ -4,36 +4,37 @@ using Microsoft.Xna.Framework.Input; using Optional; -namespace EndlessClient.Input; - -public class ArrowKeyHandler : InputHandlerBase +namespace EndlessClient.Input { - private readonly IArrowKeyController _arrowKeyController; - - public ArrowKeyHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - IArrowKeyController arrowKeyController, - ICurrentMapStateRepository currentMapStateRepository) - : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + public class ArrowKeyHandler : InputHandlerBase { - _arrowKeyController = arrowKeyController; - } + private readonly IArrowKeyController _arrowKeyController; - protected override Option HandleInput() - { - if (IsKeyHeld(Keys.Left) && _arrowKeyController.MoveLeft()) - return Option.Some(Keys.Left); - if (IsKeyHeld(Keys.Right) && _arrowKeyController.MoveRight()) - return Option.Some(Keys.Right); - if (IsKeyHeld(Keys.Up) && _arrowKeyController.MoveUp()) - return Option.Some(Keys.Up); - if (IsKeyHeld(Keys.Down) && _arrowKeyController.MoveDown()) - return Option.Some(Keys.Down); + public ArrowKeyHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + IArrowKeyController arrowKeyController, + ICurrentMapStateRepository currentMapStateRepository) + : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + { + _arrowKeyController = arrowKeyController; + } + + protected override Option HandleInput() + { + if (IsKeyHeld(Keys.Left) && _arrowKeyController.MoveLeft()) + return Option.Some(Keys.Left); + if (IsKeyHeld(Keys.Right) && _arrowKeyController.MoveRight()) + return Option.Some(Keys.Right); + if (IsKeyHeld(Keys.Up) && _arrowKeyController.MoveUp()) + return Option.Some(Keys.Up); + if (IsKeyHeld(Keys.Down) && _arrowKeyController.MoveDown()) + return Option.Some(Keys.Down); - if (KeysAreUp(Keys.Left, Keys.Right, Keys.Up, Keys.Down)) - _arrowKeyController.KeysUp(); + if (KeysAreUp(Keys.Left, Keys.Right, Keys.Up, Keys.Down)) + _arrowKeyController.KeysUp(); - return Option.None(); + return Option.None(); + } } } \ No newline at end of file diff --git a/EndlessClient/Input/ControlKeyHandler.cs b/EndlessClient/Input/ControlKeyHandler.cs index b7a21af76..d0e51f4f1 100644 --- a/EndlessClient/Input/ControlKeyHandler.cs +++ b/EndlessClient/Input/ControlKeyHandler.cs @@ -4,29 +4,30 @@ using Microsoft.Xna.Framework.Input; using Optional; -namespace EndlessClient.Input; - -public class ControlKeyHandler : InputHandlerBase +namespace EndlessClient.Input { - private readonly IControlKeyController _controlKeyController; - - public ControlKeyHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - IControlKeyController controlKeyController, - ICurrentMapStateRepository currentMapStateRepository) - : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + public class ControlKeyHandler : InputHandlerBase { - _controlKeyController = controlKeyController; - } + private readonly IControlKeyController _controlKeyController; - protected override Option HandleInput() - { - if (IsKeyHeld(Keys.LeftControl) && _controlKeyController.Attack()) - return Option.Some(Keys.LeftControl); - if (IsKeyHeld(Keys.RightControl) && _controlKeyController.Attack()) - return Option.Some(Keys.RightControl); + public ControlKeyHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + IControlKeyController controlKeyController, + ICurrentMapStateRepository currentMapStateRepository) + : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + { + _controlKeyController = controlKeyController; + } + + protected override Option HandleInput() + { + if (IsKeyHeld(Keys.LeftControl) && _controlKeyController.Attack()) + return Option.Some(Keys.LeftControl); + if (IsKeyHeld(Keys.RightControl) && _controlKeyController.Attack()) + return Option.Some(Keys.RightControl); - return Option.None(); + return Option.None(); + } } } \ No newline at end of file diff --git a/EndlessClient/Input/CurrentUserInputTracker.cs b/EndlessClient/Input/CurrentUserInputTracker.cs index 87dcb51e7..f09bb9f5e 100644 --- a/EndlessClient/Input/CurrentUserInputTracker.cs +++ b/EndlessClient/Input/CurrentUserInputTracker.cs @@ -2,27 +2,28 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; -namespace EndlessClient.Input; - -public class CurrentUserInputTracker : GameComponent +namespace EndlessClient.Input { - private readonly IUserInputRepository _userInputRepository; - - public CurrentUserInputTracker( - IEndlessGameProvider endlessGameProvider, - IUserInputRepository userInputRepository) - : base((Game)endlessGameProvider.Game) + public class CurrentUserInputTracker : GameComponent { - _userInputRepository = userInputRepository; + private readonly IUserInputRepository _userInputRepository; - UpdateOrder = int.MinValue; - } + public CurrentUserInputTracker( + IEndlessGameProvider endlessGameProvider, + IUserInputRepository userInputRepository) + : base((Game)endlessGameProvider.Game) + { + _userInputRepository = userInputRepository; - public override void Update(GameTime gameTime) - { - _userInputRepository.CurrentKeyState = Keyboard.GetState(); - _userInputRepository.CurrentMouseState = Mouse.GetState(); + UpdateOrder = int.MinValue; + } + + public override void Update(GameTime gameTime) + { + _userInputRepository.CurrentKeyState = Keyboard.GetState(); + _userInputRepository.CurrentMouseState = Mouse.GetState(); - base.Update(gameTime); + base.Update(gameTime); + } } } \ No newline at end of file diff --git a/EndlessClient/Input/FunctionKeyHandler.cs b/EndlessClient/Input/FunctionKeyHandler.cs index d507eec29..e0a1de145 100644 --- a/EndlessClient/Input/FunctionKeyHandler.cs +++ b/EndlessClient/Input/FunctionKeyHandler.cs @@ -4,40 +4,41 @@ using Microsoft.Xna.Framework.Input; using Optional; -namespace EndlessClient.Input; - -public class FunctionKeyHandler : InputHandlerBase +namespace EndlessClient.Input { - private readonly IFunctionKeyController _functionKeyController; - - public FunctionKeyHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - IFunctionKeyController functionKeyController, - ICurrentMapStateRepository currentMapStateRepository) - : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + public class FunctionKeyHandler : InputHandlerBase { - _functionKeyController = functionKeyController; - } + private readonly IFunctionKeyController _functionKeyController; - protected override Option HandleInput() - { - for (var key = Keys.F1; key <= Keys.F8; key++) + public FunctionKeyHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + IFunctionKeyController functionKeyController, + ICurrentMapStateRepository currentMapStateRepository) + : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) { - if (IsKeyHeld(key)) + _functionKeyController = functionKeyController; + } + + protected override Option HandleInput() + { + for (var key = Keys.F1; key <= Keys.F8; key++) { - var isShiftHeld = IsKeyHeld(Keys.LeftShift) || IsKeyHeld(Keys.RightShift); - if (_functionKeyController.SelectSpell(key - Keys.F1, isShiftHeld)) - return Option.Some(key); + if (IsKeyHeld(key)) + { + var isShiftHeld = IsKeyHeld(Keys.LeftShift) || IsKeyHeld(Keys.RightShift); + if (_functionKeyController.SelectSpell(key - Keys.F1, isShiftHeld)) + return Option.Some(key); + } } - } - if (IsKeyPressedOnce(Keys.F11) && _functionKeyController.Sit()) - return Option.Some(Keys.F11); + if (IsKeyPressedOnce(Keys.F11) && _functionKeyController.Sit()) + return Option.Some(Keys.F11); - if (IsKeyPressedOnce(Keys.F12) && _functionKeyController.RefreshMapState()) - return Option.Some(Keys.F12); + if (IsKeyPressedOnce(Keys.F12) && _functionKeyController.RefreshMapState()) + return Option.Some(Keys.F12); - return Option.None(); + return Option.None(); + } } } \ No newline at end of file diff --git a/EndlessClient/Input/IUserInputRepository.cs b/EndlessClient/Input/IUserInputRepository.cs index 1e5486ef1..8382d233a 100644 --- a/EndlessClient/Input/IUserInputRepository.cs +++ b/EndlessClient/Input/IUserInputRepository.cs @@ -1,39 +1,40 @@ using AutomaticTypeMapper; using Microsoft.Xna.Framework.Input; -namespace EndlessClient.Input; - -public interface IUserInputRepository +namespace EndlessClient.Input { - KeyboardState PreviousKeyState { get; set; } + public interface IUserInputRepository + { + KeyboardState PreviousKeyState { get; set; } - KeyboardState CurrentKeyState { get; set; } + KeyboardState CurrentKeyState { get; set; } - MouseState PreviousMouseState { get; set; } + MouseState PreviousMouseState { get; set; } - MouseState CurrentMouseState { get; set; } -} + MouseState CurrentMouseState { get; set; } + } -public interface IUserInputProvider -{ - KeyboardState PreviousKeyState { get; } + public interface IUserInputProvider + { + KeyboardState PreviousKeyState { get; } - KeyboardState CurrentKeyState { get; } + KeyboardState CurrentKeyState { get; } - MouseState PreviousMouseState { get; } + MouseState PreviousMouseState { get; } - MouseState CurrentMouseState { get; } -} + MouseState CurrentMouseState { get; } + } -[MappedType(BaseType = typeof(IUserInputRepository), IsSingleton = true)] -[MappedType(BaseType = typeof(IUserInputProvider), IsSingleton = true)] -public class KeyStateRepository : IUserInputRepository, IUserInputProvider -{ - public KeyboardState PreviousKeyState { get; set; } + [MappedType(BaseType = typeof(IUserInputRepository), IsSingleton = true)] + [MappedType(BaseType = typeof(IUserInputProvider), IsSingleton = true)] + public class KeyStateRepository : IUserInputRepository, IUserInputProvider + { + public KeyboardState PreviousKeyState { get; set; } - public KeyboardState CurrentKeyState { get; set; } + public KeyboardState CurrentKeyState { get; set; } - public MouseState PreviousMouseState { get; set; } + public MouseState PreviousMouseState { get; set; } - public MouseState CurrentMouseState { get; set; } + public MouseState CurrentMouseState { get; set; } + } } \ No newline at end of file diff --git a/EndlessClient/Input/IUserInputTimeRepository.cs b/EndlessClient/Input/IUserInputTimeRepository.cs index 444799d09..e4d074b4b 100644 --- a/EndlessClient/Input/IUserInputTimeRepository.cs +++ b/EndlessClient/Input/IUserInputTimeRepository.cs @@ -1,25 +1,26 @@ using AutomaticTypeMapper; using System; -namespace EndlessClient.Input; - -public interface IUserInputTimeRepository -{ - DateTime LastInputTime { get; set; } -} - -public interface IUserInputTimeProvider +namespace EndlessClient.Input { - DateTime LastInputTime { get; } -} + public interface IUserInputTimeRepository + { + DateTime LastInputTime { get; set; } + } -[AutoMappedType(IsSingleton = true)] -public class UserInputTimeRepository : IUserInputTimeRepository, IUserInputTimeProvider -{ - public DateTime LastInputTime { get; set; } + public interface IUserInputTimeProvider + { + DateTime LastInputTime { get; } + } - public UserInputTimeRepository() + [AutoMappedType(IsSingleton = true)] + public class UserInputTimeRepository : IUserInputTimeRepository, IUserInputTimeProvider { - LastInputTime = DateTime.Now; + public DateTime LastInputTime { get; set; } + + public UserInputTimeRepository() + { + LastInputTime = DateTime.Now; + } } } \ No newline at end of file diff --git a/EndlessClient/Input/InputHandlerBase.cs b/EndlessClient/Input/InputHandlerBase.cs index 2cb9f154d..e93648ddd 100644 --- a/EndlessClient/Input/InputHandlerBase.cs +++ b/EndlessClient/Input/InputHandlerBase.cs @@ -5,83 +5,84 @@ using System; using System.Linq; -namespace EndlessClient.Input; - -public abstract class InputHandlerBase : IInputHandler +namespace EndlessClient.Input { - private const int INPUT_RATE_LIMIT_MILLISECONDS = 200; - private const int WARP_BACKOFF_TIME_MILLISECONDS = 300; - private const int WARP_SLEEP_BACKOFF_TIME_MILLISECONDS = 5000; - - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IUserInputProvider _keyStateProvider; - private readonly IUserInputTimeRepository _userInputTimeRepository; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - - private KeyboardState CurrentState => _keyStateProvider.CurrentKeyState; - - private KeyboardState PreviousState => _keyStateProvider.PreviousKeyState; - - protected InputHandlerBase(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - ICurrentMapStateRepository currentMapStateRepository) - { - _endlessGameProvider = endlessGameProvider; - _keyStateProvider = userInputProvider; - _userInputTimeRepository = userInputTimeRepository; - _currentMapStateRepository = currentMapStateRepository; - } - - public void HandleKeyboardInput(DateTime timeAtBeginningOfUpdate) + public abstract class InputHandlerBase : IInputHandler { - var millisecondsSinceLastUpdate = GetMillisecondsSinceLastUpdate(timeAtBeginningOfUpdate); - if (!_endlessGameProvider.Game.IsActive || - millisecondsSinceLastUpdate < INPUT_RATE_LIMIT_MILLISECONDS || - _currentMapStateRepository.MapWarpState != WarpState.None) - return; - - _currentMapStateRepository.MapWarpTime.MatchSome( - some: t => - { - var span = (DateTime.Now - t).TotalMilliseconds; - var isSleepBackoffDone = _currentMapStateRepository.IsSleepWarp && span >= WARP_SLEEP_BACKOFF_TIME_MILLISECONDS; - var isWarpBackoffDone = !_currentMapStateRepository.IsSleepWarp && span >= WARP_BACKOFF_TIME_MILLISECONDS; - - if (isSleepBackoffDone || isWarpBackoffDone) + private const int INPUT_RATE_LIMIT_MILLISECONDS = 200; + private const int WARP_BACKOFF_TIME_MILLISECONDS = 300; + private const int WARP_SLEEP_BACKOFF_TIME_MILLISECONDS = 5000; + + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IUserInputProvider _keyStateProvider; + private readonly IUserInputTimeRepository _userInputTimeRepository; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + + private KeyboardState CurrentState => _keyStateProvider.CurrentKeyState; + + private KeyboardState PreviousState => _keyStateProvider.PreviousKeyState; + + protected InputHandlerBase(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + ICurrentMapStateRepository currentMapStateRepository) + { + _endlessGameProvider = endlessGameProvider; + _keyStateProvider = userInputProvider; + _userInputTimeRepository = userInputTimeRepository; + _currentMapStateRepository = currentMapStateRepository; + } + + public void HandleKeyboardInput(DateTime timeAtBeginningOfUpdate) + { + var millisecondsSinceLastUpdate = GetMillisecondsSinceLastUpdate(timeAtBeginningOfUpdate); + if (!_endlessGameProvider.Game.IsActive || + millisecondsSinceLastUpdate < INPUT_RATE_LIMIT_MILLISECONDS || + _currentMapStateRepository.MapWarpState != WarpState.None) + return; + + _currentMapStateRepository.MapWarpTime.MatchSome( + some: t => { - _currentMapStateRepository.MapWarpTime = Option.None(); - _currentMapStateRepository.IsSleepWarp = false; - } - }); - - _currentMapStateRepository.MapWarpTime.MatchNone(() => HandleInput().MatchSome(_ => _userInputTimeRepository.LastInputTime = timeAtBeginningOfUpdate)); + var span = (DateTime.Now - t).TotalMilliseconds; + var isSleepBackoffDone = _currentMapStateRepository.IsSleepWarp && span >= WARP_SLEEP_BACKOFF_TIME_MILLISECONDS; + var isWarpBackoffDone = !_currentMapStateRepository.IsSleepWarp && span >= WARP_BACKOFF_TIME_MILLISECONDS; + + if (isSleepBackoffDone || isWarpBackoffDone) + { + _currentMapStateRepository.MapWarpTime = Option.None(); + _currentMapStateRepository.IsSleepWarp = false; + } + }); + + _currentMapStateRepository.MapWarpTime.MatchNone(() => HandleInput().MatchSome(_ => _userInputTimeRepository.LastInputTime = timeAtBeginningOfUpdate)); + } + + private double GetMillisecondsSinceLastUpdate(DateTime timeAtBeginningOfUpdate) + { + return (timeAtBeginningOfUpdate - _userInputTimeRepository.LastInputTime).TotalMilliseconds; + } + + protected abstract Option HandleInput(); + + protected bool IsKeyHeld(params Keys[] keys) + { + return keys.Any(key => CurrentState.IsKeyHeld(PreviousState, key)); + } + + protected bool IsKeyPressedOnce(params Keys[] keys) + { + return keys.Any(key => CurrentState.IsKeyPressedOnce(PreviousState, key)); + } + + protected bool KeysAreUp(params Keys[] keys) + { + return keys.All(CurrentState.IsKeyUp); + } } - private double GetMillisecondsSinceLastUpdate(DateTime timeAtBeginningOfUpdate) + public interface IInputHandler { - return (timeAtBeginningOfUpdate - _userInputTimeRepository.LastInputTime).TotalMilliseconds; + void HandleKeyboardInput(DateTime timeAtStart); } - - protected abstract Option HandleInput(); - - protected bool IsKeyHeld(params Keys[] keys) - { - return keys.Any(key => CurrentState.IsKeyHeld(PreviousState, key)); - } - - protected bool IsKeyPressedOnce(params Keys[] keys) - { - return keys.Any(key => CurrentState.IsKeyPressedOnce(PreviousState, key)); - } - - protected bool KeysAreUp(params Keys[] keys) - { - return keys.All(CurrentState.IsKeyUp); - } -} - -public interface IInputHandler -{ - void HandleKeyboardInput(DateTime timeAtStart); } \ No newline at end of file diff --git a/EndlessClient/Input/KeyboardStateExtensions.cs b/EndlessClient/Input/KeyboardStateExtensions.cs index 4da269423..977060c9b 100644 --- a/EndlessClient/Input/KeyboardStateExtensions.cs +++ b/EndlessClient/Input/KeyboardStateExtensions.cs @@ -1,30 +1,31 @@ using Microsoft.Xna.Framework.Input; -namespace EndlessClient.Input; - -public static class KeyboardStateExtensions +namespace EndlessClient.Input { - /// - /// Compares the state of a single key between two KeyboardStates to determine if the key is being held down - /// - /// The current keystate - /// The previous keystate - /// The key to test - /// True if the key is held (down for both states); false otherwise - public static bool IsKeyHeld(this KeyboardState keyState, KeyboardState previousKeyState, Keys key) + public static class KeyboardStateExtensions { - return previousKeyState.IsKeyDown(key) && keyState.IsKeyDown(key); - } + /// + /// Compares the state of a single key between two KeyboardStates to determine if the key is being held down + /// + /// The current keystate + /// The previous keystate + /// The key to test + /// True if the key is held (down for both states); false otherwise + public static bool IsKeyHeld(this KeyboardState keyState, KeyboardState previousKeyState, Keys key) + { + return previousKeyState.IsKeyDown(key) && keyState.IsKeyDown(key); + } - /// - /// Compares the state of a single key between two KeyboardStates to determine if the key was pressed once - /// - /// The current keystate - /// The previous keystate - /// The key to test - /// True if the key was pressed once (down in previous then up in current); false otherwise - public static bool IsKeyPressedOnce(this KeyboardState keyState, KeyboardState previousKeyState, Keys key) - { - return previousKeyState.IsKeyDown(key) && keyState.IsKeyUp(key); + /// + /// Compares the state of a single key between two KeyboardStates to determine if the key was pressed once + /// + /// The current keystate + /// The previous keystate + /// The key to test + /// True if the key was pressed once (down in previous then up in current); false otherwise + public static bool IsKeyPressedOnce(this KeyboardState keyState, KeyboardState previousKeyState, Keys key) + { + return previousKeyState.IsKeyDown(key) && keyState.IsKeyUp(key); + } } } \ No newline at end of file diff --git a/EndlessClient/Input/NumPadHandler.cs b/EndlessClient/Input/NumPadHandler.cs index 84582705d..44c490bd6 100644 --- a/EndlessClient/Input/NumPadHandler.cs +++ b/EndlessClient/Input/NumPadHandler.cs @@ -5,42 +5,43 @@ using Microsoft.Xna.Framework.Input; using Optional; -namespace EndlessClient.Input; - - -public class NumPadHandler : InputHandlerBase +namespace EndlessClient.Input { - private readonly INumPadController _numPadController; - public NumPadHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - ICurrentMapStateRepository currentMapStateRepository, - INumPadController numPadController) - : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + public class NumPadHandler : InputHandlerBase { - _numPadController = numPadController; - } + private readonly INumPadController _numPadController; - protected override Option HandleInput() - { - for (var key = Keys.NumPad0; key <= Keys.NumPad9; ++key) + public NumPadHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + ICurrentMapStateRepository currentMapStateRepository, + INumPadController numPadController) + : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) { - if (IsKeyHeld(key)) - { - var emote = key == Keys.NumPad0 ? Emote.Playful : (Emote)(key - Keys.NumPad0); - _numPadController.Emote(emote); - return Option.Some(key); - } + _numPadController = numPadController; } - // Keys.Decimal == ./DEL on the num pad - if (IsKeyHeld(Keys.Decimal)) + protected override Option HandleInput() { - _numPadController.Emote(Emote.Embarassed); - return Option.Some(Keys.Decimal); - } + for (var key = Keys.NumPad0; key <= Keys.NumPad9; ++key) + { + if (IsKeyHeld(key)) + { + var emote = key == Keys.NumPad0 ? Emote.Playful : (Emote)(key - Keys.NumPad0); + _numPadController.Emote(emote); + return Option.Some(key); + } + } + + // Keys.Decimal == ./DEL on the num pad + if (IsKeyHeld(Keys.Decimal)) + { + _numPadController.Emote(Emote.Embarassed); + return Option.Some(Keys.Decimal); + } - return Option.None(); + return Option.None(); + } } } \ No newline at end of file diff --git a/EndlessClient/Input/PanelShortcutHandler.cs b/EndlessClient/Input/PanelShortcutHandler.cs index f6c807338..6287056b9 100644 --- a/EndlessClient/Input/PanelShortcutHandler.cs +++ b/EndlessClient/Input/PanelShortcutHandler.cs @@ -5,55 +5,56 @@ using Optional; using System.Linq; -namespace EndlessClient.Input; - -public class PanelShortcutHandler : InputHandlerBase +namespace EndlessClient.Input { - private readonly IHudButtonController _hudButtonController; - - public PanelShortcutHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - ICurrentMapStateRepository currentMapStateRepository, - IHudButtonController hudButtonController) - : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + public class PanelShortcutHandler : InputHandlerBase { - _hudButtonController = hudButtonController; - } + private readonly IHudButtonController _hudButtonController; + + public PanelShortcutHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + ICurrentMapStateRepository currentMapStateRepository, + IHudButtonController hudButtonController) + : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) + { + _hudButtonController = hudButtonController; + } - protected override Option HandleInput() - { - if (!IsKeyHeld(Keys.LeftAlt) && !IsKeyHeld(Keys.RightAlt)) - return Option.None(); + protected override Option HandleInput() + { + if (!IsKeyHeld(Keys.LeftAlt) && !IsKeyHeld(Keys.RightAlt)) + return Option.None(); - var keys = Enumerable.Range((int)Keys.D0, 10).Select(i => (Keys)i).Concat(new[] { Keys.OemTilde }); + var keys = Enumerable.Range((int)Keys.D0, 10).Select(i => (Keys)i).Concat(new[] { Keys.OemTilde }); - foreach (var key in keys) - { - if (IsKeyPressedOnce(key)) + foreach (var key in keys) { - switch (key) + if (IsKeyPressedOnce(key)) { - case Keys.OemTilde: _hudButtonController.ShowNews(); break; - - case Keys.D1: _hudButtonController.ClickInventory(); break; - case Keys.D2: _hudButtonController.ClickViewMapToggle(); break; - case Keys.D3: _hudButtonController.ClickActiveSpells(); break; - case Keys.D4: _hudButtonController.ClickPassiveSpells(); break; - case Keys.D5: _hudButtonController.ClickChat(); break; - case Keys.D6: _hudButtonController.ClickStats(); break; - - case Keys.D7: _hudButtonController.ClickOnlineList(); break; - case Keys.D8: _hudButtonController.ClickParty(); break; - // macro: intentionally not implemented - case Keys.D9: _hudButtonController.ClickSettings(); break; - case Keys.D0: _hudButtonController.ClickHelp(); break; + switch (key) + { + case Keys.OemTilde: _hudButtonController.ShowNews(); break; + + case Keys.D1: _hudButtonController.ClickInventory(); break; + case Keys.D2: _hudButtonController.ClickViewMapToggle(); break; + case Keys.D3: _hudButtonController.ClickActiveSpells(); break; + case Keys.D4: _hudButtonController.ClickPassiveSpells(); break; + case Keys.D5: _hudButtonController.ClickChat(); break; + case Keys.D6: _hudButtonController.ClickStats(); break; + + case Keys.D7: _hudButtonController.ClickOnlineList(); break; + case Keys.D8: _hudButtonController.ClickParty(); break; + // macro: intentionally not implemented + case Keys.D9: _hudButtonController.ClickSettings(); break; + case Keys.D0: _hudButtonController.ClickHelp(); break; + } + + return Option.Some(key); } - - return Option.Some(key); } - } - return Option.None(); + return Option.None(); + } } } \ No newline at end of file diff --git a/EndlessClient/Input/PreviousUserInputTracker.cs b/EndlessClient/Input/PreviousUserInputTracker.cs index 3b9e86547..d157bc31c 100644 --- a/EndlessClient/Input/PreviousUserInputTracker.cs +++ b/EndlessClient/Input/PreviousUserInputTracker.cs @@ -1,26 +1,27 @@ using EndlessClient.GameExecution; using Microsoft.Xna.Framework; -namespace EndlessClient.Input; - -public class PreviousUserInputTracker : GameComponent +namespace EndlessClient.Input { - private readonly IUserInputRepository _userInputRepository; - - public PreviousUserInputTracker( - IEndlessGameProvider endlessGameProvider, - IUserInputRepository userInputRepository) - : base((Game)endlessGameProvider.Game) + public class PreviousUserInputTracker : GameComponent { - _userInputRepository = userInputRepository; - UpdateOrder = int.MaxValue; - } + private readonly IUserInputRepository _userInputRepository; - public override void Update(GameTime gameTime) - { - _userInputRepository.PreviousKeyState = _userInputRepository.CurrentKeyState; - _userInputRepository.PreviousMouseState = _userInputRepository.CurrentMouseState; + public PreviousUserInputTracker( + IEndlessGameProvider endlessGameProvider, + IUserInputRepository userInputRepository) + : base((Game)endlessGameProvider.Game) + { + _userInputRepository = userInputRepository; + UpdateOrder = int.MaxValue; + } + + public override void Update(GameTime gameTime) + { + _userInputRepository.PreviousKeyState = _userInputRepository.CurrentKeyState; + _userInputRepository.PreviousMouseState = _userInputRepository.CurrentMouseState; - base.Update(gameTime); + base.Update(gameTime); + } } } \ No newline at end of file diff --git a/EndlessClient/Input/UnwalkableTileActions.cs b/EndlessClient/Input/UnwalkableTileActions.cs index 261770b27..5eeed3648 100644 --- a/EndlessClient/Input/UnwalkableTileActions.cs +++ b/EndlessClient/Input/UnwalkableTileActions.cs @@ -9,171 +9,172 @@ using EOLib.Localization; using System.Collections.Generic; -namespace EndlessClient.Input; - -public enum UnwalkableTileAction -{ - None, - Chair, - Chest, - Door, - Locker, - Board, - Jukebox, -} - -[AutoMappedType] -public class UnwalkableTileActions : IUnwalkableTileActions +namespace EndlessClient.Input { - private readonly IMapCellStateProvider _mapCellStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IUnlockDoorValidator _unlockDoorValidator; - private readonly IUnlockChestValidator _unlockChestValidator; - private readonly IEOMessageBoxFactory _eoMessageBoxFactory; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ISfxPlayer _sfxPlayer; - - public UnwalkableTileActions(IMapCellStateProvider mapCellStateProvider, - ICharacterProvider characterProvider, - IStatusLabelSetter statusLabelSetter, - ICurrentMapStateRepository currentMapStateRepository, - IUnlockDoorValidator unlockDoorValidator, - IUnlockChestValidator unlockChestValidator, - IEOMessageBoxFactory eoMessageBoxFactory, - IEOMessageBoxFactory messageBoxFactory, - ISfxPlayer sfxPlayer) - { - _mapCellStateProvider = mapCellStateProvider; - _characterProvider = characterProvider; - _statusLabelSetter = statusLabelSetter; - _currentMapStateRepository = currentMapStateRepository; - _unlockDoorValidator = unlockDoorValidator; - _unlockChestValidator = unlockChestValidator; - _eoMessageBoxFactory = eoMessageBoxFactory; - _messageBoxFactory = messageBoxFactory; - _sfxPlayer = sfxPlayer; - } - - public (IReadOnlyList, IMapCellState) GetUnwalkableTileActions() + public enum UnwalkableTileAction { - var destX = MainCharacter.RenderProperties.GetDestinationX(); - var destY = MainCharacter.RenderProperties.GetDestinationY(); - return GetUnwalkableTileActions(destX, destY); + None, + Chair, + Chest, + Door, + Locker, + Board, + Jukebox, } - public (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(int x, int y) + [AutoMappedType] + public class UnwalkableTileActions : IUnwalkableTileActions { - var cellState = _mapCellStateProvider.GetCellStateAt(x, y); - var action = GetUnwalkableTileActions(cellState); - return (action, cellState); - } + private readonly IMapCellStateProvider _mapCellStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IUnlockDoorValidator _unlockDoorValidator; + private readonly IUnlockChestValidator _unlockChestValidator; + private readonly IEOMessageBoxFactory _eoMessageBoxFactory; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ISfxPlayer _sfxPlayer; + + public UnwalkableTileActions(IMapCellStateProvider mapCellStateProvider, + ICharacterProvider characterProvider, + IStatusLabelSetter statusLabelSetter, + ICurrentMapStateRepository currentMapStateRepository, + IUnlockDoorValidator unlockDoorValidator, + IUnlockChestValidator unlockChestValidator, + IEOMessageBoxFactory eoMessageBoxFactory, + IEOMessageBoxFactory messageBoxFactory, + ISfxPlayer sfxPlayer) + { + _mapCellStateProvider = mapCellStateProvider; + _characterProvider = characterProvider; + _statusLabelSetter = statusLabelSetter; + _currentMapStateRepository = currentMapStateRepository; + _unlockDoorValidator = unlockDoorValidator; + _unlockChestValidator = unlockChestValidator; + _eoMessageBoxFactory = eoMessageBoxFactory; + _messageBoxFactory = messageBoxFactory; + _sfxPlayer = sfxPlayer; + } - public IReadOnlyList GetUnwalkableTileActions(IMapCellState cellState) - { - if (MainCharacter.RenderProperties.SitState != SitState.Standing) - return new[] { UnwalkableTileAction.None }; + public (IReadOnlyList, IMapCellState) GetUnwalkableTileActions() + { + var destX = MainCharacter.RenderProperties.GetDestinationX(); + var destY = MainCharacter.RenderProperties.GetDestinationY(); + return GetUnwalkableTileActions(destX, destY); + } - return cellState.Warp.Match( - some: w => new[] { HandleWalkToWarpTile(w), HandleWalkToTileSpec(cellState) }, - none: () => new[] { HandleWalkToTileSpec(cellState) }); - } + public (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(int x, int y) + { + var cellState = _mapCellStateProvider.GetCellStateAt(x, y); + var action = GetUnwalkableTileActions(cellState); + return (action, cellState); + } - private UnwalkableTileAction HandleWalkToWarpTile(Warp warp) - { - if (warp.DoorType != DoorSpec.NoDoor) + public IReadOnlyList GetUnwalkableTileActions(IMapCellState cellState) { - if (!_unlockDoorValidator.CanMainCharacterOpenDoor(warp)) - { - var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.DOOR_LOCKED); - messageBox.ShowDialog(); + if (MainCharacter.RenderProperties.SitState != SitState.Standing) + return new[] { UnwalkableTileAction.None }; - var requiredKey = _unlockDoorValidator.GetRequiredKey(warp); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.STATUS_LABEL_THE_DOOR_IS_LOCKED_EXCLAMATION, - requiredKey.Match(x => $" - {x}", () => string.Empty)); + return cellState.Warp.Match( + some: w => new[] { HandleWalkToWarpTile(w), HandleWalkToTileSpec(cellState) }, + none: () => new[] { HandleWalkToTileSpec(cellState) }); + } - _sfxPlayer.PlaySfx(SoundEffectID.DoorOrChestLocked); + private UnwalkableTileAction HandleWalkToWarpTile(Warp warp) + { + if (warp.DoorType != DoorSpec.NoDoor) + { + if (!_unlockDoorValidator.CanMainCharacterOpenDoor(warp)) + { + var messageBox = _eoMessageBoxFactory.CreateMessageBox(DialogResourceID.DOOR_LOCKED); + messageBox.ShowDialog(); + + var requiredKey = _unlockDoorValidator.GetRequiredKey(warp); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.STATUS_LABEL_THE_DOOR_IS_LOCKED_EXCLAMATION, + requiredKey.Match(x => $" - {x}", () => string.Empty)); + + _sfxPlayer.PlaySfx(SoundEffectID.DoorOrChestLocked); + } + else if (!_currentMapStateRepository.OpenDoors.Contains(warp) && + !_currentMapStateRepository.PendingDoors.Contains(warp)) + { + return UnwalkableTileAction.Door; + } } - else if (!_currentMapStateRepository.OpenDoors.Contains(warp) && - !_currentMapStateRepository.PendingDoors.Contains(warp)) + else if (warp.LevelRequirement > 0 && MainCharacter.Stats[CharacterStat.Level] < warp.LevelRequirement) { - return UnwalkableTileAction.Door; + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, + EOResourceID.STATUS_LABEL_NOT_READY_TO_USE_ENTRANCE, + " - LVL " + warp.LevelRequirement); } - } - else if (warp.LevelRequirement > 0 && MainCharacter.Stats[CharacterStat.Level] < warp.LevelRequirement) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, - EOResourceID.STATUS_LABEL_NOT_READY_TO_USE_ENTRANCE, - " - LVL " + warp.LevelRequirement); - } - return UnwalkableTileAction.None; - } + return UnwalkableTileAction.None; + } - private UnwalkableTileAction HandleWalkToTileSpec(IMapCellState cellState) - { - switch (cellState.TileSpec) + private UnwalkableTileAction HandleWalkToTileSpec(IMapCellState cellState) { - case TileSpec.ChairDown: - case TileSpec.ChairLeft: - case TileSpec.ChairRight: - case TileSpec.ChairUp: - case TileSpec.ChairDownRight: - case TileSpec.ChairUpLeft: - case TileSpec.ChairAll: - return UnwalkableTileAction.Chair; - case TileSpec.Chest: - return cellState.ChestKey.Match( - some: key => - { - if (!_unlockChestValidator.CanMainCharacterOpenChest(key)) + switch (cellState.TileSpec) + { + case TileSpec.ChairDown: + case TileSpec.ChairLeft: + case TileSpec.ChairRight: + case TileSpec.ChairUp: + case TileSpec.ChairDownRight: + case TileSpec.ChairUpLeft: + case TileSpec.ChairAll: + return UnwalkableTileAction.Chair; + case TileSpec.Chest: + return cellState.ChestKey.Match( + some: key => { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.CHEST_LOCKED); - dlg.ShowDialog(); - - var requiredKey = _unlockChestValidator.GetRequiredKeyName(key); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_THE_CHEST_IS_LOCKED_EXCLAMATION, requiredKey.Match(x => $" - {x}", () => string.Empty)); - - _sfxPlayer.PlaySfx(SoundEffectID.DoorOrChestLocked); - - return UnwalkableTileAction.None; - } - else + if (!_unlockChestValidator.CanMainCharacterOpenChest(key)) + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.CHEST_LOCKED); + dlg.ShowDialog(); + + var requiredKey = _unlockChestValidator.GetRequiredKeyName(key); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_THE_CHEST_IS_LOCKED_EXCLAMATION, requiredKey.Match(x => $" - {x}", () => string.Empty)); + + _sfxPlayer.PlaySfx(SoundEffectID.DoorOrChestLocked); + + return UnwalkableTileAction.None; + } + else + { + return UnwalkableTileAction.Chest; + } + }, + none: () => { return UnwalkableTileAction.Chest; - } - }, - none: () => - { - return UnwalkableTileAction.Chest; - }); - case TileSpec.BankVault: - return UnwalkableTileAction.Locker; - case TileSpec.Board1: - case TileSpec.Board2: - case TileSpec.Board3: - case TileSpec.Board4: - case TileSpec.Board5: - case TileSpec.Board6: - case TileSpec.Board7: - case TileSpec.Board8: - return UnwalkableTileAction.Board; - case TileSpec.Jukebox: - return UnwalkableTileAction.Jukebox; - } + }); + case TileSpec.BankVault: + return UnwalkableTileAction.Locker; + case TileSpec.Board1: + case TileSpec.Board2: + case TileSpec.Board3: + case TileSpec.Board4: + case TileSpec.Board5: + case TileSpec.Board6: + case TileSpec.Board7: + case TileSpec.Board8: + return UnwalkableTileAction.Board; + case TileSpec.Jukebox: + return UnwalkableTileAction.Jukebox; + } - return UnwalkableTileAction.None; + return UnwalkableTileAction.None; + } + private Character MainCharacter => _characterProvider.MainCharacter; } - private Character MainCharacter => _characterProvider.MainCharacter; -} -public interface IUnwalkableTileActions -{ - (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(); + public interface IUnwalkableTileActions + { + (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(); - (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(int x, int y); + (IReadOnlyList, IMapCellState) GetUnwalkableTileActions(int x, int y); - IReadOnlyList GetUnwalkableTileActions(IMapCellState mapCellState); + IReadOnlyList GetUnwalkableTileActions(IMapCellState mapCellState); + } } \ No newline at end of file diff --git a/EndlessClient/Input/UnwalkableTileActionsHandler.cs b/EndlessClient/Input/UnwalkableTileActionsHandler.cs index a3bc993ac..c09c702eb 100644 --- a/EndlessClient/Input/UnwalkableTileActionsHandler.cs +++ b/EndlessClient/Input/UnwalkableTileActionsHandler.cs @@ -4,58 +4,59 @@ using EOLib.Domain.Map; using System.Collections.Generic; -namespace EndlessClient.Input; - -[AutoMappedType] -public class UnwalkableTileActionsHandler : IUnwalkableTileActionsHandler +namespace EndlessClient.Input { - private readonly IMapActions _mapActions; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly ICharacterActions _characterActions; - - public UnwalkableTileActionsHandler(IMapActions mapActions, - IInGameDialogActions inGameDialogActions, - ICharacterActions characterActions) + [AutoMappedType] + public class UnwalkableTileActionsHandler : IUnwalkableTileActionsHandler { - _mapActions = mapActions; - _inGameDialogActions = inGameDialogActions; - _characterActions = characterActions; - } + private readonly IMapActions _mapActions; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly ICharacterActions _characterActions; - public void HandleUnwalkableTileActions(IReadOnlyList unwalkableActions, IMapCellState cellState) - { - foreach (var action in unwalkableActions) + public UnwalkableTileActionsHandler(IMapActions mapActions, + IInGameDialogActions inGameDialogActions, + ICharacterActions characterActions) + { + _mapActions = mapActions; + _inGameDialogActions = inGameDialogActions; + _characterActions = characterActions; + } + + public void HandleUnwalkableTileActions(IReadOnlyList unwalkableActions, IMapCellState cellState) { - switch (action) + foreach (var action in unwalkableActions) { - case UnwalkableTileAction.Chest: - _mapActions.OpenChest(cellState.Coordinate); - _inGameDialogActions.ShowChestDialog(); - break; - case UnwalkableTileAction.Locker: - _mapActions.OpenLocker(cellState.Coordinate); - _inGameDialogActions.ShowLockerDialog(); - break; - case UnwalkableTileAction.Chair: - _characterActions.Sit(cellState.Coordinate, isChair: true); - break; - case UnwalkableTileAction.Door: - cellState.Warp.MatchSome(w => _mapActions.OpenDoor(w)); - break; - case UnwalkableTileAction.Board: - _mapActions.OpenBoard(cellState.TileSpec); - _inGameDialogActions.ShowBoardDialog(); - break; - case UnwalkableTileAction.Jukebox: - _mapActions.OpenJukebox(cellState.Coordinate); - _inGameDialogActions.ShowJukeboxDialog(); - break; + switch (action) + { + case UnwalkableTileAction.Chest: + _mapActions.OpenChest(cellState.Coordinate); + _inGameDialogActions.ShowChestDialog(); + break; + case UnwalkableTileAction.Locker: + _mapActions.OpenLocker(cellState.Coordinate); + _inGameDialogActions.ShowLockerDialog(); + break; + case UnwalkableTileAction.Chair: + _characterActions.Sit(cellState.Coordinate, isChair: true); + break; + case UnwalkableTileAction.Door: + cellState.Warp.MatchSome(w => _mapActions.OpenDoor(w)); + break; + case UnwalkableTileAction.Board: + _mapActions.OpenBoard(cellState.TileSpec); + _inGameDialogActions.ShowBoardDialog(); + break; + case UnwalkableTileAction.Jukebox: + _mapActions.OpenJukebox(cellState.Coordinate); + _inGameDialogActions.ShowJukeboxDialog(); + break; + } } } } -} -public interface IUnwalkableTileActionsHandler -{ - void HandleUnwalkableTileActions(IReadOnlyList unwalkableActions, IMapCellState cellState); + public interface IUnwalkableTileActionsHandler + { + void HandleUnwalkableTileActions(IReadOnlyList unwalkableActions, IMapCellState cellState); + } } \ No newline at end of file diff --git a/EndlessClient/Input/UserInputHandler.cs b/EndlessClient/Input/UserInputHandler.cs index 2eb8dd56b..376889d2f 100644 --- a/EndlessClient/Input/UserInputHandler.cs +++ b/EndlessClient/Input/UserInputHandler.cs @@ -10,71 +10,72 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Input; - -public class UserInputHandler : XNAControl, IUserInputHandler +namespace EndlessClient.Input { - private readonly List _handlers; - private readonly IActiveDialogProvider _activeDialogProvider; - - public UserInputHandler(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - IArrowKeyController arrowKeyController, - IControlKeyController controlKeyController, - IFunctionKeyController functionKeyController, - INumPadController numPadController, - IHudButtonController hudButtonController, - ICurrentMapStateRepository currentMapStateRepository, - IActiveDialogProvider activeDialogProvider, - IClientWindowSizeProvider clientWindowSizeProvider) + public class UserInputHandler : XNAControl, IUserInputHandler { - _handlers = new List - { - new ArrowKeyHandler(endlessGameProvider, - userInputProvider, - userInputTimeRepository, - arrowKeyController, - currentMapStateRepository), - new ControlKeyHandler(endlessGameProvider, - userInputProvider, - userInputTimeRepository, - controlKeyController, - currentMapStateRepository), - new FunctionKeyHandler(endlessGameProvider, - userInputProvider, - userInputTimeRepository, - functionKeyController, - currentMapStateRepository), - new NumPadHandler(endlessGameProvider, - userInputProvider, - userInputTimeRepository, - currentMapStateRepository, - numPadController), - }; + private readonly List _handlers; + private readonly IActiveDialogProvider _activeDialogProvider; - if (clientWindowSizeProvider.Resizable) + public UserInputHandler(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + IArrowKeyController arrowKeyController, + IControlKeyController controlKeyController, + IFunctionKeyController functionKeyController, + INumPadController numPadController, + IHudButtonController hudButtonController, + ICurrentMapStateRepository currentMapStateRepository, + IActiveDialogProvider activeDialogProvider, + IClientWindowSizeProvider clientWindowSizeProvider) { - _handlers.Add(new PanelShortcutHandler(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository, hudButtonController)); - } + _handlers = new List + { + new ArrowKeyHandler(endlessGameProvider, + userInputProvider, + userInputTimeRepository, + arrowKeyController, + currentMapStateRepository), + new ControlKeyHandler(endlessGameProvider, + userInputProvider, + userInputTimeRepository, + controlKeyController, + currentMapStateRepository), + new FunctionKeyHandler(endlessGameProvider, + userInputProvider, + userInputTimeRepository, + functionKeyController, + currentMapStateRepository), + new NumPadHandler(endlessGameProvider, + userInputProvider, + userInputTimeRepository, + currentMapStateRepository, + numPadController), + }; - _activeDialogProvider = activeDialogProvider; - } + if (clientWindowSizeProvider.Resizable) + { + _handlers.Add(new PanelShortcutHandler(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository, hudButtonController)); + } - protected override void OnUpdateControl(GameTime gameTime) - { - if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) - return; + _activeDialogProvider = activeDialogProvider; + } - var timeAtBeginningOfUpdate = DateTime.Now; + protected override void OnUpdateControl(GameTime gameTime) + { + if (_activeDialogProvider.ActiveDialogs.Any(x => x.HasValue)) + return; + + var timeAtBeginningOfUpdate = DateTime.Now; - foreach (var handler in _handlers) - handler.HandleKeyboardInput(timeAtBeginningOfUpdate); + foreach (var handler in _handlers) + handler.HandleKeyboardInput(timeAtBeginningOfUpdate); - base.OnUpdateControl(gameTime); + base.OnUpdateControl(gameTime); + } } -} -public interface IUserInputHandler : IGameComponent -{ + public interface IUserInputHandler : IGameComponent + { + } } \ No newline at end of file diff --git a/EndlessClient/Input/UserInputHandlerFactory.cs b/EndlessClient/Input/UserInputHandlerFactory.cs index 9ea3484df..0b7a37162 100644 --- a/EndlessClient/Input/UserInputHandlerFactory.cs +++ b/EndlessClient/Input/UserInputHandlerFactory.cs @@ -6,65 +6,66 @@ using EndlessClient.Rendering; using EOLib.Domain.Map; -namespace EndlessClient.Input; - -[MappedType(BaseType = typeof(IUserInputHandlerFactory))] -public class UserInputHandlerFactory : IUserInputHandlerFactory +namespace EndlessClient.Input { - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly IUserInputTimeRepository _userInputTimeRepository; - private readonly IArrowKeyController _arrowKeyController; - private readonly IControlKeyController _controlKeyController; - private readonly IFunctionKeyController _functionKeyController; - private readonly INumPadController _numPadController; - private readonly IHudButtonController _hudButtonController; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - - public UserInputHandlerFactory(IEndlessGameProvider endlessGameProvider, - IUserInputProvider userInputProvider, - IUserInputTimeRepository userInputTimeRepository, - IArrowKeyController arrowKeyController, - IControlKeyController controlKeyController, - IFunctionKeyController functionKeyController, - INumPadController numPadController, - IHudButtonController hudButtonController, - ICurrentMapStateRepository currentMapStateRepository, - IActiveDialogProvider activeDialogProvider, - IClientWindowSizeProvider clientWindowSizeProvider) + [MappedType(BaseType = typeof(IUserInputHandlerFactory))] + public class UserInputHandlerFactory : IUserInputHandlerFactory { - _endlessGameProvider = endlessGameProvider; - _userInputProvider = userInputProvider; - _userInputTimeRepository = userInputTimeRepository; - _arrowKeyController = arrowKeyController; - _controlKeyController = controlKeyController; - _functionKeyController = functionKeyController; - _numPadController = numPadController; - _hudButtonController = hudButtonController; - _currentMapStateRepository = currentMapStateRepository; - _activeDialogProvider = activeDialogProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly IUserInputTimeRepository _userInputTimeRepository; + private readonly IArrowKeyController _arrowKeyController; + private readonly IControlKeyController _controlKeyController; + private readonly IFunctionKeyController _functionKeyController; + private readonly INumPadController _numPadController; + private readonly IHudButtonController _hudButtonController; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + + public UserInputHandlerFactory(IEndlessGameProvider endlessGameProvider, + IUserInputProvider userInputProvider, + IUserInputTimeRepository userInputTimeRepository, + IArrowKeyController arrowKeyController, + IControlKeyController controlKeyController, + IFunctionKeyController functionKeyController, + INumPadController numPadController, + IHudButtonController hudButtonController, + ICurrentMapStateRepository currentMapStateRepository, + IActiveDialogProvider activeDialogProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _endlessGameProvider = endlessGameProvider; + _userInputProvider = userInputProvider; + _userInputTimeRepository = userInputTimeRepository; + _arrowKeyController = arrowKeyController; + _controlKeyController = controlKeyController; + _functionKeyController = functionKeyController; + _numPadController = numPadController; + _hudButtonController = hudButtonController; + _currentMapStateRepository = currentMapStateRepository; + _activeDialogProvider = activeDialogProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + } + + public IUserInputHandler CreateUserInputHandler() + { + return new UserInputHandler(_endlessGameProvider, + _userInputProvider, + _userInputTimeRepository, + _arrowKeyController, + _controlKeyController, + _functionKeyController, + _numPadController, + _hudButtonController, + _currentMapStateRepository, + _activeDialogProvider, + _clientWindowSizeProvider); + } } - public IUserInputHandler CreateUserInputHandler() + public interface IUserInputHandlerFactory { - return new UserInputHandler(_endlessGameProvider, - _userInputProvider, - _userInputTimeRepository, - _arrowKeyController, - _controlKeyController, - _functionKeyController, - _numPadController, - _hudButtonController, - _currentMapStateRepository, - _activeDialogProvider, - _clientWindowSizeProvider); + IUserInputHandler CreateUserInputHandler(); } -} - -public interface IUserInputHandlerFactory -{ - IUserInputHandler CreateUserInputHandler(); } \ No newline at end of file diff --git a/EndlessClient/Network/PacketHandlerGameComponent.cs b/EndlessClient/Network/PacketHandlerGameComponent.cs index a7f11766d..cce3832a4 100644 --- a/EndlessClient/Network/PacketHandlerGameComponent.cs +++ b/EndlessClient/Network/PacketHandlerGameComponent.cs @@ -6,46 +6,47 @@ using EOLib.Net.Handlers; using Microsoft.Xna.Framework; -namespace EndlessClient.Network; - -[MappedType(BaseType = typeof(IGameComponent), IsSingleton = true)] -public class PacketHandlerGameComponent : GameComponent +namespace EndlessClient.Network { - private readonly IOutOfBandPacketHandler _packetHandler; - private readonly INetworkClientProvider _networkClientProvider; - private readonly IBackgroundReceiveTaskRepository _backgroundReceiveTaskRepository; - private readonly IMainButtonController _mainButtonController; - - public PacketHandlerGameComponent(IEndlessGame game, - IOutOfBandPacketHandler packetHandler, - INetworkClientProvider networkClientProvider, - IBackgroundReceiveTaskRepository backgroundReceiveTaskRepository, - IMainButtonController mainButtonController) - : base((Game)game) + [MappedType(BaseType = typeof(IGameComponent), IsSingleton = true)] + public class PacketHandlerGameComponent : GameComponent { - _packetHandler = packetHandler; - _networkClientProvider = networkClientProvider; - _backgroundReceiveTaskRepository = backgroundReceiveTaskRepository; - _mainButtonController = mainButtonController; + private readonly IOutOfBandPacketHandler _packetHandler; + private readonly INetworkClientProvider _networkClientProvider; + private readonly IBackgroundReceiveTaskRepository _backgroundReceiveTaskRepository; + private readonly IMainButtonController _mainButtonController; + + public PacketHandlerGameComponent(IEndlessGame game, + IOutOfBandPacketHandler packetHandler, + INetworkClientProvider networkClientProvider, + IBackgroundReceiveTaskRepository backgroundReceiveTaskRepository, + IMainButtonController mainButtonController) + : base((Game)game) + { + _packetHandler = packetHandler; + _networkClientProvider = networkClientProvider; + _backgroundReceiveTaskRepository = backgroundReceiveTaskRepository; + _mainButtonController = mainButtonController; - UpdateOrder = int.MinValue; - } + UpdateOrder = int.MinValue; + } - public override void Update(GameTime gameTime) - { - if (_networkClientProvider.NetworkClient != null && _networkClientProvider.NetworkClient.Started) + public override void Update(GameTime gameTime) { - var connected = _networkClientProvider.NetworkClient.Connected; - var receiveLoopFaulted = _backgroundReceiveTaskRepository.Task?.IsFaulted ?? false; - - if (!connected || receiveLoopFaulted) + if (_networkClientProvider.NetworkClient != null && _networkClientProvider.NetworkClient.Started) { - _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); + var connected = _networkClientProvider.NetworkClient.Connected; + var receiveLoopFaulted = _backgroundReceiveTaskRepository.Task?.IsFaulted ?? false; + + if (!connected || receiveLoopFaulted) + { + _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); + } } - } - _packetHandler.PollForPacketsAndHandle(); + _packetHandler.PollForPacketsAndHandle(); - base.Update(gameTime); + base.Update(gameTime); + } } } \ No newline at end of file diff --git a/EndlessClient/Network/UnknownEntitiesRequester.cs b/EndlessClient/Network/UnknownEntitiesRequester.cs index ec1694f06..53446e24f 100644 --- a/EndlessClient/Network/UnknownEntitiesRequester.cs +++ b/EndlessClient/Network/UnknownEntitiesRequester.cs @@ -12,103 +12,104 @@ using System.Diagnostics; using System.Linq; -namespace EndlessClient.Network; - -public class UnknownEntitiesRequester : GameComponent +namespace EndlessClient.Network { - private const int UPPER_SEE_DISTANCE = 12; - private const int LOWER_SEE_DISTANCE = 15; - - private const int REQUEST_INTERVAL_MS = 1000; - - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly INPCRendererProvider _npcRendererProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly IUnknownEntitiesRequestActions _unknownEntitiesRequestActions; - - private readonly Stopwatch _requestTimer; - - public UnknownEntitiesRequester(IEndlessGameProvider gameProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - ICharacterProvider characterProvider, - ICurrentMapStateRepository currentMapStateRepository, - INPCRendererProvider npcRendererProvider, - ICharacterRendererProvider characterRendererProvider, - IUnknownEntitiesRequestActions unknownEntitiesRequestActions) - : base((Game)gameProvider.Game) - { - _clientWindowSizeProvider = clientWindowSizeProvider; - _characterProvider = characterProvider; - _currentMapStateRepository = currentMapStateRepository; - _npcRendererProvider = npcRendererProvider; - _characterRendererProvider = characterRendererProvider; - _unknownEntitiesRequestActions = unknownEntitiesRequestActions; - _requestTimer = Stopwatch.StartNew(); - } - - public override void Update(GameTime gameTime) + public class UnknownEntitiesRequester : GameComponent { - if (_requestTimer.ElapsedMilliseconds >= REQUEST_INTERVAL_MS) + private const int UPPER_SEE_DISTANCE = 12; + private const int LOWER_SEE_DISTANCE = 15; + + private const int REQUEST_INTERVAL_MS = 1000; + + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly INPCRendererProvider _npcRendererProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly IUnknownEntitiesRequestActions _unknownEntitiesRequestActions; + + private readonly Stopwatch _requestTimer; + + public UnknownEntitiesRequester(IEndlessGameProvider gameProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + ICharacterProvider characterProvider, + ICurrentMapStateRepository currentMapStateRepository, + INPCRendererProvider npcRendererProvider, + ICharacterRendererProvider characterRendererProvider, + IUnknownEntitiesRequestActions unknownEntitiesRequestActions) + : base((Game)gameProvider.Game) { - ClearOutOfRangeActors(); + _clientWindowSizeProvider = clientWindowSizeProvider; + _characterProvider = characterProvider; + _currentMapStateRepository = currentMapStateRepository; + _npcRendererProvider = npcRendererProvider; + _characterRendererProvider = characterRendererProvider; + _unknownEntitiesRequestActions = unknownEntitiesRequestActions; + _requestTimer = Stopwatch.StartNew(); + } - if (_currentMapStateRepository.UnknownNPCIndexes.Count > 0 && _currentMapStateRepository.UnknownPlayerIDs.Count > 0) - { - _unknownEntitiesRequestActions.RequestAll(); - } - else if (_currentMapStateRepository.UnknownNPCIndexes.Count > 0) - { - _unknownEntitiesRequestActions.RequestUnknownNPCs(); - } - else if (_currentMapStateRepository.UnknownPlayerIDs.Count > 0) + public override void Update(GameTime gameTime) + { + if (_requestTimer.ElapsedMilliseconds >= REQUEST_INTERVAL_MS) { - _unknownEntitiesRequestActions.RequestUnknownPlayers(); + ClearOutOfRangeActors(); + + if (_currentMapStateRepository.UnknownNPCIndexes.Count > 0 && _currentMapStateRepository.UnknownPlayerIDs.Count > 0) + { + _unknownEntitiesRequestActions.RequestAll(); + } + else if (_currentMapStateRepository.UnknownNPCIndexes.Count > 0) + { + _unknownEntitiesRequestActions.RequestUnknownNPCs(); + } + else if (_currentMapStateRepository.UnknownPlayerIDs.Count > 0) + { + _unknownEntitiesRequestActions.RequestUnknownPlayers(); + } + + _requestTimer.Restart(); } - _requestTimer.Restart(); + base.Update(gameTime); } - base.Update(gameTime); - } - - private void ClearOutOfRangeActors() - { - var mc = _characterProvider.MainCharacter; - - var entities = new List(_currentMapStateRepository.Characters) - .Concat(_currentMapStateRepository.NPCs) - .Concat(_currentMapStateRepository.MapItems); + private void ClearOutOfRangeActors() + { + var mc = _characterProvider.MainCharacter; - var seeDistanceUpper = (int)(_clientWindowSizeProvider.Height / 480.0 * UPPER_SEE_DISTANCE); - var seeDistanceLower = (int)(_clientWindowSizeProvider.Height / 480.0 * LOWER_SEE_DISTANCE); + var entities = new List(_currentMapStateRepository.Characters) + .Concat(_currentMapStateRepository.NPCs) + .Concat(_currentMapStateRepository.MapItems); - var entitiesToRemove = new List(); - foreach (var entity in entities) - { - var xDiff = Math.Abs(mc.X - entity.X); - var yDiff = Math.Abs(mc.Y - entity.Y); + var seeDistanceUpper = (int)(_clientWindowSizeProvider.Height / 480.0 * UPPER_SEE_DISTANCE); + var seeDistanceLower = (int)(_clientWindowSizeProvider.Height / 480.0 * LOWER_SEE_DISTANCE); - if (entity.X < mc.X || entity.Y < mc.Y) + var entitiesToRemove = new List(); + foreach (var entity in entities) { - if (xDiff + yDiff > seeDistanceUpper) + var xDiff = Math.Abs(mc.X - entity.X); + var yDiff = Math.Abs(mc.Y - entity.Y); + + if (entity.X < mc.X || entity.Y < mc.Y) + { + if (xDiff + yDiff > seeDistanceUpper) + entitiesToRemove.Add(entity); + } + else if (xDiff + yDiff > seeDistanceLower) + { entitiesToRemove.Add(entity); + } } - else if (xDiff + yDiff > seeDistanceLower) + + foreach (var entity in entitiesToRemove) { - entitiesToRemove.Add(entity); + if (entity is Character c && _characterRendererProvider.CharacterRenderers.ContainsKey(c.ID)) + _currentMapStateRepository.Characters.Remove(c); + else if (entity is NPC n && _npcRendererProvider.NPCRenderers.ContainsKey(n.Index)) + _currentMapStateRepository.NPCs.Remove(n); + else if (entity is MapItem i) + _currentMapStateRepository.MapItems.Remove(i); } } - - foreach (var entity in entitiesToRemove) - { - if (entity is Character c && _characterRendererProvider.CharacterRenderers.ContainsKey(c.ID)) - _currentMapStateRepository.Characters.Remove(c); - else if (entity is NPC n && _npcRendererProvider.NPCRenderers.ContainsKey(n.Index)) - _currentMapStateRepository.NPCs.Remove(n); - else if (entity is MapItem i) - _currentMapStateRepository.MapItems.Remove(i); - } } } \ No newline at end of file diff --git a/EndlessClient/Program.cs b/EndlessClient/Program.cs index 47a8c09b3..3b86ced2b 100644 --- a/EndlessClient/Program.cs +++ b/EndlessClient/Program.cs @@ -3,35 +3,36 @@ using System; using System.Reflection; -namespace EndlessClient; - -public static class Program +namespace EndlessClient { - private static IGameRunner _gameRunner; - - [STAThread] - public static void Main(string[] args) + public static class Program { - var assemblyNames = new[] - { - Assembly.GetExecutingAssembly().FullName, - "EOLib", - "EOLib.Config", - "EOLib.Graphics", - "EOLib.IO", - "EOLib.Localization", - "EOLib.Logger" - }; + private static IGameRunner _gameRunner; - using (ITypeRegistry registry = new UnityRegistry(assemblyNames)) + [STAThread] + public static void Main(string[] args) { + var assemblyNames = new[] + { + Assembly.GetExecutingAssembly().FullName, + "EOLib", + "EOLib.Config", + "EOLib.Graphics", + "EOLib.IO", + "EOLib.Localization", + "EOLib.Logger" + }; + + using (ITypeRegistry registry = new UnityRegistry(assemblyNames)) + { #if DEBUG - _gameRunner = new DebugGameRunner(registry, args); + _gameRunner = new DebugGameRunner(registry, args); #else - _gameRunner = new ReleaseGameRunner(registry, args); + _gameRunner = new ReleaseGameRunner(registry, args); #endif - if (_gameRunner.SetupDependencies()) - _gameRunner.RunGame(); + if (_gameRunner.SetupDependencies()) + _gameRunner.RunGame(); + } } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterAnimationActions.cs b/EndlessClient/Rendering/Character/CharacterAnimationActions.cs index 6e55d1228..ae352a600 100644 --- a/EndlessClient/Rendering/Character/CharacterAnimationActions.cs +++ b/EndlessClient/Rendering/Character/CharacterAnimationActions.cs @@ -25,417 +25,418 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.Character; - -[AutoMappedType] -public class CharacterAnimationActions : ICharacterAnimationActions, IOtherCharacterAnimationNotifier, IEffectNotifier, IEmoteNotifier +namespace EndlessClient.Rendering.Character { - private readonly IHudControlProvider _hudControlProvider; - private readonly ICharacterRepository _characterRepository; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IPubFileProvider _pubFileProvider; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly ISfxPlayer _sfxPlayer; - private readonly IMetadataProvider _weaponMetadataProvider; - - private readonly Random _random; - - public CharacterAnimationActions(IHudControlProvider hudControlProvider, - ICharacterRepository characterRepository, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterRendererProvider characterRendererProvider, - ICurrentMapProvider currentMapProvider, - IPubFileProvider pubFileProvider, - IStatusLabelSetter statusLabelSetter, - ISfxPlayer sfxPlayer, - IMetadataProvider weaponMetadataProvider) - { - _hudControlProvider = hudControlProvider; - _characterRepository = characterRepository; - _currentMapStateProvider = currentMapStateProvider; - _characterRendererProvider = characterRendererProvider; - _currentMapProvider = currentMapProvider; - _pubFileProvider = pubFileProvider; - _statusLabelSetter = statusLabelSetter; - _sfxPlayer = sfxPlayer; - _weaponMetadataProvider = weaponMetadataProvider; - _random = new Random(); - } - - public void Face(EODirection direction) - { - if (!_hudControlProvider.IsInGame) - return; - - CancelSpellPrep(); - Animator.MainCharacterFace(direction); - } - - public void StartWalking(Option targetCoordinate, bool ghosted = false) + [AutoMappedType] + public class CharacterAnimationActions : ICharacterAnimationActions, IOtherCharacterAnimationNotifier, IEffectNotifier, IEmoteNotifier { - if (!_hudControlProvider.IsInGame) - return; - - _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler).CancelArenaBlockTimer(); + private readonly IHudControlProvider _hudControlProvider; + private readonly ICharacterRepository _characterRepository; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IPubFileProvider _pubFileProvider; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly ISfxPlayer _sfxPlayer; + private readonly IMetadataProvider _weaponMetadataProvider; + + private readonly Random _random; + + public CharacterAnimationActions(IHudControlProvider hudControlProvider, + ICharacterRepository characterRepository, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterRendererProvider characterRendererProvider, + ICurrentMapProvider currentMapProvider, + IPubFileProvider pubFileProvider, + IStatusLabelSetter statusLabelSetter, + ISfxPlayer sfxPlayer, + IMetadataProvider weaponMetadataProvider) + { + _hudControlProvider = hudControlProvider; + _characterRepository = characterRepository; + _currentMapStateProvider = currentMapStateProvider; + _characterRendererProvider = characterRendererProvider; + _currentMapProvider = currentMapProvider; + _pubFileProvider = pubFileProvider; + _statusLabelSetter = statusLabelSetter; + _sfxPlayer = sfxPlayer; + _weaponMetadataProvider = weaponMetadataProvider; + _random = new Random(); + } - CancelSpellPrep(); - Animator.StartMainCharacterWalkAnimation(targetCoordinate, ghosted, () => + public void Face(EODirection direction) { - PlayMainCharacterWalkSfx(); - ShowWaterSplashiesIfNeeded(CharacterActionState.Walking, _characterRepository.MainCharacter.ID); - }); - } + if (!_hudControlProvider.IsInGame) + return; - public void CancelClickToWalk() - { - Animator.CancelClickToWalk(); - } + CancelSpellPrep(); + Animator.MainCharacterFace(direction); + } - public void StartAttacking(int noteIndex = -1) - { - if (!_hudControlProvider.IsInGame) - return; + public void StartWalking(Option targetCoordinate, bool ghosted = false) + { + if (!_hudControlProvider.IsInGame) + return; - CancelSpellPrep(); + _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler).CancelArenaBlockTimer(); - if (noteIndex >= 0 || IsInstrumentWeapon(_characterRepository.MainCharacter.RenderProperties.WeaponGraphic)) - Animator.Emote(_characterRepository.MainCharacter.ID, EOLib.Domain.Character.Emote.MusicNotes); - Animator.StartMainCharacterAttackAnimation(() => PlayWeaponSound(_characterRepository.MainCharacter, noteIndex)); - ShowWaterSplashiesIfNeeded(CharacterActionState.Attacking, _characterRepository.MainCharacter.ID); - } + CancelSpellPrep(); + Animator.StartMainCharacterWalkAnimation(targetCoordinate, ghosted, () => + { + PlayMainCharacterWalkSfx(); + ShowWaterSplashiesIfNeeded(CharacterActionState.Walking, _characterRepository.MainCharacter.ID); + }); + } - public bool PrepareMainCharacterSpell(int spellId, ISpellTargetable spellTarget) - { - if (!_hudControlProvider.IsInGame) - return false; + public void CancelClickToWalk() + { + Animator.CancelClickToWalk(); + } - var spellData = _pubFileProvider.ESFFile[spellId]; - _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.ShoutSpellPrep(spellData.Shout)); - return Animator.MainCharacterShoutSpellPrep(spellData, spellTarget); - } + public void StartAttacking(int noteIndex = -1) + { + if (!_hudControlProvider.IsInGame) + return; - public void Emote(Emote whichEmote) - { - if (!_hudControlProvider.IsInGame) - return; + CancelSpellPrep(); - Animator.Emote(_characterRepository.MainCharacter.ID, whichEmote); - } + if (noteIndex >= 0 || IsInstrumentWeapon(_characterRepository.MainCharacter.RenderProperties.WeaponGraphic)) + Animator.Emote(_characterRepository.MainCharacter.ID, EOLib.Domain.Character.Emote.MusicNotes); + Animator.StartMainCharacterAttackAnimation(() => PlayWeaponSound(_characterRepository.MainCharacter, noteIndex)); + ShowWaterSplashiesIfNeeded(CharacterActionState.Attacking, _characterRepository.MainCharacter.ID); + } - public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) - { - if (!_hudControlProvider.IsInGame || !_currentMapStateProvider.Characters.TryGetValue(characterID, out var character)) - return; + public bool PrepareMainCharacterSpell(int spellId, ISpellTargetable spellTarget) + { + if (!_hudControlProvider.IsInGame) + return false; - Animator.StartOtherCharacterWalkAnimation(characterID, destination, direction); + var spellData = _pubFileProvider.ESFFile[spellId]; + _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.ShoutSpellPrep(spellData.Shout)); + return Animator.MainCharacterShoutSpellPrep(spellData, spellTarget); + } - ShowWaterSplashiesIfNeeded(CharacterActionState.Walking, characterID); + public void Emote(Emote whichEmote) + { + if (!_hudControlProvider.IsInGame) + return; - if (IsSteppingStone(character.RenderProperties)) - _sfxPlayer.PlaySfx(SoundEffectID.JumpStone); - } + Animator.Emote(_characterRepository.MainCharacter.ID, whichEmote); + } - public void StartOtherCharacterAttackAnimation(int characterID, int noteIndex = -1) - { - if (!_hudControlProvider.IsInGame || !_currentMapStateProvider.Characters.TryGetValue(characterID, out var character)) - return; + public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) + { + if (!_hudControlProvider.IsInGame || !_currentMapStateProvider.Characters.TryGetValue(characterID, out var character)) + return; - if (noteIndex >= 0 || IsInstrumentWeapon(character.RenderProperties.WeaponGraphic)) - Animator.Emote(characterID, EOLib.Domain.Character.Emote.MusicNotes); + Animator.StartOtherCharacterWalkAnimation(characterID, destination, direction); - Animator.StartOtherCharacterAttackAnimation(characterID, () => PlayWeaponSound(character, noteIndex)); - ShowWaterSplashiesIfNeeded(CharacterActionState.Attacking, characterID); - } + ShowWaterSplashiesIfNeeded(CharacterActionState.Walking, characterID); - public void NotifyWarpLeaveEffect(int characterId, WarpEffect anim) - { - if (anim == WarpEffect.Admin && _characterRendererProvider.CharacterRenderers.ContainsKey(characterId)) - _characterRendererProvider.CharacterRenderers[characterId].PlayEffect((int)HardCodedEffect.WarpLeave); - else if (characterId != _characterRepository.MainCharacter.ID && anim == WarpEffect.Scroll) - _sfxPlayer.PlaySfx(SoundEffectID.ScrollTeleport); - } + if (IsSteppingStone(character.RenderProperties)) + _sfxPlayer.PlaySfx(SoundEffectID.JumpStone); + } - public void NotifyWarpEnterEffect(int characterId, WarpEffect anim) - { - if (anim == WarpEffect.Admin) + public void StartOtherCharacterAttackAnimation(int characterID, int noteIndex = -1) { - if (!_characterRendererProvider.CharacterRenderers.ContainsKey(characterId)) - _characterRendererProvider.NeedsWarpArriveAnimation.Add(characterId); - else - _characterRendererProvider.CharacterRenderers[characterId].PlayEffect((int)HardCodedEffect.WarpArrive); - } - } + if (!_hudControlProvider.IsInGame || !_currentMapStateProvider.Characters.TryGetValue(characterID, out var character)) + return; - public void NotifyPotionEffect(int playerId, int effectId) - { - if (playerId == _characterRepository.MainCharacter.ID) - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.PlayEffect(effectId + 1)); - else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) - _characterRendererProvider.CharacterRenderers[playerId].PlayEffect(effectId + 1); - } + if (noteIndex >= 0 || IsInstrumentWeapon(character.RenderProperties.WeaponGraphic)) + Animator.Emote(characterID, EOLib.Domain.Character.Emote.MusicNotes); - public void NotifyStartSpellCast(int playerId, int spellId) - { - var shoutName = _pubFileProvider.ESFFile[spellId].Shout; - _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellPrep(shoutName.ToLower()); - } + Animator.StartOtherCharacterAttackAnimation(characterID, () => PlayWeaponSound(character, noteIndex)); + ShowWaterSplashiesIfNeeded(CharacterActionState.Attacking, characterID); + } - public void NotifyTargetNpcSpellCast(int playerId) - { - // Main player starts its spell cast animation immediately when targeting NPC - // Other players need to wait for packet to be received and do it here - // this is some spaghetti... - if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) + public void NotifyWarpLeaveEffect(int characterId, WarpEffect anim) { - Animator.StartOtherCharacterSpellCast(playerId); + if (anim == WarpEffect.Admin && _characterRendererProvider.CharacterRenderers.ContainsKey(characterId)) + _characterRendererProvider.CharacterRenderers[characterId].PlayEffect((int)HardCodedEffect.WarpLeave); + else if (characterId != _characterRepository.MainCharacter.ID && anim == WarpEffect.Scroll) + _sfxPlayer.PlaySfx(SoundEffectID.ScrollTeleport); } - } - public void NotifySelfSpellCast(int playerId, int spellId, int spellHp, int percentHealth) - { - var spellGraphic = _pubFileProvider.ESFFile[spellId].Graphic; - - if (playerId == _characterRepository.MainCharacter.ID) + public void NotifyWarpEnterEffect(int characterId, WarpEffect anim) { - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => + if (anim == WarpEffect.Admin) { - cr.ShoutSpellCast(); - cr.PlayEffect(spellGraphic); - cr.ShowDamageCounter(spellHp, percentHealth, isHeal: true); - }); - } - else - { - Animator.StartOtherCharacterSpellCast(playerId); - _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellCast(); - _characterRendererProvider.CharacterRenderers[playerId].PlayEffect(spellGraphic); - _characterRendererProvider.CharacterRenderers[playerId].ShowDamageCounter(spellHp, percentHealth, isHeal: true); + if (!_characterRendererProvider.CharacterRenderers.ContainsKey(characterId)) + _characterRendererProvider.NeedsWarpArriveAnimation.Add(characterId); + else + _characterRendererProvider.CharacterRenderers[characterId].PlayEffect((int)HardCodedEffect.WarpArrive); + } } - } - public void NotifyTargetOtherSpellCast(int sourcePlayerID, int targetPlayerID, int spellId, int recoveredHP, int targetPercentHealth) - { - if (sourcePlayerID == _characterRepository.MainCharacter.ID) + public void NotifyPotionEffect(int playerId, int effectId) { - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.ShoutSpellCast()); + if (playerId == _characterRepository.MainCharacter.ID) + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.PlayEffect(effectId + 1)); + else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) + _characterRendererProvider.CharacterRenderers[playerId].PlayEffect(effectId + 1); } - else + + public void NotifyStartSpellCast(int playerId, int spellId) { - Animator.StartOtherCharacterSpellCast(sourcePlayerID); - _characterRendererProvider.CharacterRenderers[sourcePlayerID].ShoutSpellCast(); + var shoutName = _pubFileProvider.ESFFile[spellId].Shout; + _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellPrep(shoutName.ToLower()); } - var spellData = _pubFileProvider.ESFFile[spellId]; - - if (targetPlayerID == _characterRepository.MainCharacter.ID) + public void NotifyTargetNpcSpellCast(int playerId) { - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => + // Main player starts its spell cast animation immediately when targeting NPC + // Other players need to wait for packet to be received and do it here + // this is some spaghetti... + if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) { - cr.PlayEffect(spellData.Graphic); - cr.ShowDamageCounter(recoveredHP, targetPercentHealth, isHeal: spellData.Type == EOLib.IO.SpellType.Heal); - }); - } - else - { - _characterRendererProvider.CharacterRenderers[targetPlayerID].PlayEffect(spellData.Graphic); - _characterRendererProvider.CharacterRenderers[targetPlayerID].ShowDamageCounter(recoveredHP, targetPercentHealth, isHeal: spellData.Type == EOLib.IO.SpellType.Heal); + Animator.StartOtherCharacterSpellCast(playerId); + } } - } - public void NotifyGroupSpellCast(int playerId, int spellId, int spellHp, List spellTargets) - { - if (playerId == _characterRepository.MainCharacter.ID) + public void NotifySelfSpellCast(int playerId, int spellId, int spellHp, int percentHealth) { - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.ShoutSpellCast()); + var spellGraphic = _pubFileProvider.ESFFile[spellId].Graphic; + + if (playerId == _characterRepository.MainCharacter.ID) + { + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => + { + cr.ShoutSpellCast(); + cr.PlayEffect(spellGraphic); + cr.ShowDamageCounter(spellHp, percentHealth, isHeal: true); + }); + } + else + { + Animator.StartOtherCharacterSpellCast(playerId); + _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellCast(); + _characterRendererProvider.CharacterRenderers[playerId].PlayEffect(spellGraphic); + _characterRendererProvider.CharacterRenderers[playerId].ShowDamageCounter(spellHp, percentHealth, isHeal: true); + } } - else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) + + public void NotifyTargetOtherSpellCast(int sourcePlayerID, int targetPlayerID, int spellId, int recoveredHP, int targetPercentHealth) { - Animator.StartOtherCharacterSpellCast(playerId); - _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellCast(); - } + if (sourcePlayerID == _characterRepository.MainCharacter.ID) + { + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.ShoutSpellCast()); + } + else + { + Animator.StartOtherCharacterSpellCast(sourcePlayerID); + _characterRendererProvider.CharacterRenderers[sourcePlayerID].ShoutSpellCast(); + } - var spellData = _pubFileProvider.ESFFile[spellId]; + var spellData = _pubFileProvider.ESFFile[spellId]; - foreach (var target in spellTargets) - { - if (target.TargetId == _characterRepository.MainCharacter.ID) + if (targetPlayerID == _characterRepository.MainCharacter.ID) { _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => { cr.PlayEffect(spellData.Graphic); - cr.ShowDamageCounter(spellHp, target.PercentHealth, isHeal: true); + cr.ShowDamageCounter(recoveredHP, targetPercentHealth, isHeal: spellData.Type == EOLib.IO.SpellType.Heal); }); } - else if (_characterRendererProvider.CharacterRenderers.ContainsKey(target.TargetId)) + else { - _characterRendererProvider.CharacterRenderers[target.TargetId].PlayEffect(spellData.Graphic); - _characterRendererProvider.CharacterRenderers[target.TargetId].ShowDamageCounter(spellHp, target.PercentHealth, isHeal: true); + _characterRendererProvider.CharacterRenderers[targetPlayerID].PlayEffect(spellData.Graphic); + _characterRendererProvider.CharacterRenderers[targetPlayerID].ShowDamageCounter(recoveredHP, targetPercentHealth, isHeal: spellData.Type == EOLib.IO.SpellType.Heal); } } - } - public void NotifyMapEffect(EOLib.IO.Map.MapEffect effect, int strength = 0) - { - switch (effect) + public void NotifyGroupSpellCast(int playerId, int spellId, int spellHp, List spellTargets) { - case EOLib.IO.Map.MapEffect.Quake1: - case EOLib.IO.Map.MapEffect.Quake2: - case EOLib.IO.Map.MapEffect.Quake3: - case EOLib.IO.Map.MapEffect.Quake4: - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - mapRenderer.StartEarthquake(strength); - _sfxPlayer.PlaySfx(SoundEffectID.Earthquake); - break; - case EOLib.IO.Map.MapEffect.HPDrain: - _sfxPlayer.PlaySfx(SoundEffectID.MapEffectHPDrain); - break; - case EOLib.IO.Map.MapEffect.TPDrain: - _sfxPlayer.PlaySfx(SoundEffectID.MapEffectTPDrain); - break; - case EOLib.IO.Map.MapEffect.Spikes: - _sfxPlayer.PlaySfx(SoundEffectID.Spikes); - break; + if (playerId == _characterRepository.MainCharacter.ID) + { + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.ShoutSpellCast()); + } + else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) + { + Animator.StartOtherCharacterSpellCast(playerId); + _characterRendererProvider.CharacterRenderers[playerId].ShoutSpellCast(); + } + + var spellData = _pubFileProvider.ESFFile[spellId]; + + foreach (var target in spellTargets) + { + if (target.TargetId == _characterRepository.MainCharacter.ID) + { + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => + { + cr.PlayEffect(spellData.Graphic); + cr.ShowDamageCounter(spellHp, target.PercentHealth, isHeal: true); + }); + } + else if (_characterRendererProvider.CharacterRenderers.ContainsKey(target.TargetId)) + { + _characterRendererProvider.CharacterRenderers[target.TargetId].PlayEffect(spellData.Graphic); + _characterRendererProvider.CharacterRenderers[target.TargetId].ShowDamageCounter(spellHp, target.PercentHealth, isHeal: true); + } + } } - } - public void NotifyEmote(int playerId, Emote emote) - { - switch (emote) + public void NotifyMapEffect(EOLib.IO.Map.MapEffect effect, int strength = 0) { - case EOLib.Domain.Character.Emote.Trade: - _sfxPlayer.PlaySfx(SoundEffectID.TradeAccepted); - break; - case EOLib.Domain.Character.Emote.LevelUp: - _sfxPlayer.PlaySfx(SoundEffectID.LevelUp); - break; + switch (effect) + { + case EOLib.IO.Map.MapEffect.Quake1: + case EOLib.IO.Map.MapEffect.Quake2: + case EOLib.IO.Map.MapEffect.Quake3: + case EOLib.IO.Map.MapEffect.Quake4: + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + mapRenderer.StartEarthquake(strength); + _sfxPlayer.PlaySfx(SoundEffectID.Earthquake); + break; + case EOLib.IO.Map.MapEffect.HPDrain: + _sfxPlayer.PlaySfx(SoundEffectID.MapEffectHPDrain); + break; + case EOLib.IO.Map.MapEffect.TPDrain: + _sfxPlayer.PlaySfx(SoundEffectID.MapEffectTPDrain); + break; + case EOLib.IO.Map.MapEffect.Spikes: + _sfxPlayer.PlaySfx(SoundEffectID.Spikes); + break; + } } - try + public void NotifyEmote(int playerId, Emote emote) { - Animator.Emote(playerId, emote); + switch (emote) + { + case EOLib.Domain.Character.Emote.Trade: + _sfxPlayer.PlaySfx(SoundEffectID.TradeAccepted); + break; + case EOLib.Domain.Character.Emote.LevelUp: + _sfxPlayer.PlaySfx(SoundEffectID.LevelUp); + break; + } + + try + { + Animator.Emote(playerId, emote); + } + catch (InvalidOperationException) + { + // if still transitioning to in-game state, the game will crash because the in-game control set is not completely set up yet + } } - catch (InvalidOperationException) + + public void MakeMainPlayerDrunk() { - // if still transitioning to in-game state, the game will crash because the in-game control set is not completely set up yet + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_USE_DRUNK); } - } - - public void MakeMainPlayerDrunk() - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_ITEM_USE_DRUNK); - } - public void NotifyEffectAtLocation(MapCoordinate location, int effectId) - { - if (_hudControlProvider.IsInGame) + public void NotifyEffectAtLocation(MapCoordinate location, int effectId) { - _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer) - .RenderEffect(location, effectId); + if (_hudControlProvider.IsInGame) + { + _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer) + .RenderEffect(location, effectId); + } + } + public void NotifyAdminHideEffect(int playerId) + { + if (playerId == _characterRepository.MainCharacter.ID) + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.PlayEffect((int)HardCodedEffect.AdminHide)); + else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) + _characterRendererProvider.CharacterRenderers[playerId].PlayEffect((int)HardCodedEffect.AdminHide); } - } - public void NotifyAdminHideEffect(int playerId) - { - if (playerId == _characterRepository.MainCharacter.ID) - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => cr.PlayEffect((int)HardCodedEffect.AdminHide)); - else if (_characterRendererProvider.CharacterRenderers.ContainsKey(playerId)) - _characterRendererProvider.CharacterRenderers[playerId].PlayEffect((int)HardCodedEffect.AdminHide); - } - - private void ShowWaterSplashiesIfNeeded(CharacterActionState action, int characterID) - { - var characterRenderer = characterID == _characterRepository.MainCharacter.ID - ? _characterRendererProvider.MainCharacterRenderer - : _characterRendererProvider.CharacterRenderers.ContainsKey(characterID) - ? Option.Some(_characterRendererProvider.CharacterRenderers[characterID]) - : Option.None(); - characterRenderer.MatchSome(cr => + private void ShowWaterSplashiesIfNeeded(CharacterActionState action, int characterID) { - var rp = cr.Character.RenderProperties; + var characterRenderer = characterID == _characterRepository.MainCharacter.ID + ? _characterRendererProvider.MainCharacterRenderer + : _characterRendererProvider.CharacterRenderers.ContainsKey(characterID) + ? Option.Some(_characterRendererProvider.CharacterRenderers[characterID]) + : Option.None(); - if (action == CharacterActionState.Attacking) + characterRenderer.MatchSome(cr => { - if (_currentMapProvider.CurrentMap.Tiles[rp.MapY, rp.MapX] == TileSpec.Water) + var rp = cr.Character.RenderProperties; + + if (action == CharacterActionState.Attacking) { - cr.PlayEffect((int)HardCodedEffect.WaterSplashies); - _sfxPlayer.PlaySfx(SoundEffectID.Water); + if (_currentMapProvider.CurrentMap.Tiles[rp.MapY, rp.MapX] == TileSpec.Water) + { + cr.PlayEffect((int)HardCodedEffect.WaterSplashies); + _sfxPlayer.PlaySfx(SoundEffectID.Water); + } } - } - else if (action == CharacterActionState.Walking) - { - if (_currentMapProvider.CurrentMap.Tiles[rp.GetDestinationY(), rp.GetDestinationX()] == TileSpec.Water) + else if (action == CharacterActionState.Walking) { - cr.PlayEffect((int)HardCodedEffect.WaterSplashies); - _sfxPlayer.PlaySfx(SoundEffectID.Water); + if (_currentMapProvider.CurrentMap.Tiles[rp.GetDestinationY(), rp.GetDestinationX()] == TileSpec.Water) + { + cr.PlayEffect((int)HardCodedEffect.WaterSplashies); + _sfxPlayer.PlaySfx(SoundEffectID.Water); + } } - } - }); - } - - private void CancelSpellPrep() - { - Animator.MainCharacterCancelSpellPrep(); - _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.StopShout()); - } + }); + } - private void PlayMainCharacterWalkSfx() - { - if (_characterRepository.MainCharacter.NoWall) - _sfxPlayer.PlaySfx(SoundEffectID.NoWallWalk); - else if (IsSteppingStone(_characterRepository.MainCharacter.RenderProperties)) - _sfxPlayer.PlaySfx(SoundEffectID.JumpStone); - } + private void CancelSpellPrep() + { + Animator.MainCharacterCancelSpellPrep(); + _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.StopShout()); + } - private void PlayWeaponSound(EOLib.Domain.Character.Character character, int noteIndex = -1) - { - var weaponMetadata = _weaponMetadataProvider.GetValueOrDefault(character.RenderProperties.WeaponGraphic); + private void PlayMainCharacterWalkSfx() + { + if (_characterRepository.MainCharacter.NoWall) + _sfxPlayer.PlaySfx(SoundEffectID.NoWallWalk); + else if (IsSteppingStone(_characterRepository.MainCharacter.RenderProperties)) + _sfxPlayer.PlaySfx(SoundEffectID.JumpStone); + } - if (noteIndex >= 0 && noteIndex < 36) + private void PlayWeaponSound(EOLib.Domain.Character.Character character, int noteIndex = -1) { - var firstSfx = weaponMetadata.SFX.FirstOrDefault(); - if (firstSfx == SoundEffectID.Harp1) + var weaponMetadata = _weaponMetadataProvider.GetValueOrDefault(character.RenderProperties.WeaponGraphic); + + if (noteIndex >= 0 && noteIndex < 36) { - _sfxPlayer.PlayHarpNote(noteIndex); + var firstSfx = weaponMetadata.SFX.FirstOrDefault(); + if (firstSfx == SoundEffectID.Harp1) + { + _sfxPlayer.PlayHarpNote(noteIndex); + } + else if (firstSfx == SoundEffectID.Guitar1) + { + _sfxPlayer.PlayGuitarNote(noteIndex); + } } - else if (firstSfx == SoundEffectID.Guitar1) + else { - _sfxPlayer.PlayGuitarNote(noteIndex); + var index = _random.Next(0, weaponMetadata.SFX.Length); + _sfxPlayer.PlaySfx(weaponMetadata.SFX[index]); } } - else + + private bool IsInstrumentWeapon(int weaponGraphic) + { + return Constants.Instruments.Any(x => x == weaponGraphic); + } + + private bool IsSteppingStone(CharacterRenderProperties renderProps) { - var index = _random.Next(0, weaponMetadata.SFX.Length); - _sfxPlayer.PlaySfx(weaponMetadata.SFX[index]); + return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump + || _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump; } - } - private bool IsInstrumentWeapon(int weaponGraphic) - { - return Constants.Instruments.Any(x => x == weaponGraphic); + private ICharacterAnimator Animator => _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator); } - private bool IsSteppingStone(CharacterRenderProperties renderProps) + public interface ICharacterAnimationActions { - return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump - || _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump; - } - - private ICharacterAnimator Animator => _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator); -} + void Face(EODirection direction); -public interface ICharacterAnimationActions -{ - void Face(EODirection direction); + void StartWalking(Option targetCoordinate, bool ghosted = false); - void StartWalking(Option targetCoordinate, bool ghosted = false); + void CancelClickToWalk(); - void CancelClickToWalk(); + void StartAttacking(int noteIndex = -1); - void StartAttacking(int noteIndex = -1); + bool PrepareMainCharacterSpell(int spellId, ISpellTargetable spellTarget); - bool PrepareMainCharacterSpell(int spellId, ISpellTargetable spellTarget); - - void Emote(Emote whichEmote); + void Emote(Emote whichEmote); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterAnimator.cs b/EndlessClient/Rendering/Character/CharacterAnimator.cs index c6ac50068..496a02f01 100644 --- a/EndlessClient/Rendering/Character/CharacterAnimator.cs +++ b/EndlessClient/Rendering/Character/CharacterAnimator.cs @@ -17,595 +17,596 @@ using System.Diagnostics; using System.Linq; -namespace EndlessClient.Rendering.Character; - -public class CharacterAnimator : GameComponent, ICharacterAnimator +namespace EndlessClient.Rendering.Character { - public const int TICKS_PER_WALK_FRAME = 9; // 9 x10ms ticks per walk frame - public const int TICKS_PER_FRAME = 12; // 12 x10ms ticks per attack frame - public const int TICKS_PER_CAST_TIME = 48; - - private readonly ICharacterRepository _characterRepository; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ISpellSlotDataRepository _spellSlotDataRepository; - private readonly ICharacterActions _characterActions; - private readonly IWalkValidationActions _walkValidationActions; - private readonly IPathFinder _pathFinder; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - private readonly IMetadataProvider _weaponMetadataProvider; - - // todo: this state should really be managed better - private readonly Dictionary _queuedDirections; - private readonly Dictionary _queuedPositions; - private readonly Dictionary _otherPlayerStartWalkingTimes; - private readonly Dictionary _otherPlayerStartAttackingTimes; - private readonly Dictionary _otherPlayerStartSpellCastTimes; - private readonly Dictionary _startEmoteTimes; - - private Option _mainPlayerStartShoutTick; - private ESFRecord _shoutSpellData; - private ISpellTargetable _spellTarget; - - private Queue _walkPath; - private Option _targetCoordinate; - - public CharacterAnimator(IEndlessGameProvider gameProvider, - ICharacterRepository characterRepository, - ICurrentMapStateRepository currentMapStateRepository, - ICurrentMapProvider currentMapProvider, - ISpellSlotDataRepository spellSlotDataRepository, - ICharacterActions characterActions, - IWalkValidationActions walkValidationActions, - IPathFinder pathFinder, - IFixedTimeStepRepository fixedTimeStepRepository, - IMetadataProvider weaponMetadataProvider) - : base((Game)gameProvider.Game) - { - _characterRepository = characterRepository; - _currentMapStateRepository = currentMapStateRepository; - _currentMapProvider = currentMapProvider; - _spellSlotDataRepository = spellSlotDataRepository; - _characterActions = characterActions; - _walkValidationActions = walkValidationActions; - _pathFinder = pathFinder; - _fixedTimeStepRepository = fixedTimeStepRepository; - _weaponMetadataProvider = weaponMetadataProvider; - _queuedDirections = new Dictionary(); - _queuedPositions = new Dictionary(); - _otherPlayerStartWalkingTimes = new Dictionary(); - _otherPlayerStartAttackingTimes = new Dictionary(); - _otherPlayerStartSpellCastTimes = new Dictionary(); - _startEmoteTimes = new Dictionary(); - - _walkPath = new Queue(); - } - - public override void Update(GameTime gameTime) + public class CharacterAnimator : GameComponent, ICharacterAnimator { - if (_fixedTimeStepRepository.IsWalkUpdateFrame) + public const int TICKS_PER_WALK_FRAME = 9; // 9 x10ms ticks per walk frame + public const int TICKS_PER_FRAME = 12; // 12 x10ms ticks per attack frame + public const int TICKS_PER_CAST_TIME = 48; + + private readonly ICharacterRepository _characterRepository; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ISpellSlotDataRepository _spellSlotDataRepository; + private readonly ICharacterActions _characterActions; + private readonly IWalkValidationActions _walkValidationActions; + private readonly IPathFinder _pathFinder; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + private readonly IMetadataProvider _weaponMetadataProvider; + + // todo: this state should really be managed better + private readonly Dictionary _queuedDirections; + private readonly Dictionary _queuedPositions; + private readonly Dictionary _otherPlayerStartWalkingTimes; + private readonly Dictionary _otherPlayerStartAttackingTimes; + private readonly Dictionary _otherPlayerStartSpellCastTimes; + private readonly Dictionary _startEmoteTimes; + + private Option _mainPlayerStartShoutTick; + private ESFRecord _shoutSpellData; + private ISpellTargetable _spellTarget; + + private Queue _walkPath; + private Option _targetCoordinate; + + public CharacterAnimator(IEndlessGameProvider gameProvider, + ICharacterRepository characterRepository, + ICurrentMapStateRepository currentMapStateRepository, + ICurrentMapProvider currentMapProvider, + ISpellSlotDataRepository spellSlotDataRepository, + ICharacterActions characterActions, + IWalkValidationActions walkValidationActions, + IPathFinder pathFinder, + IFixedTimeStepRepository fixedTimeStepRepository, + IMetadataProvider weaponMetadataProvider) + : base((Game)gameProvider.Game) { - AnimateCharacterWalking(); + _characterRepository = characterRepository; + _currentMapStateRepository = currentMapStateRepository; + _currentMapProvider = currentMapProvider; + _spellSlotDataRepository = spellSlotDataRepository; + _characterActions = characterActions; + _walkValidationActions = walkValidationActions; + _pathFinder = pathFinder; + _fixedTimeStepRepository = fixedTimeStepRepository; + _weaponMetadataProvider = weaponMetadataProvider; + _queuedDirections = new Dictionary(); + _queuedPositions = new Dictionary(); + _otherPlayerStartWalkingTimes = new Dictionary(); + _otherPlayerStartAttackingTimes = new Dictionary(); + _otherPlayerStartSpellCastTimes = new Dictionary(); + _startEmoteTimes = new Dictionary(); + + _walkPath = new Queue(); } - AnimateCharacterAttacking(); - AnimateCharacterSpells(); - AnimateCharacterEmotes(); + public override void Update(GameTime gameTime) + { + if (_fixedTimeStepRepository.IsWalkUpdateFrame) + { + AnimateCharacterWalking(); + } - base.Update(gameTime); - } + AnimateCharacterAttacking(); + AnimateCharacterSpells(); + AnimateCharacterEmotes(); - public void MainCharacterFace(EODirection direction) - { - if (_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) + base.Update(gameTime); + } + + public void MainCharacterFace(EODirection direction) { - _queuedDirections[_characterRepository.MainCharacter.ID] = direction; - return; + if (_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) + { + _queuedDirections[_characterRepository.MainCharacter.ID] = direction; + return; + } + + var renderProperties = _characterRepository.MainCharacter.RenderProperties.WithDirection(direction); + var newMainCharacter = _characterRepository.MainCharacter.WithRenderProperties(renderProperties); + _characterRepository.MainCharacter = newMainCharacter; + + _characterActions.Face(direction); } - var renderProperties = _characterRepository.MainCharacter.RenderProperties.WithDirection(direction); - var newMainCharacter = _characterRepository.MainCharacter.WithRenderProperties(renderProperties); - _characterRepository.MainCharacter = newMainCharacter; + public void StartMainCharacterWalkAnimation(Option targetCoordinate, bool ghosted, Action sfxCallback) + { + _walkPath.Clear(); - _characterActions.Face(direction); - } + targetCoordinate.Match( + some: tc => + { + _targetCoordinate = targetCoordinate; - public void StartMainCharacterWalkAnimation(Option targetCoordinate, bool ghosted, Action sfxCallback) - { - _walkPath.Clear(); + var rp = _characterRepository.MainCharacter.RenderProperties; + var characterCoord = new MapCoordinate(rp.MapX, rp.MapY); - targetCoordinate.Match( - some: tc => - { - _targetCoordinate = targetCoordinate; + _walkPath = _pathFinder.FindPath(characterCoord, tc); - var rp = _characterRepository.MainCharacter.RenderProperties; - var characterCoord = new MapCoordinate(rp.MapX, rp.MapY); + if (!_walkPath.Any()) return; - _walkPath = _pathFinder.FindPath(characterCoord, tc); + if (!_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) + { + rp = FaceTarget(characterCoord, _walkPath.Peek(), rp); + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(rp); + } - if (!_walkPath.Any()) return; + doTheWalk(); + }, + none: doTheWalk); - if (!_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) + void doTheWalk() + { + if (_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) { - rp = FaceTarget(characterCoord, _walkPath.Peek(), rp); - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(rp); + _otherPlayerStartWalkingTimes[_characterRepository.MainCharacter.ID].SetReplay(sfxCallback); + return; } - doTheWalk(); - }, - none: doTheWalk); + var startWalkingTime = new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount, sfxCallback); + _otherPlayerStartWalkingTimes.Add(_characterRepository.MainCharacter.ID, startWalkingTime); - void doTheWalk() - { - if (_otherPlayerStartWalkingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) - { - _otherPlayerStartWalkingTimes[_characterRepository.MainCharacter.ID].SetReplay(sfxCallback); - return; + _characterActions.Walk(ghosted); + startWalkingTime.SoundEffect(); } - - var startWalkingTime = new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount, sfxCallback); - _otherPlayerStartWalkingTimes.Add(_characterRepository.MainCharacter.ID, startWalkingTime); - - _characterActions.Walk(ghosted); - startWalkingTime.SoundEffect(); } - } - public void CancelClickToWalk() - { - _walkPath.Clear(); - } - - public void StartMainCharacterAttackAnimation(Action sfxCallback) - { - if (_otherPlayerStartAttackingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) + public void CancelClickToWalk() { - _otherPlayerStartAttackingTimes[_characterRepository.MainCharacter.ID].SetReplay(sfxCallback); - return; + _walkPath.Clear(); } - var startAttackingTime = new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount, sfxCallback); - _otherPlayerStartAttackingTimes.Add(_characterRepository.MainCharacter.ID, startAttackingTime); - } - - public bool MainCharacterShoutSpellPrep(ESFRecord spellData, ISpellTargetable target) - { - if (_mainPlayerStartShoutTick.HasValue) - return false; + public void StartMainCharacterAttackAnimation(Action sfxCallback) + { + if (_otherPlayerStartAttackingTimes.ContainsKey(_characterRepository.MainCharacter.ID)) + { + _otherPlayerStartAttackingTimes[_characterRepository.MainCharacter.ID].SetReplay(sfxCallback); + return; + } - _mainPlayerStartShoutTick = Option.Some(_fixedTimeStepRepository.TickCount); - _shoutSpellData = spellData; - _spellTarget = target; - return true; - } + var startAttackingTime = new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount, sfxCallback); + _otherPlayerStartAttackingTimes.Add(_characterRepository.MainCharacter.ID, startAttackingTime); + } - public void MainCharacterCancelSpellPrep() - { - _mainPlayerStartShoutTick = Option.None(); - _shoutSpellData = null; - _spellTarget = null; + public bool MainCharacterShoutSpellPrep(ESFRecord spellData, ISpellTargetable target) + { + if (_mainPlayerStartShoutTick.HasValue) + return false; - _spellSlotDataRepository.SelectedSpellSlot = Option.None(); - _spellSlotDataRepository.SpellIsPrepared = false; - } + _mainPlayerStartShoutTick = Option.Some(_fixedTimeStepRepository.TickCount); + _shoutSpellData = spellData; + _spellTarget = target; + return true; + } - public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) - { - if (_otherPlayerStartWalkingTimes.ContainsKey(characterID)) + public void MainCharacterCancelSpellPrep() { - _otherPlayerStartWalkingTimes[characterID].SetReplay(); - _queuedDirections[characterID] = direction; - _queuedPositions[characterID] = destination; - return; - } + _mainPlayerStartShoutTick = Option.None(); + _shoutSpellData = null; + _spellTarget = null; - var startWalkingTimeAndID = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); - _otherPlayerStartWalkingTimes.Add(characterID, startWalkingTimeAndID); - } + _spellSlotDataRepository.SelectedSpellSlot = Option.None(); + _spellSlotDataRepository.SpellIsPrepared = false; + } - public void StartOtherCharacterAttackAnimation(int characterID, Action sfxCallback) - { - if (_otherPlayerStartAttackingTimes.ContainsKey(characterID)) + public void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction) { - _otherPlayerStartAttackingTimes[characterID].SetReplay(sfxCallback); - return; + if (_otherPlayerStartWalkingTimes.ContainsKey(characterID)) + { + _otherPlayerStartWalkingTimes[characterID].SetReplay(); + _queuedDirections[characterID] = direction; + _queuedPositions[characterID] = destination; + return; + } + + var startWalkingTimeAndID = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); + _otherPlayerStartWalkingTimes.Add(characterID, startWalkingTimeAndID); } - var startAttackingTime = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount, sfxCallback); - _otherPlayerStartAttackingTimes.Add(characterID, startAttackingTime); - } + public void StartOtherCharacterAttackAnimation(int characterID, Action sfxCallback) + { + if (_otherPlayerStartAttackingTimes.ContainsKey(characterID)) + { + _otherPlayerStartAttackingTimes[characterID].SetReplay(sfxCallback); + return; + } - public void StartOtherCharacterSpellCast(int characterID) - { - if (_otherPlayerStartWalkingTimes.ContainsKey(characterID) || - _otherPlayerStartAttackingTimes.ContainsKey(characterID)) - return; + var startAttackingTime = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount, sfxCallback); + _otherPlayerStartAttackingTimes.Add(characterID, startAttackingTime); + } - if (_otherPlayerStartSpellCastTimes.ContainsKey(characterID)) + public void StartOtherCharacterSpellCast(int characterID) { - ResetCharacterAnimationFrames(characterID); - _otherPlayerStartSpellCastTimes.Remove(characterID); - } + if (_otherPlayerStartWalkingTimes.ContainsKey(characterID) || + _otherPlayerStartAttackingTimes.ContainsKey(characterID)) + return; - var startAttackingTimeAndID = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); - _otherPlayerStartSpellCastTimes.Add(characterID, startAttackingTimeAndID); - } + if (_otherPlayerStartSpellCastTimes.ContainsKey(characterID)) + { + ResetCharacterAnimationFrames(characterID); + _otherPlayerStartSpellCastTimes.Remove(characterID); + } - public bool Emote(int characterID, Emote whichEmote) - { - if (((_otherPlayerStartWalkingTimes.ContainsKey(characterID) || - _otherPlayerStartAttackingTimes.ContainsKey(characterID) || - _otherPlayerStartSpellCastTimes.ContainsKey(characterID)) && whichEmote != EOLib.Domain.Character.Emote.LevelUp) || - _startEmoteTimes.ContainsKey(characterID)) - return false; - - var startEmoteTime = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); - if (characterID == _characterRepository.MainCharacter.ID) - { - var rp = _characterRepository.MainCharacter.RenderProperties.WithEmote(whichEmote); - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(rp); + var startAttackingTimeAndID = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); + _otherPlayerStartSpellCastTimes.Add(characterID, startAttackingTimeAndID); } - else if (_currentMapStateRepository.Characters.TryGetValue(characterID, out var otherCharacter)) + + public bool Emote(int characterID, Emote whichEmote) { - var rp = otherCharacter.RenderProperties.WithEmote(whichEmote); - _currentMapStateRepository.Characters.Update(otherCharacter, otherCharacter.WithRenderProperties(rp)); + if (((_otherPlayerStartWalkingTimes.ContainsKey(characterID) || + _otherPlayerStartAttackingTimes.ContainsKey(characterID) || + _otherPlayerStartSpellCastTimes.ContainsKey(characterID)) && whichEmote != EOLib.Domain.Character.Emote.LevelUp) || + _startEmoteTimes.ContainsKey(characterID)) + return false; + + var startEmoteTime = new RenderFrameActionTime(characterID, _fixedTimeStepRepository.TickCount); + if (characterID == _characterRepository.MainCharacter.ID) + { + var rp = _characterRepository.MainCharacter.RenderProperties.WithEmote(whichEmote); + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(rp); + } + else if (_currentMapStateRepository.Characters.TryGetValue(characterID, out var otherCharacter)) + { + var rp = otherCharacter.RenderProperties.WithEmote(whichEmote); + _currentMapStateRepository.Characters.Update(otherCharacter, otherCharacter.WithRenderProperties(rp)); + } + else + { + _currentMapStateRepository.UnknownPlayerIDs.Add(characterID); + return false; + } + + _startEmoteTimes[characterID] = startEmoteTime; + return true; } - else + + public void StopAllCharacterAnimations() { - _currentMapStateRepository.UnknownPlayerIDs.Add(characterID); - return false; + _otherPlayerStartWalkingTimes.Clear(); + _otherPlayerStartAttackingTimes.Clear(); + _otherPlayerStartSpellCastTimes.Clear(); + _walkPath.Clear(); + + _characterRepository.MainCharacter = + _characterRepository.MainCharacter.WithRenderProperties( + _characterRepository.MainCharacter.RenderProperties.ResetAnimationFrames()); + + var characterPairs = _currentMapStateRepository.Characters + .Select(c => (Old: c, New: c.WithRenderProperties(c.RenderProperties.ResetAnimationFrames()))) + .ToList(); + foreach (var (Old, New) in characterPairs) + _currentMapStateRepository.Characters.Update(Old, New); } - _startEmoteTimes[characterID] = startEmoteTime; - return true; - } - - public void StopAllCharacterAnimations() - { - _otherPlayerStartWalkingTimes.Clear(); - _otherPlayerStartAttackingTimes.Clear(); - _otherPlayerStartSpellCastTimes.Clear(); - _walkPath.Clear(); - - _characterRepository.MainCharacter = - _characterRepository.MainCharacter.WithRenderProperties( - _characterRepository.MainCharacter.RenderProperties.ResetAnimationFrames()); - - var characterPairs = _currentMapStateRepository.Characters - .Select(c => (Old: c, New: c.WithRenderProperties(c.RenderProperties.ResetAnimationFrames()))) - .ToList(); - foreach (var (Old, New) in characterPairs) - _currentMapStateRepository.Characters.Update(Old, New); - } - - #region Walk Animation + #region Walk Animation - private void AnimateCharacterWalking() - { - var playersDoneWalking = new List(); - foreach (var pair in _otherPlayerStartWalkingTimes.Values) + private void AnimateCharacterWalking() { - var sendWalk = false; - - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_WALK_FRAME) + var playersDoneWalking = new List(); + foreach (var pair in _otherPlayerStartWalkingTimes.Values) { - GetCurrentCharacterFromRepository(pair).Match( - none: () => playersDoneWalking.Add(pair.UniqueID), - some: currentCharacter => - { - var renderProperties = currentCharacter.RenderProperties; - var nextFrameRenderProperties = AnimateOneWalkFrame(renderProperties); + var sendWalk = false; - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_WALK_FRAME) + { + GetCurrentCharacterFromRepository(pair).Match( + none: () => playersDoneWalking.Add(pair.UniqueID), + some: currentCharacter => { - var isMainCharacter = currentCharacter == _characterRepository.MainCharacter; + var renderProperties = currentCharacter.RenderProperties; + var nextFrameRenderProperties = AnimateOneWalkFrame(renderProperties); - if (pair.Replay) + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) { - var nextFramePropertiesWithDirection = _queuedDirections.ContainsKey(pair.UniqueID) - ? nextFrameRenderProperties.WithDirection(_queuedDirections[pair.UniqueID]) - : nextFrameRenderProperties; - _queuedDirections.Remove(pair.UniqueID); - - var canMoveToDestinationCoordinates = _walkValidationActions.CanMoveToCoordinates( - nextFramePropertiesWithDirection.GetDestinationX(), - nextFramePropertiesWithDirection.GetDestinationY()) == WalkValidationResult.Walkable; + var isMainCharacter = currentCharacter == _characterRepository.MainCharacter; - if (!isMainCharacter || (isMainCharacter && canMoveToDestinationCoordinates)) + if (pair.Replay) { - // send the walk packet after the game state has been updated so the correct coordinates are sent - sendWalk = isMainCharacter; - - var extraFrameProps = AnimateOneWalkFrame(nextFramePropertiesWithDirection.ResetAnimationFrames()); - pair.ClearReplay(); + var nextFramePropertiesWithDirection = _queuedDirections.ContainsKey(pair.UniqueID) + ? nextFrameRenderProperties.WithDirection(_queuedDirections[pair.UniqueID]) + : nextFrameRenderProperties; + _queuedDirections.Remove(pair.UniqueID); - nextFrameRenderProperties = extraFrameProps; - pair.SoundEffect(); - } - else - { - // tried to replay but the new destination position is not walkable - playersDoneWalking.Add(pair.UniqueID); - } - } - else if (isMainCharacter && _walkPath.Any()) - { - var characterCoord = new MapCoordinate(nextFrameRenderProperties.MapX, nextFrameRenderProperties.MapY); + var canMoveToDestinationCoordinates = _walkValidationActions.CanMoveToCoordinates( + nextFramePropertiesWithDirection.GetDestinationX(), + nextFramePropertiesWithDirection.GetDestinationY()) == WalkValidationResult.Walkable; - _walkPath = _targetCoordinate.Match( - some: tc => + if (!isMainCharacter || (isMainCharacter && canMoveToDestinationCoordinates)) { - if (tc.Equals(characterCoord)) - return new Queue(); - return _pathFinder.FindPath(characterCoord, tc); - }, - none: () => new Queue()); + // send the walk packet after the game state has been updated so the correct coordinates are sent + sendWalk = isMainCharacter; - if (_walkPath.Any()) - { - var next = _walkPath.Dequeue(); - nextFrameRenderProperties = FaceTarget(characterCoord, next, nextFrameRenderProperties); + var extraFrameProps = AnimateOneWalkFrame(nextFramePropertiesWithDirection.ResetAnimationFrames()); + pair.ClearReplay(); - sendWalk = true; - pair.SoundEffect(); - nextFrameRenderProperties = AnimateOneWalkFrame(nextFrameRenderProperties.ResetAnimationFrames()); + nextFrameRenderProperties = extraFrameProps; + pair.SoundEffect(); + } + else + { + // tried to replay but the new destination position is not walkable + playersDoneWalking.Add(pair.UniqueID); + } } - else + else if (isMainCharacter && _walkPath.Any()) { - playersDoneWalking.Add(pair.UniqueID); + var characterCoord = new MapCoordinate(nextFrameRenderProperties.MapX, nextFrameRenderProperties.MapY); + + _walkPath = _targetCoordinate.Match( + some: tc => + { + if (tc.Equals(characterCoord)) + return new Queue(); + return _pathFinder.FindPath(characterCoord, tc); + }, + none: () => new Queue()); + + if (_walkPath.Any()) + { + var next = _walkPath.Dequeue(); + nextFrameRenderProperties = FaceTarget(characterCoord, next, nextFrameRenderProperties); + + sendWalk = true; + pair.SoundEffect(); + nextFrameRenderProperties = AnimateOneWalkFrame(nextFrameRenderProperties.ResetAnimationFrames()); + } + else + { + playersDoneWalking.Add(pair.UniqueID); + } } - } - else - { - if (_queuedPositions.ContainsKey(pair.UniqueID)) + else { - nextFrameRenderProperties = nextFrameRenderProperties - .WithMapX(_queuedPositions[pair.UniqueID].X) - .WithMapY(_queuedPositions[pair.UniqueID].Y); - _queuedPositions.Remove(pair.UniqueID); - } + if (_queuedPositions.ContainsKey(pair.UniqueID)) + { + nextFrameRenderProperties = nextFrameRenderProperties + .WithMapX(_queuedPositions[pair.UniqueID].X) + .WithMapY(_queuedPositions[pair.UniqueID].Y); + _queuedPositions.Remove(pair.UniqueID); + } - playersDoneWalking.Add(pair.UniqueID); + playersDoneWalking.Add(pair.UniqueID); + } } - } - var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); - UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); + var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); + UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); - if (sendWalk) - { - _characterActions.Walk(false); - } - }); + if (sendWalk) + { + _characterActions.Walk(false); + } + }); + } } + + foreach (var key in playersDoneWalking) + _otherPlayerStartWalkingTimes.Remove(key); } - foreach (var key in playersDoneWalking) - _otherPlayerStartWalkingTimes.Remove(key); - } + private CharacterRenderProperties AnimateOneWalkFrame(CharacterRenderProperties renderProperties) + { + var isSteppingStone = _currentMapProvider.CurrentMap.Tiles[renderProperties.MapY, renderProperties.MapX] == TileSpec.Jump + || _currentMapProvider.CurrentMap.Tiles[renderProperties.GetDestinationY(), renderProperties.GetDestinationX()] == TileSpec.Jump; - private CharacterRenderProperties AnimateOneWalkFrame(CharacterRenderProperties renderProperties) - { - var isSteppingStone = _currentMapProvider.CurrentMap.Tiles[renderProperties.MapY, renderProperties.MapX] == TileSpec.Jump - || _currentMapProvider.CurrentMap.Tiles[renderProperties.GetDestinationY(), renderProperties.GetDestinationX()] == TileSpec.Jump; + var nextFrameRenderProperties = renderProperties.WithNextWalkFrame(isSteppingStone); + if (nextFrameRenderProperties.CurrentAction != CharacterActionState.Walking) + { + nextFrameRenderProperties = nextFrameRenderProperties + .WithMapX(nextFrameRenderProperties.GetDestinationX()) + .WithMapY(nextFrameRenderProperties.GetDestinationY()); + } - var nextFrameRenderProperties = renderProperties.WithNextWalkFrame(isSteppingStone); - if (nextFrameRenderProperties.CurrentAction != CharacterActionState.Walking) - { - nextFrameRenderProperties = nextFrameRenderProperties - .WithMapX(nextFrameRenderProperties.GetDestinationX()) - .WithMapY(nextFrameRenderProperties.GetDestinationY()); + return nextFrameRenderProperties; } - return nextFrameRenderProperties; - } + private CharacterRenderProperties FaceTarget(MapCoordinate characterCoord, MapCoordinate next, CharacterRenderProperties rp) + { + var diff = next - characterCoord; - private CharacterRenderProperties FaceTarget(MapCoordinate characterCoord, MapCoordinate next, CharacterRenderProperties rp) - { - var diff = next - characterCoord; + if (diff.X != 0 && diff.Y != 0) + throw new InvalidOperationException("Trying to move in a diagonal."); - if (diff.X != 0 && diff.Y != 0) - throw new InvalidOperationException("Trying to move in a diagonal."); + if (diff.X < 0) + { + return rp.WithDirection(EODirection.Left); + } + else if (diff.X > 0) + { + return rp.WithDirection(EODirection.Right); + } + else if (diff.Y < 0) + { + return rp.WithDirection(EODirection.Up); + } + else if (diff.Y > 0) + { + return rp.WithDirection(EODirection.Down); + } - if (diff.X < 0) - { - return rp.WithDirection(EODirection.Left); - } - else if (diff.X > 0) - { - return rp.WithDirection(EODirection.Right); - } - else if (diff.Y < 0) - { - return rp.WithDirection(EODirection.Up); - } - else if (diff.Y > 0) - { - return rp.WithDirection(EODirection.Down); + return rp; } - return rp; - } - - #endregion + #endregion - #region Attack Animation + #region Attack Animation - private void AnimateCharacterAttacking() - { - var playersDoneAttacking = new HashSet(); - foreach (var pair in _otherPlayerStartAttackingTimes.Values) + private void AnimateCharacterAttacking() { - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME) + var playersDoneAttacking = new HashSet(); + foreach (var pair in _otherPlayerStartAttackingTimes.Values) { - GetCurrentCharacterFromRepository(pair).Match( - none: () => playersDoneAttacking.Add(pair.UniqueID), - some: currentCharacter => - { - var renderProperties = currentCharacter.RenderProperties; - var isRanged = _weaponMetadataProvider.GetValueOrDefault(renderProperties.WeaponGraphic).Ranged; - var nextFrameRenderProperties = renderProperties.WithNextAttackFrame(isRanged); + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME) + { + GetCurrentCharacterFromRepository(pair).Match( + none: () => playersDoneAttacking.Add(pair.UniqueID), + some: currentCharacter => + { + var renderProperties = currentCharacter.RenderProperties; + var isRanged = _weaponMetadataProvider.GetValueOrDefault(renderProperties.WeaponGraphic).Ranged; + var nextFrameRenderProperties = renderProperties.WithNextAttackFrame(isRanged); - if (nextFrameRenderProperties.ActualAttackFrame == 2) - pair.SoundEffect(); + if (nextFrameRenderProperties.ActualAttackFrame == 2) + pair.SoundEffect(); - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) - { - if (pair.Replay) - { - nextFrameRenderProperties = renderProperties.ResetAnimationFrames().WithNextAttackFrame(isRanged); - pair.ClearReplay(); - } - else + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) { - playersDoneAttacking.Add(pair.UniqueID); + if (pair.Replay) + { + nextFrameRenderProperties = renderProperties.ResetAnimationFrames().WithNextAttackFrame(isRanged); + pair.ClearReplay(); + } + else + { + playersDoneAttacking.Add(pair.UniqueID); + } } - } - var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); - UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); - }); + var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); + UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); + }); + } } - } - foreach (var key in playersDoneAttacking) - _otherPlayerStartAttackingTimes.Remove(key); - } + foreach (var key in playersDoneAttacking) + _otherPlayerStartAttackingTimes.Remove(key); + } - #endregion + #endregion - #region Spell Animation + #region Spell Animation - private void AnimateCharacterSpells() - { - _mainPlayerStartShoutTick.MatchSome(startTick => + private void AnimateCharacterSpells() { - if (_fixedTimeStepRepository.TickCount - startTick >= (ulong)(_shoutSpellData.CastTime * TICKS_PER_CAST_TIME)) + _mainPlayerStartShoutTick.MatchSome(startTick => { - _otherPlayerStartSpellCastTimes.Add(_characterRepository.MainCharacter.ID, new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount)); - _characterActions.CastSpell(_shoutSpellData.ID, _spellTarget); - MainCharacterCancelSpellPrep(); + if (_fixedTimeStepRepository.TickCount - startTick >= (ulong)(_shoutSpellData.CastTime * TICKS_PER_CAST_TIME)) + { + _otherPlayerStartSpellCastTimes.Add(_characterRepository.MainCharacter.ID, new RenderFrameActionTime(_characterRepository.MainCharacter.ID, _fixedTimeStepRepository.TickCount)); + _characterActions.CastSpell(_shoutSpellData.ID, _spellTarget); + MainCharacterCancelSpellPrep(); - var nextRenderProps = _characterRepository.MainCharacter.RenderProperties.WithCurrentAction(CharacterActionState.SpellCast); - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(nextRenderProps); - } - }); + var nextRenderProps = _characterRepository.MainCharacter.RenderProperties.WithCurrentAction(CharacterActionState.SpellCast); + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties(nextRenderProps); + } + }); - var playersDoneCasting = new HashSet(); - foreach (var pair in _otherPlayerStartSpellCastTimes.Values) - { - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME) + var playersDoneCasting = new HashSet(); + foreach (var pair in _otherPlayerStartSpellCastTimes.Values) { - GetCurrentCharacterFromRepository(pair).Match( - none: () => playersDoneCasting.Add(pair.UniqueID), - some: currentCharacter => - { - var renderProperties = currentCharacter.RenderProperties; - var nextFrameRenderProperties = renderProperties.WithNextSpellCastFrame(); + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME) + { + GetCurrentCharacterFromRepository(pair).Match( + none: () => playersDoneCasting.Add(pair.UniqueID), + some: currentCharacter => + { + var renderProperties = currentCharacter.RenderProperties; + var nextFrameRenderProperties = renderProperties.WithNextSpellCastFrame(); - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) - playersDoneCasting.Add(pair.UniqueID); + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing)) + playersDoneCasting.Add(pair.UniqueID); - var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); - UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); - }); + var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); + UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); + }); + } } - } - foreach (var key in playersDoneCasting) - _otherPlayerStartSpellCastTimes.Remove(key); - } + foreach (var key in playersDoneCasting) + _otherPlayerStartSpellCastTimes.Remove(key); + } - #endregion + #endregion - #region Emote Animation + #region Emote Animation - private void AnimateCharacterEmotes() - { - var playersDoneEmoting = new HashSet(); - foreach (var pair in _startEmoteTimes.Values) + private void AnimateCharacterEmotes() { - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME * 2) + var playersDoneEmoting = new HashSet(); + foreach (var pair in _startEmoteTimes.Values) { - GetCurrentCharacterFromRepository(pair).Match( - none: () => playersDoneEmoting.Add(pair.UniqueID), - some: currentCharacter => - { - var renderProperties = currentCharacter.RenderProperties; - var nextFrameRenderProperties = renderProperties.WithNextEmoteFrame(); + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_FRAME * 2) + { + GetCurrentCharacterFromRepository(pair).Match( + none: () => playersDoneEmoting.Add(pair.UniqueID), + some: currentCharacter => + { + var renderProperties = currentCharacter.RenderProperties; + var nextFrameRenderProperties = renderProperties.WithNextEmoteFrame(); - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing, CharacterActionState.Sitting)) - playersDoneEmoting.Add(pair.UniqueID); + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + if (nextFrameRenderProperties.IsActing(CharacterActionState.Standing, CharacterActionState.Sitting)) + playersDoneEmoting.Add(pair.UniqueID); - var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); - UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); - }); + var nextFrameCharacter = currentCharacter.WithRenderProperties(nextFrameRenderProperties); + UpdateCharacterInRepository(currentCharacter, nextFrameCharacter); + }); + } } - } - foreach (var key in playersDoneEmoting) - _startEmoteTimes.Remove(key); - } + foreach (var key in playersDoneEmoting) + _startEmoteTimes.Remove(key); + } - #endregion + #endregion - private Option GetCurrentCharacterFromRepository(RenderFrameActionTime pair) - { - return pair.UniqueID == _characterRepository.MainCharacter.ID - ? Option.Some(_characterRepository.MainCharacter) - : _currentMapStateRepository.Characters.TryGetValue(pair.UniqueID, out var character) - ? Option.Some(character) - : Option.None(); - } + private Option GetCurrentCharacterFromRepository(RenderFrameActionTime pair) + { + return pair.UniqueID == _characterRepository.MainCharacter.ID + ? Option.Some(_characterRepository.MainCharacter) + : _currentMapStateRepository.Characters.TryGetValue(pair.UniqueID, out var character) + ? Option.Some(character) + : Option.None(); + } - private void UpdateCharacterInRepository(EOLib.Domain.Character.Character currentCharacter, - EOLib.Domain.Character.Character nextFrameCharacter) - { - if (currentCharacter == _characterRepository.MainCharacter) + private void UpdateCharacterInRepository(EOLib.Domain.Character.Character currentCharacter, + EOLib.Domain.Character.Character nextFrameCharacter) { - _characterRepository.MainCharacter = nextFrameCharacter; + if (currentCharacter == _characterRepository.MainCharacter) + { + _characterRepository.MainCharacter = nextFrameCharacter; + } + else + { + _currentMapStateRepository.Characters.Update(currentCharacter, nextFrameCharacter); + } } - else + + private void ResetCharacterAnimationFrames(int characterID) { - _currentMapStateRepository.Characters.Update(currentCharacter, nextFrameCharacter); + var character = _currentMapStateRepository.Characters[characterID]; + var renderProps = character.RenderProperties.ResetAnimationFrames(); + var newCharacter = character.WithRenderProperties(renderProps); + _currentMapStateRepository.Characters.Update(character, newCharacter); } } - private void ResetCharacterAnimationFrames(int characterID) + public interface ICharacterAnimator : IGameComponent { - var character = _currentMapStateRepository.Characters[characterID]; - var renderProps = character.RenderProperties.ResetAnimationFrames(); - var newCharacter = character.WithRenderProperties(renderProps); - _currentMapStateRepository.Characters.Update(character, newCharacter); - } -} + void MainCharacterFace(EODirection direction); -public interface ICharacterAnimator : IGameComponent -{ - void MainCharacterFace(EODirection direction); - - void StartMainCharacterWalkAnimation(Option targetCoordinate, bool ghosted, Action sfxCallback); + void StartMainCharacterWalkAnimation(Option targetCoordinate, bool ghosted, Action sfxCallback); - void CancelClickToWalk(); + void CancelClickToWalk(); - void StartMainCharacterAttackAnimation(Action sfxCallback); + void StartMainCharacterAttackAnimation(Action sfxCallback); - bool MainCharacterShoutSpellPrep(ESFRecord spellData, ISpellTargetable spellTarget); + bool MainCharacterShoutSpellPrep(ESFRecord spellData, ISpellTargetable spellTarget); - void MainCharacterCancelSpellPrep(); + void MainCharacterCancelSpellPrep(); - void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction); + void StartOtherCharacterWalkAnimation(int characterID, MapCoordinate destination, EODirection direction); - void StartOtherCharacterAttackAnimation(int characterID, Action sfxCallback); + void StartOtherCharacterAttackAnimation(int characterID, Action sfxCallback); - void StartOtherCharacterSpellCast(int characterID); + void StartOtherCharacterSpellCast(int characterID); - bool Emote(int characterID, Emote whichEmote); + bool Emote(int characterID, Emote whichEmote); - void StopAllCharacterAnimations(); + void StopAllCharacterAnimations(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterRenderer.cs b/EndlessClient/Rendering/Character/CharacterRenderer.cs index a88126a80..be14bc636 100644 --- a/EndlessClient/Rendering/Character/CharacterRenderer.cs +++ b/EndlessClient/Rendering/Character/CharacterRenderer.cs @@ -22,533 +22,534 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering.Character; - -public class CharacterRenderer : DrawableGameComponent, ICharacterRenderer +namespace EndlessClient.Rendering.Character { - private readonly object _rt_locker_ = new object(); + public class CharacterRenderer : DrawableGameComponent, ICharacterRenderer + { + private readonly object _rt_locker_ = new object(); - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IHealthBarRendererFactory _healthBarRendererFactory; - private readonly IChatBubbleFactory _chatBubbleFactory; - private readonly ICharacterProvider _characterProvider; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly ICharacterPropertyRendererBuilder _characterPropertyRendererBuilder; - private readonly ICharacterTextures _characterTextures; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly IMetadataProvider _hatMetadataProvider; - private readonly IMetadataProvider _weaponMetadataProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private readonly IEffectRenderer _effectRenderer; + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IHealthBarRendererFactory _healthBarRendererFactory; + private readonly IChatBubbleFactory _chatBubbleFactory; + private readonly ICharacterProvider _characterProvider; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly ICharacterPropertyRendererBuilder _characterPropertyRendererBuilder; + private readonly ICharacterTextures _characterTextures; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly IMetadataProvider _hatMetadataProvider; + private readonly IMetadataProvider _weaponMetadataProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IEffectRenderer _effectRenderer; - private readonly bool _isUiControl; + private readonly bool _isUiControl; - private EOLib.Domain.Character.Character _character; - private bool _textureUpdateRequired, _positionIsRelative = true; + private EOLib.Domain.Character.Character _character; + private bool _textureUpdateRequired, _positionIsRelative = true; - private SpriteBatch _sb; - private RenderTarget2D _charRenderTarget; - private Texture2D _outline; + private SpriteBatch _sb; + private RenderTarget2D _charRenderTarget; + private Texture2D _outline; - private BlinkingLabel _nameLabel; - private string _shoutName = string.Empty; - private DateTime? _spellCastTime; - private bool _showName = true; + private BlinkingLabel _nameLabel; + private string _shoutName = string.Empty; + private DateTime? _spellCastTime; + private bool _showName = true; - private IHealthBarRenderer _healthBarRenderer; - private Lazy _chatBubble; + private IHealthBarRenderer _healthBarRenderer; + private Lazy _chatBubble; - private bool _lastIsDead; + private bool _lastIsDead; - private Color[] _rtColorData; + private Color[] _rtColorData; - public EOLib.Domain.Character.Character Character - { - get { return _character; } - set + public EOLib.Domain.Character.Character Character { - if (_character == value) return; - _textureUpdateRequired = _character.RenderProperties.GetHashCode() != value.RenderProperties.GetHashCode(); - _character = value; + get { return _character; } + set + { + if (_character == value) return; + _textureUpdateRequired = _character.RenderProperties.GetHashCode() != value.RenderProperties.GetHashCode(); + _character = value; + } } - } - public bool Transparent { get; set; } + public bool Transparent { get; set; } - public Rectangle DrawArea { get; private set; } + public Rectangle DrawArea { get; private set; } - public ISpellTargetable SpellTarget => Character; + public ISpellTargetable SpellTarget => Character; - public int NameLabelY { get; private set; } + public int NameLabelY { get; private set; } - public int HorizontalCenter { get; private set; } + public int HorizontalCenter { get; private set; } - public bool IsAlive => !Character.RenderProperties.IsDead; - - public CharacterRenderer(Game game, - IRenderTargetFactory renderTargetFactory, - IHealthBarRendererFactory healthBarRendererFactory, - IChatBubbleFactory chatBubbleFactory, - ICharacterProvider characterProvider, - IRenderOffsetCalculator renderOffsetCalculator, - ICharacterPropertyRendererBuilder characterPropertyRendererBuilder, - ICharacterTextures characterTextures, - ICurrentMapProvider currentMapProvider, - IUserInputProvider userInputProvider, - IEffectRendererFactory effectRendererFactory, - IMetadataProvider hatMetadataProvider, - IMetadataProvider weaponMetadataProvider, - ISfxPlayer sfxPlayer, - IClientWindowSizeRepository clientWindowSizeRepository, - EOLib.Domain.Character.Character character, - bool isUiControl) - : base(game) - { - _renderTargetFactory = renderTargetFactory; - _healthBarRendererFactory = healthBarRendererFactory; - _chatBubbleFactory = chatBubbleFactory; - _characterProvider = characterProvider; - _renderOffsetCalculator = renderOffsetCalculator; - _characterPropertyRendererBuilder = characterPropertyRendererBuilder; - _characterTextures = characterTextures; - _currentMapProvider = currentMapProvider; - _userInputProvider = userInputProvider; - _hatMetadataProvider = hatMetadataProvider; - _weaponMetadataProvider = weaponMetadataProvider; - _effectRenderer = effectRendererFactory.Create(); - _sfxPlayer = sfxPlayer; - _clientWindowSizeRepository = clientWindowSizeRepository; - _character = character; - _isUiControl = isUiControl; - - _chatBubble = new Lazy(() => _chatBubbleFactory.CreateChatBubble(this)); - - _clientWindowSizeRepository.GameWindowSizeChanged += RecreateRenderTargetEvent; - } - - #region Game Component - - public override void Initialize() - { - RecreateRenderTarget(); + public bool IsAlive => !Character.RenderProperties.IsDead; - _sb = new SpriteBatch(Game.GraphicsDevice); - - if (!_isUiControl) + public CharacterRenderer(Game game, + IRenderTargetFactory renderTargetFactory, + IHealthBarRendererFactory healthBarRendererFactory, + IChatBubbleFactory chatBubbleFactory, + ICharacterProvider characterProvider, + IRenderOffsetCalculator renderOffsetCalculator, + ICharacterPropertyRendererBuilder characterPropertyRendererBuilder, + ICharacterTextures characterTextures, + ICurrentMapProvider currentMapProvider, + IUserInputProvider userInputProvider, + IEffectRendererFactory effectRendererFactory, + IMetadataProvider hatMetadataProvider, + IMetadataProvider weaponMetadataProvider, + ISfxPlayer sfxPlayer, + IClientWindowSizeRepository clientWindowSizeRepository, + EOLib.Domain.Character.Character character, + bool isUiControl) + : base(game) { - _nameLabel = new BlinkingLabel(Constants.FontSize08pt5) - { - Visible = true, - TextWidth = 89, - TextAlign = LabelAlignment.MiddleCenter, - ForeColor = Color.White, - AutoSize = true, - Text = _character?.Name ?? string.Empty, - DrawOrder = 30, - KeepInClientWindowBounds = false, - }; - _nameLabel.Initialize(); - - if (!_nameLabel.Game.Components.Contains(_nameLabel)) - _nameLabel.Game.Components.Add(_nameLabel); - - _nameLabel.DrawPosition = GetNameLabelPosition(); - - _healthBarRenderer = _healthBarRendererFactory.CreateHealthBarRenderer(this); + _renderTargetFactory = renderTargetFactory; + _healthBarRendererFactory = healthBarRendererFactory; + _chatBubbleFactory = chatBubbleFactory; + _characterProvider = characterProvider; + _renderOffsetCalculator = renderOffsetCalculator; + _characterPropertyRendererBuilder = characterPropertyRendererBuilder; + _characterTextures = characterTextures; + _currentMapProvider = currentMapProvider; + _userInputProvider = userInputProvider; + _hatMetadataProvider = hatMetadataProvider; + _weaponMetadataProvider = weaponMetadataProvider; + _effectRenderer = effectRendererFactory.Create(); + _sfxPlayer = sfxPlayer; + _clientWindowSizeRepository = clientWindowSizeRepository; + _character = character; + _isUiControl = isUiControl; + + _chatBubble = new Lazy(() => _chatBubbleFactory.CreateChatBubble(this)); + + _clientWindowSizeRepository.GameWindowSizeChanged += RecreateRenderTargetEvent; } - base.Initialize(); - } + #region Game Component - protected override void LoadContent() - { - _textureUpdateRequired = true; - _characterTextures.Refresh(_character.RenderProperties); + public override void Initialize() + { + RecreateRenderTarget(); - _outline = new Texture2D(GraphicsDevice, 1, 1); - _outline.SetData(new[] { Color.White }); + _sb = new SpriteBatch(Game.GraphicsDevice); - base.LoadContent(); - } - - public override void Update(GameTime gameTime) - { - // Effects can be rendered when character is not visible (leaving map) - _effectRenderer.Update(); - - if (!Visible) - return; + if (!_isUiControl) + { + _nameLabel = new BlinkingLabel(Constants.FontSize08pt5) + { + Visible = true, + TextWidth = 89, + TextAlign = LabelAlignment.MiddleCenter, + ForeColor = Color.White, + AutoSize = true, + Text = _character?.Name ?? string.Empty, + DrawOrder = 30, + KeepInClientWindowBounds = false, + }; + _nameLabel.Initialize(); + + if (!_nameLabel.Game.Components.Contains(_nameLabel)) + _nameLabel.Game.Components.Add(_nameLabel); + + _nameLabel.DrawPosition = GetNameLabelPosition(); + + _healthBarRenderer = _healthBarRendererFactory.CreateHealthBarRenderer(this); + } - if (_positionIsRelative) - SetGridCoordinatePosition(); + base.Initialize(); + } - if (_textureUpdateRequired) + protected override void LoadContent() { + _textureUpdateRequired = true; _characterTextures.Refresh(_character.RenderProperties); - DrawToRenderTarget(); - _textureUpdateRequired = false; + _outline = new Texture2D(GraphicsDevice, 1, 1); + _outline.SetData(new[] { Color.White }); + + base.LoadContent(); } - if (!_isUiControl) + public override void Update(GameTime gameTime) { - UpdateNameLabel(); + // Effects can be rendered when character is not visible (leaving map) + _effectRenderer.Update(); - _healthBarRenderer?.Update(gameTime); + if (!Visible) + return; - CheckForDead(); - } + if (_positionIsRelative) + SetGridCoordinatePosition(); - base.Update(gameTime); - } + if (_textureUpdateRequired) + { + _characterTextures.Refresh(_character.RenderProperties); + DrawToRenderTarget(); - public override void Draw(GameTime gameTime) - { - if (!Visible || _sb.IsDisposed || - (Character == _characterProvider.MainCharacter && !_characterProvider.HasAvatar)) - return; + _textureUpdateRequired = false; + } - if (!Character.RenderProperties.IsHidden || _characterProvider.MainCharacter.AdminLevel > 0) - { - _sb.Begin(); - DrawToSpriteBatch(_sb); + if (!_isUiControl) + { + UpdateNameLabel(); - if (_sb.IsDisposed) - return; - _sb.End(); - } + _healthBarRenderer?.Update(gameTime); - base.Draw(gameTime); - } + CheckForDead(); + } - #endregion + base.Update(gameTime); + } - #region ICharacterRenderer + public override void Draw(GameTime gameTime) + { + if (!Visible || _sb.IsDisposed || + (Character == _characterProvider.MainCharacter && !_characterProvider.HasAvatar)) + return; - public void SetAbsoluteScreenPosition(int xPosition, int yPosition) - { - SetScreenCoordinates(xPosition, yPosition); - _positionIsRelative = false; - } + if (!Character.RenderProperties.IsHidden || _characterProvider.MainCharacter.AdminLevel > 0) + { + _sb.Begin(); + DrawToSpriteBatch(_sb); - public void SetToCenterScreenPosition() - { - var skinRect = _characterTextures.Skin.SourceRectangle; + if (_sb.IsDisposed) + return; + _sb.End(); + } - var xCoord = _clientWindowSizeRepository.Resizable - ? (_clientWindowSizeRepository.Width - skinRect.Width) / 2 - : 310; - var yCoord = _clientWindowSizeRepository.Resizable - ? (_clientWindowSizeRepository.Height - skinRect.Height) / 2 - 11 - : (298 - skinRect.Height) / 2 - skinRect.Height / 4 - 3; + base.Draw(gameTime); + } - SetAbsoluteScreenPosition(xCoord, yCoord); - } + #endregion - public void DrawToSpriteBatch(SpriteBatch spriteBatch) - { - _effectRenderer.DrawBehindTarget(spriteBatch); + #region ICharacterRenderer - if (Visible) + public void SetAbsoluteScreenPosition(int xPosition, int yPosition) { - lock (_rt_locker_) - { - spriteBatch.Draw(_charRenderTarget, new Vector2(0, GetSteppingStoneOffset(Character.RenderProperties)), GetAlphaColor()); - } + SetScreenCoordinates(xPosition, yPosition); + _positionIsRelative = false; } - _effectRenderer.DrawInFrontOfTarget(spriteBatch); - - if (!_isUiControl) - _healthBarRenderer?.DrawToSpriteBatch(spriteBatch); - } + public void SetToCenterScreenPosition() + { + var skinRect = _characterTextures.Skin.SourceRectangle; - public void ShowName() => _showName = true; + var xCoord = _clientWindowSizeRepository.Resizable + ? (_clientWindowSizeRepository.Width - skinRect.Width) / 2 + : 310; + var yCoord = _clientWindowSizeRepository.Resizable + ? (_clientWindowSizeRepository.Height - skinRect.Height) / 2 - 11 + : (298 - skinRect.Height) / 2 - skinRect.Height / 4 - 3; - public void HideName() => _showName = false; + SetAbsoluteScreenPosition(xCoord, yCoord); + } - #endregion + public void DrawToSpriteBatch(SpriteBatch spriteBatch) + { + _effectRenderer.DrawBehindTarget(spriteBatch); - #region Update/Drawing Helpers + if (Visible) + { + lock (_rt_locker_) + { + spriteBatch.Draw(_charRenderTarget, new Vector2(0, GetSteppingStoneOffset(Character.RenderProperties)), GetAlphaColor()); + } + } - private void DrawToRenderTarget() - { - var weaponMetadata = _weaponMetadataProvider.GetValueOrDefault(Character.RenderProperties.WeaponGraphic); + _effectRenderer.DrawInFrontOfTarget(spriteBatch); - lock (_rt_locker_) - { - GraphicsDevice.SetRenderTarget(_charRenderTarget); - GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); - _sb.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend); - - var characterPropertyRenderers = _characterPropertyRendererBuilder - .BuildList(_characterTextures, _character.RenderProperties) - .Where(x => x.CanRender); - foreach (var renderer in characterPropertyRenderers) - renderer.Render(_sb, DrawArea, weaponMetadata); - - //if (_gameStateProvider.CurrentState == GameStates.None) - //{ - // _sb.Draw(_outline, DrawArea.WithSize(DrawArea.Width, 1), Color.Black); - // _sb.Draw(_outline, DrawArea.WithPosition(new Vector2(DrawArea.X + DrawArea.Width, DrawArea.Y)).WithSize(1, DrawArea.Height), Color.Black); - // _sb.Draw(_outline, DrawArea.WithPosition(new Vector2(DrawArea.X, DrawArea.Y + DrawArea.Height)).WithSize(DrawArea.Width, 1), Color.Black); - // _sb.Draw(_outline, DrawArea.WithSize(1, DrawArea.Height), Color.Black); - - // _sb.Draw(_outline, DrawArea, Color.FromNonPremultiplied(255, 0, 0, 64)); - //} - - _sb.End(); - GraphicsDevice.SetRenderTarget(null); - - ClipHair(); + if (!_isUiControl) + _healthBarRenderer?.DrawToSpriteBatch(spriteBatch); } - } - private Color GetAlphaColor() - { - // don't render the transparent character layer if hidden/dead, otherwise the additive blending - // will render it with full alpha - if (_character.RenderProperties.IsHidden || _character.RenderProperties.IsDead) - return Transparent ? Color.Transparent : Color.FromNonPremultiplied(255, 255, 255, 128); - - return Transparent - ? Color.FromNonPremultiplied(255, 255, 255, 128) - : Color.White; - } + public void ShowName() => _showName = true; - private void SetGridCoordinatePosition() - { - var centerX = _clientWindowSizeRepository.Resizable ? (_clientWindowSizeRepository.Width - DrawArea.Width) / 2 : 310; - var centerY = _clientWindowSizeRepository.Resizable ? (_clientWindowSizeRepository.Height - DrawArea.Height) / 2 - 8 : 104; + public void HideName() => _showName = false; - var screenX = _renderOffsetCalculator.CalculateOffsetX(_character.RenderProperties) + centerX - GetMainCharacterOffsetX(); - var screenY = _renderOffsetCalculator.CalculateOffsetY(_character.RenderProperties) + centerY - GetMainCharacterOffsetY(); + #endregion - SetScreenCoordinates(screenX, screenY); - } + #region Update/Drawing Helpers - private void SetScreenCoordinates(int xPosition, int yPosition) - { - if (DrawArea.X != xPosition || DrawArea.Y != yPosition) + private void DrawToRenderTarget() { - // size of standing still skin texture - DrawArea = new Rectangle(xPosition, yPosition, 18, 58); - HorizontalCenter = xPosition + 9; - _textureUpdateRequired = true; + var weaponMetadata = _weaponMetadataProvider.GetValueOrDefault(Character.RenderProperties.WeaponGraphic); + + lock (_rt_locker_) + { + GraphicsDevice.SetRenderTarget(_charRenderTarget); + GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); + _sb.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend); + + var characterPropertyRenderers = _characterPropertyRendererBuilder + .BuildList(_characterTextures, _character.RenderProperties) + .Where(x => x.CanRender); + foreach (var renderer in characterPropertyRenderers) + renderer.Render(_sb, DrawArea, weaponMetadata); + + //if (_gameStateProvider.CurrentState == GameStates.None) + //{ + // _sb.Draw(_outline, DrawArea.WithSize(DrawArea.Width, 1), Color.Black); + // _sb.Draw(_outline, DrawArea.WithPosition(new Vector2(DrawArea.X + DrawArea.Width, DrawArea.Y)).WithSize(1, DrawArea.Height), Color.Black); + // _sb.Draw(_outline, DrawArea.WithPosition(new Vector2(DrawArea.X, DrawArea.Y + DrawArea.Height)).WithSize(DrawArea.Width, 1), Color.Black); + // _sb.Draw(_outline, DrawArea.WithSize(1, DrawArea.Height), Color.Black); + + // _sb.Draw(_outline, DrawArea, Color.FromNonPremultiplied(255, 0, 0, 64)); + //} + + _sb.End(); + GraphicsDevice.SetRenderTarget(null); + + ClipHair(); + } } - } - private int GetMainCharacterOffsetX() - { - return _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); - } + private Color GetAlphaColor() + { + // don't render the transparent character layer if hidden/dead, otherwise the additive blending + // will render it with full alpha + if (_character.RenderProperties.IsHidden || _character.RenderProperties.IsDead) + return Transparent ? Color.Transparent : Color.FromNonPremultiplied(255, 255, 255, 128); + + return Transparent + ? Color.FromNonPremultiplied(255, 255, 255, 128) + : Color.White; + } - private int GetMainCharacterOffsetY() - { - return _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); - } + private void SetGridCoordinatePosition() + { + var centerX = _clientWindowSizeRepository.Resizable ? (_clientWindowSizeRepository.Width - DrawArea.Width) / 2 : 310; + var centerY = _clientWindowSizeRepository.Resizable ? (_clientWindowSizeRepository.Height - DrawArea.Height) / 2 - 8 : 104; - private void UpdateNameLabel() - { - if (_isUiControl || _healthBarRenderer == null || _nameLabel == null) - return; + var screenX = _renderOffsetCalculator.CalculateOffsetX(_character.RenderProperties) + centerX - GetMainCharacterOffsetX(); + var screenY = _renderOffsetCalculator.CalculateOffsetY(_character.RenderProperties) + centerY - GetMainCharacterOffsetY(); - if (_healthBarRenderer.Visible) - { - _nameLabel.Visible = false; + SetScreenCoordinates(screenX, screenY); } - else if (DrawArea.Contains(_userInputProvider.CurrentMouseState.Position) && _showName) + + private void SetScreenCoordinates(int xPosition, int yPosition) { - _nameLabel.Visible = true; - _nameLabel.BlinkRate = null; - _nameLabel.Text = !string.IsNullOrWhiteSpace(_character.GuildTag) ? $"{_character.Name} {_character.GuildTag}" : _character.Name; + if (DrawArea.X != xPosition || DrawArea.Y != yPosition) + { + // size of standing still skin texture + DrawArea = new Rectangle(xPosition, yPosition, 18, 58); + HorizontalCenter = xPosition + 9; + _textureUpdateRequired = true; + } } - else if (_shoutName != string.Empty && _nameLabel.Text != _shoutName) + + private int GetMainCharacterOffsetX() { - _nameLabel.Visible = true; - _nameLabel.BlinkRate = 250; - _nameLabel.Text = _shoutName; + return _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); } - else if (_shoutName == string.Empty) + + private int GetMainCharacterOffsetY() { - _nameLabel.Visible = false; + return _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); } - if (_spellCastTime.HasValue && (DateTime.Now - _spellCastTime.Value).TotalMilliseconds >= 600) + private void UpdateNameLabel() { - StopShout(); - } + if (_isUiControl || _healthBarRenderer == null || _nameLabel == null) + return; - _nameLabel.DrawPosition = GetNameLabelPosition(); - } + if (_healthBarRenderer.Visible) + { + _nameLabel.Visible = false; + } + else if (DrawArea.Contains(_userInputProvider.CurrentMouseState.Position) && _showName) + { + _nameLabel.Visible = true; + _nameLabel.BlinkRate = null; + _nameLabel.Text = !string.IsNullOrWhiteSpace(_character.GuildTag) ? $"{_character.Name} {_character.GuildTag}" : _character.Name; + } + else if (_shoutName != string.Empty && _nameLabel.Text != _shoutName) + { + _nameLabel.Visible = true; + _nameLabel.BlinkRate = 250; + _nameLabel.Text = _shoutName; + } + else if (_shoutName == string.Empty) + { + _nameLabel.Visible = false; + } - private Vector2 GetNameLabelPosition() - { - NameLabelY = DrawArea.Y - 12 - (int)(_nameLabel?.ActualHeight ?? 0) + ((int)Character.RenderProperties.SitState) * 10; - return new Vector2(HorizontalCenter - (_nameLabel.ActualWidth / 2f), NameLabelY); - } + if (_spellCastTime.HasValue && (DateTime.Now - _spellCastTime.Value).TotalMilliseconds >= 600) + { + StopShout(); + } - private bool GetIsSteppingStone(CharacterRenderProperties renderProps) - { - if (_isUiControl) - return false; + _nameLabel.DrawPosition = GetNameLabelPosition(); + } - return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump - || (renderProps.IsActing(CharacterActionState.Walking) && _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump); - } + private Vector2 GetNameLabelPosition() + { + NameLabelY = DrawArea.Y - 12 - (int)(_nameLabel?.ActualHeight ?? 0) + ((int)Character.RenderProperties.SitState) * 10; + return new Vector2(HorizontalCenter - (_nameLabel.ActualWidth / 2f), NameLabelY); + } - private int GetSteppingStoneOffset(CharacterRenderProperties renderProps) - { - var isSteppingStone = GetIsSteppingStone(renderProps); + private bool GetIsSteppingStone(CharacterRenderProperties renderProps) + { + if (_isUiControl) + return false; - if (isSteppingStone && renderProps.IsActing(CharacterActionState.Walking)) + return _currentMapProvider.CurrentMap.Tiles[renderProps.MapY, renderProps.MapX] == TileSpec.Jump + || (renderProps.IsActing(CharacterActionState.Walking) && _currentMapProvider.CurrentMap.Tiles[renderProps.GetDestinationY(), renderProps.GetDestinationX()] == TileSpec.Jump); + } + + private int GetSteppingStoneOffset(CharacterRenderProperties renderProps) { - switch (renderProps.ActualWalkFrame) + var isSteppingStone = GetIsSteppingStone(renderProps); + + if (isSteppingStone && renderProps.IsActing(CharacterActionState.Walking)) { - case 1: return -8; - case 2: return -16; - case 3: return -16; - case 4: return -8; + switch (renderProps.ActualWalkFrame) + { + case 1: return -8; + case 2: return -16; + case 3: return -16; + case 4: return -8; + } } - } - return 0; - } + return 0; + } - private void CheckForDead() - { - if (_lastIsDead != _character.RenderProperties.IsDead) + private void CheckForDead() { - _lastIsDead = _character.RenderProperties.IsDead; - if (_lastIsDead) + if (_lastIsDead != _character.RenderProperties.IsDead) { - _sfxPlayer.PlaySfx(SoundEffectID.Dead); + _lastIsDead = _character.RenderProperties.IsDead; + if (_lastIsDead) + { + _sfxPlayer.PlaySfx(SoundEffectID.Dead); + } } } - } - private void ClipHair() - { - if (Character.RenderProperties.HatGraphic == 0 || - _hatMetadataProvider.GetValueOrDefault(Character.RenderProperties.HatGraphic).ClipMode != HatMaskType.Standard) - return; - - lock (_rt_locker_) + private void ClipHair() { - // oof. I really need to learn how to use shaders or stencil buffer. - // https://gamedev.stackexchange.com/questions/38118/best-way-to-mask-2d-sprites-in-xna/38150#38150 + if (Character.RenderProperties.HatGraphic == 0 || + _hatMetadataProvider.GetValueOrDefault(Character.RenderProperties.HatGraphic).ClipMode != HatMaskType.Standard) + return; - // note: this operation causes a high number of GC events as the character's frame changes (walking/attacking) - _charRenderTarget.GetData(_rtColorData); - for (int i = 0; i < _rtColorData.Length; i++) + lock (_rt_locker_) { - if (_rtColorData[i] == Color.Black) - _rtColorData[i].A = 0; + // oof. I really need to learn how to use shaders or stencil buffer. + // https://gamedev.stackexchange.com/questions/38118/best-way-to-mask-2d-sprites-in-xna/38150#38150 + + // note: this operation causes a high number of GC events as the character's frame changes (walking/attacking) + _charRenderTarget.GetData(_rtColorData); + for (int i = 0; i < _rtColorData.Length; i++) + { + if (_rtColorData[i] == Color.Black) + _rtColorData[i].A = 0; + } + _charRenderTarget.SetData(_rtColorData); } - _charRenderTarget.SetData(_rtColorData); } - } - #endregion + #endregion - public bool EffectIsPlaying() - { - return _effectRenderer.State == EffectState.Playing; - } + public bool EffectIsPlaying() + { + return _effectRenderer.State == EffectState.Playing; + } - public void PlayEffect(int graphic) - { - if (_effectRenderer.EffectID == graphic && _effectRenderer.State == EffectState.Playing) - _effectRenderer.Restart(); + public void PlayEffect(int graphic) + { + if (_effectRenderer.EffectID == graphic && _effectRenderer.State == EffectState.Playing) + _effectRenderer.Restart(); - _effectRenderer.PlayEffect(graphic, this); - } + _effectRenderer.PlayEffect(graphic, this); + } - // Called when the spell cast begins - public void ShoutSpellPrep(string spellName) - { - _shoutName = spellName; - } + // Called when the spell cast begins + public void ShoutSpellPrep(string spellName) + { + _shoutName = spellName; + } - // Called when the spell prep time ends and the player actually casts the spell - public void ShoutSpellCast() - { - _nameLabel.BlinkRate = null; - _nameLabel.ForeColor = Color.FromNonPremultiplied(0xf5, 0xc8, 0x9c, 0xff); // todo: make constant for this - _spellCastTime = DateTime.Now; - } + // Called when the spell prep time ends and the player actually casts the spell + public void ShoutSpellCast() + { + _nameLabel.BlinkRate = null; + _nameLabel.ForeColor = Color.FromNonPremultiplied(0xf5, 0xc8, 0x9c, 0xff); // todo: make constant for this + _spellCastTime = DateTime.Now; + } - // Called when the shout (spell prep time) should be cancelled without casting - public void StopShout() - { - if (_nameLabel == null) - return; - - _nameLabel.Visible = false; - _nameLabel.Text = _character.Name; - _nameLabel.ForeColor = Color.White; - _nameLabel.BlinkRate = null; - _shoutName = string.Empty; - _spellCastTime = null; - } + // Called when the shout (spell prep time) should be cancelled without casting + public void StopShout() + { + if (_nameLabel == null) + return; - public void ShowDamageCounter(int damage, int percentHealth, bool isHeal) - { - if (isHeal) - _healthBarRenderer.SetHealth(damage, percentHealth, () => _chatBubble.Value.Show()); - else - _healthBarRenderer.SetDamage(damage.SomeWhen(d => d > 0), percentHealth, () => _chatBubble.Value.Show()); + _nameLabel.Visible = false; + _nameLabel.Text = _character.Name; + _nameLabel.ForeColor = Color.White; + _nameLabel.BlinkRate = null; + _shoutName = string.Empty; + _spellCastTime = null; + } - _chatBubble.Value.Hide(); - } + public void ShowDamageCounter(int damage, int percentHealth, bool isHeal) + { + if (isHeal) + _healthBarRenderer.SetHealth(damage, percentHealth, () => _chatBubble.Value.Show()); + else + _healthBarRenderer.SetDamage(damage.SomeWhen(d => d > 0), percentHealth, () => _chatBubble.Value.Show()); - public void ShowChatBubble(string message, bool isGroupChat) - { - _chatBubble.Value.SetMessage(message, isGroupChat); - } + _chatBubble.Value.Hide(); + } - private void RecreateRenderTarget() - { - lock (_rt_locker_) + public void ShowChatBubble(string message, bool isGroupChat) { - _charRenderTarget?.Dispose(); - _charRenderTarget = _renderTargetFactory.CreateRenderTarget(); + _chatBubble.Value.SetMessage(message, isGroupChat); + } - _rtColorData = new Color[_charRenderTarget.Width * _charRenderTarget.Height]; + private void RecreateRenderTarget() + { + lock (_rt_locker_) + { + _charRenderTarget?.Dispose(); + _charRenderTarget = _renderTargetFactory.CreateRenderTarget(); + + _rtColorData = new Color[_charRenderTarget.Width * _charRenderTarget.Height]; + } } - } - private void RecreateRenderTargetEvent(object sender, EventArgs e) - { - RecreateRenderTarget(); + private void RecreateRenderTargetEvent(object sender, EventArgs e) + { + RecreateRenderTarget(); - if (_character == _characterProvider.MainCharacter) - SetToCenterScreenPosition(); - } + if (_character == _characterProvider.MainCharacter) + SetToCenterScreenPosition(); + } - protected override void Dispose(bool disposing) - { - if (disposing) + protected override void Dispose(bool disposing) { - _outline?.Dispose(); + if (disposing) + { + _outline?.Dispose(); - if (Game != null && Game.Components != null && Game.Components.Contains(_nameLabel)) - Game.Components.Remove(_nameLabel); - _nameLabel?.Dispose(); + if (Game != null && Game.Components != null && Game.Components.Contains(_nameLabel)) + Game.Components.Remove(_nameLabel); + _nameLabel?.Dispose(); - if (_chatBubble.IsValueCreated) - _chatBubble.Value?.Dispose(); + if (_chatBubble.IsValueCreated) + _chatBubble.Value?.Dispose(); - _sb?.Dispose(); + _sb?.Dispose(); - _clientWindowSizeRepository.GameWindowSizeChanged -= RecreateRenderTargetEvent; + _clientWindowSizeRepository.GameWindowSizeChanged -= RecreateRenderTargetEvent; - lock (_rt_locker_) - _charRenderTarget?.Dispose(); - } + lock (_rt_locker_) + _charRenderTarget?.Dispose(); + } - base.Dispose(disposing); + base.Dispose(disposing); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs b/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs index 2aea2c751..219739c6f 100644 --- a/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs +++ b/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs @@ -11,185 +11,186 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.Character; - -[AutoMappedType] -public class CharacterRendererUpdater : ICharacterRendererUpdater +namespace EndlessClient.Rendering.Character { - private readonly ICharacterProvider _characterProvider; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly ICharacterRendererRepository _characterRendererRepository; - private readonly ICharacterStateCache _characterStateCache; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - - public CharacterRendererUpdater(ICharacterProvider characterProvider, - ICurrentMapStateRepository currentMapStateRepository, - ICharacterRendererFactory characterRendererFactory, - ICharacterRendererRepository characterRendererRepository, - ICharacterStateCache characterStateCache, - IFixedTimeStepRepository fixedTimeStepRepository) + [AutoMappedType] + public class CharacterRendererUpdater : ICharacterRendererUpdater { - _characterProvider = characterProvider; - _currentMapStateRepository = currentMapStateRepository; - _characterRendererFactory = characterRendererFactory; - _characterRendererRepository = characterRendererRepository; - _characterStateCache = characterStateCache; - _fixedTimeStepRepository = fixedTimeStepRepository; - } + private readonly ICharacterProvider _characterProvider; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly ICharacterRendererRepository _characterRendererRepository; + private readonly ICharacterStateCache _characterStateCache; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + + public CharacterRendererUpdater(ICharacterProvider characterProvider, + ICurrentMapStateRepository currentMapStateRepository, + ICharacterRendererFactory characterRendererFactory, + ICharacterRendererRepository characterRendererRepository, + ICharacterStateCache characterStateCache, + IFixedTimeStepRepository fixedTimeStepRepository) + { + _characterProvider = characterProvider; + _currentMapStateRepository = currentMapStateRepository; + _characterRendererFactory = characterRendererFactory; + _characterRendererRepository = characterRendererRepository; + _characterStateCache = characterStateCache; + _fixedTimeStepRepository = fixedTimeStepRepository; + } - public void UpdateCharacters(GameTime gameTime) - { - CreateMainCharacterRendererAndCacheProperties(); - CreateOtherCharacterRenderersAndCacheProperties(); - UpdateAllCharacters(gameTime); + public void UpdateCharacters(GameTime gameTime) + { + CreateMainCharacterRendererAndCacheProperties(); + CreateOtherCharacterRenderersAndCacheProperties(); + UpdateAllCharacters(gameTime); - RemoveStaleCharacters(); - UpdateDeadCharacters(); - } + RemoveStaleCharacters(); + UpdateDeadCharacters(); + } - private void CreateMainCharacterRendererAndCacheProperties() - { - var actual = _characterProvider.MainCharacter; - var cached = _characterStateCache.MainCharacter; + private void CreateMainCharacterRendererAndCacheProperties() + { + var actual = _characterProvider.MainCharacter; + var cached = _characterStateCache.MainCharacter; - cached.Match( - some: c => - { - if (c != actual) + cached.Match( + some: c => + { + if (c != actual) + { + _characterRendererRepository.MainCharacterRenderer.MatchSome(r => r.Character = _characterProvider.MainCharacter); + _characterStateCache.UpdateMainCharacterState(actual); + } + }, + none: () => { - _characterRendererRepository.MainCharacterRenderer.MatchSome(r => r.Character = _characterProvider.MainCharacter); _characterStateCache.UpdateMainCharacterState(actual); - } - }, - none: () => - { - _characterStateCache.UpdateMainCharacterState(actual); - var renderer = InitializeRendererForCharacter(_characterProvider.MainCharacter); - renderer.SetToCenterScreenPosition(); - _characterRendererRepository.MainCharacterRenderer = Option.Some(renderer); - }); - } + var renderer = InitializeRendererForCharacter(_characterProvider.MainCharacter); + renderer.SetToCenterScreenPosition(); + _characterRendererRepository.MainCharacterRenderer = Option.Some(renderer); + }); + } - private void CreateOtherCharacterRenderersAndCacheProperties() - { - foreach (var character in _currentMapStateRepository.Characters) + private void CreateOtherCharacterRenderersAndCacheProperties() { - var id = character.ID; + foreach (var character in _currentMapStateRepository.Characters) + { + var id = character.ID; - _characterStateCache.HasCharacterWithID(id) - .SomeWhen(b => b) - .Map(_ => _characterStateCache.OtherCharacters[id]) - .Match( - some: cached => - { - if (cached != character) + _characterStateCache.HasCharacterWithID(id) + .SomeWhen(b => b) + .Map(_ => _characterStateCache.OtherCharacters[id]) + .Match( + some: cached => + { + if (cached != character) + { + if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) + _characterRendererRepository.CharacterRenderers[id].Character = character; + _characterStateCache.UpdateCharacterState(id, character); + } + }, + none: () => { - if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) - _characterRendererRepository.CharacterRenderers[id].Character = character; _characterStateCache.UpdateCharacterState(id, character); - } - }, - none: () => - { - _characterStateCache.UpdateCharacterState(id, character); - var renderer = InitializeRendererForCharacter(character); + var renderer = InitializeRendererForCharacter(character); - if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) - { - _characterRendererRepository.CharacterRenderers[id].Dispose(); - _characterRendererRepository.CharacterRenderers.Remove(id); - } - _characterRendererRepository.CharacterRenderers.Add(id, renderer); - }); - - if (_characterRendererRepository.NeedsWarpArriveAnimation.Contains(id) && - _characterRendererRepository.CharacterRenderers.ContainsKey(id)) - { - _characterRendererRepository.CharacterRenderers[id].PlayEffect((int)HardCodedEffect.WarpArrive); - _characterRendererRepository.NeedsWarpArriveAnimation.Remove(id); + if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) + { + _characterRendererRepository.CharacterRenderers[id].Dispose(); + _characterRendererRepository.CharacterRenderers.Remove(id); + } + _characterRendererRepository.CharacterRenderers.Add(id, renderer); + }); + + if (_characterRendererRepository.NeedsWarpArriveAnimation.Contains(id) && + _characterRendererRepository.CharacterRenderers.ContainsKey(id)) + { + _characterRendererRepository.CharacterRenderers[id].PlayEffect((int)HardCodedEffect.WarpArrive); + _characterRendererRepository.NeedsWarpArriveAnimation.Remove(id); + } } } - } - - private void UpdateAllCharacters(GameTime gameTime) - { - _characterRendererRepository.MainCharacterRenderer.MatchSome(x => x.Update(gameTime)); - foreach (var renderer in _characterRendererRepository.CharacterRenderers.Values) - renderer.Update(gameTime); - } - private void RemoveStaleCharacters() - { - var staleIDs = _characterStateCache.OtherCharacters.Keys - .Where(x => !_currentMapStateRepository.Characters.ContainsKey(x)); + private void UpdateAllCharacters(GameTime gameTime) + { + _characterRendererRepository.MainCharacterRenderer.MatchSome(x => x.Update(gameTime)); + foreach (var renderer in _characterRendererRepository.CharacterRenderers.Values) + renderer.Update(gameTime); + } - foreach (var id in staleIDs) + private void RemoveStaleCharacters() { - _characterStateCache.RemoveCharacterState(id); + var staleIDs = _characterStateCache.OtherCharacters.Keys + .Where(x => !_currentMapStateRepository.Characters.ContainsKey(x)); - if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) + foreach (var id in staleIDs) { - if (_characterRendererRepository.CharacterRenderers[id].EffectIsPlaying()) + _characterStateCache.RemoveCharacterState(id); + + if (_characterRendererRepository.CharacterRenderers.ContainsKey(id)) { - _characterRendererRepository.CharacterRenderers[id].Visible = false; - continue; - } + if (_characterRendererRepository.CharacterRenderers[id].EffectIsPlaying()) + { + _characterRendererRepository.CharacterRenderers[id].Visible = false; + continue; + } - _characterRendererRepository.CharacterRenderers[id].Dispose(); - _characterRendererRepository.CharacterRenderers.Remove(id); + _characterRendererRepository.CharacterRenderers[id].Dispose(); + _characterRendererRepository.CharacterRenderers.Remove(id); + } } } - } - - private void UpdateDeadCharacters() - { - var deadCharacters = new List(); - foreach (var character in _currentMapStateRepository.Characters.Where(x => x.RenderProperties.IsDead)) + private void UpdateDeadCharacters() { - _characterStateCache.DeathStartTimes.SingleOrNone(x => x.UniqueID == character.ID) - .Match( - none: () => _characterStateCache.AddDeathStartTime(character.ID), - some: actionTime => - { - if ((_fixedTimeStepRepository.TickCount - actionTime.ActionTick) >= 200) // 200 ticks * 10ms = 2 seconds - { - _characterStateCache.RemoveDeathStartTime(character.ID); - _characterStateCache.RemoveCharacterState(character.ID); + var deadCharacters = new List(); - if (_characterRendererRepository.CharacterRenderers.ContainsKey(character.ID)) + foreach (var character in _currentMapStateRepository.Characters.Where(x => x.RenderProperties.IsDead)) + { + _characterStateCache.DeathStartTimes.SingleOrNone(x => x.UniqueID == character.ID) + .Match( + none: () => _characterStateCache.AddDeathStartTime(character.ID), + some: actionTime => + { + if ((_fixedTimeStepRepository.TickCount - actionTime.ActionTick) >= 200) // 200 ticks * 10ms = 2 seconds { - _characterRendererRepository.CharacterRenderers[character.ID].Dispose(); - _characterRendererRepository.CharacterRenderers.Remove(character.ID); + _characterStateCache.RemoveDeathStartTime(character.ID); + _characterStateCache.RemoveCharacterState(character.ID); + + if (_characterRendererRepository.CharacterRenderers.ContainsKey(character.ID)) + { + _characterRendererRepository.CharacterRenderers[character.ID].Dispose(); + _characterRendererRepository.CharacterRenderers.Remove(character.ID); + } + + deadCharacters.Add(character); } + }); + } - deadCharacters.Add(character); - } - }); + foreach (var dead in deadCharacters) + _currentMapStateRepository.Characters.Remove(dead); } - foreach (var dead in deadCharacters) - _currentMapStateRepository.Characters.Remove(dead); - } + private ICharacterRenderer InitializeRendererForCharacter(EOLib.Domain.Character.Character character) + { + var renderer = _characterRendererFactory.CreateCharacterRenderer(character, isUiControl: false); + renderer.Initialize(); + return renderer; + } - private ICharacterRenderer InitializeRendererForCharacter(EOLib.Domain.Character.Character character) - { - var renderer = _characterRendererFactory.CreateCharacterRenderer(character, isUiControl: false); - renderer.Initialize(); - return renderer; + public void Dispose() + { + _characterStateCache.Reset(); + _characterRendererRepository.Dispose(); + } } - public void Dispose() + public interface ICharacterRendererUpdater : IDisposable { - _characterStateCache.Reset(); - _characterRendererRepository.Dispose(); + void UpdateCharacters(GameTime gameTime); } -} - -public interface ICharacterRendererUpdater : IDisposable -{ - void UpdateCharacters(GameTime gameTime); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterStateCache.cs b/EndlessClient/Rendering/Character/CharacterStateCache.cs index ebdc70dc1..bbd518cf3 100644 --- a/EndlessClient/Rendering/Character/CharacterStateCache.cs +++ b/EndlessClient/Rendering/Character/CharacterStateCache.cs @@ -7,73 +7,74 @@ using DomainCharacter = EOLib.Domain.Character.Character; -namespace EndlessClient.Rendering.Character; - -[AutoMappedType(IsSingleton = true)] -public class CharacterStateCache : ICharacterStateCache +namespace EndlessClient.Rendering.Character { - public Option MainCharacter { get; private set; } - - private readonly Dictionary _otherCharacters; - private readonly List _deathStartTimes; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - - public IReadOnlyDictionary OtherCharacters => _otherCharacters; - - public IReadOnlyList DeathStartTimes => _deathStartTimes; - - public CharacterStateCache(IFixedTimeStepRepository fixedTimeStepRepository) - { - MainCharacter = Option.None(); - _otherCharacters = new Dictionary(); - _deathStartTimes = new List(); - _fixedTimeStepRepository = fixedTimeStepRepository; - } - - public bool HasCharacterWithID(int id) - { - return _otherCharacters.ContainsKey(id); - } - - public void UpdateMainCharacterState(DomainCharacter updatedCharacter) - { - MainCharacter = Option.Some(updatedCharacter); - } - - public void UpdateCharacterState(int id, DomainCharacter updatedCharacter) - { - _otherCharacters[id] = updatedCharacter; - } - - public void RemoveCharacterState(int id) - { - _otherCharacters.Remove(id); - } - - public void AddDeathStartTime(int id) - { - if (_deathStartTimes.Any(x => x.UniqueID == id)) - throw new ArgumentException("That character already started dying...", nameof(id)); - - _deathStartTimes.Add(new RenderFrameActionTime(id, _fixedTimeStepRepository.TickCount)); - } - - public void RemoveDeathStartTime(int id) - { - if (_deathStartTimes.All(x => x.UniqueID != id)) - throw new ArgumentException("That character isn't dying...", nameof(id)); - - _deathStartTimes.RemoveAll(x => x.UniqueID == id); - } - - public void ClearAllOtherCharacterStates() - { - _otherCharacters.Clear(); - } - - public void Reset() + [AutoMappedType(IsSingleton = true)] + public class CharacterStateCache : ICharacterStateCache { - MainCharacter = Option.None(); - ClearAllOtherCharacterStates(); + public Option MainCharacter { get; private set; } + + private readonly Dictionary _otherCharacters; + private readonly List _deathStartTimes; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + + public IReadOnlyDictionary OtherCharacters => _otherCharacters; + + public IReadOnlyList DeathStartTimes => _deathStartTimes; + + public CharacterStateCache(IFixedTimeStepRepository fixedTimeStepRepository) + { + MainCharacter = Option.None(); + _otherCharacters = new Dictionary(); + _deathStartTimes = new List(); + _fixedTimeStepRepository = fixedTimeStepRepository; + } + + public bool HasCharacterWithID(int id) + { + return _otherCharacters.ContainsKey(id); + } + + public void UpdateMainCharacterState(DomainCharacter updatedCharacter) + { + MainCharacter = Option.Some(updatedCharacter); + } + + public void UpdateCharacterState(int id, DomainCharacter updatedCharacter) + { + _otherCharacters[id] = updatedCharacter; + } + + public void RemoveCharacterState(int id) + { + _otherCharacters.Remove(id); + } + + public void AddDeathStartTime(int id) + { + if (_deathStartTimes.Any(x => x.UniqueID == id)) + throw new ArgumentException("That character already started dying...", nameof(id)); + + _deathStartTimes.Add(new RenderFrameActionTime(id, _fixedTimeStepRepository.TickCount)); + } + + public void RemoveDeathStartTime(int id) + { + if (_deathStartTimes.All(x => x.UniqueID != id)) + throw new ArgumentException("That character isn't dying...", nameof(id)); + + _deathStartTimes.RemoveAll(x => x.UniqueID == id); + } + + public void ClearAllOtherCharacterStates() + { + _otherCharacters.Clear(); + } + + public void Reset() + { + MainCharacter = Option.None(); + ClearAllOtherCharacterStates(); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/CharacterTextures.cs b/EndlessClient/Rendering/Character/CharacterTextures.cs index 23997259b..9cfa89f4c 100644 --- a/EndlessClient/Rendering/Character/CharacterTextures.cs +++ b/EndlessClient/Rendering/Character/CharacterTextures.cs @@ -3,47 +3,48 @@ using EOLib.Domain.Character; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Character; - -[MappedType(BaseType = typeof(ICharacterTextures))] -public class CharacterTextures : ICharacterTextures +namespace EndlessClient.Rendering.Character { - private readonly ICharacterSpriteCalculator _characterSpriteCalculator; - public ISpriteSheet Boots { get; private set; } - public ISpriteSheet Armor { get; private set; } - public ISpriteSheet Hat { get; private set; } - public ISpriteSheet Shield { get; private set; } - public ISpriteSheet Weapon { get; private set; } - public ISpriteSheet WeaponExtra { get; private set; } - public ISpriteSheet WeaponSlash { get; private set; } - - public ISpriteSheet Hair { get; private set; } - public ISpriteSheet Skin { get; private set; } - - public ISpriteSheet Emote { get; private set; } - public ISpriteSheet Face { get; private set; } - - public CharacterTextures(ICharacterSpriteCalculator characterSpriteCalculator) - { - _characterSpriteCalculator = characterSpriteCalculator; - } - - public void Refresh(CharacterRenderProperties characterRenderProperties) + [MappedType(BaseType = typeof(ICharacterTextures))] + public class CharacterTextures : ICharacterTextures { - Boots = _characterSpriteCalculator.GetBootsTexture(characterRenderProperties); - Armor = _characterSpriteCalculator.GetArmorTexture(characterRenderProperties); - Hat = _characterSpriteCalculator.GetHatTexture(characterRenderProperties); - Shield = _characterSpriteCalculator.GetShieldTexture(characterRenderProperties); - - var weaponTextures = _characterSpriteCalculator.GetWeaponTextures(characterRenderProperties); - Weapon = weaponTextures[0]; - WeaponExtra = weaponTextures[1]; - - WeaponSlash = _characterSpriteCalculator.GetWeaponSlash(characterRenderProperties); - - Hair = _characterSpriteCalculator.GetHairTexture(characterRenderProperties); - Skin = _characterSpriteCalculator.GetSkinTexture(characterRenderProperties); - Emote = _characterSpriteCalculator.GetEmoteTexture(characterRenderProperties); - Face = _characterSpriteCalculator.GetFaceTexture(characterRenderProperties); + private readonly ICharacterSpriteCalculator _characterSpriteCalculator; + public ISpriteSheet Boots { get; private set; } + public ISpriteSheet Armor { get; private set; } + public ISpriteSheet Hat { get; private set; } + public ISpriteSheet Shield { get; private set; } + public ISpriteSheet Weapon { get; private set; } + public ISpriteSheet WeaponExtra { get; private set; } + public ISpriteSheet WeaponSlash { get; private set; } + + public ISpriteSheet Hair { get; private set; } + public ISpriteSheet Skin { get; private set; } + + public ISpriteSheet Emote { get; private set; } + public ISpriteSheet Face { get; private set; } + + public CharacterTextures(ICharacterSpriteCalculator characterSpriteCalculator) + { + _characterSpriteCalculator = characterSpriteCalculator; + } + + public void Refresh(CharacterRenderProperties characterRenderProperties) + { + Boots = _characterSpriteCalculator.GetBootsTexture(characterRenderProperties); + Armor = _characterSpriteCalculator.GetArmorTexture(characterRenderProperties); + Hat = _characterSpriteCalculator.GetHatTexture(characterRenderProperties); + Shield = _characterSpriteCalculator.GetShieldTexture(characterRenderProperties); + + var weaponTextures = _characterSpriteCalculator.GetWeaponTextures(characterRenderProperties); + Weapon = weaponTextures[0]; + WeaponExtra = weaponTextures[1]; + + WeaponSlash = _characterSpriteCalculator.GetWeaponSlash(characterRenderProperties); + + Hair = _characterSpriteCalculator.GetHairTexture(characterRenderProperties); + Skin = _characterSpriteCalculator.GetSkinTexture(characterRenderProperties); + Emote = _characterSpriteCalculator.GetEmoteTexture(characterRenderProperties); + Face = _characterSpriteCalculator.GetFaceTexture(characterRenderProperties); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ICharacterRenderer.cs b/EndlessClient/Rendering/Character/ICharacterRenderer.cs index b0b30b0d4..02a7d51a4 100644 --- a/EndlessClient/Rendering/Character/ICharacterRenderer.cs +++ b/EndlessClient/Rendering/Character/ICharacterRenderer.cs @@ -2,23 +2,24 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.Character; - -public interface ICharacterRenderer : IDrawable, IUpdateable, IGameComponent, IDisposable, IMapActor, ISpellCaster +namespace EndlessClient.Rendering.Character { - EOLib.Domain.Character.Character Character { get; set; } + public interface ICharacterRenderer : IDrawable, IUpdateable, IGameComponent, IDisposable, IMapActor, ISpellCaster + { + EOLib.Domain.Character.Character Character { get; set; } - new bool Visible { get; set; } + new bool Visible { get; set; } - bool Transparent { get; set; } + bool Transparent { get; set; } - void SetAbsoluteScreenPosition(int xPosition, int yPosition); + void SetAbsoluteScreenPosition(int xPosition, int yPosition); - void SetToCenterScreenPosition(); + void SetToCenterScreenPosition(); - void DrawToSpriteBatch(SpriteBatch spriteBatch); + void DrawToSpriteBatch(SpriteBatch spriteBatch); - void ShowName(); + void ShowName(); - void HideName(); + void HideName(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs b/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs index 78122a6fb..3249f039e 100644 --- a/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs +++ b/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs @@ -3,50 +3,51 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering.Character; - -public interface ICharacterRendererRepository : IDisposable +namespace EndlessClient.Rendering.Character { - Option MainCharacterRenderer { get; set; } + public interface ICharacterRendererRepository : IDisposable + { + Option MainCharacterRenderer { get; set; } - Dictionary CharacterRenderers { get; set; } + Dictionary CharacterRenderers { get; set; } - HashSet NeedsWarpArriveAnimation { get; } -} + HashSet NeedsWarpArriveAnimation { get; } + } -public interface ICharacterRendererProvider -{ - Option MainCharacterRenderer { get; } + public interface ICharacterRendererProvider + { + Option MainCharacterRenderer { get; } - IReadOnlyDictionary CharacterRenderers { get; } + IReadOnlyDictionary CharacterRenderers { get; } - HashSet NeedsWarpArriveAnimation { get; } -} + HashSet NeedsWarpArriveAnimation { get; } + } -[AutoMappedType(IsSingleton = true)] -public class CharacterRendererRepository : ICharacterRendererRepository, ICharacterRendererProvider -{ - public Option MainCharacterRenderer { get; set; } + [AutoMappedType(IsSingleton = true)] + public class CharacterRendererRepository : ICharacterRendererRepository, ICharacterRendererProvider + { + public Option MainCharacterRenderer { get; set; } - public Dictionary CharacterRenderers { get; set; } + public Dictionary CharacterRenderers { get; set; } - IReadOnlyDictionary ICharacterRendererProvider.CharacterRenderers => CharacterRenderers; + IReadOnlyDictionary ICharacterRendererProvider.CharacterRenderers => CharacterRenderers; - public HashSet NeedsWarpArriveAnimation { get; set; } + public HashSet NeedsWarpArriveAnimation { get; set; } - public CharacterRendererRepository() - { - CharacterRenderers = new Dictionary(64); - NeedsWarpArriveAnimation = new HashSet(); - } + public CharacterRendererRepository() + { + CharacterRenderers = new Dictionary(64); + NeedsWarpArriveAnimation = new HashSet(); + } - public void Dispose() - { - MainCharacterRenderer.MatchSome(x => x.Dispose()); - MainCharacterRenderer = Option.None(); + public void Dispose() + { + MainCharacterRenderer.MatchSome(x => x.Dispose()); + MainCharacterRenderer = Option.None(); - foreach (var renderer in CharacterRenderers.Values) - renderer.Dispose(); - CharacterRenderers.Clear(); + foreach (var renderer in CharacterRenderers.Values) + renderer.Dispose(); + CharacterRenderers.Clear(); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ICharacterStateCache.cs b/EndlessClient/Rendering/Character/ICharacterStateCache.cs index 5fa2892af..4dba53934 100644 --- a/EndlessClient/Rendering/Character/ICharacterStateCache.cs +++ b/EndlessClient/Rendering/Character/ICharacterStateCache.cs @@ -3,29 +3,30 @@ using DomainCharacter = EOLib.Domain.Character.Character; -namespace EndlessClient.Rendering.Character; - -public interface ICharacterStateCache +namespace EndlessClient.Rendering.Character { - Option MainCharacter { get; } + public interface ICharacterStateCache + { + Option MainCharacter { get; } - IReadOnlyDictionary OtherCharacters { get; } + IReadOnlyDictionary OtherCharacters { get; } - IReadOnlyList DeathStartTimes { get; } + IReadOnlyList DeathStartTimes { get; } - bool HasCharacterWithID(int id); + bool HasCharacterWithID(int id); - void UpdateMainCharacterState(DomainCharacter updatedCharacter); + void UpdateMainCharacterState(DomainCharacter updatedCharacter); - void UpdateCharacterState(int id, DomainCharacter updatedCharacter); + void UpdateCharacterState(int id, DomainCharacter updatedCharacter); - void RemoveCharacterState(int id); + void RemoveCharacterState(int id); - void AddDeathStartTime(int id); + void AddDeathStartTime(int id); - void RemoveDeathStartTime(int id); + void RemoveDeathStartTime(int id); - void ClearAllOtherCharacterStates(); + void ClearAllOtherCharacterStates(); - void Reset(); + void Reset(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ICharacterTextures.cs b/EndlessClient/Rendering/Character/ICharacterTextures.cs index 3c29d3d07..ae4e0d2f5 100644 --- a/EndlessClient/Rendering/Character/ICharacterTextures.cs +++ b/EndlessClient/Rendering/Character/ICharacterTextures.cs @@ -2,23 +2,24 @@ using EOLib.Domain.Character; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Character; - -public interface ICharacterTextures +namespace EndlessClient.Rendering.Character { - ISpriteSheet Boots { get; } - ISpriteSheet Armor { get; } - ISpriteSheet Hat { get; } - ISpriteSheet Shield { get; } - ISpriteSheet Weapon { get; } - ISpriteSheet WeaponExtra { get; } - ISpriteSheet WeaponSlash { get; } + public interface ICharacterTextures + { + ISpriteSheet Boots { get; } + ISpriteSheet Armor { get; } + ISpriteSheet Hat { get; } + ISpriteSheet Shield { get; } + ISpriteSheet Weapon { get; } + ISpriteSheet WeaponExtra { get; } + ISpriteSheet WeaponSlash { get; } - ISpriteSheet Hair { get; } - ISpriteSheet Skin { get; } + ISpriteSheet Hair { get; } + ISpriteSheet Skin { get; } - ISpriteSheet Emote { get; } - ISpriteSheet Face { get; } + ISpriteSheet Emote { get; } + ISpriteSheet Face { get; } - void Refresh(CharacterRenderProperties characterRenderProperties); + void Refresh(CharacterRenderProperties characterRenderProperties); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/ISpellCaster.cs b/EndlessClient/Rendering/Character/ISpellCaster.cs index 06a26c4ff..b357779ac 100644 --- a/EndlessClient/Rendering/Character/ISpellCaster.cs +++ b/EndlessClient/Rendering/Character/ISpellCaster.cs @@ -1,10 +1,11 @@ -namespace EndlessClient.Rendering.Character; - -public interface ISpellCaster +namespace EndlessClient.Rendering.Character { - void ShoutSpellPrep(string spellName); + public interface ISpellCaster + { + void ShoutSpellPrep(string spellName); - void ShoutSpellCast(); + void ShoutSpellCast(); - void StopShout(); + void StopShout(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs b/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs index 2ea30d84c..fda41ba48 100644 --- a/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs +++ b/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs @@ -11,238 +11,239 @@ using System; using System.Diagnostics; -namespace EndlessClient.Rendering.Character; - -public class PeriodicEmoteHandler : GameComponent, IPeriodicEmoteHandler +namespace EndlessClient.Rendering.Character { - // Time before periodic AFK emotes start firing (5 minutes) - private const int AFK_TIME_MS = 300000; - // Time between each emote once period emotes start firing (30 seconds) - private const int AFK_TIME_BETWEEN_EMOTES_MS = 30000; - - // Time before periodic alert messages start firing (30 minutes) - private const int AFK_TIME_ALERT_MS = 1800000; - // Time between each periodic alert message fires (60 seconds) - private const int AFK_TIME_BETWEEN_ALERTS_MS = 60000; - // Time between first alert and alternate alert (3.6 seconds) - private const int AFK_TIME_ALT_ALERT_MS = 3600; - - // Time from arena launch until the block messages start showing - private const int ARENA_BLOCK_INITIAL_TIME_MS = 6000; - // Time between subsequent messages - private const int ARENA_BLOCK_WARNING_INTERVAL_MS = 1200; - // Intervals before disconnect - private const int ARENA_BLOCK_MAX_WARNINGS = 6; - - private readonly ICharacterActions _characterActions; - private readonly IChatBubbleActions _chatBubbleActions; - private readonly IUserInputTimeProvider _userInputTimeProvider; - private readonly ICharacterRepository _characterRepository; - private readonly ICharacterAnimator _animator; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IMainButtonController _mainButtonController; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ISfxPlayer _sfxPlayer; - - private readonly Random _random; - - // drunk stuff - private Option _drunkStart; - private Option _drunkTimeSinceLastEmote; - private int _drunkIntervalSeconds; - private double _drunkTimeoutSeconds; - - // afk stuff - private Option _afkTimeSinceLastEmote; - private Option _afkTimeSinceLastAlert; - private bool _altAlert; - - // arena block stuff - private Option _arenaTimer; - private int _arenaWarningCounter; - - public PeriodicEmoteHandler(IEndlessGameProvider endlessGameProvider, - ICharacterActions characterActions, - IChatBubbleActions chatBubbleActions, - IUserInputTimeProvider userInputTimeProvider, - ICharacterRepository characterRepository, - ICharacterAnimator animator, - IStatusLabelSetter statusLabelSetter, - IMainButtonController mainButtonController, - ILocalizedStringFinder localizedStringFinder, - ISfxPlayer sfxPlayer) - : base((Game)endlessGameProvider.Game) + public class PeriodicEmoteHandler : GameComponent, IPeriodicEmoteHandler { - _characterActions = characterActions; - _chatBubbleActions = chatBubbleActions; - _userInputTimeProvider = userInputTimeProvider; - _characterRepository = characterRepository; - _animator = animator; - _statusLabelSetter = statusLabelSetter; - _mainButtonController = mainButtonController; - _localizedStringFinder = localizedStringFinder; - _sfxPlayer = sfxPlayer; - _random = new Random(); - } + // Time before periodic AFK emotes start firing (5 minutes) + private const int AFK_TIME_MS = 300000; + // Time between each emote once period emotes start firing (30 seconds) + private const int AFK_TIME_BETWEEN_EMOTES_MS = 30000; + + // Time before periodic alert messages start firing (30 minutes) + private const int AFK_TIME_ALERT_MS = 1800000; + // Time between each periodic alert message fires (60 seconds) + private const int AFK_TIME_BETWEEN_ALERTS_MS = 60000; + // Time between first alert and alternate alert (3.6 seconds) + private const int AFK_TIME_ALT_ALERT_MS = 3600; + + // Time from arena launch until the block messages start showing + private const int ARENA_BLOCK_INITIAL_TIME_MS = 6000; + // Time between subsequent messages + private const int ARENA_BLOCK_WARNING_INTERVAL_MS = 1200; + // Intervals before disconnect + private const int ARENA_BLOCK_MAX_WARNINGS = 6; + + private readonly ICharacterActions _characterActions; + private readonly IChatBubbleActions _chatBubbleActions; + private readonly IUserInputTimeProvider _userInputTimeProvider; + private readonly ICharacterRepository _characterRepository; + private readonly ICharacterAnimator _animator; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IMainButtonController _mainButtonController; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ISfxPlayer _sfxPlayer; + + private readonly Random _random; + + // drunk stuff + private Option _drunkStart; + private Option _drunkTimeSinceLastEmote; + private int _drunkIntervalSeconds; + private double _drunkTimeoutSeconds; + + // afk stuff + private Option _afkTimeSinceLastEmote; + private Option _afkTimeSinceLastAlert; + private bool _altAlert; + + // arena block stuff + private Option _arenaTimer; + private int _arenaWarningCounter; + + public PeriodicEmoteHandler(IEndlessGameProvider endlessGameProvider, + ICharacterActions characterActions, + IChatBubbleActions chatBubbleActions, + IUserInputTimeProvider userInputTimeProvider, + ICharacterRepository characterRepository, + ICharacterAnimator animator, + IStatusLabelSetter statusLabelSetter, + IMainButtonController mainButtonController, + ILocalizedStringFinder localizedStringFinder, + ISfxPlayer sfxPlayer) + : base((Game)endlessGameProvider.Game) + { + _characterActions = characterActions; + _chatBubbleActions = chatBubbleActions; + _userInputTimeProvider = userInputTimeProvider; + _characterRepository = characterRepository; + _animator = animator; + _statusLabelSetter = statusLabelSetter; + _mainButtonController = mainButtonController; + _localizedStringFinder = localizedStringFinder; + _sfxPlayer = sfxPlayer; + _random = new Random(); + } - public override void Update(GameTime gameTime) - { - _drunkStart.Match( - some: ds => - { - if ((DateTime.Now - ds).TotalSeconds > _drunkTimeoutSeconds) + public override void Update(GameTime gameTime) + { + _drunkStart.Match( + some: ds => { - _drunkStart = Option.None(); - _drunkTimeSinceLastEmote = Option.None(); - _drunkIntervalSeconds = 0; + if ((DateTime.Now - ds).TotalSeconds > _drunkTimeoutSeconds) + { + _drunkStart = Option.None(); + _drunkTimeSinceLastEmote = Option.None(); + _drunkIntervalSeconds = 0; - _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties( - _characterRepository.MainCharacter.RenderProperties.WithIsDrunk(false)); - } - else - { - _drunkTimeSinceLastEmote.MatchSome(dt => + _characterRepository.MainCharacter = _characterRepository.MainCharacter.WithRenderProperties( + _characterRepository.MainCharacter.RenderProperties.WithIsDrunk(false)); + } + else { - if (dt.Elapsed.TotalSeconds > _drunkIntervalSeconds) + _drunkTimeSinceLastEmote.MatchSome(dt => { - _drunkIntervalSeconds = _random.Next(4, 7); - _drunkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); + if (dt.Elapsed.TotalSeconds > _drunkIntervalSeconds) + { + _drunkIntervalSeconds = _random.Next(4, 7); + _drunkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); - if (_animator.Emote(_characterRepository.MainCharacter.ID, Emote.Drunk)) - _characterActions.Emote(Emote.Drunk); - } - }); - } - }, - none: () => - { - if (_characterRepository.MainCharacter.RenderProperties.IsDrunk) + if (_animator.Emote(_characterRepository.MainCharacter.ID, Emote.Drunk)) + _characterActions.Emote(Emote.Drunk); + } + }); + } + }, + none: () => { - _drunkStart = Option.Some(DateTime.Now); - _drunkIntervalSeconds = _random.Next(4, 7); - _drunkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); + if (_characterRepository.MainCharacter.RenderProperties.IsDrunk) + { + _drunkStart = Option.Some(DateTime.Now); + _drunkIntervalSeconds = _random.Next(4, 7); + _drunkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); - if (_animator.Emote(_characterRepository.MainCharacter.ID, Emote.Drunk)) - _characterActions.Emote(Emote.Drunk); - } - }); + if (_animator.Emote(_characterRepository.MainCharacter.ID, Emote.Drunk)) + _characterActions.Emote(Emote.Drunk); + } + }); - var now = DateTime.Now; + var now = DateTime.Now; - if ((now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_MS) - { - if ((now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_MS + AFK_TIME_ALERT_MS) - { - _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); - } - else + if ((now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_MS) { - _afkTimeSinceLastEmote.Match( - some: at => - { - if (at.ElapsedMilliseconds >= AFK_TIME_BETWEEN_EMOTES_MS) - { - _animator.Emote(_characterRepository.MainCharacter.ID, Emote.Moon); - _characterActions.Emote(Emote.Moon); - _afkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); - } - }, - none: () => - { - _animator.Emote(_characterRepository.MainCharacter.ID, Emote.Moon); - _characterActions.Emote(Emote.Moon); - _afkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); - }); - - if ((DateTime.Now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_ALERT_MS) + if ((now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_MS + AFK_TIME_ALERT_MS) + { + _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); + } + else { - _afkTimeSinceLastAlert.Match( + _afkTimeSinceLastEmote.Match( some: at => { - if (at.ElapsedMilliseconds >= AFK_TIME_BETWEEN_ALERTS_MS) + if (at.ElapsedMilliseconds >= AFK_TIME_BETWEEN_EMOTES_MS) { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_TOO_LONG); - _afkTimeSinceLastAlert = Option.Some(Stopwatch.StartNew()); - _altAlert = false; + _animator.Emote(_characterRepository.MainCharacter.ID, Emote.Moon); + _characterActions.Emote(Emote.Moon); + _afkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); } }, none: () => { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_TOO_LONG); - _afkTimeSinceLastAlert = Option.Some(Stopwatch.StartNew()); - _altAlert = false; + _animator.Emote(_characterRepository.MainCharacter.ID, Emote.Moon); + _characterActions.Emote(Emote.Moon); + _afkTimeSinceLastEmote = Option.Some(Stopwatch.StartNew()); }); - _afkTimeSinceLastAlert.Match( - some: at => - { - if (at.ElapsedMilliseconds >= AFK_TIME_ALT_ALERT_MS && !_altAlert) + if ((DateTime.Now - _userInputTimeProvider.LastInputTime).TotalMilliseconds >= AFK_TIME_ALERT_MS) + { + _afkTimeSinceLastAlert.Match( + some: at => { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_PLEASE_START_MOVING); - _altAlert = true; - } - }, - none: () => _altAlert = false); + if (at.ElapsedMilliseconds >= AFK_TIME_BETWEEN_ALERTS_MS) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_TOO_LONG); + _afkTimeSinceLastAlert = Option.Some(Stopwatch.StartNew()); + _altAlert = false; + } + }, + none: () => + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_TOO_LONG); + _afkTimeSinceLastAlert = Option.Some(Stopwatch.StartNew()); + _altAlert = false; + }); + + _afkTimeSinceLastAlert.Match( + some: at => + { + if (at.ElapsedMilliseconds >= AFK_TIME_ALT_ALERT_MS && !_altAlert) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.IDLE_PLEASE_START_MOVING); + _altAlert = true; + } + }, + none: () => _altAlert = false); + } } } - } - else - { - _afkTimeSinceLastEmote = Option.None(); - _afkTimeSinceLastAlert = Option.None(); - } - - _arenaTimer.MatchSome( - some: a => + else { - if ((_arenaWarningCounter == 0 && a.ElapsedMilliseconds >= ARENA_BLOCK_INITIAL_TIME_MS) || - (_arenaWarningCounter > 0 && a.ElapsedMilliseconds >= ARENA_BLOCK_WARNING_INTERVAL_MS)) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ARENA_DO_NOT_BLOCK_LINE); - _sfxPlayer.PlaySfx(SoundEffectID.ArenaTickSound); + _afkTimeSinceLastEmote = Option.None(); + _afkTimeSinceLastAlert = Option.None(); + } - if (_arenaWarningCounter == 1) - { - var resource = _localizedStringFinder.GetString(EOResourceID.ARENA_PLEASE_MOVE_FROM_PLACE); - _chatBubbleActions.ShowChatBubbleForMainCharacter(resource); - } - else if (_arenaWarningCounter == ARENA_BLOCK_MAX_WARNINGS) + _arenaTimer.MatchSome( + some: a => + { + if ((_arenaWarningCounter == 0 && a.ElapsedMilliseconds >= ARENA_BLOCK_INITIAL_TIME_MS) || + (_arenaWarningCounter > 0 && a.ElapsedMilliseconds >= ARENA_BLOCK_WARNING_INTERVAL_MS)) { - _arenaTimer = Option.None(); - _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.ARENA_DO_NOT_BLOCK_LINE); + _sfxPlayer.PlaySfx(SoundEffectID.ArenaTickSound); + + if (_arenaWarningCounter == 1) + { + var resource = _localizedStringFinder.GetString(EOResourceID.ARENA_PLEASE_MOVE_FROM_PLACE); + _chatBubbleActions.ShowChatBubbleForMainCharacter(resource); + } + else if (_arenaWarningCounter == ARENA_BLOCK_MAX_WARNINGS) + { + _arenaTimer = Option.None(); + _mainButtonController.GoToInitialStateAndDisconnect(showLostConnection: true); + } + + StartArenaBlockTimer(); + _arenaWarningCounter++; } - StartArenaBlockTimer(); - _arenaWarningCounter++; - } + }); - }); + base.Update(gameTime); + } - base.Update(gameTime); - } + public void SetDrunkTimeout(int beerPotency) + { + _drunkTimeoutSeconds = (100 + (beerPotency * 10)) / 8.0; + } - public void SetDrunkTimeout(int beerPotency) - { - _drunkTimeoutSeconds = (100 + (beerPotency * 10)) / 8.0; - } + public void StartArenaBlockTimer() + { + _arenaTimer = Option.Some(Stopwatch.StartNew()); + } - public void StartArenaBlockTimer() - { - _arenaTimer = Option.Some(Stopwatch.StartNew()); + public void CancelArenaBlockTimer() + { + _arenaTimer = Option.None(); + _arenaWarningCounter = 0; + } } - public void CancelArenaBlockTimer() + public interface IPeriodicEmoteHandler : IGameComponent, IUpdateable { - _arenaTimer = Option.None(); - _arenaWarningCounter = 0; - } -} + void SetDrunkTimeout(int beerPotency); -public interface IPeriodicEmoteHandler : IGameComponent, IUpdateable -{ - void SetDrunkTimeout(int beerPotency); + void StartArenaBlockTimer(); - void StartArenaBlockTimer(); - - void CancelArenaBlockTimer(); + void CancelArenaBlockTimer(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs index 6facc7822..768f8320c 100644 --- a/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs @@ -7,70 +7,71 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.CharacterProperties; - -public class ArmorRenderer : BaseCharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - private readonly ISpriteSheet _armorSheet; - - public override bool CanRender => _armorSheet.HasTexture && _renderProperties.ArmorGraphic != 0; - - public ArmorRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet armorSheet) - : base(renderProperties) + public class ArmorRenderer : BaseCharacterPropertyRenderer { - _armorSheet = armorSheet; - } + private readonly ISpriteSheet _armorSheet; - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var offsets = GetOffsets(parentCharacterDrawArea.Size.ToVector2(), weaponMetadata.Ranged); - var drawLoc = new Vector2(parentCharacterDrawArea.X - 2 + offsets.X, parentCharacterDrawArea.Y + offsets.Y); - Render(spriteBatch, _armorSheet, drawLoc); - } + public override bool CanRender => _armorSheet.HasTexture && _renderProperties.ArmorGraphic != 0; - private Vector2 GetOffsets(Vector2 parentCharacterSize, bool ranged) - { - var resX = -(float)Math.Floor(Math.Abs(_armorSheet.SourceRectangle.Width - parentCharacterSize.X) / 2); - var resY = -(float)Math.Floor(Math.Abs(_armorSheet.SourceRectangle.Height - parentCharacterSize.Y) / 2); + public ArmorRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet armorSheet) + : base(renderProperties) + { + _armorSheet = armorSheet; + } - if ((_renderProperties.RenderAttackFrame == 2 && !ranged) || - (_renderProperties.RenderAttackFrame == 1 && ranged)) + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) { - resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 4 : 0; + var offsets = GetOffsets(parentCharacterDrawArea.Size.ToVector2(), weaponMetadata.Ranged); + var drawLoc = new Vector2(parentCharacterDrawArea.X - 2 + offsets.X, parentCharacterDrawArea.Y + offsets.Y); + Render(spriteBatch, _armorSheet, drawLoc); + } - if (ranged) + private Vector2 GetOffsets(Vector2 parentCharacterSize, bool ranged) + { + var resX = -(float)Math.Floor(Math.Abs(_armorSheet.SourceRectangle.Width - parentCharacterSize.X) / 2); + var resY = -(float)Math.Floor(Math.Abs(_armorSheet.SourceRectangle.Height - parentCharacterSize.Y) / 2); + + if ((_renderProperties.RenderAttackFrame == 2 && !ranged) || + (_renderProperties.RenderAttackFrame == 1 && ranged)) { - var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; - resX += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) - ? 2 * factor - : 4 * factor; + resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 4 : 0; + + if (ranged) + { + var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; + resX += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) + ? 2 * factor + : 4 * factor; - resY += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? 1 : 0; + resY += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? 1 : 0; + } } - } - else if (_renderProperties.SitState != SitState.Standing) - { - if (_renderProperties.SitState == SitState.Chair) + else if (_renderProperties.SitState != SitState.Standing) { - resX -= 1; - resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 2 : 0; + if (_renderProperties.SitState == SitState.Chair) + { + resX -= 1; + resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 2 : 0; + } + else + { + resX += _renderProperties.IsFacing(EODirection.Left) ? _renderProperties.Gender : _renderProperties.IsFacing(EODirection.Up) ? -_renderProperties.Gender : 0; + resX -= _renderProperties.IsFacing(EODirection.Down, EODirection.Up) ? (2 - _renderProperties.Gender) : _renderProperties.Gender; + resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 12 : 9; + } } else { - resX += _renderProperties.IsFacing(EODirection.Left) ? _renderProperties.Gender : _renderProperties.IsFacing(EODirection.Up) ? -_renderProperties.Gender : 0; - resX -= _renderProperties.IsFacing(EODirection.Down, EODirection.Up) ? (2 - _renderProperties.Gender) : _renderProperties.Gender; - resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 12 : 9; + resX += 2; } - } - else - { - resX += 2; - } - if (_renderProperties.SitState == SitState.Standing) - resY -= (_renderProperties.IsActing(CharacterActionState.Walking) ? 4 : 3) + _renderProperties.Gender; + if (_renderProperties.SitState == SitState.Standing) + resY -= (_renderProperties.IsActing(CharacterActionState.Walking) ? 4 : 3) + _renderProperties.Gender; - return new Vector2(resX, resY); + return new Vector2(resX, resY); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs b/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs index 5970278c9..2eae9521b 100644 --- a/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/BaseCharacterPropertyRenderer.cs @@ -6,30 +6,31 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties; - -public abstract class BaseCharacterPropertyRenderer : ICharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - protected readonly CharacterRenderProperties _renderProperties; + public abstract class BaseCharacterPropertyRenderer : ICharacterPropertyRenderer + { + protected readonly CharacterRenderProperties _renderProperties; - public abstract bool CanRender { get; } + public abstract bool CanRender { get; } - public float LayerDepth { get; set; } + public float LayerDepth { get; set; } - protected virtual bool ShouldFlip => _renderProperties.IsFacing(EODirection.Up, EODirection.Right); + protected virtual bool ShouldFlip => _renderProperties.IsFacing(EODirection.Up, EODirection.Right); - protected BaseCharacterPropertyRenderer(CharacterRenderProperties renderProperties) - { - _renderProperties = renderProperties; - LayerDepth = 1.0f; - } + protected BaseCharacterPropertyRenderer(CharacterRenderProperties renderProperties) + { + _renderProperties = renderProperties; + LayerDepth = 1.0f; + } - public abstract void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata); + public abstract void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata); - protected virtual void Render(SpriteBatch spriteBatch, ISpriteSheet sheet, Vector2 drawLoc, int alpha = 255) - { - spriteBatch.Draw(sheet.SheetTexture, drawLoc, sheet.SourceRectangle, Color.FromNonPremultiplied(255, 255, 255, alpha), 0.0f, Vector2.Zero, 1.0f, - ShouldFlip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, - LayerDepth); + protected virtual void Render(SpriteBatch spriteBatch, ISpriteSheet sheet, Vector2 drawLoc, int alpha = 255) + { + spriteBatch.Draw(sheet.SheetTexture, drawLoc, sheet.SourceRectangle, Color.FromNonPremultiplied(255, 255, 255, alpha), 0.0f, Vector2.Zero, 1.0f, + ShouldFlip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, + LayerDepth); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs b/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs index cdbe4f5ac..f2ca4ee5e 100644 --- a/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs @@ -7,83 +7,84 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.CharacterProperties; - -public class BootsRenderer : BaseCharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - private readonly ISpriteSheet _bootsSheet; - - public override bool CanRender => _bootsSheet.HasTexture && _renderProperties.BootsGraphic != 0; - - public BootsRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet bootsSheet) - : base(renderProperties) - { - _bootsSheet = bootsSheet; - } - - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + public class BootsRenderer : BaseCharacterPropertyRenderer { - var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); - var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, - // Center the Y coordinate over the bottom half of the character sprite - parentCharacterDrawArea.Y + offsets.Y); - Render(spriteBatch, _bootsSheet, drawLoc); - } + private readonly ISpriteSheet _bootsSheet; - private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) - { - var resX = -(float)Math.Floor(Math.Abs((float)_bootsSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); - var resY = (int)Math.Floor(parentCharacterDrawArea.Height / 3f) * 2 - 1 - _renderProperties.Gender; + public override bool CanRender => _bootsSheet.HasTexture && _renderProperties.BootsGraphic != 0; - if (_renderProperties.IsActing(CharacterActionState.Walking)) + public BootsRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet bootsSheet) + : base(renderProperties) { - resY -= 1; - - if (_renderProperties.RenderWalkFrame == 2) - resY -= 1; + _bootsSheet = bootsSheet; } - else if (_renderProperties.RenderAttackFrame == 2) - { - var isDownOrLeft = _renderProperties.IsFacing(EODirection.Down, EODirection.Left); - var factor = isDownOrLeft ? -1 : 1; - var extra = !isDownOrLeft ? 2 * _renderProperties.Gender : 0; - resX += 2 * factor; - resY += 1 * factor - extra; - } - else if (_renderProperties.RenderAttackFrame == 1 && ranged) + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) { - var isDownOrLeft = _renderProperties.IsFacing(EODirection.Down, EODirection.Left); - var isDownOrRight = _renderProperties.IsFacing(EODirection.Down, EODirection.Right); - var factor = isDownOrLeft ? -1 : 1; - var offset = isDownOrRight ? 5 : 3; - var extra = !isDownOrRight ? 4 * _renderProperties.Gender : 1 * _renderProperties.Gender; - - resX += factor * (offset + extra); + var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); + var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, + // Center the Y coordinate over the bottom half of the character sprite + parentCharacterDrawArea.Y + offsets.Y); + Render(spriteBatch, _bootsSheet, drawLoc); } - else if (_renderProperties.SitState != SitState.Standing) + + private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) { - resX -= 3; - resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? -3 : 2; + var resX = -(float)Math.Floor(Math.Abs((float)_bootsSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); + var resY = (int)Math.Floor(parentCharacterDrawArea.Height / 3f) * 2 - 1 - _renderProperties.Gender; - if (_renderProperties.SitState == SitState.Floor) + if (_renderProperties.IsActing(CharacterActionState.Walking)) { - var factor = _renderProperties.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; + resY -= 1; - if (_renderProperties.Gender == 0) - { - resX += (_renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 1 : -1) * factor; - resY += _renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 2 : 3; - } - else if (_renderProperties.Gender == 1) + if (_renderProperties.RenderWalkFrame == 2) + resY -= 1; + } + else if (_renderProperties.RenderAttackFrame == 2) + { + var isDownOrLeft = _renderProperties.IsFacing(EODirection.Down, EODirection.Left); + var factor = isDownOrLeft ? -1 : 1; + var extra = !isDownOrLeft ? 2 * _renderProperties.Gender : 0; + + resX += 2 * factor; + resY += 1 * factor - extra; + } + else if (_renderProperties.RenderAttackFrame == 1 && ranged) + { + var isDownOrLeft = _renderProperties.IsFacing(EODirection.Down, EODirection.Left); + var isDownOrRight = _renderProperties.IsFacing(EODirection.Down, EODirection.Right); + var factor = isDownOrLeft ? -1 : 1; + var offset = isDownOrRight ? 5 : 3; + var extra = !isDownOrRight ? 4 * _renderProperties.Gender : 1 * _renderProperties.Gender; + + resX += factor * (offset + extra); + } + else if (_renderProperties.SitState != SitState.Standing) + { + resX -= 3; + resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? -3 : 2; + + if (_renderProperties.SitState == SitState.Floor) { - resX += (_renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 0 : -1) * factor; - resY += 4; + var factor = _renderProperties.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; + + if (_renderProperties.Gender == 0) + { + resX += (_renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 1 : -1) * factor; + resY += _renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 2 : 3; + } + else if (_renderProperties.Gender == 1) + { + resX += (_renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? 0 : -1) * factor; + resY += 4; + } } } - } - return new Vector2(resX, resY); + return new Vector2(resX, resY); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs b/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs index 07e590ae6..016df3bc5 100644 --- a/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs +++ b/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs @@ -11,91 +11,92 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.CharacterProperties; - -[AutoMappedType] -public class CharacterPropertyRendererBuilder : ICharacterPropertyRendererBuilder +namespace EndlessClient.Rendering.CharacterProperties { - private readonly IEIFFileProvider _eifFileProvider; - private readonly IMetadataProvider _hatMetadataProvider; - private readonly IMetadataProvider _shieldMetadataProvider; - - public CharacterPropertyRendererBuilder(IEIFFileProvider eifFileProvider, - IMetadataProvider hatMetadataProvider, - IMetadataProvider shieldMetadataProvider) + [AutoMappedType] + public class CharacterPropertyRendererBuilder : ICharacterPropertyRendererBuilder { - _eifFileProvider = eifFileProvider; - _hatMetadataProvider = hatMetadataProvider; - _shieldMetadataProvider = shieldMetadataProvider; - } + private readonly IEIFFileProvider _eifFileProvider; + private readonly IMetadataProvider _hatMetadataProvider; + private readonly IMetadataProvider _shieldMetadataProvider; - public IEnumerable BuildList(ICharacterTextures textures, - CharacterRenderProperties renderProperties) - { - const float BaseLayer = 0.00001f; - - // Melee weapons render extra behind the character - yield return new WeaponRenderer(renderProperties, textures.WeaponExtra) { LayerDepth = BaseLayer }; - yield return new ShieldRenderer(renderProperties, textures.Shield, IsShieldOnBack(renderProperties.ShieldGraphic)) + public CharacterPropertyRendererBuilder(IEIFFileProvider eifFileProvider, + IMetadataProvider hatMetadataProvider, + IMetadataProvider shieldMetadataProvider) { - LayerDepth = BaseLayer * (IsShieldBehindCharacter(renderProperties) ? 2 : 13) - }; - yield return new WeaponRenderer(renderProperties, textures.Weapon) + _eifFileProvider = eifFileProvider; + _hatMetadataProvider = hatMetadataProvider; + _shieldMetadataProvider = shieldMetadataProvider; + } + + public IEnumerable BuildList(ICharacterTextures textures, + CharacterRenderProperties renderProperties) { - LayerDepth = BaseLayer * (IsWeaponBehindCharacter(renderProperties) ? 3 : 12) - }; + const float BaseLayer = 0.00001f; - yield return new SkinRenderer(renderProperties, textures.Skin) { LayerDepth = BaseLayer * 4 }; - yield return new FaceRenderer(renderProperties, textures.Face, textures.Skin) { LayerDepth = BaseLayer * 5 }; - yield return new EmoteRenderer(renderProperties, textures.Emote, textures.Skin) { LayerDepth = BaseLayer * 6 }; + // Melee weapons render extra behind the character + yield return new WeaponRenderer(renderProperties, textures.WeaponExtra) { LayerDepth = BaseLayer }; + yield return new ShieldRenderer(renderProperties, textures.Shield, IsShieldOnBack(renderProperties.ShieldGraphic)) + { + LayerDepth = BaseLayer * (IsShieldBehindCharacter(renderProperties) ? 2 : 13) + }; + yield return new WeaponRenderer(renderProperties, textures.Weapon) + { + LayerDepth = BaseLayer * (IsWeaponBehindCharacter(renderProperties) ? 3 : 12) + }; - yield return new BootsRenderer(renderProperties, textures.Boots) { LayerDepth = BaseLayer * 7 }; - yield return new ArmorRenderer(renderProperties, textures.Armor) { LayerDepth = BaseLayer * 8 }; + yield return new SkinRenderer(renderProperties, textures.Skin) { LayerDepth = BaseLayer * 4 }; + yield return new FaceRenderer(renderProperties, textures.Face, textures.Skin) { LayerDepth = BaseLayer * 5 }; + yield return new EmoteRenderer(renderProperties, textures.Emote, textures.Skin) { LayerDepth = BaseLayer * 6 }; - var hatMaskType = GetHatMaskType(renderProperties.HatGraphic); - yield return new HatRenderer(renderProperties, textures.Hat, textures.Hair) - { - LayerDepth = BaseLayer * (hatMaskType == HatMaskType.FaceMask ? 10 : 11) - }; + yield return new BootsRenderer(renderProperties, textures.Boots) { LayerDepth = BaseLayer * 7 }; + yield return new ArmorRenderer(renderProperties, textures.Armor) { LayerDepth = BaseLayer * 8 }; - if (hatMaskType != HatMaskType.HideHair) - yield return new HairRenderer(renderProperties, textures.Hair) + var hatMaskType = GetHatMaskType(renderProperties.HatGraphic); + yield return new HatRenderer(renderProperties, textures.Hat, textures.Hair) { - LayerDepth = BaseLayer * (hatMaskType == HatMaskType.FaceMask ? 11 : 10) + LayerDepth = BaseLayer * (hatMaskType == HatMaskType.FaceMask ? 10 : 11) }; - yield return new WeaponSlashRenderer(renderProperties, textures.WeaponSlash) { LayerDepth = BaseLayer * 14 }; - } + if (hatMaskType != HatMaskType.HideHair) + yield return new HairRenderer(renderProperties, textures.Hair) + { + LayerDepth = BaseLayer * (hatMaskType == HatMaskType.FaceMask ? 11 : 10) + }; - private bool IsShieldBehindCharacter(CharacterRenderProperties renderProperties) - { - return renderProperties.IsFacing(EODirection.Right, EODirection.Down) && IsShieldOnBack(renderProperties.ShieldGraphic); - } + yield return new WeaponSlashRenderer(renderProperties, textures.WeaponSlash) { LayerDepth = BaseLayer * 14 }; + } - private bool IsWeaponBehindCharacter(CharacterRenderProperties renderProperties) - { - var weaponInfo = EIFFile.FirstOrDefault( - x => x.Type == ItemType.Weapon && - x.DollGraphic == renderProperties.WeaponGraphic); + private bool IsShieldBehindCharacter(CharacterRenderProperties renderProperties) + { + return renderProperties.IsFacing(EODirection.Right, EODirection.Down) && IsShieldOnBack(renderProperties.ShieldGraphic); + } - var pass1 = renderProperties.RenderAttackFrame < 2; - var pass2 = renderProperties.IsFacing(EODirection.Up, EODirection.Left); - var pass3 = weaponInfo == null || weaponInfo.SubType == ItemSubType.Ranged; + private bool IsWeaponBehindCharacter(CharacterRenderProperties renderProperties) + { + var weaponInfo = EIFFile.FirstOrDefault( + x => x.Type == ItemType.Weapon && + x.DollGraphic == renderProperties.WeaponGraphic); - return pass1 || pass2 || pass3; - } + var pass1 = renderProperties.RenderAttackFrame < 2; + var pass2 = renderProperties.IsFacing(EODirection.Up, EODirection.Left); + var pass3 = weaponInfo == null || weaponInfo.SubType == ItemSubType.Ranged; - private HatMaskType GetHatMaskType(int hatGraphic) - { - if (hatGraphic == 0) return HatMaskType.Standard; - return _hatMetadataProvider.GetValueOrDefault(hatGraphic).ClipMode; - } + return pass1 || pass2 || pass3; + } - private bool IsShieldOnBack(int shieldGraphic) - { - if (shieldGraphic == 0) return false; - return _shieldMetadataProvider.GetValueOrDefault(shieldGraphic).IsShieldOnBack; - } + private HatMaskType GetHatMaskType(int hatGraphic) + { + if (hatGraphic == 0) return HatMaskType.Standard; + return _hatMetadataProvider.GetValueOrDefault(hatGraphic).ClipMode; + } - private IPubFile EIFFile => _eifFileProvider.EIFFile ?? new EIFFile(); + private bool IsShieldOnBack(int shieldGraphic) + { + if (shieldGraphic == 0) return false; + return _shieldMetadataProvider.GetValueOrDefault(shieldGraphic).IsShieldOnBack; + } + + private IPubFile EIFFile => _eifFileProvider.EIFFile ?? new EIFFile(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs b/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs index 3431c6d7b..10978e828 100644 --- a/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/EmoteRenderer.cs @@ -4,35 +4,36 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties; - -public class EmoteRenderer : BaseCharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - private readonly ISpriteSheet _emoteSheet; - private readonly ISpriteSheet _skinSheet; - private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; + public class EmoteRenderer : BaseCharacterPropertyRenderer + { + private readonly ISpriteSheet _emoteSheet; + private readonly ISpriteSheet _skinSheet; + private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; - public override bool CanRender => _renderProperties.EmoteFrame > 0; + public override bool CanRender => _renderProperties.EmoteFrame > 0; - protected override bool ShouldFlip => false; + protected override bool ShouldFlip => false; - public EmoteRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet emoteSheet, - ISpriteSheet skinSheet) - : base(renderProperties) - { - _emoteSheet = emoteSheet; - _skinSheet = skinSheet; - _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); - } + public EmoteRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet emoteSheet, + ISpriteSheet skinSheet) + : base(renderProperties) + { + _emoteSheet = emoteSheet; + _skinSheet = skinSheet; + _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - if (_emoteSheet is EmptySpriteSheet) - return; + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + if (_emoteSheet is EmptySpriteSheet) + return; - var skinLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); - var emotePos = new Vector2(skinLoc.X - 15, parentCharacterDrawArea.Y - _emoteSheet.SheetTexture.Height); - Render(spriteBatch, _emoteSheet, emotePos, 128); + var skinLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); + var emotePos = new Vector2(skinLoc.X - 15, parentCharacterDrawArea.Y - _emoteSheet.SheetTexture.Height); + Render(spriteBatch, _emoteSheet, emotePos, 128); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs b/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs index 737f36d63..80f57e6b0 100644 --- a/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/FaceRenderer.cs @@ -6,43 +6,44 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties; - -public class FaceRenderer : BaseCharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - private readonly ISpriteSheet _faceSheet; - private readonly ISpriteSheet _skinSheet; - private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; - - public override bool CanRender => _renderProperties.IsActing(CharacterActionState.Emote) && - _renderProperties.EmoteFrame > 0 && - _renderProperties.Emote != Emote.Trade && - _renderProperties.Emote != Emote.LevelUp && - _renderProperties.Emote != Emote.MusicNotes; - - public FaceRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet faceSheet, - ISpriteSheet skinSheet) - : base(renderProperties) - { - _faceSheet = faceSheet; - _skinSheet = skinSheet; - _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); - } - - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + public class FaceRenderer : BaseCharacterPropertyRenderer { - if (!_renderProperties.IsFacing(EODirection.Down, EODirection.Right)) - return; - - var skinLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); - - var adjustX = _renderProperties.IsFacing(EODirection.Down) - ? _renderProperties.SitState == SitState.Standing ? 2 : 8 - : 3; - - var facePos = new Vector2(skinLoc.X + adjustX, skinLoc.Y + (_renderProperties.Gender == 0 ? 2 : 0)); - - Render(spriteBatch, _faceSheet, facePos); + private readonly ISpriteSheet _faceSheet; + private readonly ISpriteSheet _skinSheet; + private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; + + public override bool CanRender => _renderProperties.IsActing(CharacterActionState.Emote) && + _renderProperties.EmoteFrame > 0 && + _renderProperties.Emote != Emote.Trade && + _renderProperties.Emote != Emote.LevelUp && + _renderProperties.Emote != Emote.MusicNotes; + + public FaceRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet faceSheet, + ISpriteSheet skinSheet) + : base(renderProperties) + { + _faceSheet = faceSheet; + _skinSheet = skinSheet; + _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); + } + + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + if (!_renderProperties.IsFacing(EODirection.Down, EODirection.Right)) + return; + + var skinLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); + + var adjustX = _renderProperties.IsFacing(EODirection.Down) + ? _renderProperties.SitState == SitState.Standing ? 2 : 8 + : 3; + + var facePos = new Vector2(skinLoc.X + adjustX, skinLoc.Y + (_renderProperties.Gender == 0 ? 2 : 0)); + + Render(spriteBatch, _faceSheet, facePos); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs b/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs index 69e96510b..53e904a0d 100644 --- a/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs +++ b/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs @@ -4,64 +4,65 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.Rendering.CharacterProperties; - -public class HairRenderLocationCalculator +namespace EndlessClient.Rendering.CharacterProperties { - private readonly CharacterRenderProperties _renderProperties; - - public HairRenderLocationCalculator(CharacterRenderProperties renderProperties) - { - _renderProperties = renderProperties; - } - - public Vector2 CalculateDrawLocationOfCharacterHair(Rectangle hairRectangle, Rectangle parentCharacterDrawArea, bool ranged) + public class HairRenderLocationCalculator { - var resX = -(float)Math.Floor(Math.Abs((float)hairRectangle.Width - parentCharacterDrawArea.Width) / 2) - 1; - var resY = -(float)Math.Floor(Math.Abs(hairRectangle.Height - (parentCharacterDrawArea.Height / 2f)) / 2) - _renderProperties.Gender; + private readonly CharacterRenderProperties _renderProperties; - var isFlipped = _renderProperties.IsFacing(EODirection.Up, EODirection.Right); - - if (ranged && _renderProperties.RenderAttackFrame == 1) + public HairRenderLocationCalculator(CharacterRenderProperties renderProperties) { - var rangedXOff = _renderProperties.Gender == 0 ? 1 : 3; - resX += rangedXOff * (isFlipped ? 1 : -1); - resY += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? _renderProperties.Gender : 0; + _renderProperties = renderProperties; } - else if (_renderProperties.RenderAttackFrame == 2) - { - resX += isFlipped ? 4 : -4; - resX += _renderProperties.IsFacing(EODirection.Up) - ? _renderProperties.Gender * -2 - : _renderProperties.IsFacing(EODirection.Left) - ? _renderProperties.Gender * 2 - : 0; - resY += _renderProperties.IsFacing(EODirection.Up, EODirection.Left) ? 1 : 5; - resY -= _renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? _renderProperties.Gender : 0; - } - else if (_renderProperties.SitState != SitState.Standing) + public Vector2 CalculateDrawLocationOfCharacterHair(Rectangle hairRectangle, Rectangle parentCharacterDrawArea, bool ranged) { - resX -= 3; + var resX = -(float)Math.Floor(Math.Abs((float)hairRectangle.Width - parentCharacterDrawArea.Width) / 2) - 1; + var resY = -(float)Math.Floor(Math.Abs(hairRectangle.Height - (parentCharacterDrawArea.Height / 2f)) / 2) - _renderProperties.Gender; + + var isFlipped = _renderProperties.IsFacing(EODirection.Up, EODirection.Right); - var flootSitFactor = _renderProperties.SitState == SitState.Floor ? 2 : 1; - if (_renderProperties.IsFacing(EODirection.Right, EODirection.Down)) + if (ranged && _renderProperties.RenderAttackFrame == 1) { - resY += (9 + _renderProperties.Gender) * flootSitFactor; + var rangedXOff = _renderProperties.Gender == 0 ? 1 : 3; + resX += rangedXOff * (isFlipped ? 1 : -1); + resY += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? _renderProperties.Gender : 0; } - else + else if (_renderProperties.RenderAttackFrame == 2) { - if (_renderProperties.SitState == SitState.Floor) + resX += isFlipped ? 4 : -4; + resX += _renderProperties.IsFacing(EODirection.Up) + ? _renderProperties.Gender * -2 + : _renderProperties.IsFacing(EODirection.Left) + ? _renderProperties.Gender * 2 + : 0; + + resY += _renderProperties.IsFacing(EODirection.Up, EODirection.Left) ? 1 : 5; + resY -= _renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? _renderProperties.Gender : 0; + } + else if (_renderProperties.SitState != SitState.Standing) + { + resX -= 3; + + var flootSitFactor = _renderProperties.SitState == SitState.Floor ? 2 : 1; + if (_renderProperties.IsFacing(EODirection.Right, EODirection.Down)) { - resX += _renderProperties.IsFacing(EODirection.Left) ? 2 : -2; - resY -= 1; + resY += (9 + _renderProperties.Gender) * flootSitFactor; } + else + { + if (_renderProperties.SitState == SitState.Floor) + { + resX += _renderProperties.IsFacing(EODirection.Left) ? 2 : -2; + resY -= 1; + } - resY += (11 + _renderProperties.Gender) * flootSitFactor; + resY += (11 + _renderProperties.Gender) * flootSitFactor; + } } - } - var flippedOffset = isFlipped ? 2 : 0; - return parentCharacterDrawArea.Location.ToVector2() + new Vector2(resX + flippedOffset, resY); + var flippedOffset = isFlipped ? 2 : 0; + return parentCharacterDrawArea.Location.ToVector2() + new Vector2(resX + flippedOffset, resY); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs b/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs index 18e7d75df..e499b7f4c 100644 --- a/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/HairRenderer.cs @@ -4,26 +4,27 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties; - -public class HairRenderer : BaseCharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - private readonly ISpriteSheet _hairSheet; - private readonly HairRenderLocationCalculator _hairRenderLocationCalculator; + public class HairRenderer : BaseCharacterPropertyRenderer + { + private readonly ISpriteSheet _hairSheet; + private readonly HairRenderLocationCalculator _hairRenderLocationCalculator; - public override bool CanRender => _hairSheet.HasTexture && _renderProperties.HairStyle != 0; + public override bool CanRender => _hairSheet.HasTexture && _renderProperties.HairStyle != 0; - public HairRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet hairSheet) - : base(renderProperties) - { - _hairSheet = hairSheet; - _hairRenderLocationCalculator = new HairRenderLocationCalculator(_renderProperties); - } + public HairRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet hairSheet) + : base(renderProperties) + { + _hairSheet = hairSheet; + _hairRenderLocationCalculator = new HairRenderLocationCalculator(_renderProperties); + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var drawLoc = _hairRenderLocationCalculator.CalculateDrawLocationOfCharacterHair(_hairSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); - Render(spriteBatch, _hairSheet, drawLoc); + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + var drawLoc = _hairRenderLocationCalculator.CalculateDrawLocationOfCharacterHair(_hairSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); + Render(spriteBatch, _hairSheet, drawLoc); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs b/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs index 180fe6c1b..798c50454 100644 --- a/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/HatRenderer.cs @@ -6,42 +6,43 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties; - -public class HatRenderer : BaseCharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - private readonly ISpriteSheet _hatSheet; - private readonly ISpriteSheet _hairSheet; - private readonly HairRenderLocationCalculator _hairRenderLocationCalculator; + public class HatRenderer : BaseCharacterPropertyRenderer + { + private readonly ISpriteSheet _hatSheet; + private readonly ISpriteSheet _hairSheet; + private readonly HairRenderLocationCalculator _hairRenderLocationCalculator; - public override bool CanRender => _hatSheet.HasTexture && _renderProperties.HatGraphic != 0; + public override bool CanRender => _hatSheet.HasTexture && _renderProperties.HatGraphic != 0; - public HatRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet hatSheet, - ISpriteSheet hairSheet) - : base(renderProperties) - { - _hatSheet = hatSheet; - _hairSheet = hairSheet; + public HatRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet hatSheet, + ISpriteSheet hairSheet) + : base(renderProperties) + { + _hatSheet = hatSheet; + _hairSheet = hairSheet; - _hairRenderLocationCalculator = new HairRenderLocationCalculator(_renderProperties); - } + _hairRenderLocationCalculator = new HairRenderLocationCalculator(_renderProperties); + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var hairDrawLoc = _hairRenderLocationCalculator.CalculateDrawLocationOfCharacterHair(_hairSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); - var offsets = GetOffsets(); + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + var hairDrawLoc = _hairRenderLocationCalculator.CalculateDrawLocationOfCharacterHair(_hairSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); + var offsets = GetOffsets(); - Render(spriteBatch, _hatSheet, hairDrawLoc + offsets); - } + Render(spriteBatch, _hatSheet, hairDrawLoc + offsets); + } - private Vector2 GetOffsets() - { - var xOff = 0f; - var yOff = -3f; + private Vector2 GetOffsets() + { + var xOff = 0f; + var yOff = -3f; - var flippedOffset = _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? -2 : 0; + var flippedOffset = _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? -2 : 0; - return new Vector2(xOff + flippedOffset, yOff); + return new Vector2(xOff + flippedOffset, yOff); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs index f57affd94..fc8199f84 100644 --- a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRenderer.cs @@ -2,13 +2,14 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties; - -public interface ICharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - bool CanRender { get; } + public interface ICharacterPropertyRenderer + { + bool CanRender { get; } - float LayerDepth { get; set; } + float LayerDepth { get; set; } - void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata); + void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs index 844e1f027..be977a4be 100644 --- a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs +++ b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs @@ -2,10 +2,11 @@ using EOLib.Domain.Character; using System.Collections.Generic; -namespace EndlessClient.Rendering.CharacterProperties; - -public interface ICharacterPropertyRendererBuilder +namespace EndlessClient.Rendering.CharacterProperties { - IEnumerable BuildList(ICharacterTextures characterTextures, - CharacterRenderProperties renderProperties); + public interface ICharacterPropertyRendererBuilder + { + IEnumerable BuildList(ICharacterTextures characterTextures, + CharacterRenderProperties renderProperties); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs index 95e52c593..c8c7f54dd 100644 --- a/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs @@ -7,109 +7,110 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.CharacterProperties; - -public class ShieldRenderer : BaseCharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - private readonly ISpriteSheet _shieldSheet; - private readonly bool _isShieldOnBack; - - public override bool CanRender => _shieldSheet.HasTexture && _renderProperties.ShieldGraphic != 0; + public class ShieldRenderer : BaseCharacterPropertyRenderer + { + private readonly ISpriteSheet _shieldSheet; + private readonly bool _isShieldOnBack; - // NOTE: The original client flips the arrows when facing left or up from the standing frame. - // I'm guessing this is a Vult bug. The offsets are wonky if this is enabled and I don't feel like figuring them out. - //protected override bool ShouldFlip => _renderProperties.SitState == SitState.Floor - //? _isShieldOnBack && _renderProperties.IsFacing(EODirection.Left, EODirection.Right) - //: base.ShouldFlip; + public override bool CanRender => _shieldSheet.HasTexture && _renderProperties.ShieldGraphic != 0; - public ShieldRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet shieldSheet, - bool isShieldOnBack) - : base(renderProperties) - { - _shieldSheet = shieldSheet; - _isShieldOnBack = isShieldOnBack; - } + // NOTE: The original client flips the arrows when facing left or up from the standing frame. + // I'm guessing this is a Vult bug. The offsets are wonky if this is enabled and I don't feel like figuring them out. + //protected override bool ShouldFlip => _renderProperties.SitState == SitState.Floor + //? _isShieldOnBack && _renderProperties.IsFacing(EODirection.Left, EODirection.Right) + //: base.ShouldFlip; - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); - var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, parentCharacterDrawArea.Y + offsets.Y); - Render(spriteBatch, _shieldSheet, drawLoc); - } + public ShieldRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet shieldSheet, + bool isShieldOnBack) + : base(renderProperties) + { + _shieldSheet = shieldSheet; + _isShieldOnBack = isShieldOnBack; + } - private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) - { - float resX, resY; + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); + var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, parentCharacterDrawArea.Y + offsets.Y); + Render(spriteBatch, _shieldSheet, drawLoc); + } - if (_isShieldOnBack) + private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) { - resX = -(float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); - resY = -(float)Math.Floor(parentCharacterDrawArea.Height / 3f) - _renderProperties.Gender; + float resX, resY; - if (_renderProperties.RenderAttackFrame == 2) - resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 2 : -2; - else if (ranged && _renderProperties.RenderAttackFrame == 1) + if (_isShieldOnBack) { - // This currently does *not* match up perfectly with the original client. The original client doesn't keep - // the arrows aligned on the attack frame, so they look like they are sliding across the back of the character. - // I like it better this way (the offset is fixed for the arrows) so I'm not fixing it. - var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; - var extra = _renderProperties.Gender * 2; - resX += factor * (1 + extra); - } - else if (_renderProperties.SitState != SitState.Standing) - { - // These are the same offsets as hair - - resX -= 3; + resX = -(float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); + resY = -(float)Math.Floor(parentCharacterDrawArea.Height / 3f) - _renderProperties.Gender; - var flootSitFactor = _renderProperties.SitState == SitState.Floor ? 2 : 1; - if (_renderProperties.IsFacing(EODirection.Right, EODirection.Down)) + if (_renderProperties.RenderAttackFrame == 2) + resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 2 : -2; + else if (ranged && _renderProperties.RenderAttackFrame == 1) { - resY += (9 + _renderProperties.Gender) * flootSitFactor; + // This currently does *not* match up perfectly with the original client. The original client doesn't keep + // the arrows aligned on the attack frame, so they look like they are sliding across the back of the character. + // I like it better this way (the offset is fixed for the arrows) so I'm not fixing it. + var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; + var extra = _renderProperties.Gender * 2; + resX += factor * (1 + extra); } - else + else if (_renderProperties.SitState != SitState.Standing) { - if (_renderProperties.SitState == SitState.Floor) + // These are the same offsets as hair + + resX -= 3; + + var flootSitFactor = _renderProperties.SitState == SitState.Floor ? 2 : 1; + if (_renderProperties.IsFacing(EODirection.Right, EODirection.Down)) { - resX += _renderProperties.IsFacing(EODirection.Left) ? 2 : -2; - resY -= 1; + resY += (9 + _renderProperties.Gender) * flootSitFactor; } + else + { + if (_renderProperties.SitState == SitState.Floor) + { + resX += _renderProperties.IsFacing(EODirection.Left) ? 2 : -2; + resY -= 1; + } - resY += (11 + _renderProperties.Gender) * flootSitFactor; + resY += (11 + _renderProperties.Gender) * flootSitFactor; + } } } - } - else - { - resX = (float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); - resY = (float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Height - parentCharacterDrawArea.Height) / 2) + 5; - - if (_renderProperties.IsFacing(EODirection.Down, EODirection.Left)) + else { - resX -= parentCharacterDrawArea.Width * 1.5f; + resX = (float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); + resY = (float)Math.Floor(Math.Abs((float)_shieldSheet.SourceRectangle.Height - parentCharacterDrawArea.Height) / 2) + 5; - if (_renderProperties.RenderAttackFrame == 2) - resX -= 2; + if (_renderProperties.IsFacing(EODirection.Down, EODirection.Left)) + { + resX -= parentCharacterDrawArea.Width * 1.5f; - resX += 2; - } - else - { - resX -= parentCharacterDrawArea.Width / 1.5f; + if (_renderProperties.RenderAttackFrame == 2) + resX -= 2; - if (_renderProperties.RenderAttackFrame == 2) resX += 2; + } + else + { + resX -= parentCharacterDrawArea.Width / 1.5f; - resX -= 3; + if (_renderProperties.RenderAttackFrame == 2) + resX += 2; + + resX -= 3; + } + + resY -= _renderProperties.Gender; + if (_renderProperties.IsActing(CharacterActionState.Walking)) + resY -= 1; } - resY -= _renderProperties.Gender; - if (_renderProperties.IsActing(CharacterActionState.Walking)) - resY -= 1; + return new Vector2(resX, resY); } - - return new Vector2(resX, resY); } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs b/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs index 28843211c..c346df073 100644 --- a/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs +++ b/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs @@ -4,79 +4,80 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.Rendering.CharacterProperties; - -public class SkinRenderLocationCalculator +namespace EndlessClient.Rendering.CharacterProperties { - private readonly CharacterRenderProperties _renderProperties; - - public SkinRenderLocationCalculator(CharacterRenderProperties renderProperties) + public class SkinRenderLocationCalculator { - _renderProperties = renderProperties; - } + private readonly CharacterRenderProperties _renderProperties; - public Vector2 CalculateDrawLocationOfCharacterSkin(Rectangle skinRectangle, Rectangle parentCharacterDrawArea, bool ranged) - { - float resX, resY; + public SkinRenderLocationCalculator(CharacterRenderProperties renderProperties) + { + _renderProperties = renderProperties; + } - // Ranged weapon attack frame is offset based on the Left or Right border of the parent character draw area - // Ranged weapon graphics do not use the centering approach - if (ranged && _renderProperties.RenderAttackFrame == 1) + public Vector2 CalculateDrawLocationOfCharacterSkin(Rectangle skinRectangle, Rectangle parentCharacterDrawArea, bool ranged) { - var isFlipped = _renderProperties.IsFacing(EODirection.Right, EODirection.Up); - var needsExtraOffset = _renderProperties.IsFacing(EODirection.Right, EODirection.Down); + float resX, resY; - var startPixelX = isFlipped ? parentCharacterDrawArea.Left : parentCharacterDrawArea.Right; - var offsetFactor = isFlipped ? 0 : -1; + // Ranged weapon attack frame is offset based on the Left or Right border of the parent character draw area + // Ranged weapon graphics do not use the centering approach + if (ranged && _renderProperties.RenderAttackFrame == 1) + { + var isFlipped = _renderProperties.IsFacing(EODirection.Right, EODirection.Up); + var needsExtraOffset = _renderProperties.IsFacing(EODirection.Right, EODirection.Down); - resX = startPixelX + ((needsExtraOffset ? 2 : 0) + skinRectangle.Width) * offsetFactor; + var startPixelX = isFlipped ? parentCharacterDrawArea.Left : parentCharacterDrawArea.Right; + var offsetFactor = isFlipped ? 0 : -1; - // essentially, is it facing EODirection.Right? - if (isFlipped && needsExtraOffset) - resX += 2; + resX = startPixelX + ((needsExtraOffset ? 2 : 0) + skinRectangle.Width) * offsetFactor; - // male needs an extra +/- 2 - if (_renderProperties.Gender == 1) - resX += 2 * (isFlipped ? 1 : -1); + // essentially, is it facing EODirection.Right? + if (isFlipped && needsExtraOffset) + resX += 2; - resY = parentCharacterDrawArea.Y + (needsExtraOffset ? 1 : 0); - } - else if (_renderProperties.SitState != SitState.Standing) - { - var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; + // male needs an extra +/- 2 + if (_renderProperties.Gender == 1) + resX += 2 * (isFlipped ? 1 : -1); - resX = -(int)Math.Floor((float)(skinRectangle.Width - parentCharacterDrawArea.Width)); - resY = parentCharacterDrawArea.Bottom - skinRectangle.Height; + resY = parentCharacterDrawArea.Y + (needsExtraOffset ? 1 : 0); + } + else if (_renderProperties.SitState != SitState.Standing) + { + var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; - resX += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? 2 * factor : 3 * factor; + resX = -(int)Math.Floor((float)(skinRectangle.Width - parentCharacterDrawArea.Width)); + resY = parentCharacterDrawArea.Bottom - skinRectangle.Height; - var genderAdjustFactor = (_renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 0 : 1) * _renderProperties.Gender; - resX += parentCharacterDrawArea.X + (genderAdjustFactor * factor); + resX += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? 2 * factor : 3 * factor; - resY += (_renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 7 : 5) - _renderProperties.Gender; + var genderAdjustFactor = (_renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 0 : 1) * _renderProperties.Gender; + resX += parentCharacterDrawArea.X + (genderAdjustFactor * factor); - if (_renderProperties.SitState == SitState.Floor) - { - resX += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? -factor : 0; - resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 1 : 0; + resY += (_renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 7 : 5) - _renderProperties.Gender; + + if (_renderProperties.SitState == SitState.Floor) + { + resX += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? -factor : 0; + resY += _renderProperties.IsFacing(EODirection.Left, EODirection.Up) ? 1 : 0; + } } - } - else - { - resX = -(float)Math.Floor(Math.Abs((float)skinRectangle.Width - parentCharacterDrawArea.Width) / 2); - resY = -(float)Math.Floor(Math.Abs((float)skinRectangle.Height - parentCharacterDrawArea.Height) / 2); + else + { + resX = -(float)Math.Floor(Math.Abs((float)skinRectangle.Width - parentCharacterDrawArea.Width) / 2); + resY = -(float)Math.Floor(Math.Abs((float)skinRectangle.Height - parentCharacterDrawArea.Height) / 2); - if (_renderProperties.IsActing(CharacterActionState.SpellCast)) - resY -= 2; + if (_renderProperties.IsActing(CharacterActionState.SpellCast)) + resY -= 2; - // This specific frame is a bitch - if (_renderProperties.Gender == 1 && _renderProperties.RenderAttackFrame == 1) - resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 2 : -2; + // This specific frame is a bitch + if (_renderProperties.Gender == 1 && _renderProperties.RenderAttackFrame == 1) + resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 2 : -2; - resX += parentCharacterDrawArea.X; - resY += parentCharacterDrawArea.Y; - } + resX += parentCharacterDrawArea.X; + resY += parentCharacterDrawArea.Y; + } - return new Vector2(resX, resY); + return new Vector2(resX, resY); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs b/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs index f8d1e78c4..99c2c8107 100644 --- a/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/SkinRenderer.cs @@ -4,27 +4,28 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties; - -public class SkinRenderer : BaseCharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - private readonly ISpriteSheet _skinSheet; - private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; + public class SkinRenderer : BaseCharacterPropertyRenderer + { + private readonly ISpriteSheet _skinSheet; + private readonly SkinRenderLocationCalculator _skinRenderLocationCalculator; - public override bool CanRender => true; + public override bool CanRender => true; - public SkinRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet skinSheet) - : base(renderProperties) - { - _skinSheet = skinSheet; + public SkinRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet skinSheet) + : base(renderProperties) + { + _skinSheet = skinSheet; - _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); - } + _skinRenderLocationCalculator = new SkinRenderLocationCalculator(_renderProperties); + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - var drawLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); - Render(spriteBatch, _skinSheet, drawLoc); + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + var drawLoc = _skinRenderLocationCalculator.CalculateDrawLocationOfCharacterSkin(_skinSheet.SourceRectangle, parentCharacterDrawArea, weaponMetadata.Ranged); + Render(spriteBatch, _skinSheet, drawLoc); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs b/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs index 783e4f063..7709d977d 100644 --- a/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs @@ -7,54 +7,55 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.CharacterProperties; - -public class WeaponRenderer : BaseCharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - private readonly ISpriteSheet _weaponSheet; - - public override bool CanRender => _weaponSheet.HasTexture && _renderProperties.WeaponGraphic != 0; - - public WeaponRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet weaponSheet) - : base(renderProperties) - { - _weaponSheet = weaponSheet; - } - - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + public class WeaponRenderer : BaseCharacterPropertyRenderer { - if (_renderProperties.IsActing(CharacterActionState.Sitting, CharacterActionState.SpellCast) || - (_renderProperties.CurrentAction == CharacterActionState.Emote && _renderProperties.SitState != SitState.Standing)) - return; - - var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); - var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, parentCharacterDrawArea.Y + offsets.Y); - Render(spriteBatch, _weaponSheet, drawLoc); - } - - private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) - { - float resX, resY; - - resX = -(float)Math.Floor(Math.Abs((float)_weaponSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); - resY = -(float)Math.Floor(Math.Abs((float)_weaponSheet.SourceRectangle.Height - parentCharacterDrawArea.Height) / 2) - 5; - - var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; - var isDownOrRight = _renderProperties.IsFacing(EODirection.Down, EODirection.Right); - - resX += (parentCharacterDrawArea.Width / 1.5f - 3) * factor; - if (_renderProperties.RenderAttackFrame == 2) - resX += 2 * factor; - else if (_renderProperties.RenderAttackFrame == 1 && ranged) - resX += (isDownOrRight ? 6 : 4) * factor; - - resY -= 1 + _renderProperties.Gender; - if (_renderProperties.IsActing(CharacterActionState.Walking)) - resY -= 1; - else if (_renderProperties.RenderAttackFrame == 1 && ranged) - resY += isDownOrRight ? 1 : 0; - - return new Vector2(resX, resY); + private readonly ISpriteSheet _weaponSheet; + + public override bool CanRender => _weaponSheet.HasTexture && _renderProperties.WeaponGraphic != 0; + + public WeaponRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet weaponSheet) + : base(renderProperties) + { + _weaponSheet = weaponSheet; + } + + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + if (_renderProperties.IsActing(CharacterActionState.Sitting, CharacterActionState.SpellCast) || + (_renderProperties.CurrentAction == CharacterActionState.Emote && _renderProperties.SitState != SitState.Standing)) + return; + + var offsets = GetOffsets(parentCharacterDrawArea, weaponMetadata.Ranged); + var drawLoc = new Vector2(parentCharacterDrawArea.X + offsets.X, parentCharacterDrawArea.Y + offsets.Y); + Render(spriteBatch, _weaponSheet, drawLoc); + } + + private Vector2 GetOffsets(Rectangle parentCharacterDrawArea, bool ranged) + { + float resX, resY; + + resX = -(float)Math.Floor(Math.Abs((float)_weaponSheet.SourceRectangle.Width - parentCharacterDrawArea.Width) / 2); + resY = -(float)Math.Floor(Math.Abs((float)_weaponSheet.SourceRectangle.Height - parentCharacterDrawArea.Height) / 2) - 5; + + var factor = _renderProperties.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1; + var isDownOrRight = _renderProperties.IsFacing(EODirection.Down, EODirection.Right); + + resX += (parentCharacterDrawArea.Width / 1.5f - 3) * factor; + if (_renderProperties.RenderAttackFrame == 2) + resX += 2 * factor; + else if (_renderProperties.RenderAttackFrame == 1 && ranged) + resX += (isDownOrRight ? 6 : 4) * factor; + + resY -= 1 + _renderProperties.Gender; + if (_renderProperties.IsActing(CharacterActionState.Walking)) + resY -= 1; + else if (_renderProperties.RenderAttackFrame == 1 && ranged) + resY += isDownOrRight ? 1 : 0; + + return new Vector2(resX, resY); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs b/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs index e7404f10c..3ac4ca2a7 100644 --- a/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/WeaponSlashRenderer.cs @@ -5,41 +5,42 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.CharacterProperties; - -public class WeaponSlashRenderer : BaseCharacterPropertyRenderer +namespace EndlessClient.Rendering.CharacterProperties { - private readonly ISpriteSheet _slashSheet; + public class WeaponSlashRenderer : BaseCharacterPropertyRenderer + { + private readonly ISpriteSheet _slashSheet; - public override bool CanRender => _slashSheet.HasTexture && _renderProperties.WeaponGraphic != 0 && _renderProperties.RenderAttackFrame == 2; + public override bool CanRender => _slashSheet.HasTexture && _renderProperties.WeaponGraphic != 0 && _renderProperties.RenderAttackFrame == 2; - protected override bool ShouldFlip => false; + protected override bool ShouldFlip => false; - public WeaponSlashRenderer(CharacterRenderProperties renderProperties, - ISpriteSheet slashSheet) - : base(renderProperties) - { - _slashSheet = slashSheet; - } + public WeaponSlashRenderer(CharacterRenderProperties renderProperties, + ISpriteSheet slashSheet) + : base(renderProperties) + { + _slashSheet = slashSheet; + } - public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) - { - if (weaponMetadata.Slash == null || weaponMetadata.Ranged) - return; + public override void Render(SpriteBatch spriteBatch, Rectangle parentCharacterDrawArea, WeaponMetadata weaponMetadata) + { + if (weaponMetadata.Slash == null || weaponMetadata.Ranged) + return; - var offsets = GetOffsets(parentCharacterDrawArea) - new Vector2(0, _renderProperties.Gender); - Render(spriteBatch, _slashSheet, parentCharacterDrawArea.Location.ToVector2() + offsets, 96); - } + var offsets = GetOffsets(parentCharacterDrawArea) - new Vector2(0, _renderProperties.Gender); + Render(spriteBatch, _slashSheet, parentCharacterDrawArea.Location.ToVector2() + offsets, 96); + } - private Vector2 GetOffsets(Rectangle parentCharacterDrawArea) - { - return _renderProperties.Direction switch + private Vector2 GetOffsets(Rectangle parentCharacterDrawArea) { - EODirection.Down => new Vector2(-30, 4), - EODirection.Left => new Vector2(-34, -9), - EODirection.Up => new Vector2(-6, -9), - EODirection.Right => new Vector2(-10, 4), - _ => Vector2.Zero - }; + return _renderProperties.Direction switch + { + EODirection.Down => new Vector2(-30, 4), + EODirection.Left => new Vector2(-34, -9), + EODirection.Up => new Vector2(-6, -9), + EODirection.Right => new Vector2(-10, 4), + _ => Vector2.Zero + }; + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubble.cs b/EndlessClient/Rendering/Chat/ChatBubble.cs index d4ca72f6f..58add07d0 100644 --- a/EndlessClient/Rendering/Chat/ChatBubble.cs +++ b/EndlessClient/Rendering/Chat/ChatBubble.cs @@ -8,191 +8,192 @@ using System.Diagnostics; using XNAControls; -namespace EndlessClient.Rendering.Chat; - -public class ChatBubble : DrawableGameComponent, IChatBubble +namespace EndlessClient.Rendering.Chat { - private readonly IMapActor _parent; - private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; - private readonly IConfigurationProvider _configurationProvider; - private readonly SpriteBatch _spriteBatch; - - private readonly XNALabel _textLabel; - - private bool _isGroupChat; - private Vector2 _drawLocation; - private Option _startTime; - - public ChatBubble(IMapActor referenceRenderer, - IChatBubbleTextureProvider chatBubbleTextureProvider, - IEndlessGameProvider gameProvider, - IConfigurationProvider configurationProvider) - : base((Game)gameProvider.Game) + public class ChatBubble : DrawableGameComponent, IChatBubble { - _parent = referenceRenderer; - _chatBubbleTextureProvider = chatBubbleTextureProvider; - _configurationProvider = configurationProvider; - _spriteBatch = new SpriteBatch(((Game)gameProvider.Game).GraphicsDevice); + private readonly IMapActor _parent; + private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; + private readonly IConfigurationProvider _configurationProvider; + private readonly SpriteBatch _spriteBatch; + + private readonly XNALabel _textLabel; + + private bool _isGroupChat; + private Vector2 _drawLocation; + private Option _startTime; + + public ChatBubble(IMapActor referenceRenderer, + IChatBubbleTextureProvider chatBubbleTextureProvider, + IEndlessGameProvider gameProvider, + IConfigurationProvider configurationProvider) + : base((Game)gameProvider.Game) + { + _parent = referenceRenderer; + _chatBubbleTextureProvider = chatBubbleTextureProvider; + _configurationProvider = configurationProvider; + _spriteBatch = new SpriteBatch(((Game)gameProvider.Game).GraphicsDevice); - _textLabel = new XNALabel(Constants.FontSize08pt5) + _textLabel = new XNALabel(Constants.FontSize08pt5) + { + Visible = false, + TextWidth = 102, + HardBreak = 150, + Hyphen = "-", + ForeColor = Color.Black, + AutoSize = true, + Text = string.Empty, + DrawOrder = 30, + KeepInClientWindowBounds = false, + }; + + _drawLocation = Vector2.Zero; + _startTime = Option.None(); + + DrawOrder = 29; + Visible = false; + } + + public override void Initialize() { - Visible = false, - TextWidth = 102, - HardBreak = 150, - Hyphen = "-", - ForeColor = Color.Black, - AutoSize = true, - Text = string.Empty, - DrawOrder = 30, - KeepInClientWindowBounds = false, - }; - - _drawLocation = Vector2.Zero; - _startTime = Option.None(); - - DrawOrder = 29; - Visible = false; - } + _textLabel.Initialize(); - public override void Initialize() - { - _textLabel.Initialize(); + if (!_textLabel.Game.Components.Contains(_textLabel)) + _textLabel.Game.Components.Add(_textLabel); - if (!_textLabel.Game.Components.Contains(_textLabel)) - _textLabel.Game.Components.Add(_textLabel); + base.Initialize(); + } - base.Initialize(); - } + public void SetMessage(string message, bool isGroupChat) + { + if (!_configurationProvider.ShowChatBubbles || !_parent.IsAlive) + return; - public void SetMessage(string message, bool isGroupChat) - { - if (!_configurationProvider.ShowChatBubbles || !_parent.IsAlive) - return; + _isGroupChat = isGroupChat; + _textLabel.Text = message; + Visible = true; + _textLabel.Visible = true; - _isGroupChat = isGroupChat; - _textLabel.Text = message; - Visible = true; - _textLabel.Visible = true; + _startTime = Option.Some(Stopwatch.StartNew()); + } - _startTime = Option.Some(Stopwatch.StartNew()); - } + public void Hide() + { + Visible = _textLabel.Visible = false; + } - public void Hide() - { - Visible = _textLabel.Visible = false; - } + public void Show() + { + Visible = _textLabel.Visible = _parent.IsAlive && _startTime.HasValue; + } - public void Show() - { - Visible = _textLabel.Visible = _parent.IsAlive && _startTime.HasValue; - } + public override void Update(GameTime gameTime) + { + SetLabelDrawPosition(); + _drawLocation = _textLabel.DrawPosition - new Vector2( + _chatBubbleTextureProvider.ChatBubbleTextures[ChatBubbleTexture.TopLeft].Width, + _chatBubbleTextureProvider.ChatBubbleTextures[ChatBubbleTexture.TopLeft].Height); - public override void Update(GameTime gameTime) - { - SetLabelDrawPosition(); - _drawLocation = _textLabel.DrawPosition - new Vector2( - _chatBubbleTextureProvider.ChatBubbleTextures[ChatBubbleTexture.TopLeft].Width, - _chatBubbleTextureProvider.ChatBubbleTextures[ChatBubbleTexture.TopLeft].Height); + _startTime.MatchSome(st => + { + if (st.ElapsedMilliseconds > (24 + _textLabel.Text.Length / 3) * 120) + { + _textLabel.Visible = false; + Visible = false; + _startTime = Option.None(); + } + }); + + base.Update(gameTime); + } - _startTime.MatchSome(st => + public override void Draw(GameTime gameTime) { - if (st.ElapsedMilliseconds > (24 + _textLabel.Text.Length / 3) * 120) + var TL = GetTexture(ChatBubbleTexture.TopLeft); + var TM = GetTexture(ChatBubbleTexture.TopMiddle); + var TR = GetTexture(ChatBubbleTexture.TopRight); + var ML = GetTexture(ChatBubbleTexture.MiddleLeft); + var MM = GetTexture(ChatBubbleTexture.MiddleMiddle); + var MR = GetTexture(ChatBubbleTexture.MiddleRight); + var BL = GetTexture(ChatBubbleTexture.BottomLeft); + var BM = GetTexture(ChatBubbleTexture.BottomMiddle); + var BR = GetTexture(ChatBubbleTexture.BottomRight); + var NUB = GetTexture(ChatBubbleTexture.Nubbin); + + var xCov = TL.Width; + var yCov = TL.Height; + + var color = _isGroupChat ? Color.FromNonPremultiplied(247, 234, 164, 232) : Color.FromNonPremultiplied(255, 255, 255, 232); + + _spriteBatch.Begin(); + + //top row + _spriteBatch.Draw(TL, _drawLocation, color); + int xCur; + for (xCur = xCov; xCur < _textLabel.ActualWidth + 6; xCur += TM.Width) { - _textLabel.Visible = false; - Visible = false; - _startTime = Option.None(); + _spriteBatch.Draw(TM, _drawLocation + new Vector2(xCur, 0), color); } - }); + _spriteBatch.Draw(TR, _drawLocation + new Vector2(xCur, 0), color); - base.Update(gameTime); - } - - public override void Draw(GameTime gameTime) - { - var TL = GetTexture(ChatBubbleTexture.TopLeft); - var TM = GetTexture(ChatBubbleTexture.TopMiddle); - var TR = GetTexture(ChatBubbleTexture.TopRight); - var ML = GetTexture(ChatBubbleTexture.MiddleLeft); - var MM = GetTexture(ChatBubbleTexture.MiddleMiddle); - var MR = GetTexture(ChatBubbleTexture.MiddleRight); - var BL = GetTexture(ChatBubbleTexture.BottomLeft); - var BM = GetTexture(ChatBubbleTexture.BottomMiddle); - var BR = GetTexture(ChatBubbleTexture.BottomRight); - var NUB = GetTexture(ChatBubbleTexture.Nubbin); - - var xCov = TL.Width; - var yCov = TL.Height; - - var color = _isGroupChat ? Color.FromNonPremultiplied(247, 234, 164, 232) : Color.FromNonPremultiplied(255, 255, 255, 232); - - _spriteBatch.Begin(); - - //top row - _spriteBatch.Draw(TL, _drawLocation, color); - int xCur; - for (xCur = xCov; xCur < _textLabel.ActualWidth + 6; xCur += TM.Width) - { - _spriteBatch.Draw(TM, _drawLocation + new Vector2(xCur, 0), color); - } - _spriteBatch.Draw(TR, _drawLocation + new Vector2(xCur, 0), color); + //middle area + int y; + for (y = yCov; y < _textLabel.ActualHeight; y += ML.Height) + { + _spriteBatch.Draw(ML, _drawLocation + new Vector2(0, y), color); + int x; + for (x = xCov; x < xCur; x += MM.Width) + { + _spriteBatch.Draw(MM, _drawLocation + new Vector2(x, y), color); + } + _spriteBatch.Draw(MR, _drawLocation + new Vector2(xCur, y), color); + } - //middle area - int y; - for (y = yCov; y < _textLabel.ActualHeight; y += ML.Height) - { - _spriteBatch.Draw(ML, _drawLocation + new Vector2(0, y), color); - int x; - for (x = xCov; x < xCur; x += MM.Width) + //bottom row + _spriteBatch.Draw(BL, _drawLocation + new Vector2(0, y), color); + int x2; + for (x2 = xCov; x2 < xCur; x2 += BM.Width) { - _spriteBatch.Draw(MM, _drawLocation + new Vector2(x, y), color); + _spriteBatch.Draw(BM, _drawLocation + new Vector2(x2, y), color); } - _spriteBatch.Draw(MR, _drawLocation + new Vector2(xCur, y), color); + _spriteBatch.Draw(BR, _drawLocation + new Vector2(x2, y), color); + + y += BM.Height; + _spriteBatch.Draw(NUB, _drawLocation + new Vector2((x2 + BR.Width - NUB.Width) / 2f, y - 1), color); + + _spriteBatch.End(); } - //bottom row - _spriteBatch.Draw(BL, _drawLocation + new Vector2(0, y), color); - int x2; - for (x2 = xCov; x2 < xCur; x2 += BM.Width) + private void SetLabelDrawPosition() { - _spriteBatch.Draw(BM, _drawLocation + new Vector2(x2, y), color); + _textLabel.DrawPosition = new Vector2( + _parent.HorizontalCenter - _textLabel.ActualWidth / 2.0f, + _parent.NameLabelY - _textLabel.ActualHeight + 10); } - _spriteBatch.Draw(BR, _drawLocation + new Vector2(x2, y), color); - - y += BM.Height; - _spriteBatch.Draw(NUB, _drawLocation + new Vector2((x2 + BR.Width - NUB.Width) / 2f, y - 1), color); - - _spriteBatch.End(); - } - - private void SetLabelDrawPosition() - { - _textLabel.DrawPosition = new Vector2( - _parent.HorizontalCenter - _textLabel.ActualWidth / 2.0f, - _parent.NameLabelY - _textLabel.ActualHeight + 10); - } - protected override void Dispose(bool disposing) - { - if (disposing) + protected override void Dispose(bool disposing) { - if (Game.Components != null && Game.Components.Contains(this)) - Game.Components.Remove(this); + if (disposing) + { + if (Game.Components != null && Game.Components.Contains(this)) + Game.Components.Remove(this); - _textLabel.Dispose(); + _textLabel.Dispose(); + } } - } - private Texture2D GetTexture(ChatBubbleTexture whichTexture) => - _chatBubbleTextureProvider.ChatBubbleTextures[whichTexture]; -} + private Texture2D GetTexture(ChatBubbleTexture whichTexture) => + _chatBubbleTextureProvider.ChatBubbleTextures[whichTexture]; + } -public interface IChatBubble : IDisposable -{ - bool Visible { get; } + public interface IChatBubble : IDisposable + { + bool Visible { get; } - void SetMessage(string message, bool isGroupChat); + void SetMessage(string message, bool isGroupChat); - void Hide(); + void Hide(); - void Show(); + void Show(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs b/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs index 8d53216a0..630c98a05 100644 --- a/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs +++ b/EndlessClient/Rendering/Chat/ChatBubbleFactory.cs @@ -2,36 +2,37 @@ using EndlessClient.GameExecution; using EOLib.Config; -namespace EndlessClient.Rendering.Chat; - -[AutoMappedType] -public class ChatBubbleFactory : IChatBubbleFactory +namespace EndlessClient.Rendering.Chat { - private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IConfigurationProvider _configurationProvider; - - public ChatBubbleFactory(IChatBubbleTextureProvider chatBubbleTextureProvider, - IEndlessGameProvider endlessGameProvider, - IConfigurationProvider configurationProvider) + [AutoMappedType] + public class ChatBubbleFactory : IChatBubbleFactory { - _chatBubbleTextureProvider = chatBubbleTextureProvider; - _endlessGameProvider = endlessGameProvider; - _configurationProvider = configurationProvider; - } + private readonly IChatBubbleTextureProvider _chatBubbleTextureProvider; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IConfigurationProvider _configurationProvider; - public IChatBubble CreateChatBubble(IMapActor owner) - { - var chatBubble = new ChatBubble(owner, _chatBubbleTextureProvider, _endlessGameProvider, _configurationProvider); + public ChatBubbleFactory(IChatBubbleTextureProvider chatBubbleTextureProvider, + IEndlessGameProvider endlessGameProvider, + IConfigurationProvider configurationProvider) + { + _chatBubbleTextureProvider = chatBubbleTextureProvider; + _endlessGameProvider = endlessGameProvider; + _configurationProvider = configurationProvider; + } - if (!_endlessGameProvider.Game.Components.Contains(chatBubble)) - _endlessGameProvider.Game.Components.Add(chatBubble); + public IChatBubble CreateChatBubble(IMapActor owner) + { + var chatBubble = new ChatBubble(owner, _chatBubbleTextureProvider, _endlessGameProvider, _configurationProvider); - return chatBubble; + if (!_endlessGameProvider.Game.Components.Contains(chatBubble)) + _endlessGameProvider.Game.Components.Add(chatBubble); + + return chatBubble; + } } -} -public interface IChatBubbleFactory -{ - IChatBubble CreateChatBubble(IMapActor owner); + public interface IChatBubbleFactory + { + IChatBubble CreateChatBubble(IMapActor owner); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs b/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs index 6d7905973..ee6c96602 100644 --- a/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs +++ b/EndlessClient/Rendering/Chat/ChatBubbleTexture.cs @@ -1,15 +1,16 @@ -namespace EndlessClient.Rendering.Chat; - -public enum ChatBubbleTexture +namespace EndlessClient.Rendering.Chat { - TopLeft, - TopMiddle, - TopRight, - MiddleLeft, - MiddleMiddle, - MiddleRight, - BottomLeft, - BottomMiddle, - BottomRight, - Nubbin + public enum ChatBubbleTexture + { + TopLeft, + TopMiddle, + TopRight, + MiddleLeft, + MiddleMiddle, + MiddleRight, + BottomLeft, + BottomMiddle, + BottomRight, + Nubbin + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs b/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs index 9a70b3ceb..e9a3cdbf9 100644 --- a/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs +++ b/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs @@ -4,41 +4,42 @@ using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; -namespace EndlessClient.Rendering.Chat; - -[MappedType(BaseType = typeof(IChatBubbleTextureProvider), IsSingleton = true)] -public class ChatBubbleTextureProvider : IChatBubbleTextureProvider +namespace EndlessClient.Rendering.Chat { - private readonly IContentProvider _contentProvider; - private readonly Dictionary _chatBubbleTextures; + [MappedType(BaseType = typeof(IChatBubbleTextureProvider), IsSingleton = true)] + public class ChatBubbleTextureProvider : IChatBubbleTextureProvider + { + private readonly IContentProvider _contentProvider; + private readonly Dictionary _chatBubbleTextures; - public IReadOnlyDictionary ChatBubbleTextures => _chatBubbleTextures; + public IReadOnlyDictionary ChatBubbleTextures => _chatBubbleTextures; - public ChatBubbleTextureProvider(IContentProvider contentProvider) - { - _contentProvider = contentProvider; - _chatBubbleTextures = new Dictionary(); - } + public ChatBubbleTextureProvider(IContentProvider contentProvider) + { + _contentProvider = contentProvider; + _chatBubbleTextures = new Dictionary(); + } - public void LoadContent() - { - _chatBubbleTextures.Add(ChatBubbleTexture.TopLeft, _contentProvider.Textures[ContentProvider.ChatTL]); - _chatBubbleTextures.Add(ChatBubbleTexture.TopMiddle, _contentProvider.Textures[ContentProvider.ChatTM]); - _chatBubbleTextures.Add(ChatBubbleTexture.TopRight, _contentProvider.Textures[ContentProvider.ChatTR]); - _chatBubbleTextures.Add(ChatBubbleTexture.MiddleLeft, _contentProvider.Textures[ContentProvider.ChatML]); - _chatBubbleTextures.Add(ChatBubbleTexture.MiddleMiddle, _contentProvider.Textures[ContentProvider.ChatMM]); - _chatBubbleTextures.Add(ChatBubbleTexture.MiddleRight, _contentProvider.Textures[ContentProvider.ChatMR]); - //todo: change the first 'R' to a 'B' (for bottom) - _chatBubbleTextures.Add(ChatBubbleTexture.BottomLeft, _contentProvider.Textures[ContentProvider.ChatRL]); - _chatBubbleTextures.Add(ChatBubbleTexture.BottomMiddle, _contentProvider.Textures[ContentProvider.ChatRM]); - _chatBubbleTextures.Add(ChatBubbleTexture.BottomRight, _contentProvider.Textures[ContentProvider.ChatRR]); - _chatBubbleTextures.Add(ChatBubbleTexture.Nubbin, _contentProvider.Textures[ContentProvider.ChatNUB]); + public void LoadContent() + { + _chatBubbleTextures.Add(ChatBubbleTexture.TopLeft, _contentProvider.Textures[ContentProvider.ChatTL]); + _chatBubbleTextures.Add(ChatBubbleTexture.TopMiddle, _contentProvider.Textures[ContentProvider.ChatTM]); + _chatBubbleTextures.Add(ChatBubbleTexture.TopRight, _contentProvider.Textures[ContentProvider.ChatTR]); + _chatBubbleTextures.Add(ChatBubbleTexture.MiddleLeft, _contentProvider.Textures[ContentProvider.ChatML]); + _chatBubbleTextures.Add(ChatBubbleTexture.MiddleMiddle, _contentProvider.Textures[ContentProvider.ChatMM]); + _chatBubbleTextures.Add(ChatBubbleTexture.MiddleRight, _contentProvider.Textures[ContentProvider.ChatMR]); + //todo: change the first 'R' to a 'B' (for bottom) + _chatBubbleTextures.Add(ChatBubbleTexture.BottomLeft, _contentProvider.Textures[ContentProvider.ChatRL]); + _chatBubbleTextures.Add(ChatBubbleTexture.BottomMiddle, _contentProvider.Textures[ContentProvider.ChatRM]); + _chatBubbleTextures.Add(ChatBubbleTexture.BottomRight, _contentProvider.Textures[ContentProvider.ChatRR]); + _chatBubbleTextures.Add(ChatBubbleTexture.Nubbin, _contentProvider.Textures[ContentProvider.ChatNUB]); + } } -} -public interface IChatBubbleTextureProvider -{ - IReadOnlyDictionary ChatBubbleTextures { get; } + public interface IChatBubbleTextureProvider + { + IReadOnlyDictionary ChatBubbleTextures { get; } - void LoadContent(); + void LoadContent(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatColorExtensions.cs b/EndlessClient/Rendering/Chat/ChatColorExtensions.cs index 4d68c3a28..cf46f5dff 100644 --- a/EndlessClient/Rendering/Chat/ChatColorExtensions.cs +++ b/EndlessClient/Rendering/Chat/ChatColorExtensions.cs @@ -3,21 +3,22 @@ using Microsoft.Xna.Framework; using System; -namespace EndlessClient.Rendering.Chat; - -public static class ChatColorExtensions +namespace EndlessClient.Rendering.Chat { - public static Color ToColor(this ChatColor chatColor) + public static class ChatColorExtensions { - switch (chatColor) + public static Color ToColor(this ChatColor chatColor) { - case ChatColor.Default: return Color.Black; - case ChatColor.Error: return Color.FromNonPremultiplied(0x7d, 0x0a, 0x0a, 0xff); - case ChatColor.PM: return Color.FromNonPremultiplied(0x5a, 0x3c, 0x00, 0xff); - case ChatColor.Server: return Color.FromNonPremultiplied(0xe6, 0xd2, 0xc8, 0xff); - case ChatColor.ServerGlobal: return ColorConstants.LightYellowText; - case ChatColor.Admin: return Color.FromNonPremultiplied(0xc8, 0xaa, 0x96, 0xff); - default: throw new ArgumentOutOfRangeException(nameof(chatColor), chatColor, "Unrecognized chat color"); + switch (chatColor) + { + case ChatColor.Default: return Color.Black; + case ChatColor.Error: return Color.FromNonPremultiplied(0x7d, 0x0a, 0x0a, 0xff); + case ChatColor.PM: return Color.FromNonPremultiplied(0x5a, 0x3c, 0x00, 0xff); + case ChatColor.Server: return Color.FromNonPremultiplied(0xe6, 0xd2, 0xc8, 0xff); + case ChatColor.ServerGlobal: return ColorConstants.LightYellowText; + case ChatColor.Admin: return Color.FromNonPremultiplied(0xc8, 0xaa, 0x96, 0xff); + default: throw new ArgumentOutOfRangeException(nameof(chatColor), chatColor, "Unrecognized chat color"); + } } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatRenderable.cs b/EndlessClient/Rendering/Chat/ChatRenderable.cs index 073f03ddd..9d9728d3b 100644 --- a/EndlessClient/Rendering/Chat/ChatRenderable.cs +++ b/EndlessClient/Rendering/Chat/ChatRenderable.cs @@ -7,89 +7,90 @@ using MonoGame.Extended.BitmapFonts; using Optional.Unsafe; -namespace EndlessClient.Rendering.Chat; - -public class ChatRenderable : IChatRenderable +namespace EndlessClient.Rendering.Chat { - private const int ICON_GRAPHIC_X_OFF = 3; - private const int CHAT_MESSAGE_X_OFF = 20; - - private readonly INativeGraphicsManager _nativeGraphicsManager; - - private readonly string _partialMessage; - - protected virtual int HeaderYOffset => 3; - - public int DisplayIndex { get; set; } - - public ChatData Data { get; private set; } - - public ChatRenderable(INativeGraphicsManager nativeGraphicsManager, - int displayIndex, - ChatData data, - string partialMessage = null) - { - _nativeGraphicsManager = nativeGraphicsManager; - - DisplayIndex = displayIndex; - Data = data; - _partialMessage = partialMessage; - } - - public override bool Equals(object obj) + public class ChatRenderable : IChatRenderable { - if (!(obj is ChatRenderable)) return false; - var other = (ChatRenderable)obj; - - return other.Data.Equals(Data) - && other._partialMessage.Equals(_partialMessage); - } - - public override int GetHashCode() - { - var hash = 397 ^ Data.GetHashCode(); - hash = (hash * 397) ^ DisplayIndex.GetHashCode(); - hash = (hash * 397) ^ _partialMessage.GetHashCode(); - return hash; + private const int ICON_GRAPHIC_X_OFF = 3; + private const int CHAT_MESSAGE_X_OFF = 20; + + private readonly INativeGraphicsManager _nativeGraphicsManager; + + private readonly string _partialMessage; + + protected virtual int HeaderYOffset => 3; + + public int DisplayIndex { get; set; } + + public ChatData Data { get; private set; } + + public ChatRenderable(INativeGraphicsManager nativeGraphicsManager, + int displayIndex, + ChatData data, + string partialMessage = null) + { + _nativeGraphicsManager = nativeGraphicsManager; + + DisplayIndex = displayIndex; + Data = data; + _partialMessage = partialMessage; + } + + public override bool Equals(object obj) + { + if (!(obj is ChatRenderable)) return false; + var other = (ChatRenderable)obj; + + return other.Data.Equals(Data) + && other._partialMessage.Equals(_partialMessage); + } + + public override int GetHashCode() + { + var hash = 397 ^ Data.GetHashCode(); + hash = (hash * 397) ^ DisplayIndex.GetHashCode(); + hash = (hash * 397) ^ _partialMessage.GetHashCode(); + return hash; + } + + public void Render(IHudPanel parentPanel, SpriteBatch spriteBatch, BitmapFont chatFont) + { + spriteBatch.Begin(); + + var pos = parentPanel.DrawPosition + new Vector2(0, DisplayIndex * 13); + spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true), + new Vector2(pos.X + ICON_GRAPHIC_X_OFF, pos.Y + HeaderYOffset), + GetChatIconRectangle(Data.Icon), + Color.White); + + string strToDraw; + if (string.IsNullOrEmpty(Data.Who)) + strToDraw = _partialMessage; + else + strToDraw = Data.Who + " " + _partialMessage; + + spriteBatch.DrawString(chatFont, + strToDraw, + new Vector2(pos.X + CHAT_MESSAGE_X_OFF, pos.Y + HeaderYOffset), + Data.ChatColor.ToColor()); + + spriteBatch.End(); + } + + private static Rectangle? GetChatIconRectangle(ChatIcon icon) + { + var (x, y, width, height) = icon.GetChatIconRectangleBounds().ValueOrDefault(); + return new Rectangle(x, y, width, height); + } } - public void Render(IHudPanel parentPanel, SpriteBatch spriteBatch, BitmapFont chatFont) + public class NewsChatRenderable : ChatRenderable { - spriteBatch.Begin(); - - var pos = parentPanel.DrawPosition + new Vector2(0, DisplayIndex * 13); - spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 32, true), - new Vector2(pos.X + ICON_GRAPHIC_X_OFF, pos.Y + HeaderYOffset), - GetChatIconRectangle(Data.Icon), - Color.White); - - string strToDraw; - if (string.IsNullOrEmpty(Data.Who)) - strToDraw = _partialMessage; - else - strToDraw = Data.Who + " " + _partialMessage; - - spriteBatch.DrawString(chatFont, - strToDraw, - new Vector2(pos.X + CHAT_MESSAGE_X_OFF, pos.Y + HeaderYOffset), - Data.ChatColor.ToColor()); - - spriteBatch.End(); - } + protected override int HeaderYOffset => 23; - private static Rectangle? GetChatIconRectangle(ChatIcon icon) - { - var (x, y, width, height) = icon.GetChatIconRectangleBounds().ValueOrDefault(); - return new Rectangle(x, y, width, height); - } -} - -public class NewsChatRenderable : ChatRenderable -{ - protected override int HeaderYOffset => 23; - - public NewsChatRenderable(INativeGraphicsManager nativeGraphicsManager, int displayIndex, ChatData data, string partialMessage) - : base(nativeGraphicsManager, displayIndex, data, partialMessage) - { + public NewsChatRenderable(INativeGraphicsManager nativeGraphicsManager, int displayIndex, ChatData data, string partialMessage) + : base(nativeGraphicsManager, displayIndex, data, partialMessage) + { + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs b/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs index da6fdded7..6e0ac4955 100644 --- a/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs +++ b/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs @@ -9,127 +9,128 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering.Chat; - -public class ChatRenderableGenerator : IChatRenderableGenerator +namespace EndlessClient.Rendering.Chat { - private class ChatPair - { - public string Text { get; set; } - public bool IsFirstLineOfMultilineMessage { get; set; } - } - - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly BitmapFont _chatFont; - - public ChatRenderableGenerator(INativeGraphicsManager nativeGraphicsManager, - IFriendIgnoreListService friendIgnoreListService, - BitmapFont chatFont) + public class ChatRenderableGenerator : IChatRenderableGenerator { - _nativeGraphicsManager = nativeGraphicsManager; - _friendIgnoreListService = friendIgnoreListService; - _chatFont = chatFont; - } - - public IReadOnlyList GenerateNewsRenderables(IReadOnlyList newsText) - { - newsText = newsText.Where(x => !string.IsNullOrEmpty(x)).ToList(); - - var newsTextWithBlankLines = new List(); - foreach (var news in newsText) + private class ChatPair { - newsTextWithBlankLines.Add(news); - if (news != newsText.Last()) - newsTextWithBlankLines.Add(" "); + public string Text { get; set; } + public bool IsFirstLineOfMultilineMessage { get; set; } } - var splitStrings = SplitTextIntoLines(string.Empty, newsTextWithBlankLines); - return splitStrings.Select(CreateNewsRenderableFromChatPair).ToList(); - } - - public IReadOnlyList GenerateChatRenderables(IEnumerable chatData) - { - var ignoreList = _friendIgnoreListService.LoadList(Constants.IgnoreListFile); + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly BitmapFont _chatFont; - var retList = new List(); - foreach (var data in chatData) + public ChatRenderableGenerator(INativeGraphicsManager nativeGraphicsManager, + IFriendIgnoreListService friendIgnoreListService, + BitmapFont chatFont) { - if (ignoreList.Any(x => x.Equals(data.Who, StringComparison.InvariantCultureIgnoreCase))) - continue; - - var splitStrings = SplitTextIntoLines(data.Who, new[] { data.Message }); - var renderables = splitStrings.Select( - (pair, i) => CreateChatRenderableFromChatPair(pair, i, data)) - .ToList(); - retList.AddRange(renderables); + _nativeGraphicsManager = nativeGraphicsManager; + _friendIgnoreListService = friendIgnoreListService; + _chatFont = chatFont; } - return retList; - } + public IReadOnlyList GenerateNewsRenderables(IReadOnlyList newsText) + { + newsText = newsText.Where(x => !string.IsNullOrEmpty(x)).ToList(); - private IReadOnlyList SplitTextIntoLines(string who, IReadOnlyList input) - { - var retStrings = new List(); - who = who ?? string.Empty; + var newsTextWithBlankLines = new List(); + foreach (var news in newsText) + { + newsTextWithBlankLines.Add(news); + if (news != newsText.Last()) + newsTextWithBlankLines.Add(" "); + } - // padding string for additional lines if it is a multi-line message - var indentForUserName = string.Empty; - while (_chatFont.MeasureString(indentForUserName).Width < _chatFont.MeasureString(who).Width) - indentForUserName += " "; - indentForUserName += string.IsNullOrEmpty(who) ? string.Empty : " "; + var splitStrings = SplitTextIntoLines(string.Empty, newsTextWithBlankLines); + return splitStrings.Select(CreateNewsRenderableFromChatPair).ToList(); + } - var splitter = new TextSplitter("", _chatFont) + public IReadOnlyList GenerateChatRenderables(IEnumerable chatData) { - LineLength = 380, - HardBreak = 425, - Hyphen = "-", - LineIndent = indentForUserName - }; + var ignoreList = _friendIgnoreListService.LoadList(Constants.IgnoreListFile); - foreach (var text in input) - { - if (string.IsNullOrWhiteSpace(who) && string.IsNullOrWhiteSpace(text)) + var retList = new List(); + foreach (var data in chatData) { - retStrings.Add(new ChatPair { Text = " ", IsFirstLineOfMultilineMessage = true }); - continue; + if (ignoreList.Any(x => x.Equals(data.Who, StringComparison.InvariantCultureIgnoreCase))) + continue; + + var splitStrings = SplitTextIntoLines(data.Who, new[] { data.Message }); + var renderables = splitStrings.Select( + (pair, i) => CreateChatRenderableFromChatPair(pair, i, data)) + .ToList(); + retList.AddRange(renderables); } - splitter.Text = string.IsNullOrEmpty(who) ? text : $"{who} {text}"; - if (!splitter.NeedsProcessing) + return retList; + } + + private IReadOnlyList SplitTextIntoLines(string who, IReadOnlyList input) + { + var retStrings = new List(); + who = who ?? string.Empty; + + // padding string for additional lines if it is a multi-line message + var indentForUserName = string.Empty; + while (_chatFont.MeasureString(indentForUserName).Width < _chatFont.MeasureString(who).Width) + indentForUserName += " "; + indentForUserName += string.IsNullOrEmpty(who) ? string.Empty : " "; + + var splitter = new TextSplitter("", _chatFont) { - retStrings.Add(new ChatPair { Text = text, IsFirstLineOfMultilineMessage = true }); - continue; - } + LineLength = 380, + HardBreak = 425, + Hyphen = "-", + LineIndent = indentForUserName + }; - var stringsToAdd = splitter.SplitIntoLines(); - if (who.Length > 0) + foreach (var text in input) { - stringsToAdd[0] = stringsToAdd[0].Remove(0, who.Length + 1); + if (string.IsNullOrWhiteSpace(who) && string.IsNullOrWhiteSpace(text)) + { + retStrings.Add(new ChatPair { Text = " ", IsFirstLineOfMultilineMessage = true }); + continue; + } + + splitter.Text = string.IsNullOrEmpty(who) ? text : $"{who} {text}"; + if (!splitter.NeedsProcessing) + { + retStrings.Add(new ChatPair { Text = text, IsFirstLineOfMultilineMessage = true }); + continue; + } + + var stringsToAdd = splitter.SplitIntoLines(); + if (who.Length > 0) + { + stringsToAdd[0] = stringsToAdd[0].Remove(0, who.Length + 1); + } + + retStrings.AddRange(stringsToAdd.Select((str, i) => new ChatPair { Text = str, IsFirstLineOfMultilineMessage = i == 0 })); } - retStrings.AddRange(stringsToAdd.Select((str, i) => new ChatPair { Text = str, IsFirstLineOfMultilineMessage = i == 0 })); + return retStrings; } - return retStrings; - } - - private NewsChatRenderable CreateNewsRenderableFromChatPair(ChatPair pair, int i) - { - var shouldShowNoteIcon = pair.IsFirstLineOfMultilineMessage && !string.IsNullOrWhiteSpace(pair.Text); - var chatData = new ChatData(ChatTab.Local, "", pair.Text, shouldShowNoteIcon ? ChatIcon.Note : ChatIcon.None, log: false); - return new NewsChatRenderable(_nativeGraphicsManager, i, chatData, pair.Text); - } + private NewsChatRenderable CreateNewsRenderableFromChatPair(ChatPair pair, int i) + { + var shouldShowNoteIcon = pair.IsFirstLineOfMultilineMessage && !string.IsNullOrWhiteSpace(pair.Text); + var chatData = new ChatData(ChatTab.Local, "", pair.Text, shouldShowNoteIcon ? ChatIcon.Note : ChatIcon.None, log: false); + return new NewsChatRenderable(_nativeGraphicsManager, i, chatData, pair.Text); + } - private ChatRenderable CreateChatRenderableFromChatPair(ChatPair pair, int displayIndex, ChatData data) - { - var modifiedData = new ChatData( - data.Tab, - pair.IsFirstLineOfMultilineMessage ? data.Who : string.Empty, - data.Message, - pair.IsFirstLineOfMultilineMessage ? data.Icon : ChatIcon.None, - data.ChatColor); - - return new ChatRenderable(_nativeGraphicsManager, displayIndex, modifiedData, pair.Text); + private ChatRenderable CreateChatRenderableFromChatPair(ChatPair pair, int displayIndex, ChatData data) + { + var modifiedData = new ChatData( + data.Tab, + pair.IsFirstLineOfMultilineMessage ? data.Who : string.Empty, + data.Message, + pair.IsFirstLineOfMultilineMessage ? data.Icon : ChatIcon.None, + data.ChatColor); + + return new ChatRenderable(_nativeGraphicsManager, displayIndex, modifiedData, pair.Text); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/IChatRenderable.cs b/EndlessClient/Rendering/Chat/IChatRenderable.cs index 31e65d7db..24fda7fa1 100644 --- a/EndlessClient/Rendering/Chat/IChatRenderable.cs +++ b/EndlessClient/Rendering/Chat/IChatRenderable.cs @@ -3,13 +3,14 @@ using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.BitmapFonts; -namespace EndlessClient.Rendering.Chat; - -public interface IChatRenderable +namespace EndlessClient.Rendering.Chat { - int DisplayIndex { get; set; } + public interface IChatRenderable + { + int DisplayIndex { get; set; } - ChatData Data { get; } + ChatData Data { get; } - void Render(IHudPanel parentPanel, SpriteBatch spriteBatch, BitmapFont chatFont); + void Render(IHudPanel parentPanel, SpriteBatch spriteBatch, BitmapFont chatFont); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs b/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs index 678181759..27a6ad5f3 100644 --- a/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs +++ b/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs @@ -1,11 +1,12 @@ using EOLib.Domain.Chat; using System.Collections.Generic; -namespace EndlessClient.Rendering.Chat; - -public interface IChatRenderableGenerator +namespace EndlessClient.Rendering.Chat { - IReadOnlyList GenerateNewsRenderables(IReadOnlyList newsText); + public interface IChatRenderableGenerator + { + IReadOnlyList GenerateNewsRenderables(IReadOnlyList newsText); - IReadOnlyList GenerateChatRenderables(IEnumerable chatData); + IReadOnlyList GenerateChatRenderables(IEnumerable chatData); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/ClientWindowSizeRepository.cs b/EndlessClient/Rendering/ClientWindowSizeRepository.cs index 8a5625031..17cbd99fe 100644 --- a/EndlessClient/Rendering/ClientWindowSizeRepository.cs +++ b/EndlessClient/Rendering/ClientWindowSizeRepository.cs @@ -4,106 +4,107 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering; - -public interface IClientWindowSizeProvider +namespace EndlessClient.Rendering { - int Width { get; } - int Height { get; } + public interface IClientWindowSizeProvider + { + int Width { get; } + int Height { get; } - bool Resizable { get; } + bool Resizable { get; } - event EventHandler GameWindowSizeChanged; -} + event EventHandler GameWindowSizeChanged; + } -public interface IClientWindowSizeRepository : IResettable, IClientWindowSizeProvider -{ - new int Width { get; set; } - new int Height { get; set; } + public interface IClientWindowSizeRepository : IResettable, IClientWindowSizeProvider + { + new int Width { get; set; } + new int Height { get; set; } - new bool Resizable { get; set; } -} + new bool Resizable { get; set; } + } -[AutoMappedType(IsSingleton = true)] -public class ClientWindowSizeRepository : IClientWindowSizeProvider, IClientWindowSizeRepository, IResettable -{ - public const int DEFAULT_BACKBUFFER_WIDTH = 640; - public const int DEFAULT_BACKBUFFER_HEIGHT = 480; + [AutoMappedType(IsSingleton = true)] + public class ClientWindowSizeRepository : IClientWindowSizeProvider, IClientWindowSizeRepository, IResettable + { + public const int DEFAULT_BACKBUFFER_WIDTH = 640; + public const int DEFAULT_BACKBUFFER_HEIGHT = 480; - private readonly IGameWindowRepository _gameWindowRepository; - private readonly IGraphicsDeviceRepository _graphicsDeviceRepository; + private readonly IGameWindowRepository _gameWindowRepository; + private readonly IGraphicsDeviceRepository _graphicsDeviceRepository; - private readonly List> _resizeEvents; + private readonly List> _resizeEvents; - public int Width - { - get => _gameWindowRepository.Window.ClientBounds.Width; - set + public int Width { - if (value < DEFAULT_BACKBUFFER_WIDTH) - value = DEFAULT_BACKBUFFER_WIDTH; - - _graphicsDeviceRepository.GraphicsDeviceManager.PreferredBackBufferWidth = value; - _graphicsDeviceRepository.GraphicsDeviceManager.ApplyChanges(); - - foreach (var evnt in _resizeEvents) - evnt(this, EventArgs.Empty); + get => _gameWindowRepository.Window.ClientBounds.Width; + set + { + if (value < DEFAULT_BACKBUFFER_WIDTH) + value = DEFAULT_BACKBUFFER_WIDTH; + + _graphicsDeviceRepository.GraphicsDeviceManager.PreferredBackBufferWidth = value; + _graphicsDeviceRepository.GraphicsDeviceManager.ApplyChanges(); + + foreach (var evnt in _resizeEvents) + evnt(this, EventArgs.Empty); + } } - } - public int Height - { - get => _gameWindowRepository.Window.ClientBounds.Height; - set + public int Height { - if (value < DEFAULT_BACKBUFFER_HEIGHT) - value = DEFAULT_BACKBUFFER_HEIGHT; - - _graphicsDeviceRepository.GraphicsDeviceManager.PreferredBackBufferHeight = value; - _graphicsDeviceRepository.GraphicsDeviceManager.ApplyChanges(); - - foreach (var evnt in _resizeEvents) - evnt(this, EventArgs.Empty); + get => _gameWindowRepository.Window.ClientBounds.Height; + set + { + if (value < DEFAULT_BACKBUFFER_HEIGHT) + value = DEFAULT_BACKBUFFER_HEIGHT; + + _graphicsDeviceRepository.GraphicsDeviceManager.PreferredBackBufferHeight = value; + _graphicsDeviceRepository.GraphicsDeviceManager.ApplyChanges(); + + foreach (var evnt in _resizeEvents) + evnt(this, EventArgs.Empty); + } } - } - - public bool Resizable - { - get => _gameWindowRepository.Window.AllowUserResizing; - set => _gameWindowRepository.Window.AllowUserResizing = value; - } - public event EventHandler GameWindowSizeChanged - { - add + public bool Resizable { - _gameWindowRepository.Window.ClientSizeChanged += value; - _resizeEvents.Add(value); + get => _gameWindowRepository.Window.AllowUserResizing; + set => _gameWindowRepository.Window.AllowUserResizing = value; } - remove + + public event EventHandler GameWindowSizeChanged { - _gameWindowRepository.Window.ClientSizeChanged -= value; - _resizeEvents.Remove(value); + add + { + _gameWindowRepository.Window.ClientSizeChanged += value; + _resizeEvents.Add(value); + } + remove + { + _gameWindowRepository.Window.ClientSizeChanged -= value; + _resizeEvents.Remove(value); + } } - } - public ClientWindowSizeRepository(IGameWindowRepository gameWindowRepository, - IGraphicsDeviceRepository graphicsDeviceRepository) - { - _gameWindowRepository = gameWindowRepository; - _graphicsDeviceRepository = graphicsDeviceRepository; - _resizeEvents = new List>(); - } + public ClientWindowSizeRepository(IGameWindowRepository gameWindowRepository, + IGraphicsDeviceRepository graphicsDeviceRepository) + { + _gameWindowRepository = gameWindowRepository; + _graphicsDeviceRepository = graphicsDeviceRepository; + _resizeEvents = new List>(); + } - public void ResetState() - { - foreach (var evnt in _resizeEvents) - GameWindowSizeChanged -= evnt; - _resizeEvents.Clear(); + public void ResetState() + { + foreach (var evnt in _resizeEvents) + GameWindowSizeChanged -= evnt; + _resizeEvents.Clear(); - Resizable = false; + Resizable = false; - Width = DEFAULT_BACKBUFFER_WIDTH; - Height = DEFAULT_BACKBUFFER_HEIGHT; + Width = DEFAULT_BACKBUFFER_WIDTH; + Height = DEFAULT_BACKBUFFER_HEIGHT; + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/ContextMenuRenderer.cs b/EndlessClient/Rendering/ContextMenuRenderer.cs index 5f81e1c06..c58f8d02e 100644 --- a/EndlessClient/Rendering/ContextMenuRenderer.cs +++ b/EndlessClient/Rendering/ContextMenuRenderer.cs @@ -25,333 +25,334 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering; - -public class ContextMenuRenderer : XNAControl, IContextMenuRenderer +namespace EndlessClient.Rendering { - private enum MenuAction - { - Paperdoll, - Book, - Join, - Invite, - Trade, - Whisper, - Friend, - Ignore, - NUM_MENU_ACTIONS - } - - private readonly Texture2D _backgroundTexture, _bgfill; - private readonly Rectangle _outSource, _overSource; - private readonly Dictionary _menuActions; - private Option _overRect; - - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IPaperdollActions _paperdollActions; - private readonly IBookActions _bookActions; - private readonly IPartyActions _partyActions; - private readonly ITradeActions _tradeActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly IHudControlProvider _hudControlProvider; - private readonly IContextMenuRepository _contextMenuRepository; - private readonly IPartyDataProvider _partyDataProvider; - private readonly ICharacterRenderer _characterRenderer; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ISfxPlayer _sfxPlayer; - - private static DateTime? _lastTradeRequestedTime; - private static DateTime? _lastPartyRequestTime; - - public ContextMenuRenderer(INativeGraphicsManager nativeGraphicsManager, - IInGameDialogActions inGameDialogActions, - IPaperdollActions paperdollActions, - IBookActions bookActions, - IPartyActions partyActions, - ITradeActions tradeActions, - IStatusLabelSetter statusLabelSetter, - IFriendIgnoreListService friendIgnoreListService, - IHudControlProvider hudControlProvider, - IContextMenuRepository contextMenuRepository, - IPartyDataProvider partyDataProvider, - ICharacterRenderer characterRenderer, - ICurrentMapStateProvider currentMapStateProvider, - IEOMessageBoxFactory messageBoxFactory, - IClientWindowSizeProvider clientWindowSizeProvider, - ISfxPlayer sfxPlayer) + public class ContextMenuRenderer : XNAControl, IContextMenuRenderer { - _menuActions = new Dictionary(); - _inGameDialogActions = inGameDialogActions; - _paperdollActions = paperdollActions; - _bookActions = bookActions; - _partyActions = partyActions; - _tradeActions = tradeActions; - _statusLabelSetter = statusLabelSetter; - _friendIgnoreListService = friendIgnoreListService; - _hudControlProvider = hudControlProvider; - _contextMenuRepository = contextMenuRepository; - _partyDataProvider = partyDataProvider; - _characterRenderer = characterRenderer; - _currentMapStateProvider = currentMapStateProvider; - _messageBoxFactory = messageBoxFactory; - _clientWindowSizeProvider = clientWindowSizeProvider; - _sfxPlayer = sfxPlayer; - - //first, load up the images. split in half: the right half is the 'over' text - _backgroundTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 41, true); - - const int W = 96, H = 137; - _outSource = new Rectangle(0, 0, W, H); - _overSource = new Rectangle(W, 0, W, H); - - //this GFX is stupid. a bunch of white space throws off coordinates so I have to use hard-coded values - //define regions for clicking and their associated actions - //6,11,86,14 - for (int i = 0; i < (int)MenuAction.NUM_MENU_ACTIONS; ++i) + private enum MenuAction { - Rectangle region = new Rectangle(6, (i < 5 ? 11 : 13) + 14 * i, 86, 14); - _menuActions.Add(region, GetActionFromMenuAction((MenuAction)i)); + Paperdoll, + Book, + Join, + Invite, + Trade, + Whisper, + Friend, + Ignore, + NUM_MENU_ACTIONS } - //set the fill color - _bgfill = new Texture2D(GraphicsDevice, 1, 1); - _bgfill.SetData(new[] { Color.White }); + private readonly Texture2D _backgroundTexture, _bgfill; + private readonly Rectangle _outSource, _overSource; + private readonly Dictionary _menuActions; + private Option _overRect; + + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IPaperdollActions _paperdollActions; + private readonly IBookActions _bookActions; + private readonly IPartyActions _partyActions; + private readonly ITradeActions _tradeActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly IHudControlProvider _hudControlProvider; + private readonly IContextMenuRepository _contextMenuRepository; + private readonly IPartyDataProvider _partyDataProvider; + private readonly ICharacterRenderer _characterRenderer; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ISfxPlayer _sfxPlayer; + + private static DateTime? _lastTradeRequestedTime; + private static DateTime? _lastPartyRequestTime; + + public ContextMenuRenderer(INativeGraphicsManager nativeGraphicsManager, + IInGameDialogActions inGameDialogActions, + IPaperdollActions paperdollActions, + IBookActions bookActions, + IPartyActions partyActions, + ITradeActions tradeActions, + IStatusLabelSetter statusLabelSetter, + IFriendIgnoreListService friendIgnoreListService, + IHudControlProvider hudControlProvider, + IContextMenuRepository contextMenuRepository, + IPartyDataProvider partyDataProvider, + ICharacterRenderer characterRenderer, + ICurrentMapStateProvider currentMapStateProvider, + IEOMessageBoxFactory messageBoxFactory, + IClientWindowSizeProvider clientWindowSizeProvider, + ISfxPlayer sfxPlayer) + { + _menuActions = new Dictionary(); + _inGameDialogActions = inGameDialogActions; + _paperdollActions = paperdollActions; + _bookActions = bookActions; + _partyActions = partyActions; + _tradeActions = tradeActions; + _statusLabelSetter = statusLabelSetter; + _friendIgnoreListService = friendIgnoreListService; + _hudControlProvider = hudControlProvider; + _contextMenuRepository = contextMenuRepository; + _partyDataProvider = partyDataProvider; + _characterRenderer = characterRenderer; + _currentMapStateProvider = currentMapStateProvider; + _messageBoxFactory = messageBoxFactory; + _clientWindowSizeProvider = clientWindowSizeProvider; + _sfxPlayer = sfxPlayer; + + //first, load up the images. split in half: the right half is the 'over' text + _backgroundTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 41, true); + + const int W = 96, H = 137; + _outSource = new Rectangle(0, 0, W, H); + _overSource = new Rectangle(W, 0, W, H); + + //this GFX is stupid. a bunch of white space throws off coordinates so I have to use hard-coded values + //define regions for clicking and their associated actions + //6,11,86,14 + for (int i = 0; i < (int)MenuAction.NUM_MENU_ACTIONS; ++i) + { + Rectangle region = new Rectangle(6, (i < 5 ? 11 : 13) + 14 * i, 86, 14); + _menuActions.Add(region, GetActionFromMenuAction((MenuAction)i)); + } - SetPositionBasedOnCharacterRenderer(_characterRenderer); - SetSize(W, H); + //set the fill color + _bgfill = new Texture2D(GraphicsDevice, 1, 1); + _bgfill.SetData(new[] { Color.White }); - OnMouseOver += ContextMenuRenderer_OnMouseOver; + SetPositionBasedOnCharacterRenderer(_characterRenderer); + SetSize(W, H); - // Update this before map renderer so that clicks are handled first - UpdateOrder = -20; - } + OnMouseOver += ContextMenuRenderer_OnMouseOver; - public override void Initialize() - { - base.Initialize(); + // Update this before map renderer so that clicks are handled first + UpdateOrder = -20; + } - if (!Game.Components.Contains(this)) - Game.Components.Add(this); - } + public override void Initialize() + { + base.Initialize(); - private void SetPositionBasedOnCharacterRenderer(ICharacterRenderer renderer) - { - //rules for draw location: - // 1. try to the right first - if it doesn't fit (width-wise), go to the left - // 2. if it will be out of the game area, move it up/down so that it is not clipped by the screen bounds + if (!Game.Components.Contains(this)) + Game.Components.Add(this); + } - // hide and disable as soon as mouse click either on or out of bounds -- obviously handle event for mouse click on particular text + private void SetPositionBasedOnCharacterRenderer(ICharacterRenderer renderer) + { + //rules for draw location: + // 1. try to the right first - if it doesn't fit (width-wise), go to the left + // 2. if it will be out of the game area, move it up/down so that it is not clipped by the screen bounds - Rectangle rendRect = renderer.DrawArea; + // hide and disable as soon as mouse click either on or out of bounds -- obviously handle event for mouse click on particular text - DrawPosition = new Vector2(rendRect.Right + 20, rendRect.Y); + Rectangle rendRect = renderer.DrawArea; - if (DrawArea.Right > _clientWindowSizeProvider.Width - 15) - { - // case: goes off the right side of the screen, show on the left - DrawPosition = new Vector2(rendRect.X - DrawArea.Width - 20, DrawPosition.Y); - } + DrawPosition = new Vector2(rendRect.Right + 20, rendRect.Y); - // 308px is the bottom of the display area for map stuff - if (DrawArea.Bottom > (_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Height : 308)) - { - //case: goes off bottom of the screen, adjust new rectangle so it is above 308 - DrawPosition = new Vector2(DrawPosition.X, 298 - DrawArea.Height); + if (DrawArea.Right > _clientWindowSizeProvider.Width - 15) + { + // case: goes off the right side of the screen, show on the left + DrawPosition = new Vector2(rendRect.X - DrawArea.Width - 20, DrawPosition.Y); + } + + // 308px is the bottom of the display area for map stuff + if (DrawArea.Bottom > (_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Height : 308)) + { + //case: goes off bottom of the screen, adjust new rectangle so it is above 308 + DrawPosition = new Vector2(DrawPosition.X, 298 - DrawArea.Height); + } + else if (DrawArea.Y < 25) + { + //case: goes off top of screen, adjust new rectangle so it aligns with top of character head + DrawPosition = new Vector2(DrawPosition.X, 35); + } + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_MENU_BELONGS_TO_PLAYER, $" {renderer.Character.Name}"); } - else if (DrawArea.Y < 25) + + protected override bool ShouldUpdate() { - //case: goes off top of screen, adjust new rectangle so it aligns with top of character head - DrawPosition = new Vector2(DrawPosition.X, 35); + return base.ShouldUpdate(); } - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_MENU_BELONGS_TO_PLAYER, $" {renderer.Character.Name}"); - } - - protected override bool ShouldUpdate() - { - return base.ShouldUpdate(); - } - - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); - _spriteBatch.Draw(_bgfill, DrawAreaWithParentOffset, Color.FromNonPremultiplied(0xff, 0xff, 0xff, 192)); + _spriteBatch.Draw(_bgfill, DrawAreaWithParentOffset, Color.FromNonPremultiplied(0xff, 0xff, 0xff, 192)); - _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _outSource, Color.White); - _overRect.MatchSome(r => - { - _spriteBatch.Draw(_backgroundTexture, - new Vector2(DrawAreaWithParentOffset.X, DrawAreaWithParentOffset.Y) + new Vector2(r.X, r.Y), - r.WithPosition(new Vector2(r.X + _overSource.X, r.Y + _overSource.Y)), - Color.White); - }); + _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _outSource, Color.White); + _overRect.MatchSome(r => + { + _spriteBatch.Draw(_backgroundTexture, + new Vector2(DrawAreaWithParentOffset.X, DrawAreaWithParentOffset.Y) + new Vector2(r.X, r.Y), + r.WithPosition(new Vector2(r.X + _overSource.X, r.Y + _overSource.Y)), + Color.White); + }); - _spriteBatch.End(); + _spriteBatch.End(); - base.OnDrawControl(gameTime); - } + base.OnDrawControl(gameTime); + } - private void ContextMenuRenderer_OnMouseOver(object sender, MouseStateExtended e) - { - bool found = false; - foreach (var (sourceRect, menuAction) in _menuActions) + private void ContextMenuRenderer_OnMouseOver(object sender, MouseStateExtended e) { - if (sourceRect.Contains(e.Position - DrawAreaWithParentOffset.Location)) + bool found = false; + foreach (var (sourceRect, menuAction) in _menuActions) { - _overRect = Option.Some(sourceRect); - found = true; - break; + if (sourceRect.Contains(e.Position - DrawAreaWithParentOffset.Location)) + { + _overRect = Option.Some(sourceRect); + found = true; + break; + } } - } - if (!found) - { - _overRect = Option.None(); + if (!found) + { + _overRect = Option.None(); + } } - } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - if (eventArgs.Button == MouseButton.Left) + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) { - _overRect.MatchSome(sourceRect => + if (eventArgs.Button == MouseButton.Left) { - if (!_menuActions.ContainsKey(sourceRect)) return; + _overRect.MatchSome(sourceRect => + { + if (!_menuActions.ContainsKey(sourceRect)) return; - var menuAction = _menuActions[sourceRect]; - menuAction(); - }); - } + var menuAction = _menuActions[sourceRect]; + menuAction(); + }); + } - _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); + _sfxPlayer.PlaySfx(SoundEffectID.DialogButtonClick); - Game.Components.Remove(this); - Dispose(); + Game.Components.Remove(this); + Dispose(); - _contextMenuRepository.ContextMenu = Option.None(); + _contextMenuRepository.ContextMenu = Option.None(); - return true; - } + return true; + } - /* Helper maps MenuAction enum value to a member method for easy initialization */ - private Action GetActionFromMenuAction(MenuAction menuAction) - { - switch (menuAction) + /* Helper maps MenuAction enum value to a member method for easy initialization */ + private Action GetActionFromMenuAction(MenuAction menuAction) { - case MenuAction.Paperdoll: return ShowPaperdollAction; - case MenuAction.Book: return ShowBook; - case MenuAction.Join: return JoinParty; - case MenuAction.Invite: return InviteToParty; - case MenuAction.Trade: return Trade; - case MenuAction.Whisper: return PrivateMessage; - case MenuAction.Friend: return AddFriend; - case MenuAction.Ignore: return AddIgnore; - default: throw new ArgumentOutOfRangeException(nameof(menuAction)); + switch (menuAction) + { + case MenuAction.Paperdoll: return ShowPaperdollAction; + case MenuAction.Book: return ShowBook; + case MenuAction.Join: return JoinParty; + case MenuAction.Invite: return InviteToParty; + case MenuAction.Trade: return Trade; + case MenuAction.Whisper: return PrivateMessage; + case MenuAction.Friend: return AddFriend; + case MenuAction.Ignore: return AddIgnore; + default: throw new ArgumentOutOfRangeException(nameof(menuAction)); + } } - } - private void ShowPaperdollAction() - { - _paperdollActions.RequestPaperdoll(_characterRenderer.Character.ID); - _inGameDialogActions.ShowPaperdollDialog(_characterRenderer.Character, isMainCharacter: false); - } - - private void ShowBook() - { - _bookActions.RequestBook(_characterRenderer.Character.ID); - _inGameDialogActions.ShowBookDialog(_characterRenderer.Character, isMainCharacter: false); - } - - private void JoinParty() - { - if (_partyDataProvider.Members.Any(x => x.CharacterID == _characterRenderer.Character.ID)) + private void ShowPaperdollAction() { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, _characterRenderer.Character.Name + " ", EOResourceID.STATUS_LABEL_PARTY_IS_ALREADY_MEMBER, showChatError: true); - return; + _paperdollActions.RequestPaperdoll(_characterRenderer.Character.ID); + _inGameDialogActions.ShowPaperdollDialog(_characterRenderer.Character, isMainCharacter: false); } - if (_lastPartyRequestTime != null && (DateTime.Now - _lastPartyRequestTime.Value).TotalSeconds < Constants.PartyRequestTimeoutSeconds) + private void ShowBook() { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_PARTY_RECENTLY_REQUESTED, showChatError: true); - return; + _bookActions.RequestBook(_characterRenderer.Character.ID); + _inGameDialogActions.ShowBookDialog(_characterRenderer.Character, isMainCharacter: false); } - _lastPartyRequestTime = DateTime.Now; - _partyActions.RequestParty(PartyRequestType.Join, _characterRenderer.Character.ID); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_PARTY_REQUESTED_TO_JOIN); - } - - private void InviteToParty() - { - if (_partyDataProvider.Members.Any(x => x.CharacterID == _characterRenderer.Character.ID)) + private void JoinParty() { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, _characterRenderer.Character.Name + " ", EOResourceID.STATUS_LABEL_PARTY_IS_ALREADY_MEMBER, showChatError: true); - return; + if (_partyDataProvider.Members.Any(x => x.CharacterID == _characterRenderer.Character.ID)) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, _characterRenderer.Character.Name + " ", EOResourceID.STATUS_LABEL_PARTY_IS_ALREADY_MEMBER, showChatError: true); + return; + } + + if (_lastPartyRequestTime != null && (DateTime.Now - _lastPartyRequestTime.Value).TotalSeconds < Constants.PartyRequestTimeoutSeconds) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_PARTY_RECENTLY_REQUESTED, showChatError: true); + return; + } + + _lastPartyRequestTime = DateTime.Now; + _partyActions.RequestParty(PartyRequestType.Join, _characterRenderer.Character.ID); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_PARTY_REQUESTED_TO_JOIN); } - if (_lastPartyRequestTime != null && (DateTime.Now - _lastPartyRequestTime.Value).TotalSeconds < Constants.PartyRequestTimeoutSeconds) + private void InviteToParty() { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_PARTY_RECENTLY_REQUESTED, showChatError: true); - return; - } + if (_partyDataProvider.Members.Any(x => x.CharacterID == _characterRenderer.Character.ID)) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, _characterRenderer.Character.Name + " ", EOResourceID.STATUS_LABEL_PARTY_IS_ALREADY_MEMBER, showChatError: true); + return; + } - _lastPartyRequestTime = DateTime.Now; - _partyActions.RequestParty(PartyRequestType.Invite, _characterRenderer.Character.ID); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, _characterRenderer.Character.Name, EOResourceID.STATUS_LABEL_PARTY_IS_INVITED); - } + if (_lastPartyRequestTime != null && (DateTime.Now - _lastPartyRequestTime.Value).TotalSeconds < Constants.PartyRequestTimeoutSeconds) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_PARTY_RECENTLY_REQUESTED, showChatError: true); + return; + } - private void Trade() - { - if (_currentMapStateProvider.IsJail) - { - _messageBoxFactory.CreateMessageBox(EOResourceID.JAIL_WARNING_CANNOT_TRADE, EOResourceID.STATUS_LABEL_TYPE_WARNING).ShowDialog(); - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_TRADE); - return; + _lastPartyRequestTime = DateTime.Now; + _partyActions.RequestParty(PartyRequestType.Invite, _characterRenderer.Character.ID); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, _characterRenderer.Character.Name, EOResourceID.STATUS_LABEL_PARTY_IS_INVITED); } - if (_lastTradeRequestedTime != null && (DateTime.Now - _lastTradeRequestedTime.Value).TotalSeconds < Constants.TradeRequestTimeoutSeconds) + private void Trade() { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_TRADE_RECENTLY_REQUESTED); - return; - } + if (_currentMapStateProvider.IsJail) + { + _messageBoxFactory.CreateMessageBox(EOResourceID.JAIL_WARNING_CANNOT_TRADE, EOResourceID.STATUS_LABEL_TYPE_WARNING).ShowDialog(); + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.JAIL_WARNING_CANNOT_TRADE); + return; + } - _lastTradeRequestedTime = DateTime.Now; + if (_lastTradeRequestedTime != null && (DateTime.Now - _lastTradeRequestedTime.Value).TotalSeconds < Constants.TradeRequestTimeoutSeconds) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_WARNING, EOResourceID.STATUS_LABEL_TRADE_RECENTLY_REQUESTED); + return; + } - _tradeActions.RequestTrade(_characterRenderer.Character.ID); + _lastTradeRequestedTime = DateTime.Now; - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_TRADE_REQUESTED_TO_TRADE); - } + _tradeActions.RequestTrade(_characterRenderer.Character.ID); - private void PrivateMessage() - { - _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{_characterRenderer.Character.Name} "; - } + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_TRADE_REQUESTED_TO_TRADE); + } - private void AddFriend() - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, $"{_characterRenderer.Character.Name} ", EOResourceID.STATUS_LABEL_WILL_BE_YOUR_FRIEND); - _friendIgnoreListService.SaveNewFriend(Constants.FriendListFile, _characterRenderer.Character.Name); - } + private void PrivateMessage() + { + _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox).Text = $"!{_characterRenderer.Character.Name} "; + } - private void AddIgnore() - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, $"{_characterRenderer.Character.Name} ", EOResourceID.STATUS_LABEL_WILL_BE_IGNORED); - _friendIgnoreListService.SaveNewIgnore(Constants.IgnoreListFile, _characterRenderer.Character.Name); - } + private void AddFriend() + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, $"{_characterRenderer.Character.Name} ", EOResourceID.STATUS_LABEL_WILL_BE_YOUR_FRIEND); + _friendIgnoreListService.SaveNewFriend(Constants.FriendListFile, _characterRenderer.Character.Name); + } - protected override void Dispose(bool disposing) - { - if (disposing) - _bgfill.Dispose(); + private void AddIgnore() + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, $"{_characterRenderer.Character.Name} ", EOResourceID.STATUS_LABEL_WILL_BE_IGNORED); + _friendIgnoreListService.SaveNewIgnore(Constants.IgnoreListFile, _characterRenderer.Character.Name); + } - base.Dispose(disposing); + protected override void Dispose(bool disposing) + { + if (disposing) + _bgfill.Dispose(); + + base.Dispose(disposing); + } } -} -public interface IContextMenuRenderer : IXNAControl -{ + public interface IContextMenuRenderer : IXNAControl + { + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/ContextMenuRepository.cs b/EndlessClient/Rendering/ContextMenuRepository.cs index a30d5a919..f0650e66a 100644 --- a/EndlessClient/Rendering/ContextMenuRepository.cs +++ b/EndlessClient/Rendering/ContextMenuRepository.cs @@ -1,25 +1,26 @@ using AutomaticTypeMapper; using Optional; -namespace EndlessClient.Rendering; - -public interface IContextMenuProvider -{ - Option ContextMenu { get; } -} - -public interface IContextMenuRepository +namespace EndlessClient.Rendering { - Option ContextMenu { get; set; } -} + public interface IContextMenuProvider + { + Option ContextMenu { get; } + } -[AutoMappedType(IsSingleton = true)] -public class ContextMenuRepository : IContextMenuProvider, IContextMenuRepository -{ - public Option ContextMenu { get; set; } + public interface IContextMenuRepository + { + Option ContextMenu { get; set; } + } - public ContextMenuRepository() + [AutoMappedType(IsSingleton = true)] + public class ContextMenuRepository : IContextMenuProvider, IContextMenuRepository { - ContextMenu = Option.None(); + public Option ContextMenu { get; set; } + + public ContextMenuRepository() + { + ContextMenu = Option.None(); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/DispatcherGameComponent.cs b/EndlessClient/Rendering/DispatcherGameComponent.cs index 2c27c5c26..66eeded55 100644 --- a/EndlessClient/Rendering/DispatcherGameComponent.cs +++ b/EndlessClient/Rendering/DispatcherGameComponent.cs @@ -7,41 +7,42 @@ using System.Threading; using System.Threading.Tasks; -namespace EndlessClient.Rendering; - -[MappedType(BaseType = typeof(IGameComponent), IsSingleton = true)] -public class DispatcherGameComponent : GameComponent +namespace EndlessClient.Rendering { - private static readonly object _queuelocker_ = new object(); - private static readonly Queue _actions = new Queue(); - private static readonly SemaphoreSlim _signal = new SemaphoreSlim(0); - - public DispatcherGameComponent(IEndlessGameProvider endlessGameProvider) - : base((Game)endlessGameProvider.Game) + [MappedType(BaseType = typeof(IGameComponent), IsSingleton = true)] + public class DispatcherGameComponent : GameComponent { - } + private static readonly object _queuelocker_ = new object(); + private static readonly Queue _actions = new Queue(); + private static readonly SemaphoreSlim _signal = new SemaphoreSlim(0); - public static async Task Invoke(Action action) - { - lock (_queuelocker_) + public DispatcherGameComponent(IEndlessGameProvider endlessGameProvider) + : base((Game)endlessGameProvider.Game) { - _actions.Enqueue(action); } - await _signal.WaitAsync().ConfigureAwait(false); - } - - public override void Update(GameTime gameTime) - { - lock (_queuelocker_) + public static async Task Invoke(Action action) { - if (_actions.Any()) + lock (_queuelocker_) { - _actions.Dequeue().Invoke(); - _signal.Release(); + _actions.Enqueue(action); } + + await _signal.WaitAsync().ConfigureAwait(false); } - base.Update(gameTime); + public override void Update(GameTime gameTime) + { + lock (_queuelocker_) + { + if (_actions.Any()) + { + _actions.Dequeue().Invoke(); + _signal.Release(); + } + } + + base.Update(gameTime); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectAnimationType.cs b/EndlessClient/Rendering/Effects/EffectAnimationType.cs index 342d22fe7..3792c38b3 100644 --- a/EndlessClient/Rendering/Effects/EffectAnimationType.cs +++ b/EndlessClient/Rendering/Effects/EffectAnimationType.cs @@ -1,11 +1,12 @@ using System; -namespace EndlessClient.Rendering.Effects; - -public enum EffectAnimationType +namespace EndlessClient.Rendering.Effects { - Static = 0, - VerticalSliding = 1, - Position = 2, - Flickering = 3 + public enum EffectAnimationType + { + Static = 0, + VerticalSliding = 1, + Position = 2, + Flickering = 3 + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectLayer.cs b/EndlessClient/Rendering/Effects/EffectLayer.cs index 380a35781..c5a37cd24 100644 --- a/EndlessClient/Rendering/Effects/EffectLayer.cs +++ b/EndlessClient/Rendering/Effects/EffectLayer.cs @@ -1,8 +1,9 @@ -namespace EndlessClient.Rendering.Effects; - -public enum EffectLayer +namespace EndlessClient.Rendering.Effects { - Behind, - Transparent, - InFront + public enum EffectLayer + { + Behind, + Transparent, + InFront + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectRenderer.cs b/EndlessClient/Rendering/Effects/EffectRenderer.cs index d4bc8289c..d23ae9644 100644 --- a/EndlessClient/Rendering/Effects/EffectRenderer.cs +++ b/EndlessClient/Rendering/Effects/EffectRenderer.cs @@ -13,207 +13,208 @@ using DomainCharacter = EOLib.Domain.Character.Character; using DomainNPC = EOLib.Domain.NPC.NPC; -namespace EndlessClient.Rendering.Effects; - -public enum EffectState -{ - Stopped, - Playing, -} - -public sealed class EffectRenderer : IEffectRenderer +namespace EndlessClient.Rendering.Effects { - private readonly IEffectSpriteManager _effectSpriteManager; - private readonly ISfxPlayer _sfxPlayer; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly ICharacterProvider _characterProvider; - - private Option _targetCoordinate; - private Option _targetActor; - - private EffectMetadata _metadata; - private IList _effectInfo; - private Stopwatch _lastFrameTimer; - - private int _nextEffectID; - private Option _nextTargetCoordinate; - - public int EffectID { get; private set; } - - public EffectState State { get; private set; } - - public EffectRenderer(IEffectSpriteManager effectSpriteManager, - ISfxPlayer sfxPlayer, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IRenderOffsetCalculator renderOffsetCalculator, - ICharacterProvider characterProvider) + public enum EffectState { - _effectSpriteManager = effectSpriteManager; - _sfxPlayer = sfxPlayer; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _renderOffsetCalculator = renderOffsetCalculator; - _characterProvider = characterProvider; - _lastFrameTimer = new Stopwatch(); - _effectInfo = new List(); + Stopped, + Playing, } - public void PlayEffect(int effectID, MapCoordinate target) + public sealed class EffectRenderer : IEffectRenderer { - EffectID = effectID; - _targetCoordinate = Option.Some(target); - StartPlaying(); - } + private readonly IEffectSpriteManager _effectSpriteManager; + private readonly ISfxPlayer _sfxPlayer; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly ICharacterProvider _characterProvider; - public void PlayEffect(int effectID, IMapActor target) - { - EffectID = effectID; - _targetActor = Option.Some(target); - StartPlaying(); - } + private Option _targetCoordinate; + private Option _targetActor; - public void QueueEffect(int effectID, MapCoordinate target) - { - _nextEffectID = effectID; - _nextTargetCoordinate = Option.Some(target); - } + private EffectMetadata _metadata; + private IList _effectInfo; + private Stopwatch _lastFrameTimer; - public void Restart() - { - if (State != EffectState.Playing) - return; + private int _nextEffectID; + private Option _nextTargetCoordinate; - foreach (var effect in _effectInfo) - effect.Restart(); + public int EffectID { get; private set; } - State = EffectState.Playing; + public EffectState State { get; private set; } - if (_metadata.SoundEffect != SoundEffectID.NONE) + public EffectRenderer(IEffectSpriteManager effectSpriteManager, + ISfxPlayer sfxPlayer, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IRenderOffsetCalculator renderOffsetCalculator, + ICharacterProvider characterProvider) { - _sfxPlayer.PlaySfx(_metadata.SoundEffect); + _effectSpriteManager = effectSpriteManager; + _sfxPlayer = sfxPlayer; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _renderOffsetCalculator = renderOffsetCalculator; + _characterProvider = characterProvider; + _lastFrameTimer = new Stopwatch(); + _effectInfo = new List(); } - } - public void Update() - { - if (!_effectInfo.Any()) - return; + public void PlayEffect(int effectID, MapCoordinate target) + { + EffectID = effectID; + _targetCoordinate = Option.Some(target); + StartPlaying(); + } - if (_lastFrameTimer.ElapsedMilliseconds >= 120) + public void PlayEffect(int effectID, IMapActor target) { - _lastFrameTimer.Restart(); - _effectInfo.ToList().ForEach(ei => ei.NextFrame()); + EffectID = effectID; + _targetActor = Option.Some(target); + StartPlaying(); + } - var doneEffects = _effectInfo.Where(ei => ei.Done); - doneEffects.ToList().ForEach(ei => _effectInfo.Remove(ei)); + public void QueueEffect(int effectID, MapCoordinate target) + { + _nextEffectID = effectID; + _nextTargetCoordinate = Option.Some(target); } - if (!_effectInfo.Any()) + public void Restart() { - State = EffectState.Stopped; - _lastFrameTimer.Stop(); + if (State != EffectState.Playing) + return; - _nextTargetCoordinate.MatchSome(_ => - { - EffectID = _nextEffectID; - _nextEffectID = 0; + foreach (var effect in _effectInfo) + effect.Restart(); + + State = EffectState.Playing; - _targetCoordinate = _nextTargetCoordinate; - _nextTargetCoordinate = Option.None(); - StartPlaying(); - }); + if (_metadata.SoundEffect != SoundEffectID.NONE) + { + _sfxPlayer.PlaySfx(_metadata.SoundEffect); + } } - } - public void DrawBehindTarget(SpriteBatch sb, bool beginHasBeenCalled = true) - { - if (!_effectInfo.Any()) - return; + public void Update() + { + if (!_effectInfo.Any()) + return; - DrawEffects(sb, beginHasBeenCalled, _effectInfo.Where(x => !x.OnTopOfCharacter)); - } + if (_lastFrameTimer.ElapsedMilliseconds >= 120) + { + _lastFrameTimer.Restart(); + _effectInfo.ToList().ForEach(ei => ei.NextFrame()); - public void DrawInFrontOfTarget(SpriteBatch sb, bool beginHasBeenCalled = true) - { - if (!_effectInfo.Any()) - return; + var doneEffects = _effectInfo.Where(ei => ei.Done); + doneEffects.ToList().ForEach(ei => _effectInfo.Remove(ei)); + } - DrawEffects(sb, beginHasBeenCalled, _effectInfo.Where(x => x.OnTopOfCharacter)); - } + if (!_effectInfo.Any()) + { + State = EffectState.Stopped; + _lastFrameTimer.Stop(); - private void StartPlaying() - { - _lastFrameTimer.Restart(); + _nextTargetCoordinate.MatchSome(_ => + { + EffectID = _nextEffectID; + _nextEffectID = 0; + + _targetCoordinate = _nextTargetCoordinate; + _nextTargetCoordinate = Option.None(); + StartPlaying(); + }); + } + } - _metadata = _effectSpriteManager.GetEffectMetadata(EffectID); - _effectInfo = _effectSpriteManager.GetEffectInfo(EffectID, _metadata); + public void DrawBehindTarget(SpriteBatch sb, bool beginHasBeenCalled = true) + { + if (!_effectInfo.Any()) + return; - State = EffectState.Playing; + DrawEffects(sb, beginHasBeenCalled, _effectInfo.Where(x => !x.OnTopOfCharacter)); + } - if (_metadata.SoundEffect != SoundEffectID.NONE) + public void DrawInFrontOfTarget(SpriteBatch sb, bool beginHasBeenCalled = true) { - _sfxPlayer.PlaySfx(_metadata.SoundEffect); + if (!_effectInfo.Any()) + return; + + DrawEffects(sb, beginHasBeenCalled, _effectInfo.Where(x => x.OnTopOfCharacter)); } - } - private void DrawEffects(SpriteBatch sb, bool beginHasBeenCalled, IEnumerable effectSprites) - { - if (!beginHasBeenCalled) - sb.Begin(); + private void StartPlaying() + { + _lastFrameTimer.Restart(); - var targetBasePosition = _targetCoordinate.Match( - some: c => _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c), - none: () => _targetActor.Match( - some: actor => - { - return actor.SpellTarget switch - { - DomainCharacter c => GetCharacterBasePosition(c), - DomainNPC n => GetNPCBasePosition(n), - _ => Vector2.Zero - }; - }, - none: () => Vector2.Zero)); - - foreach (var effectInfo in effectSprites) + _metadata = _effectSpriteManager.GetEffectMetadata(EffectID); + _effectInfo = _effectSpriteManager.GetEffectInfo(EffectID, _metadata); + + State = EffectState.Playing; + + if (_metadata.SoundEffect != SoundEffectID.NONE) + { + _sfxPlayer.PlaySfx(_metadata.SoundEffect); + } + } + + private void DrawEffects(SpriteBatch sb, bool beginHasBeenCalled, IEnumerable effectSprites) { - effectInfo.DrawToSpriteBatch(sb, targetBasePosition); + if (!beginHasBeenCalled) + sb.Begin(); + + var targetBasePosition = _targetCoordinate.Match( + some: c => _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c), + none: () => _targetActor.Match( + some: actor => + { + return actor.SpellTarget switch + { + DomainCharacter c => GetCharacterBasePosition(c), + DomainNPC n => GetNPCBasePosition(n), + _ => Vector2.Zero + }; + }, + none: () => Vector2.Zero)); + + foreach (var effectInfo in effectSprites) + { + effectInfo.DrawToSpriteBatch(sb, targetBasePosition); + } + + if (!beginHasBeenCalled) + sb.End(); } - if (!beginHasBeenCalled) - sb.End(); - } + private Vector2 GetCharacterBasePosition(DomainCharacter c) + { + var walkExtra = new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(c.RenderProperties), _renderOffsetCalculator.CalculateWalkAdjustY(c.RenderProperties)); + return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c.RenderProperties.Coordinates()) + walkExtra; + } - private Vector2 GetCharacterBasePosition(DomainCharacter c) - { - var walkExtra = new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(c.RenderProperties), _renderOffsetCalculator.CalculateWalkAdjustY(c.RenderProperties)); - return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c.RenderProperties.Coordinates()) + walkExtra; + private Vector2 GetNPCBasePosition(DomainNPC n) + { + var walkExtra = new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(n), _renderOffsetCalculator.CalculateWalkAdjustY(n)); + return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(n.X, n.Y) + walkExtra; + } } - private Vector2 GetNPCBasePosition(DomainNPC n) + public interface IEffectRenderer { - var walkExtra = new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(n), _renderOffsetCalculator.CalculateWalkAdjustY(n)); - return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(n.X, n.Y) + walkExtra; - } -} - -public interface IEffectRenderer -{ - int EffectID { get; } + int EffectID { get; } - EffectState State { get; } + EffectState State { get; } - void PlayEffect(int effectID, MapCoordinate target); + void PlayEffect(int effectID, MapCoordinate target); - void PlayEffect(int effectID, IMapActor target); + void PlayEffect(int effectID, IMapActor target); - void QueueEffect(int effectID, MapCoordinate target); + void QueueEffect(int effectID, MapCoordinate target); - void Restart(); + void Restart(); - void Update(); + void Update(); - void DrawBehindTarget(SpriteBatch sb, bool beginHasBeenCalled = true); + void DrawBehindTarget(SpriteBatch sb, bool beginHasBeenCalled = true); - void DrawInFrontOfTarget(SpriteBatch sb, bool beginHasBeenCalled = true); + void DrawInFrontOfTarget(SpriteBatch sb, bool beginHasBeenCalled = true); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectRendererFactory.cs b/EndlessClient/Rendering/Effects/EffectRendererFactory.cs index 1b9c1abea..04354f61a 100644 --- a/EndlessClient/Rendering/Effects/EffectRendererFactory.cs +++ b/EndlessClient/Rendering/Effects/EffectRendererFactory.cs @@ -2,37 +2,38 @@ using EndlessClient.Audio; using EOLib.Domain.Character; -namespace EndlessClient.Rendering.Effects; - -[AutoMappedType] -public class EffectRendererFactory : IEffectRendererFactory +namespace EndlessClient.Rendering.Effects { - private readonly IEffectSpriteManager _effectSpriteManager; - private readonly ISfxPlayer _sfxPlayer; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly ICharacterProvider _characterProvider; - - public EffectRendererFactory(IEffectSpriteManager effectSpriteManager, - ISfxPlayer sfxPlayer, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IRenderOffsetCalculator renderOffsetCalculator, - ICharacterProvider characterProvider) + [AutoMappedType] + public class EffectRendererFactory : IEffectRendererFactory { - _effectSpriteManager = effectSpriteManager; - _sfxPlayer = sfxPlayer; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _renderOffsetCalculator = renderOffsetCalculator; - _characterProvider = characterProvider; + private readonly IEffectSpriteManager _effectSpriteManager; + private readonly ISfxPlayer _sfxPlayer; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly ICharacterProvider _characterProvider; + + public EffectRendererFactory(IEffectSpriteManager effectSpriteManager, + ISfxPlayer sfxPlayer, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IRenderOffsetCalculator renderOffsetCalculator, + ICharacterProvider characterProvider) + { + _effectSpriteManager = effectSpriteManager; + _sfxPlayer = sfxPlayer; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _renderOffsetCalculator = renderOffsetCalculator; + _characterProvider = characterProvider; + } + + public IEffectRenderer Create() + { + return new EffectRenderer(_effectSpriteManager, _sfxPlayer, _gridDrawCoordinateCalculator, _renderOffsetCalculator, _characterProvider); + } } - public IEffectRenderer Create() + public interface IEffectRendererFactory { - return new EffectRenderer(_effectSpriteManager, _sfxPlayer, _gridDrawCoordinateCalculator, _renderOffsetCalculator, _characterProvider); + IEffectRenderer Create(); } -} - -public interface IEffectRendererFactory -{ - IEffectRenderer Create(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs b/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs index f93574bf9..5e19c8081 100644 --- a/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs +++ b/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs @@ -5,112 +5,113 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering.Effects; - -public class EffectSpriteInfo : IEffectSpriteInfo +namespace EndlessClient.Rendering.Effects { - private readonly EffectMetadata _metadata; - private readonly EffectLayer _layer; - private readonly Texture2D _graphic; - private readonly Random _random; + public class EffectSpriteInfo : IEffectSpriteInfo + { + private readonly EffectMetadata _metadata; + private readonly EffectLayer _layer; + private readonly Texture2D _graphic; + private readonly Random _random; - private int _displayFrame = -1; - private int _actualFrame; - private int _iterations; + private int _displayFrame = -1; + private int _actualFrame; + private int _iterations; - public bool OnTopOfCharacter => _layer != EffectLayer.Behind; - public bool Done => _iterations == _metadata.Loops; + public bool OnTopOfCharacter => _layer != EffectLayer.Behind; + public bool Done => _iterations == _metadata.Loops; - public EffectSpriteInfo(EffectMetadata metadata, - EffectLayer layer, - Texture2D graphic) - { - _metadata = metadata; - _layer = layer; - _graphic = graphic; - _random = new Random(); + public EffectSpriteInfo(EffectMetadata metadata, + EffectLayer layer, + Texture2D graphic) + { + _metadata = metadata; + _layer = layer; + _graphic = graphic; + _random = new Random(); - _displayFrame = GetDisplayFrame(); - } + _displayFrame = GetDisplayFrame(); + } - public void NextFrame() - { - if (Done) return; + public void NextFrame() + { + if (Done) return; - _displayFrame = GetDisplayFrame(); - _actualFrame++; + _displayFrame = GetDisplayFrame(); + _actualFrame++; - if (_actualFrame >= _metadata.Frames) + if (_actualFrame >= _metadata.Frames) + { + ResetFrame(); + _iterations++; + } + } + + public void Restart() { ResetFrame(); - _iterations++; + _iterations = 0; } - } - - public void Restart() - { - ResetFrame(); - _iterations = 0; - } - public void DrawToSpriteBatch(SpriteBatch sb, Vector2 gridCoordinatePosition) - { - var sourceRect = GetFrameSourceRectangle(); - var drawLocation = GetDrawLocation(sourceRect, gridCoordinatePosition); - var alpha = _layer == EffectLayer.Transparent ? 128 : 255; + public void DrawToSpriteBatch(SpriteBatch sb, Vector2 gridCoordinatePosition) + { + var sourceRect = GetFrameSourceRectangle(); + var drawLocation = GetDrawLocation(sourceRect, gridCoordinatePosition); + var alpha = _layer == EffectLayer.Transparent ? 128 : 255; - sb.Draw(_graphic, drawLocation, sourceRect, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } + sb.Draw(_graphic, drawLocation, sourceRect, Color.FromNonPremultiplied(255, 255, 255, alpha)); + } - private Rectangle GetFrameSourceRectangle() - { - var frameWidth = _graphic.Width / _metadata.Frames; - return new Rectangle(_displayFrame * frameWidth, 0, frameWidth, _graphic.Height); - } + private Rectangle GetFrameSourceRectangle() + { + var frameWidth = _graphic.Width / _metadata.Frames; + return new Rectangle(_displayFrame * frameWidth, 0, frameWidth, _graphic.Height); + } - private Vector2 GetDrawLocation(Rectangle textureSourceRectangle, Vector2 gridCoordinatePosition) - { - const int GridWidth = 64; + private Vector2 GetDrawLocation(Rectangle textureSourceRectangle, Vector2 gridCoordinatePosition) + { + const int GridWidth = 64; - var targetX = gridCoordinatePosition.X + (GridWidth - textureSourceRectangle.Width) / 2; - var targetY = gridCoordinatePosition.Y - (textureSourceRectangle.Height - (36 + (int)Math.Floor((textureSourceRectangle.Height - 100) / 2.0))); + var targetX = gridCoordinatePosition.X + (GridWidth - textureSourceRectangle.Width) / 2; + var targetY = gridCoordinatePosition.Y - (textureSourceRectangle.Height - (36 + (int)Math.Floor((textureSourceRectangle.Height - 100) / 2.0))); - var slidingMetadata = _metadata.VerticalSlidingMetadata ?? new VerticalSlidingEffectMetadata(0); - var positionMetadata = _metadata.PositionOffsetMetadata ?? new PositionOffsetEffectMetadata(new List(), new List()); + var slidingMetadata = _metadata.VerticalSlidingMetadata ?? new VerticalSlidingEffectMetadata(0); + var positionMetadata = _metadata.PositionOffsetMetadata ?? new PositionOffsetEffectMetadata(new List(), new List()); - var additionalX = _metadata.AnimationType switch - { - EffectAnimationType.Position => positionMetadata.OffsetXByFrame.Count < _displayFrame ? positionMetadata.OffsetXByFrame[_displayFrame] : 0, - _ => 0 - }; + var additionalX = _metadata.AnimationType switch + { + EffectAnimationType.Position => positionMetadata.OffsetXByFrame.Count < _displayFrame ? positionMetadata.OffsetXByFrame[_displayFrame] : 0, + _ => 0 + }; - var additionalY = _metadata.AnimationType switch - { - EffectAnimationType.VerticalSliding => slidingMetadata.FrameOffsetY * _displayFrame, - EffectAnimationType.Position => positionMetadata.OffsetYByFrame.Count < _displayFrame ? positionMetadata.OffsetYByFrame[_displayFrame] : 0, - _ => 0 - }; + var additionalY = _metadata.AnimationType switch + { + EffectAnimationType.VerticalSliding => slidingMetadata.FrameOffsetY * _displayFrame, + EffectAnimationType.Position => positionMetadata.OffsetYByFrame.Count < _displayFrame ? positionMetadata.OffsetYByFrame[_displayFrame] : 0, + _ => 0 + }; - return new Vector2(targetX + _metadata.OffsetX + additionalX, targetY + _metadata.OffsetY + additionalY); - } + return new Vector2(targetX + _metadata.OffsetX + additionalX, targetY + _metadata.OffsetY + additionalY); + } - private int GetDisplayFrame() - { - return _metadata.AnimationType switch + private int GetDisplayFrame() { - EffectAnimationType.Flickering => - _random.Next( - _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0, - 1 + (_metadata.RandomFlickeringMetadata?.LastFrame ?? _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0)), - _ => _displayFrame + 1 - }; - } + return _metadata.AnimationType switch + { + EffectAnimationType.Flickering => + _random.Next( + _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0, + 1 + (_metadata.RandomFlickeringMetadata?.LastFrame ?? _metadata.RandomFlickeringMetadata?.FirstFrame ?? 0)), + _ => _displayFrame + 1 + }; + } - private void ResetFrame() - { - _actualFrame = 0; + private void ResetFrame() + { + _actualFrame = 0; - if (_metadata.AnimationType != EffectAnimationType.Flickering) - _displayFrame = 0; + if (_metadata.AnimationType != EffectAnimationType.Flickering) + _displayFrame = 0; + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/EffectSpriteManager.cs b/EndlessClient/Rendering/Effects/EffectSpriteManager.cs index 40fc5f3a2..e04c60a53 100644 --- a/EndlessClient/Rendering/Effects/EffectSpriteManager.cs +++ b/EndlessClient/Rendering/Effects/EffectSpriteManager.cs @@ -5,57 +5,58 @@ using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; -namespace EndlessClient.Rendering.Effects; - -[AutoMappedType] -public class EffectSpriteManager : IEffectSpriteManager +namespace EndlessClient.Rendering.Effects { - private readonly INativeGraphicsManager _graphicsManager; - private readonly IMetadataProvider _effectMetadataProvider; - - public EffectSpriteManager(INativeGraphicsManager graphicsManager, - IMetadataProvider effectMetadataProvider) - { - _graphicsManager = graphicsManager; - _effectMetadataProvider = effectMetadataProvider; - } - - public EffectMetadata GetEffectMetadata(int graphic) - { - return _effectMetadataProvider.GetValueOrDefault(graphic); - } - - public IList GetEffectInfo(int graphic) + [AutoMappedType] + public class EffectSpriteManager : IEffectSpriteManager { - return GetEffectInfo(graphic, GetEffectMetadata(graphic)); + private readonly INativeGraphicsManager _graphicsManager; + private readonly IMetadataProvider _effectMetadataProvider; + + public EffectSpriteManager(INativeGraphicsManager graphicsManager, + IMetadataProvider effectMetadataProvider) + { + _graphicsManager = graphicsManager; + _effectMetadataProvider = effectMetadataProvider; + } + + public EffectMetadata GetEffectMetadata(int graphic) + { + return _effectMetadataProvider.GetValueOrDefault(graphic); + } + + public IList GetEffectInfo(int graphic) + { + return GetEffectInfo(graphic, GetEffectMetadata(graphic)); + } + + public IList GetEffectInfo(int graphic, EffectMetadata metadata) + { + var baseGraphic = 101 + (graphic - 1) * 3; + + var retList = new List(); + if (metadata.HasBehindLayer) + retList.Add(new EffectSpriteInfo(metadata, EffectLayer.Behind, GetGraphic(baseGraphic))); + if (metadata.HasTransparentLayer) + retList.Add(new EffectSpriteInfo(metadata, EffectLayer.Transparent, GetGraphic(baseGraphic + 1))); + if (metadata.HasInFrontLayer) + retList.Add(new EffectSpriteInfo(metadata, EffectLayer.InFront, GetGraphic(baseGraphic + 2))); + + return retList; + } + + private Texture2D GetGraphic(int actualResourceID) + { + return _graphicsManager.TextureFromResource(GFXTypes.Spells, actualResourceID - 100, true); + } } - public IList GetEffectInfo(int graphic, EffectMetadata metadata) + public interface IEffectSpriteManager { - var baseGraphic = 101 + (graphic - 1) * 3; + EffectMetadata GetEffectMetadata(int graphic); - var retList = new List(); - if (metadata.HasBehindLayer) - retList.Add(new EffectSpriteInfo(metadata, EffectLayer.Behind, GetGraphic(baseGraphic))); - if (metadata.HasTransparentLayer) - retList.Add(new EffectSpriteInfo(metadata, EffectLayer.Transparent, GetGraphic(baseGraphic + 1))); - if (metadata.HasInFrontLayer) - retList.Add(new EffectSpriteInfo(metadata, EffectLayer.InFront, GetGraphic(baseGraphic + 2))); + IList GetEffectInfo(int graphic); - return retList; + IList GetEffectInfo(int graphic, EffectMetadata metadata); } - - private Texture2D GetGraphic(int actualResourceID) - { - return _graphicsManager.TextureFromResource(GFXTypes.Spells, actualResourceID - 100, true); - } -} - -public interface IEffectSpriteManager -{ - EffectMetadata GetEffectMetadata(int graphic); - - IList GetEffectInfo(int graphic); - - IList GetEffectInfo(int graphic, EffectMetadata metadata); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/HardCodedEffect.cs b/EndlessClient/Rendering/Effects/HardCodedEffect.cs index b28ae5e9f..8736778b2 100644 --- a/EndlessClient/Rendering/Effects/HardCodedEffect.cs +++ b/EndlessClient/Rendering/Effects/HardCodedEffect.cs @@ -1,15 +1,16 @@ -namespace EndlessClient.Rendering.Effects; - -public enum HardCodedEffect +namespace EndlessClient.Rendering.Effects { - Fire = 1, - Love = 2, - WarpLeave = 3, - WarpArrive = 4, - Celebrate = 5, - Sparkles = 6, - Evil = 7, - Terror = 8, - WaterSplashies = 9, - AdminHide = 25, + public enum HardCodedEffect + { + Fire = 1, + Love = 2, + WarpLeave = 3, + WarpArrive = 4, + Celebrate = 5, + Sparkles = 6, + Evil = 7, + Terror = 8, + WaterSplashies = 9, + AdminHide = 25, + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs b/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs index 11a72c671..4b5d38a64 100644 --- a/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs +++ b/EndlessClient/Rendering/Effects/IEffectSpriteInfo.cs @@ -2,14 +2,15 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Effects; - -public interface IEffectSpriteInfo +namespace EndlessClient.Rendering.Effects { - bool OnTopOfCharacter { get; } - bool Done { get; } + public interface IEffectSpriteInfo + { + bool OnTopOfCharacter { get; } + bool Done { get; } - void NextFrame(); - void Restart(); - void DrawToSpriteBatch(SpriteBatch sb, Vector2 gridCoordinatePosition); + void NextFrame(); + void Restart(); + void DrawToSpriteBatch(SpriteBatch sb, Vector2 gridCoordinatePosition); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs b/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs index 751875c7d..d2d1b81a5 100644 --- a/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs +++ b/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs @@ -2,14 +2,15 @@ using Newtonsoft.Json; using System.Collections.Generic; -namespace EndlessClient.Rendering.Effects; - -[Record] -public sealed partial class PositionOffsetEffectMetadata +namespace EndlessClient.Rendering.Effects { - [JsonProperty("xOffsetPerFrame")] - public IReadOnlyList OffsetXByFrame { get; } + [Record] + public sealed partial class PositionOffsetEffectMetadata + { + [JsonProperty("xOffsetPerFrame")] + public IReadOnlyList OffsetXByFrame { get; } - [JsonProperty("yOffsetPerFrame")] - public IReadOnlyList OffsetYByFrame { get; } + [JsonProperty("yOffsetPerFrame")] + public IReadOnlyList OffsetYByFrame { get; } + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs b/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs index 891964254..4d20baae3 100644 --- a/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs +++ b/EndlessClient/Rendering/Effects/RandomFlickeringEffectMetadata.cs @@ -1,14 +1,15 @@ using Amadevus.RecordGenerator; using Newtonsoft.Json; -namespace EndlessClient.Rendering.Effects; - -[Record] -public sealed partial class RandomFlickeringEffectMetadata +namespace EndlessClient.Rendering.Effects { - [JsonProperty("firstFrame")] - public int FirstFrame { get; } + [Record] + public sealed partial class RandomFlickeringEffectMetadata + { + [JsonProperty("firstFrame")] + public int FirstFrame { get; } - [JsonProperty("lastFrame")] - public int LastFrame { get; } + [JsonProperty("lastFrame")] + public int LastFrame { get; } + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs b/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs index 342c2773b..317e2eee8 100644 --- a/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs +++ b/EndlessClient/Rendering/Effects/VerticalSlidingEffectMetadata.cs @@ -1,11 +1,12 @@ using Amadevus.RecordGenerator; using Newtonsoft.Json; -namespace EndlessClient.Rendering.Effects; - -[Record] -public sealed partial class VerticalSlidingEffectMetadata +namespace EndlessClient.Rendering.Effects { - [JsonProperty("yOffsetPerFrame")] - public int FrameOffsetY { get; } + [Record] + public sealed partial class VerticalSlidingEffectMetadata + { + [JsonProperty("yOffsetPerFrame")] + public int FrameOffsetY { get; } + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs b/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs index 0e70c6629..60c176080 100644 --- a/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/CharacterRendererFactory.cs @@ -12,79 +12,80 @@ using EOLib.Domain.Map; using Microsoft.Xna.Framework; -namespace EndlessClient.Rendering.Factories; - -[MappedType(BaseType = typeof(ICharacterRendererFactory))] -public class CharacterRendererFactory : ICharacterRendererFactory +namespace EndlessClient.Rendering.Factories { - private readonly IEndlessGameProvider _gameProvider; - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IHealthBarRendererFactory _healthBarRendererFactory; - private readonly IChatBubbleFactory _chatBubbleFactory; - private readonly ICharacterProvider _characterProvider; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly ICharacterPropertyRendererBuilder _characterPropertyRendererBuilder; - private readonly ICharacterTextures _characterTextures; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly IEffectRendererFactory _effectRendererFactory; - private readonly IMetadataProvider _hatMetadataProvider; - private readonly IMetadataProvider _weaponMetadataProvider; - private readonly ISfxPlayer _sfxPlayer; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - - public CharacterRendererFactory(IEndlessGameProvider gameProvider, - IRenderTargetFactory renderTargetFactory, - IHealthBarRendererFactory healthBarRendererFactory, - IChatBubbleFactory chatBubbleFactory, - ICharacterProvider characterProvider, - IRenderOffsetCalculator renderOffsetCalculator, - ICharacterPropertyRendererBuilder characterPropertyRendererBuilder, - ICharacterTextures characterTextures, - ICurrentMapProvider currentMapProvider, - IUserInputProvider userInputProvider, - IEffectRendererFactory effectRendererFactory, - IMetadataProvider hatMetadataProvider, - IMetadataProvider weaponMetadataProvider, - ISfxPlayer sfxPlayer, - IClientWindowSizeRepository clientWindowSizeRepository) + [MappedType(BaseType = typeof(ICharacterRendererFactory))] + public class CharacterRendererFactory : ICharacterRendererFactory { - _gameProvider = gameProvider; - _renderTargetFactory = renderTargetFactory; - _healthBarRendererFactory = healthBarRendererFactory; - _chatBubbleFactory = chatBubbleFactory; - _characterProvider = characterProvider; - _renderOffsetCalculator = renderOffsetCalculator; - _characterPropertyRendererBuilder = characterPropertyRendererBuilder; - _characterTextures = characterTextures; - _currentMapProvider = currentMapProvider; - _userInputProvider = userInputProvider; - _effectRendererFactory = effectRendererFactory; - _hatMetadataProvider = hatMetadataProvider; - _weaponMetadataProvider = weaponMetadataProvider; - _sfxPlayer = sfxPlayer; - _clientWindowSizeRepository = clientWindowSizeRepository; - } + private readonly IEndlessGameProvider _gameProvider; + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IHealthBarRendererFactory _healthBarRendererFactory; + private readonly IChatBubbleFactory _chatBubbleFactory; + private readonly ICharacterProvider _characterProvider; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly ICharacterPropertyRendererBuilder _characterPropertyRendererBuilder; + private readonly ICharacterTextures _characterTextures; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly IEffectRendererFactory _effectRendererFactory; + private readonly IMetadataProvider _hatMetadataProvider; + private readonly IMetadataProvider _weaponMetadataProvider; + private readonly ISfxPlayer _sfxPlayer; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - public ICharacterRenderer CreateCharacterRenderer(EOLib.Domain.Character.Character character, bool isUiControl) - { - return new CharacterRenderer( - (Game)_gameProvider.Game, - _renderTargetFactory, - _healthBarRendererFactory, - _chatBubbleFactory, - _characterProvider, - _renderOffsetCalculator, - _characterPropertyRendererBuilder, - _characterTextures, - _currentMapProvider, - _userInputProvider, - _effectRendererFactory, - _hatMetadataProvider, - _weaponMetadataProvider, - _sfxPlayer, - _clientWindowSizeRepository, - character, - isUiControl); + public CharacterRendererFactory(IEndlessGameProvider gameProvider, + IRenderTargetFactory renderTargetFactory, + IHealthBarRendererFactory healthBarRendererFactory, + IChatBubbleFactory chatBubbleFactory, + ICharacterProvider characterProvider, + IRenderOffsetCalculator renderOffsetCalculator, + ICharacterPropertyRendererBuilder characterPropertyRendererBuilder, + ICharacterTextures characterTextures, + ICurrentMapProvider currentMapProvider, + IUserInputProvider userInputProvider, + IEffectRendererFactory effectRendererFactory, + IMetadataProvider hatMetadataProvider, + IMetadataProvider weaponMetadataProvider, + ISfxPlayer sfxPlayer, + IClientWindowSizeRepository clientWindowSizeRepository) + { + _gameProvider = gameProvider; + _renderTargetFactory = renderTargetFactory; + _healthBarRendererFactory = healthBarRendererFactory; + _chatBubbleFactory = chatBubbleFactory; + _characterProvider = characterProvider; + _renderOffsetCalculator = renderOffsetCalculator; + _characterPropertyRendererBuilder = characterPropertyRendererBuilder; + _characterTextures = characterTextures; + _currentMapProvider = currentMapProvider; + _userInputProvider = userInputProvider; + _effectRendererFactory = effectRendererFactory; + _hatMetadataProvider = hatMetadataProvider; + _weaponMetadataProvider = weaponMetadataProvider; + _sfxPlayer = sfxPlayer; + _clientWindowSizeRepository = clientWindowSizeRepository; + } + + public ICharacterRenderer CreateCharacterRenderer(EOLib.Domain.Character.Character character, bool isUiControl) + { + return new CharacterRenderer( + (Game)_gameProvider.Game, + _renderTargetFactory, + _healthBarRendererFactory, + _chatBubbleFactory, + _characterProvider, + _renderOffsetCalculator, + _characterPropertyRendererBuilder, + _characterTextures, + _currentMapProvider, + _userInputProvider, + _effectRendererFactory, + _hatMetadataProvider, + _weaponMetadataProvider, + _sfxPlayer, + _clientWindowSizeRepository, + character, + isUiControl); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs b/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs index 3c9e08275..d65096ee6 100644 --- a/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/ContextMenuRendererFactory.cs @@ -13,82 +13,83 @@ using EOLib.Domain.Trade; using EOLib.Graphics; -namespace EndlessClient.Rendering.Factories; - -[AutoMappedType] -public class ContextMenuRendererFactory : IContextMenuRendererFactory +namespace EndlessClient.Rendering.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IInGameDialogActions _inGameDialogActions; - private readonly IPaperdollActions _paperdollActions; - private readonly IBookActions _bookActions; - private readonly IPartyActions _partyActions; - private readonly ITradeActions _tradeActions; - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly IHudControlProvider _hudControlProvider; - private readonly IContextMenuRepository _contextMenuRepository; - private readonly IPartyDataProvider _partyDataProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ISfxPlayer _sfxPlayer; - - public ContextMenuRendererFactory(INativeGraphicsManager nativeGraphicsManager, - IInGameDialogActions inGameDialogActions, - IPaperdollActions paperdollActions, - IBookActions bookActions, - IPartyActions partyActions, - ITradeActions tradeActions, - IStatusLabelSetter statusLabelSetter, - IFriendIgnoreListService friendIgnoreListService, - IHudControlProvider hudControlProvider, - IContextMenuRepository contextMenuRepository, - IPartyDataProvider partyDataProvider, - ICurrentMapStateProvider currentMapStateProvider, - IEOMessageBoxFactory messageBoxFactory, - IClientWindowSizeProvider clientWindowSizeProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class ContextMenuRendererFactory : IContextMenuRendererFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _inGameDialogActions = inGameDialogActions; - _paperdollActions = paperdollActions; - _bookActions = bookActions; - _partyActions = partyActions; - _tradeActions = tradeActions; - _statusLabelSetter = statusLabelSetter; - _friendIgnoreListService = friendIgnoreListService; - _hudControlProvider = hudControlProvider; - _contextMenuRepository = contextMenuRepository; - _partyDataProvider = partyDataProvider; - _currentMapStateProvider = currentMapStateProvider; - _messageBoxFactory = messageBoxFactory; - _clientWindowSizeProvider = clientWindowSizeProvider; - _sfxPlayer = sfxPlayer; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IInGameDialogActions _inGameDialogActions; + private readonly IPaperdollActions _paperdollActions; + private readonly IBookActions _bookActions; + private readonly IPartyActions _partyActions; + private readonly ITradeActions _tradeActions; + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly IHudControlProvider _hudControlProvider; + private readonly IContextMenuRepository _contextMenuRepository; + private readonly IPartyDataProvider _partyDataProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ISfxPlayer _sfxPlayer; + + public ContextMenuRendererFactory(INativeGraphicsManager nativeGraphicsManager, + IInGameDialogActions inGameDialogActions, + IPaperdollActions paperdollActions, + IBookActions bookActions, + IPartyActions partyActions, + ITradeActions tradeActions, + IStatusLabelSetter statusLabelSetter, + IFriendIgnoreListService friendIgnoreListService, + IHudControlProvider hudControlProvider, + IContextMenuRepository contextMenuRepository, + IPartyDataProvider partyDataProvider, + ICurrentMapStateProvider currentMapStateProvider, + IEOMessageBoxFactory messageBoxFactory, + IClientWindowSizeProvider clientWindowSizeProvider, + ISfxPlayer sfxPlayer) + { + _nativeGraphicsManager = nativeGraphicsManager; + _inGameDialogActions = inGameDialogActions; + _paperdollActions = paperdollActions; + _bookActions = bookActions; + _partyActions = partyActions; + _tradeActions = tradeActions; + _statusLabelSetter = statusLabelSetter; + _friendIgnoreListService = friendIgnoreListService; + _hudControlProvider = hudControlProvider; + _contextMenuRepository = contextMenuRepository; + _partyDataProvider = partyDataProvider; + _currentMapStateProvider = currentMapStateProvider; + _messageBoxFactory = messageBoxFactory; + _clientWindowSizeProvider = clientWindowSizeProvider; + _sfxPlayer = sfxPlayer; + } + + public IContextMenuRenderer CreateContextMenuRenderer(ICharacterRenderer characterRenderer) + { + return new ContextMenuRenderer(_nativeGraphicsManager, + _inGameDialogActions, + _paperdollActions, + _bookActions, + _partyActions, + _tradeActions, + _statusLabelSetter, + _friendIgnoreListService, + _hudControlProvider, + _contextMenuRepository, + _partyDataProvider, + characterRenderer, + _currentMapStateProvider, + _messageBoxFactory, + _clientWindowSizeProvider, + _sfxPlayer); + } } - public IContextMenuRenderer CreateContextMenuRenderer(ICharacterRenderer characterRenderer) + public interface IContextMenuRendererFactory { - return new ContextMenuRenderer(_nativeGraphicsManager, - _inGameDialogActions, - _paperdollActions, - _bookActions, - _partyActions, - _tradeActions, - _statusLabelSetter, - _friendIgnoreListService, - _hudControlProvider, - _contextMenuRepository, - _partyDataProvider, - characterRenderer, - _currentMapStateProvider, - _messageBoxFactory, - _clientWindowSizeProvider, - _sfxPlayer); + IContextMenuRenderer CreateContextMenuRenderer(ICharacterRenderer characterRenderer); } -} - -public interface IContextMenuRendererFactory -{ - IContextMenuRenderer CreateContextMenuRenderer(ICharacterRenderer characterRenderer); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs b/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs index d36ffac80..273c8002e 100644 --- a/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/HealthBarRendererFactory.cs @@ -1,25 +1,26 @@ using AutomaticTypeMapper; using EOLib.Graphics; -namespace EndlessClient.Rendering.Factories; - -[AutoMappedType] -public class HealthBarRendererFactory : IHealthBarRendererFactory +namespace EndlessClient.Rendering.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - - public HealthBarRendererFactory(INativeGraphicsManager nativeGraphicsManager) + [AutoMappedType] + public class HealthBarRendererFactory : IHealthBarRendererFactory { - _nativeGraphicsManager = nativeGraphicsManager; + private readonly INativeGraphicsManager _nativeGraphicsManager; + + public HealthBarRendererFactory(INativeGraphicsManager nativeGraphicsManager) + { + _nativeGraphicsManager = nativeGraphicsManager; + } + + public IHealthBarRenderer CreateHealthBarRenderer(IMapActor parentReference) + { + return new HealthBarRenderer(_nativeGraphicsManager, parentReference); + } } - public IHealthBarRenderer CreateHealthBarRenderer(IMapActor parentReference) + public interface IHealthBarRendererFactory { - return new HealthBarRenderer(_nativeGraphicsManager, parentReference); + IHealthBarRenderer CreateHealthBarRenderer(IMapActor entity); } -} - -public interface IHealthBarRendererFactory -{ - IHealthBarRenderer CreateHealthBarRenderer(IMapActor entity); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs b/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs index c3d2c6db2..76e9ee0b5 100644 --- a/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/ICharacterRendererFactory.cs @@ -1,8 +1,9 @@ using EndlessClient.Rendering.Character; -namespace EndlessClient.Rendering.Factories; - -public interface ICharacterRendererFactory +namespace EndlessClient.Rendering.Factories { - ICharacterRenderer CreateCharacterRenderer(EOLib.Domain.Character.Character character, bool isUiControl); + public interface ICharacterRendererFactory + { + ICharacterRenderer CreateCharacterRenderer(EOLib.Domain.Character.Character character, bool isUiControl); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/IMapRendererFactory.cs b/EndlessClient/Rendering/Factories/IMapRendererFactory.cs index 692c7226b..f70bd5d30 100644 --- a/EndlessClient/Rendering/Factories/IMapRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/IMapRendererFactory.cs @@ -1,8 +1,9 @@ using EndlessClient.Rendering.Map; -namespace EndlessClient.Rendering.Factories; - -public interface IMapRendererFactory +namespace EndlessClient.Rendering.Factories { - IMapRenderer CreateMapRenderer(); + public interface IMapRendererFactory + { + IMapRenderer CreateMapRenderer(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs b/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs index b3860ab42..5619cb444 100644 --- a/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs +++ b/EndlessClient/Rendering/Factories/IRenderTargetFactory.cs @@ -1,9 +1,10 @@ using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Factories; - -public interface IRenderTargetFactory +namespace EndlessClient.Rendering.Factories { - RenderTarget2D CreateRenderTarget(); - RenderTarget2D CreateRenderTarget(int width, int height); + public interface IRenderTargetFactory + { + RenderTarget2D CreateRenderTarget(); + RenderTarget2D CreateRenderTarget(int width, int height); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/MapRendererFactory.cs b/EndlessClient/Rendering/Factories/MapRendererFactory.cs index f79aa38f2..29815b5d8 100644 --- a/EndlessClient/Rendering/Factories/MapRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/MapRendererFactory.cs @@ -11,84 +11,85 @@ using EOLib.Domain.Character; using EOLib.Domain.Map; -namespace EndlessClient.Rendering.Factories; - -[MappedType(BaseType = typeof(IMapRendererFactory))] -public class MapRendererFactory : IMapRendererFactory +namespace EndlessClient.Rendering.Factories { - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IEffectRendererFactory _effectRendererFactory; - private readonly IMapEntityRendererProvider _mapEntityRendererProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IContentProvider _contentProvider; - private readonly IMapRenderDistanceCalculator _mapRenderDistanceCalculator; - private readonly ICharacterRendererUpdater _characterRendererUpdater; - private readonly INPCRendererUpdater _npcRendererUpdater; - private readonly IDynamicMapObjectUpdater _dynamicMapObjectUpdater; - private readonly IConfigurationProvider _configurationProvider; - private readonly IMouseCursorRendererFactory _mouseCursorRendererFactory; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - - public MapRendererFactory(IEndlessGameProvider endlessGameProvider, - IRenderTargetFactory renderTargetFactory, - IEffectRendererFactory effectRendererFactory, - IMapEntityRendererProvider mapEntityRendererProvider, - ICharacterProvider characterProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - IContentProvider contentProvider, - IMapRenderDistanceCalculator mapRenderDistanceCalculator, - ICharacterRendererUpdater characterRendererUpdater, - INPCRendererUpdater npcRendererUpdater, - IDynamicMapObjectUpdater dynamicMapObjectUpdater, - IConfigurationProvider configurationProvider, - IMouseCursorRendererFactory mouseCursorRendererFactory, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeRepository clientWindowSizeRepository, - IFixedTimeStepRepository fixedTimeStepRepository) + [MappedType(BaseType = typeof(IMapRendererFactory))] + public class MapRendererFactory : IMapRendererFactory { - _endlessGameProvider = endlessGameProvider; - _renderTargetFactory = renderTargetFactory; - _effectRendererFactory = effectRendererFactory; - _mapEntityRendererProvider = mapEntityRendererProvider; - _characterProvider = characterProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _contentProvider = contentProvider; - _mapRenderDistanceCalculator = mapRenderDistanceCalculator; - _characterRendererUpdater = characterRendererUpdater; - _npcRendererUpdater = npcRendererUpdater; - _dynamicMapObjectUpdater = dynamicMapObjectUpdater; - _configurationProvider = configurationProvider; - _mouseCursorRendererFactory = mouseCursorRendererFactory; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _clientWindowSizeRepository = clientWindowSizeRepository; - _fixedTimeStepRepository = fixedTimeStepRepository; - } + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IEffectRendererFactory _effectRendererFactory; + private readonly IMapEntityRendererProvider _mapEntityRendererProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IContentProvider _contentProvider; + private readonly IMapRenderDistanceCalculator _mapRenderDistanceCalculator; + private readonly ICharacterRendererUpdater _characterRendererUpdater; + private readonly INPCRendererUpdater _npcRendererUpdater; + private readonly IDynamicMapObjectUpdater _dynamicMapObjectUpdater; + private readonly IConfigurationProvider _configurationProvider; + private readonly IMouseCursorRendererFactory _mouseCursorRendererFactory; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - public IMapRenderer CreateMapRenderer() - { - return new MapRenderer(_endlessGameProvider.Game, - _renderTargetFactory, - _effectRendererFactory, - _mapEntityRendererProvider, - _characterProvider, - _currentMapProvider, - _currentMapStateProvider, - _contentProvider, - _mapRenderDistanceCalculator, - _characterRendererUpdater, - _npcRendererUpdater, - _dynamicMapObjectUpdater, - _configurationProvider, - _mouseCursorRendererFactory.Create(), - _gridDrawCoordinateCalculator, - _clientWindowSizeRepository, - _fixedTimeStepRepository); + public MapRendererFactory(IEndlessGameProvider endlessGameProvider, + IRenderTargetFactory renderTargetFactory, + IEffectRendererFactory effectRendererFactory, + IMapEntityRendererProvider mapEntityRendererProvider, + ICharacterProvider characterProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + IContentProvider contentProvider, + IMapRenderDistanceCalculator mapRenderDistanceCalculator, + ICharacterRendererUpdater characterRendererUpdater, + INPCRendererUpdater npcRendererUpdater, + IDynamicMapObjectUpdater dynamicMapObjectUpdater, + IConfigurationProvider configurationProvider, + IMouseCursorRendererFactory mouseCursorRendererFactory, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeRepository clientWindowSizeRepository, + IFixedTimeStepRepository fixedTimeStepRepository) + { + _endlessGameProvider = endlessGameProvider; + _renderTargetFactory = renderTargetFactory; + _effectRendererFactory = effectRendererFactory; + _mapEntityRendererProvider = mapEntityRendererProvider; + _characterProvider = characterProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _contentProvider = contentProvider; + _mapRenderDistanceCalculator = mapRenderDistanceCalculator; + _characterRendererUpdater = characterRendererUpdater; + _npcRendererUpdater = npcRendererUpdater; + _dynamicMapObjectUpdater = dynamicMapObjectUpdater; + _configurationProvider = configurationProvider; + _mouseCursorRendererFactory = mouseCursorRendererFactory; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _clientWindowSizeRepository = clientWindowSizeRepository; + _fixedTimeStepRepository = fixedTimeStepRepository; + } + + public IMapRenderer CreateMapRenderer() + { + return new MapRenderer(_endlessGameProvider.Game, + _renderTargetFactory, + _effectRendererFactory, + _mapEntityRendererProvider, + _characterProvider, + _currentMapProvider, + _currentMapStateProvider, + _contentProvider, + _mapRenderDistanceCalculator, + _characterRendererUpdater, + _npcRendererUpdater, + _dynamicMapObjectUpdater, + _configurationProvider, + _mouseCursorRendererFactory.Create(), + _gridDrawCoordinateCalculator, + _clientWindowSizeRepository, + _fixedTimeStepRepository); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs b/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs index 3fa56abc6..3ebc0e979 100644 --- a/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs +++ b/EndlessClient/Rendering/Factories/MouseCursorRendererFactory.cs @@ -8,60 +8,61 @@ using EOLib.Graphics; using EOLib.IO.Repositories; -namespace EndlessClient.Rendering.Factories; - -[AutoMappedType] -public class MouseCursorRendererFactory : IMouseCursorRendererFactory +namespace EndlessClient.Rendering.Factories { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IMapCellStateProvider _mapCellStateProvider; - private readonly IItemStringService _itemStringService; - private readonly IItemNameColorService _itemNameColorService; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly IContextMenuProvider _contextMenuProvider; - public MouseCursorRendererFactory(INativeGraphicsManager nativeGraphicsManager, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IMapCellStateProvider mapCellStateProvider, - IItemStringService itemStringService, - IItemNameColorService itemNameColorService, - IEIFFileProvider eifFileProvider, - ICurrentMapProvider currentMapProvider, - IUserInputProvider userInputProvider, - IActiveDialogProvider activeDialogProvider, - IContextMenuProvider contextMenuProvider) + [AutoMappedType] + public class MouseCursorRendererFactory : IMouseCursorRendererFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _mapCellStateProvider = mapCellStateProvider; - _itemStringService = itemStringService; - _itemNameColorService = itemNameColorService; - _eifFileProvider = eifFileProvider; - _currentMapProvider = currentMapProvider; - _userInputProvider = userInputProvider; - _activeDialogProvider = activeDialogProvider; - _contextMenuProvider = contextMenuProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IMapCellStateProvider _mapCellStateProvider; + private readonly IItemStringService _itemStringService; + private readonly IItemNameColorService _itemNameColorService; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly IContextMenuProvider _contextMenuProvider; + public MouseCursorRendererFactory(INativeGraphicsManager nativeGraphicsManager, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IMapCellStateProvider mapCellStateProvider, + IItemStringService itemStringService, + IItemNameColorService itemNameColorService, + IEIFFileProvider eifFileProvider, + ICurrentMapProvider currentMapProvider, + IUserInputProvider userInputProvider, + IActiveDialogProvider activeDialogProvider, + IContextMenuProvider contextMenuProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _mapCellStateProvider = mapCellStateProvider; + _itemStringService = itemStringService; + _itemNameColorService = itemNameColorService; + _eifFileProvider = eifFileProvider; + _currentMapProvider = currentMapProvider; + _userInputProvider = userInputProvider; + _activeDialogProvider = activeDialogProvider; + _contextMenuProvider = contextMenuProvider; + } + + public IMouseCursorRenderer Create() + { + return new MouseCursorRenderer(_nativeGraphicsManager, + _gridDrawCoordinateCalculator, + _mapCellStateProvider, + _itemStringService, + _itemNameColorService, + _eifFileProvider, + _currentMapProvider, + _userInputProvider, + _activeDialogProvider, + _contextMenuProvider); + } } - public IMouseCursorRenderer Create() + public interface IMouseCursorRendererFactory { - return new MouseCursorRenderer(_nativeGraphicsManager, - _gridDrawCoordinateCalculator, - _mapCellStateProvider, - _itemStringService, - _itemNameColorService, - _eifFileProvider, - _currentMapProvider, - _userInputProvider, - _activeDialogProvider, - _contextMenuProvider); + IMouseCursorRenderer Create(); } -} - -public interface IMouseCursorRendererFactory -{ - IMouseCursorRenderer Create(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Factories/RenderTargetFactory.cs b/EndlessClient/Rendering/Factories/RenderTargetFactory.cs index f1241659a..1234a95d7 100644 --- a/EndlessClient/Rendering/Factories/RenderTargetFactory.cs +++ b/EndlessClient/Rendering/Factories/RenderTargetFactory.cs @@ -2,34 +2,35 @@ using EOLib.Graphics; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Factories; - -[MappedType(BaseType = typeof(IRenderTargetFactory))] -public class RenderTargetFactory : IRenderTargetFactory +namespace EndlessClient.Rendering.Factories { - private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - - public RenderTargetFactory(IGraphicsDeviceProvider graphicsDeviceProvider, - IClientWindowSizeProvider clientWindowSizeProvider) + [MappedType(BaseType = typeof(IRenderTargetFactory))] + public class RenderTargetFactory : IRenderTargetFactory { - _graphicsDeviceProvider = graphicsDeviceProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - } + private readonly IGraphicsDeviceProvider _graphicsDeviceProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - public RenderTarget2D CreateRenderTarget() - { - return CreateRenderTarget(_clientWindowSizeProvider.Width, _clientWindowSizeProvider.Height); - } + public RenderTargetFactory(IGraphicsDeviceProvider graphicsDeviceProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _graphicsDeviceProvider = graphicsDeviceProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + } - public RenderTarget2D CreateRenderTarget(int width, int height) - { - return new RenderTarget2D( - _graphicsDeviceProvider.GraphicsDevice, - width, - height, - false, - SurfaceFormat.Color, - DepthFormat.None); + public RenderTarget2D CreateRenderTarget() + { + return CreateRenderTarget(_clientWindowSizeProvider.Width, _clientWindowSizeProvider.Height); + } + + public RenderTarget2D CreateRenderTarget(int width, int height) + { + return new RenderTarget2D( + _graphicsDeviceProvider.GraphicsDevice, + width, + height, + false, + SurfaceFormat.Color, + DepthFormat.None); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs b/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs index 7d8f16a45..373262174 100644 --- a/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs +++ b/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs @@ -7,180 +7,181 @@ using DomainNPC = EOLib.Domain.NPC.NPC; -namespace EndlessClient.Rendering; - -[AutoMappedType] -public class GridDrawCoordinateCalculator : IGridDrawCoordinateCalculator +namespace EndlessClient.Rendering { - private readonly ICharacterProvider _characterProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - - public GridDrawCoordinateCalculator(ICharacterProvider characterProvider, - ICurrentMapProvider currentMapProvider, - IRenderOffsetCalculator renderOffsetCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _characterProvider = characterProvider; - _currentMapProvider = currentMapProvider; - _renderOffsetCalculator = renderOffsetCalculator; - _clientWindowSizeProvider = clientWindowSizeProvider; - } - - public Vector2 CalculateRawRenderCoordinatesFromGridUnits(int gridX, int gridY, int tileWidth = 64, int tileHeight = 32) + [AutoMappedType] + public class GridDrawCoordinateCalculator : IGridDrawCoordinateCalculator { - var widthFactor = tileWidth / 2; - var heightFactor = tileHeight / 2; - - return new Vector2((gridX * widthFactor) - (gridY * widthFactor), - (gridY * heightFactor) + (gridX * heightFactor)); - } - - public Vector2 CalculateDrawCoordinatesFromGridUnits(int gridX, int gridY) - { - var widthFactor = _clientWindowSizeProvider.Width / 2; // 640 * (1/2) - 1 - var heightFactor = _clientWindowSizeProvider.Resizable - ? _clientWindowSizeProvider.Height / 2 - : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 2 - - return new Vector2(widthFactor, heightFactor) + CalculateRawRenderCoordinatesFromGridUnits(gridX, gridY) - GetMainCharacterOffsets(); - } + private readonly ICharacterProvider _characterProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + + public GridDrawCoordinateCalculator(ICharacterProvider characterProvider, + ICurrentMapProvider currentMapProvider, + IRenderOffsetCalculator renderOffsetCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _characterProvider = characterProvider; + _currentMapProvider = currentMapProvider; + _renderOffsetCalculator = renderOffsetCalculator; + _clientWindowSizeProvider = clientWindowSizeProvider; + } - public Vector2 CalculateDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate) - { - return CalculateDrawCoordinatesFromGridUnits(mapCoordinate.X, mapCoordinate.Y); - } + public Vector2 CalculateRawRenderCoordinatesFromGridUnits(int gridX, int gridY, int tileWidth = 64, int tileHeight = 32) + { + var widthFactor = tileWidth / 2; + var heightFactor = tileHeight / 2; - public Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(int gridX, int gridY) - { - return CalculateDrawCoordinatesFromGridUnits(gridX, gridY) - - new Vector2(IGridDrawCoordinateCalculator.DefaultGridWidth / 2, 0); - } + return new Vector2((gridX * widthFactor) - (gridY * widthFactor), + (gridY * heightFactor) + (gridX * heightFactor)); + } - public Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate) - { - return CalculateBaseLayerDrawCoordinatesFromGridUnits(mapCoordinate.X, mapCoordinate.Y); - } + public Vector2 CalculateDrawCoordinatesFromGridUnits(int gridX, int gridY) + { + var widthFactor = _clientWindowSizeProvider.Width / 2; // 640 * (1/2) - 1 + var heightFactor = _clientWindowSizeProvider.Resizable + ? _clientWindowSizeProvider.Height / 2 + : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 2 - public Vector2 CalculateGroundLayerRenderTargetDrawCoordinates(bool isMiniMap = false, int tileWidth = 64, int tileHeight = 32) - { - var ViewportWidthFactor = _clientWindowSizeProvider.Width / 2 - 1; // 640 * (1/2) - 1 - var ViewportHeightFactor = _clientWindowSizeProvider.Resizable - ? _clientWindowSizeProvider.Height / 2 - : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 2 + return new Vector2(widthFactor, heightFactor) + CalculateRawRenderCoordinatesFromGridUnits(gridX, gridY) - GetMainCharacterOffsets(); + } - var rp = _characterProvider.MainCharacter.RenderProperties; - var cx = isMiniMap ? _characterProvider.MainCharacter.X : rp.MapX; - var cy = isMiniMap ? _characterProvider.MainCharacter.Y : rp.MapY; + public Vector2 CalculateDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate) + { + return CalculateDrawCoordinatesFromGridUnits(mapCoordinate.X, mapCoordinate.Y); + } - var mapHeightPlusOne = _currentMapProvider.CurrentMap.Properties.Height + 1; + public Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(int gridX, int gridY) + { + return CalculateDrawCoordinatesFromGridUnits(gridX, gridY) - + new Vector2(IGridDrawCoordinateCalculator.DefaultGridWidth / 2, 0); + } - var tileWidthFactor = tileWidth / 2; - var tileHeightFactor = tileHeight / 2; + public Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate) + { + return CalculateBaseLayerDrawCoordinatesFromGridUnits(mapCoordinate.X, mapCoordinate.Y); + } - var walkAdjustOffsets = isMiniMap ? Vector2.Zero : GetMainCharacterWalkAdjustOffsets(); + public Vector2 CalculateGroundLayerRenderTargetDrawCoordinates(bool isMiniMap = false, int tileWidth = 64, int tileHeight = 32) + { + var ViewportWidthFactor = _clientWindowSizeProvider.Width / 2 - 1; // 640 * (1/2) - 1 + var ViewportHeightFactor = _clientWindowSizeProvider.Resizable + ? _clientWindowSizeProvider.Height / 2 + : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 2 - // opposite of the algorithm for rendering the base layers - return new Vector2(ViewportWidthFactor - (mapHeightPlusOne * tileWidthFactor) + (cy * tileWidthFactor) - (cx * tileWidthFactor), - ViewportHeightFactor - (cy * tileHeightFactor) - (cx * tileHeightFactor)) - walkAdjustOffsets; - } + var rp = _characterProvider.MainCharacter.RenderProperties; + var cx = isMiniMap ? _characterProvider.MainCharacter.X : rp.MapX; + var cy = isMiniMap ? _characterProvider.MainCharacter.Y : rp.MapY; - public Vector2 CalculateDrawCoordinates(DomainNPC npc) - { - var ViewportWidthFactor = _clientWindowSizeProvider.Width / 2 - 1; // 640 * (1/2) - 1 - var ViewportHeightFactor = _clientWindowSizeProvider.Resizable - ? _clientWindowSizeProvider.Height / 2 - : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 1 // ??? + var mapHeightPlusOne = _currentMapProvider.CurrentMap.Properties.Height + 1; - var npcOffsetX = _renderOffsetCalculator.CalculateOffsetX(npc); - var npcOffsetY = _renderOffsetCalculator.CalculateOffsetY(npc); + var tileWidthFactor = tileWidth / 2; + var tileHeightFactor = tileHeight / 2; - var mainOffsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); - var mainOffsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); + var walkAdjustOffsets = isMiniMap ? Vector2.Zero : GetMainCharacterWalkAdjustOffsets(); - return new Vector2(ViewportWidthFactor + npcOffsetX - mainOffsetX, - ViewportHeightFactor + npcOffsetY - mainOffsetY + 16); - } + // opposite of the algorithm for rendering the base layers + return new Vector2(ViewportWidthFactor - (mapHeightPlusOne * tileWidthFactor) + (cy * tileWidthFactor) - (cx * tileWidthFactor), + ViewportHeightFactor - (cy * tileHeightFactor) - (cx * tileHeightFactor)) - walkAdjustOffsets; + } - public MapCoordinate CalculateGridCoordinatesFromDrawLocation(Vector2 drawLocation) - { - //need to solve this system of equations to get x, y on the grid - //(x * 32) - (y * 32) + 288 - c.OffsetX, => pixX = 32x - 32y + 288 - c.OffsetX - //(y * 16) + (x * 16) + 144 - c.OffsetY => 2pixY = 32y + 32x + 288 - 2c.OffsetY - // => 2pixY + pixX = 64x + 576 - c.OffsetX - 2c.OffsetY - // => 2pixY + pixX - 576 + c.OffsetX + 2c.OffsetY = 64x - // => _gridX = (pixX + 2pixY - 576 + c.OffsetX + 2c.OffsetY) / 64; <= - //pixY = (_gridX * 16) + (_gridY * 16) + 144 - c.OffsetY => - //(pixY - (_gridX * 16) - 144 + c.OffsetY) / 16 = _gridY - - if (_clientWindowSizeProvider.Resizable) + public Vector2 CalculateDrawCoordinates(DomainNPC npc) { - var msX = drawLocation.X; - var msY = drawLocation.Y - IGridDrawCoordinateCalculator.DefaultGridHeight / 2; + var ViewportWidthFactor = _clientWindowSizeProvider.Width / 2 - 1; // 640 * (1/2) - 1 + var ViewportHeightFactor = _clientWindowSizeProvider.Resizable + ? _clientWindowSizeProvider.Height / 2 + : _clientWindowSizeProvider.Height * 3 / 10 - 2; // 480 * (3/10) - 1 // ??? - var widthFactor = _clientWindowSizeProvider.Width / 2; - var heightFactor = _clientWindowSizeProvider.Height / 2; + var npcOffsetX = _renderOffsetCalculator.CalculateOffsetX(npc); + var npcOffsetY = _renderOffsetCalculator.CalculateOffsetY(npc); - var offsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); - var offsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); + var mainOffsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); + var mainOffsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); - var gridX = (int)Math.Round((msX + (2 * msY) - widthFactor - heightFactor * 2 + offsetX + (2 * offsetY)) / 64.0); - var gridY = (int)Math.Round((msY - (16 * gridX) - heightFactor + offsetY) / 16.0); - - return new MapCoordinate(gridX, gridY); + return new Vector2(ViewportWidthFactor + npcOffsetX - mainOffsetX, + ViewportHeightFactor + npcOffsetY - mainOffsetY + 16); } - else - { - const int ViewportWidthFactor = 288; // 640 * (1/2) - 32 - const int ViewportHeightFactor = 142; // 480 * (3/10) - 2 - - var msX = drawLocation.X - IGridDrawCoordinateCalculator.DefaultGridWidth / 2; - var msY = drawLocation.Y - IGridDrawCoordinateCalculator.DefaultGridHeight / 2; - var offsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); - var offsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); - - var gridX = (int)Math.Round((msX + 2 * msY - (ViewportWidthFactor * 2) + offsetX + 2 * offsetY) / 64.0); - var gridY = (int)Math.Round((msY - gridX * 16 - ViewportHeightFactor + offsetY) / 16.0); + public MapCoordinate CalculateGridCoordinatesFromDrawLocation(Vector2 drawLocation) + { + //need to solve this system of equations to get x, y on the grid + //(x * 32) - (y * 32) + 288 - c.OffsetX, => pixX = 32x - 32y + 288 - c.OffsetX + //(y * 16) + (x * 16) + 144 - c.OffsetY => 2pixY = 32y + 32x + 288 - 2c.OffsetY + // => 2pixY + pixX = 64x + 576 - c.OffsetX - 2c.OffsetY + // => 2pixY + pixX - 576 + c.OffsetX + 2c.OffsetY = 64x + // => _gridX = (pixX + 2pixY - 576 + c.OffsetX + 2c.OffsetY) / 64; <= + //pixY = (_gridX * 16) + (_gridY * 16) + 144 - c.OffsetY => + //(pixY - (_gridX * 16) - 144 + c.OffsetY) / 16 = _gridY + + if (_clientWindowSizeProvider.Resizable) + { + var msX = drawLocation.X; + var msY = drawLocation.Y - IGridDrawCoordinateCalculator.DefaultGridHeight / 2; + + var widthFactor = _clientWindowSizeProvider.Width / 2; + var heightFactor = _clientWindowSizeProvider.Height / 2; + + var offsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); + var offsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); + + var gridX = (int)Math.Round((msX + (2 * msY) - widthFactor - heightFactor * 2 + offsetX + (2 * offsetY)) / 64.0); + var gridY = (int)Math.Round((msY - (16 * gridX) - heightFactor + offsetY) / 16.0); + + return new MapCoordinate(gridX, gridY); + } + else + { + const int ViewportWidthFactor = 288; // 640 * (1/2) - 32 + const int ViewportHeightFactor = 142; // 480 * (3/10) - 2 + + var msX = drawLocation.X - IGridDrawCoordinateCalculator.DefaultGridWidth / 2; + var msY = drawLocation.Y - IGridDrawCoordinateCalculator.DefaultGridHeight / 2; + + var offsetX = _renderOffsetCalculator.CalculateOffsetX(_characterProvider.MainCharacter.RenderProperties); + var offsetY = _renderOffsetCalculator.CalculateOffsetY(_characterProvider.MainCharacter.RenderProperties); + + var gridX = (int)Math.Round((msX + 2 * msY - (ViewportWidthFactor * 2) + offsetX + 2 * offsetY) / 64.0); + var gridY = (int)Math.Round((msY - gridX * 16 - ViewportHeightFactor + offsetY) / 16.0); + + return new MapCoordinate(gridX, gridY); + } + } - return new MapCoordinate(gridX, gridY); + private Vector2 GetMainCharacterOffsets() + { + var props = _characterProvider.MainCharacter.RenderProperties; + return new Vector2(_renderOffsetCalculator.CalculateOffsetX(props), + _renderOffsetCalculator.CalculateOffsetY(props)); } - } - private Vector2 GetMainCharacterOffsets() - { - var props = _characterProvider.MainCharacter.RenderProperties; - return new Vector2(_renderOffsetCalculator.CalculateOffsetX(props), - _renderOffsetCalculator.CalculateOffsetY(props)); + private Vector2 GetMainCharacterWalkAdjustOffsets() + { + var props = _characterProvider.MainCharacter.RenderProperties; + return new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(props), + _renderOffsetCalculator.CalculateWalkAdjustY(props)); + } } - private Vector2 GetMainCharacterWalkAdjustOffsets() + public interface IGridDrawCoordinateCalculator { - var props = _characterProvider.MainCharacter.RenderProperties; - return new Vector2(_renderOffsetCalculator.CalculateWalkAdjustX(props), - _renderOffsetCalculator.CalculateWalkAdjustY(props)); - } -} + const int DefaultGridWidth = 64; + const int DefaultGridHeight = 32; -public interface IGridDrawCoordinateCalculator -{ - const int DefaultGridWidth = 64; - const int DefaultGridHeight = 32; - - Vector2 CalculateRawRenderCoordinatesFromGridUnits(int gridX, int gridY, int tileWidth = DefaultGridWidth, int tileHeight = DefaultGridHeight); + Vector2 CalculateRawRenderCoordinatesFromGridUnits(int gridX, int gridY, int tileWidth = DefaultGridWidth, int tileHeight = DefaultGridHeight); - Vector2 CalculateDrawCoordinatesFromGridUnits(int gridX, int gridY); + Vector2 CalculateDrawCoordinatesFromGridUnits(int gridX, int gridY); - Vector2 CalculateDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate); + Vector2 CalculateDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate); - Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(int gridX, int gridY); + Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(int gridX, int gridY); - Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate); + Vector2 CalculateBaseLayerDrawCoordinatesFromGridUnits(MapCoordinate mapCoordinate); - Vector2 CalculateGroundLayerRenderTargetDrawCoordinates(bool isMiniMap = false, int tileWidth = DefaultGridWidth, int tileHeight = DefaultGridHeight); + Vector2 CalculateGroundLayerRenderTargetDrawCoordinates(bool isMiniMap = false, int tileWidth = DefaultGridWidth, int tileHeight = DefaultGridHeight); - Vector2 CalculateDrawCoordinates(DomainNPC npc); + Vector2 CalculateDrawCoordinates(DomainNPC npc); - MapCoordinate CalculateGridCoordinatesFromDrawLocation(Vector2 drawLocation); + MapCoordinate CalculateGridCoordinatesFromDrawLocation(Vector2 drawLocation); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/HealthBarRenderer.cs b/EndlessClient/Rendering/HealthBarRenderer.cs index 9d4c2ea19..11cb8b9be 100644 --- a/EndlessClient/Rendering/HealthBarRenderer.cs +++ b/EndlessClient/Rendering/HealthBarRenderer.cs @@ -6,159 +6,160 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering; - -public class HealthBarRenderer : IHealthBarRenderer +namespace EndlessClient.Rendering { - private const int DigitWidth = 9; - - private readonly IMapActor _parentReference; + public class HealthBarRenderer : IHealthBarRenderer + { + private const int DigitWidth = 9; - private readonly Texture2D _sourceTexture; - private static readonly Point _numberSpritesOffset, _healthBarSpritesOffset; - private static readonly Rectangle _healthBarBackgroundSource; + private readonly IMapActor _parentReference; - private Action _doneCallback; - private bool _isMiss; - private List _numberSourceRectangles; - private Rectangle _healthBarSourceRectangle; + private readonly Texture2D _sourceTexture; + private static readonly Point _numberSpritesOffset, _healthBarSpritesOffset; + private static readonly Rectangle _healthBarBackgroundSource; - private float _frameOffset; - private Vector2 _damageCounterPosition, _healthBarPosition; + private Action _doneCallback; + private bool _isMiss; + private List _numberSourceRectangles; + private Rectangle _healthBarSourceRectangle; - public bool Visible { get; private set; } + private float _frameOffset; + private Vector2 _damageCounterPosition, _healthBarPosition; - static HealthBarRenderer() - { - _numberSpritesOffset = new Point(40, 28); - _healthBarSpritesOffset = new Point(0, 28); - _healthBarBackgroundSource = new Rectangle(0, 28, 40, 7); - } + public bool Visible { get; private set; } - public HealthBarRenderer(INativeGraphicsManager nativeGraphicsManager, - IMapActor parentReference) - { - _parentReference = parentReference; - _sourceTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); - _numberSourceRectangles = new List(); - } - - public void SetDamage(Option value, int percentHealth, Action doneCallback = null) - { - Visible = true; - _isMiss = !value.HasValue; - _doneCallback = doneCallback; - _frameOffset = 0; + static HealthBarRenderer() + { + _numberSpritesOffset = new Point(40, 28); + _healthBarSpritesOffset = new Point(0, 28); + _healthBarBackgroundSource = new Rectangle(0, 28, 40, 7); + } - _numberSourceRectangles.Clear(); + public HealthBarRenderer(INativeGraphicsManager nativeGraphicsManager, + IMapActor parentReference) + { + _parentReference = parentReference; + _sourceTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true); + _numberSourceRectangles = new List(); + } - value.Match( - some: v => _numberSourceRectangles.AddRange( - GetNumberSourceRectangles(v, isHeal: false) - .Select(x => new Rectangle(_numberSpritesOffset + x.Location, x.Size))), - none: () => _numberSourceRectangles.Add(new Rectangle(_numberSpritesOffset + new Point(92, 0), new Point(30, 11)))); + public void SetDamage(Option value, int percentHealth, Action doneCallback = null) + { + Visible = true; + _isMiss = !value.HasValue; + _doneCallback = doneCallback; + _frameOffset = 0; - _healthBarSourceRectangle = GetHealthBarSourceRectangle(percentHealth); - _healthBarSourceRectangle = new Rectangle(_healthBarSpritesOffset + _healthBarSourceRectangle.Location, _healthBarSourceRectangle.Size); - } + _numberSourceRectangles.Clear(); - public void SetHealth(int value, int percentHealth, Action doneCallback = null) - { - Visible = true; - _isMiss = false; - _doneCallback = doneCallback; - _frameOffset = 0; - - _numberSourceRectangles.Clear(); - _numberSourceRectangles.AddRange( - GetNumberSourceRectangles(value, isHeal: true) - .Select(x => new Rectangle(_numberSpritesOffset + x.Location, x.Size))); - - _healthBarSourceRectangle = GetHealthBarSourceRectangle(percentHealth); - _healthBarSourceRectangle = new Rectangle(_healthBarSpritesOffset + _healthBarSourceRectangle.Location, _healthBarSourceRectangle.Size); - } + value.Match( + some: v => _numberSourceRectangles.AddRange( + GetNumberSourceRectangles(v, isHeal: false) + .Select(x => new Rectangle(_numberSpritesOffset + x.Location, x.Size))), + none: () => _numberSourceRectangles.Add(new Rectangle(_numberSpritesOffset + new Point(92, 0), new Point(30, 11)))); - public void Update(GameTime gameTime) - { - if (!Visible) return; + _healthBarSourceRectangle = GetHealthBarSourceRectangle(percentHealth); + _healthBarSourceRectangle = new Rectangle(_healthBarSpritesOffset + _healthBarSourceRectangle.Location, _healthBarSourceRectangle.Size); + } - _frameOffset += .1f; - if (_frameOffset > 4) + public void SetHealth(int value, int percentHealth, Action doneCallback = null) { - Visible = false; - _doneCallback?.Invoke(); + Visible = true; + _isMiss = false; + _doneCallback = doneCallback; + _frameOffset = 0; + + _numberSourceRectangles.Clear(); + _numberSourceRectangles.AddRange( + GetNumberSourceRectangles(value, isHeal: true) + .Select(x => new Rectangle(_numberSpritesOffset + x.Location, x.Size))); + + _healthBarSourceRectangle = GetHealthBarSourceRectangle(percentHealth); + _healthBarSourceRectangle = new Rectangle(_healthBarSpritesOffset + _healthBarSourceRectangle.Location, _healthBarSourceRectangle.Size); } - _healthBarPosition = new Vector2( - _parentReference.HorizontalCenter - _healthBarBackgroundSource.Width / 2f, - _parentReference.NameLabelY); - - if (_isMiss) + public void Update(GameTime gameTime) { - var xPos = _parentReference.HorizontalCenter - (_numberSourceRectangles[0].Width / 2f); - var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height * 2f; - _damageCounterPosition = new Vector2(xPos, yPos); + if (!Visible) return; + + _frameOffset += .1f; + if (_frameOffset > 4) + { + Visible = false; + _doneCallback?.Invoke(); + } + + _healthBarPosition = new Vector2( + _parentReference.HorizontalCenter - _healthBarBackgroundSource.Width / 2f, + _parentReference.NameLabelY); + + if (_isMiss) + { + var xPos = _parentReference.HorizontalCenter - (_numberSourceRectangles[0].Width / 2f); + var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height * 2f; + _damageCounterPosition = new Vector2(xPos, yPos); + } + else + { + var digitCount = _numberSourceRectangles.Count; + var xPos = _parentReference.HorizontalCenter - (digitCount * DigitWidth / 2f); + var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height * 2f; + _damageCounterPosition = new Vector2(xPos, yPos); + } } - else + + public void DrawToSpriteBatch(SpriteBatch spriteBatch) { - var digitCount = _numberSourceRectangles.Count; - var xPos = _parentReference.HorizontalCenter - (digitCount * DigitWidth / 2f); - var yPos = _parentReference.NameLabelY - _frameOffset - _healthBarBackgroundSource.Height * 2f; - _damageCounterPosition = new Vector2(xPos, yPos); - } - } + if (!Visible) return; - public void DrawToSpriteBatch(SpriteBatch spriteBatch) - { - if (!Visible) return; + var numberNdx = 0; + foreach (var numberSource in _numberSourceRectangles) + { + spriteBatch.Draw(_sourceTexture, _damageCounterPosition + new Vector2(numberNdx * DigitWidth, 0), numberSource, Color.White); + numberNdx++; + } - var numberNdx = 0; - foreach (var numberSource in _numberSourceRectangles) - { - spriteBatch.Draw(_sourceTexture, _damageCounterPosition + new Vector2(numberNdx * DigitWidth, 0), numberSource, Color.White); - numberNdx++; + spriteBatch.Draw(_sourceTexture, _healthBarPosition, _healthBarBackgroundSource, Color.White); + spriteBatch.Draw(_sourceTexture, _healthBarPosition, _healthBarSourceRectangle, Color.White); } - spriteBatch.Draw(_sourceTexture, _healthBarPosition, _healthBarBackgroundSource, Color.White); - spriteBatch.Draw(_sourceTexture, _healthBarPosition, _healthBarSourceRectangle, Color.White); - } - - private static IEnumerable GetNumberSourceRectangles(int value, bool isHeal) - { - var yCoord = isHeal ? 11 : 0; + private static IEnumerable GetNumberSourceRectangles(int value, bool isHeal) + { + var yCoord = isHeal ? 11 : 0; + + var digits = value.ToString(); + for (int i = 0; i < digits.Length; ++i) + { + int next = int.Parse($"{digits[i]}"); + yield return new Rectangle(next * DigitWidth, yCoord, 8, 11); + } + } - var digits = value.ToString(); - for (int i = 0; i < digits.Length; ++i) + private static Rectangle GetHealthBarSourceRectangle(int percentHealth) { - int next = int.Parse($"{digits[i]}"); - yield return new Rectangle(next * DigitWidth, yCoord, 8, 11); + // width of health bar is 40 + // percent -> pixels: (percentHealth / 100) * 40 + const double HealthBarFactor = .4; + + if (percentHealth >= 50) + return new Rectangle(0, 7, (int)Math.Round(percentHealth * HealthBarFactor), 7); + else if (percentHealth >= 25) + return new Rectangle(0, 14, (int)Math.Round(percentHealth * HealthBarFactor), 7); + else + return new Rectangle(0, 21, (int)Math.Round(percentHealth * HealthBarFactor), 7); } } - private static Rectangle GetHealthBarSourceRectangle(int percentHealth) + public interface IHealthBarRenderer { - // width of health bar is 40 - // percent -> pixels: (percentHealth / 100) * 40 - const double HealthBarFactor = .4; - - if (percentHealth >= 50) - return new Rectangle(0, 7, (int)Math.Round(percentHealth * HealthBarFactor), 7); - else if (percentHealth >= 25) - return new Rectangle(0, 14, (int)Math.Round(percentHealth * HealthBarFactor), 7); - else - return new Rectangle(0, 21, (int)Math.Round(percentHealth * HealthBarFactor), 7); - } -} - -public interface IHealthBarRenderer -{ - bool Visible { get; } + bool Visible { get; } - void SetDamage(Option value, int percentHealth, Action doneCallback = null); + void SetDamage(Option value, int percentHealth, Action doneCallback = null); - void SetHealth(int value, int percentHealth, Action doneCallback = null); + void SetHealth(int value, int percentHealth, Action doneCallback = null); - void Update(GameTime gameTime); + void Update(GameTime gameTime); - void DrawToSpriteBatch(SpriteBatch spriteBatch); + void DrawToSpriteBatch(SpriteBatch spriteBatch); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/IGameWindowRepository.cs b/EndlessClient/Rendering/IGameWindowRepository.cs index a11cf50ef..e2d5f912f 100644 --- a/EndlessClient/Rendering/IGameWindowRepository.cs +++ b/EndlessClient/Rendering/IGameWindowRepository.cs @@ -1,20 +1,21 @@ using AutomaticTypeMapper; using Microsoft.Xna.Framework; -namespace EndlessClient.Rendering; - -public interface IGameWindowRepository +namespace EndlessClient.Rendering { - GameWindow Window { get; set; } -} + public interface IGameWindowRepository + { + GameWindow Window { get; set; } + } -public interface IGameWindowProvider -{ - GameWindow Window { get; } -} + public interface IGameWindowProvider + { + GameWindow Window { get; } + } -[AutoMappedType(IsSingleton = true)] -public class GameWindowRepository : IGameWindowProvider, IGameWindowRepository -{ - public GameWindow Window { get; set; } + [AutoMappedType(IsSingleton = true)] + public class GameWindowRepository : IGameWindowProvider, IGameWindowRepository + { + public GameWindow Window { get; set; } + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/IMapActor.cs b/EndlessClient/Rendering/IMapActor.cs index 361b9854d..058a69ea5 100644 --- a/EndlessClient/Rendering/IMapActor.cs +++ b/EndlessClient/Rendering/IMapActor.cs @@ -1,25 +1,26 @@ using EOLib.Domain.Spells; using Microsoft.Xna.Framework; -namespace EndlessClient.Rendering; - -public interface IMapActor +namespace EndlessClient.Rendering { - int NameLabelY { get; } + public interface IMapActor + { + int NameLabelY { get; } - int HorizontalCenter { get; } + int HorizontalCenter { get; } - bool IsAlive { get; } + bool IsAlive { get; } - ISpellTargetable SpellTarget { get; } + ISpellTargetable SpellTarget { get; } - Rectangle DrawArea { get; } + Rectangle DrawArea { get; } - void ShowDamageCounter(int damage, int percentHealth, bool isHeal); + void ShowDamageCounter(int damage, int percentHealth, bool isHeal); - void ShowChatBubble(string text, bool isGroupChat = false); + void ShowChatBubble(string text, bool isGroupChat = false); - bool EffectIsPlaying(); + bool EffectIsPlaying(); - void PlayEffect(int effectId); + void PlayEffect(int effectId); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/ClickDispatcher.cs b/EndlessClient/Rendering/Map/ClickDispatcher.cs index f5459b245..9d7025423 100644 --- a/EndlessClient/Rendering/Map/ClickDispatcher.cs +++ b/EndlessClient/Rendering/Map/ClickDispatcher.cs @@ -20,244 +20,245 @@ using DomainCharacter = EOLib.Domain.Character.Character; using DomainNPC = EOLib.Domain.NPC.NPC; -namespace EndlessClient.Rendering.Map; - -public class ClickDispatcher : XNAControl, IClickDispatcher +namespace EndlessClient.Rendering.Map { - private readonly IHudControlProvider _hudControlProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IMapCellStateProvider _mapCellStateProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly INPCRendererProvider _npcRendererProvider; - private readonly ISpellSlotDataProvider _spellSlotDataProvider; - private readonly IContextMenuRepository _contextMenuRepository; - private readonly IMapObjectBoundsCalculator _mapObjectBoundsCalculator; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IMapInteractionController _mapInteractionController; - private readonly INPCInteractionController _npcInteractionController; - - public override Rectangle EventArea => new(0, 0, _clientWindowSizeProvider.Width, _clientWindowSizeProvider.Height); - - public ClickDispatcher(IHudControlProvider hudControlProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterProvider characterProvider, - IMapCellStateProvider mapCellStateProvider, - ICharacterRendererProvider characterRendererProvider, - INPCRendererProvider npcRendererProvider, - ISpellSlotDataProvider spellSlotDataProvider, - IContextMenuRepository contextMenuRepository, - - IMapObjectBoundsCalculator mapObjectBoundsCalculator, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - - IMapInteractionController mapInteractionController, - INPCInteractionController npcInteractionController) + public class ClickDispatcher : XNAControl, IClickDispatcher { - _hudControlProvider = hudControlProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _characterProvider = characterProvider; - _mapCellStateProvider = mapCellStateProvider; - _characterRendererProvider = characterRendererProvider; - _npcRendererProvider = npcRendererProvider; - _spellSlotDataProvider = spellSlotDataProvider; - _contextMenuRepository = contextMenuRepository; - _mapObjectBoundsCalculator = mapObjectBoundsCalculator; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - - _mapInteractionController = mapInteractionController; - _npcInteractionController = npcInteractionController; - } - - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - _contextMenuRepository.ContextMenu.MatchSome(contextMenu => + private readonly IHudControlProvider _hudControlProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IMapCellStateProvider _mapCellStateProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly INPCRendererProvider _npcRendererProvider; + private readonly ISpellSlotDataProvider _spellSlotDataProvider; + private readonly IContextMenuRepository _contextMenuRepository; + private readonly IMapObjectBoundsCalculator _mapObjectBoundsCalculator; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IMapInteractionController _mapInteractionController; + private readonly INPCInteractionController _npcInteractionController; + + public override Rectangle EventArea => new(0, 0, _clientWindowSizeProvider.Width, _clientWindowSizeProvider.Height); + + public ClickDispatcher(IHudControlProvider hudControlProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterProvider characterProvider, + IMapCellStateProvider mapCellStateProvider, + ICharacterRendererProvider characterRendererProvider, + INPCRendererProvider npcRendererProvider, + ISpellSlotDataProvider spellSlotDataProvider, + IContextMenuRepository contextMenuRepository, + + IMapObjectBoundsCalculator mapObjectBoundsCalculator, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + + IMapInteractionController mapInteractionController, + INPCInteractionController npcInteractionController) { - Game.Components.Remove(contextMenu); - contextMenu.Dispose(); + _hudControlProvider = hudControlProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _characterProvider = characterProvider; + _mapCellStateProvider = mapCellStateProvider; + _characterRendererProvider = characterRendererProvider; + _npcRendererProvider = npcRendererProvider; + _spellSlotDataProvider = spellSlotDataProvider; + _contextMenuRepository = contextMenuRepository; + _mapObjectBoundsCalculator = mapObjectBoundsCalculator; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + + _mapInteractionController = mapInteractionController; + _npcInteractionController = npcInteractionController; + } - _contextMenuRepository.ContextMenu = Option.None(); - }); + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + _contextMenuRepository.ContextMenu.MatchSome(contextMenu => + { + Game.Components.Remove(contextMenu); + contextMenu.Dispose(); - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - var cellState = _mapCellStateProvider.GetCellStateAt(mapRenderer.GridCoordinates); + _contextMenuRepository.ContextMenu = Option.None(); + }); - // map items should always get click priority so they can be picked up even when under a character/npc/other object - var mapItemPickupResult = CheckForMapItemClicks(cellState, eventArgs); - return CheckForEntityClicks(eventArgs) || CheckForTileClicks(cellState, eventArgs) || mapItemPickupResult; - } + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + var cellState = _mapCellStateProvider.GetCellStateAt(mapRenderer.GridCoordinates); - private bool CheckForMapItemClicks(IMapCellState cellState, MouseEventArgs eventArgs) - { - if (eventArgs.Button != MouseButton.Left) return false; + // map items should always get click priority so they can be picked up even when under a character/npc/other object + var mapItemPickupResult = CheckForMapItemClicks(cellState, eventArgs); + return CheckForEntityClicks(eventArgs) || CheckForTileClicks(cellState, eventArgs) || mapItemPickupResult; + } - if (cellState.Items.Any()) - _mapInteractionController.LeftClick(cellState); + private bool CheckForMapItemClicks(IMapCellState cellState, MouseEventArgs eventArgs) + { + if (eventArgs.Button != MouseButton.Left) return false; - return cellState.Items.Any(); - } + if (cellState.Items.Any()) + _mapInteractionController.LeftClick(cellState); - private bool CheckForEntityClicks(MouseEventArgs eventArgs) - { - var entities = new List(_currentMapStateProvider.Characters); - entities.Add(_characterProvider.MainCharacter); - entities.AddRange(_currentMapStateProvider.NPCs); - entities.AddRange(_currentMapProvider.CurrentMap.Signs); - entities.AddRange(_currentMapProvider.CurrentMap - .GetTileSpecs(TileSpec.Board1, TileSpec.Board2, TileSpec.Board3, TileSpec.Board4, - TileSpec.Board5, TileSpec.Board6, TileSpec.Board7, TileSpec.Board8, - TileSpec.Jukebox) - .Select(x => new TileSpecMapEntity(x.X, x.Y))); - - entities.Sort((a, b) => - { - return (a.Y * _currentMapProvider.CurrentMap.Properties.Width + a.X) - .CompareTo(b.Y * _currentMapProvider.CurrentMap.Properties.Width + b.X) * -1; - }); + return cellState.Items.Any(); + } - foreach (var entity in entities) + private bool CheckForEntityClicks(MouseEventArgs eventArgs) { - var bounds = GetEntityBounds(entity); + var entities = new List(_currentMapStateProvider.Characters); + entities.Add(_characterProvider.MainCharacter); + entities.AddRange(_currentMapStateProvider.NPCs); + entities.AddRange(_currentMapProvider.CurrentMap.Signs); + entities.AddRange(_currentMapProvider.CurrentMap + .GetTileSpecs(TileSpec.Board1, TileSpec.Board2, TileSpec.Board3, TileSpec.Board4, + TileSpec.Board5, TileSpec.Board6, TileSpec.Board7, TileSpec.Board8, + TileSpec.Jukebox) + .Select(x => new TileSpecMapEntity(x.X, x.Y))); + + entities.Sort((a, b) => + { + return (a.Y * _currentMapProvider.CurrentMap.Properties.Width + a.X) + .CompareTo(b.Y * _currentMapProvider.CurrentMap.Properties.Width + b.X) * -1; + }); - if (bounds.Contains(eventArgs.Position)) + foreach (var entity in entities) { - if (DispatchClickToEntity(entity, eventArgs)) + var bounds = GetEntityBounds(entity); + + if (bounds.Contains(eventArgs.Position)) { - _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator) - .CancelClickToWalk(); - return true; + if (DispatchClickToEntity(entity, eventArgs)) + { + _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator) + .CancelClickToWalk(); + return true; + } } } - } - return false; - } + return false; + } - private bool CheckForTileClicks(IMapCellState cellState, MouseEventArgs eventArgs) - { - if (eventArgs.Button == MouseButton.Left) + private bool CheckForTileClicks(IMapCellState cellState, MouseEventArgs eventArgs) { - _mapInteractionController.LeftClick(cellState); - return true; + if (eventArgs.Button == MouseButton.Left) + { + _mapInteractionController.LeftClick(cellState); + return true; + } + + return false; } - return false; - } + private bool DispatchClickToEntity(IMapEntity entity, MouseEventArgs eventArgs) + { + return entity switch + { + DomainCharacter c => HandleCharacterClick(c, eventArgs.Button), + DomainNPC n => eventArgs.Button == MouseButton.Left && HandleNPCClick(n, eventArgs.Position), + SignMapEntity s => eventArgs.Button == MouseButton.Left && HandleSignClick(s), + TileSpecMapEntity ts => eventArgs.Button == MouseButton.Left && HandleTileSpecClick(ts), + _ => throw new ArgumentException() + }; + } - private bool DispatchClickToEntity(IMapEntity entity, MouseEventArgs eventArgs) - { - return entity switch + private Rectangle GetEntityBounds(IMapEntity entity) { - DomainCharacter c => HandleCharacterClick(c, eventArgs.Button), - DomainNPC n => eventArgs.Button == MouseButton.Left && HandleNPCClick(n, eventArgs.Position), - SignMapEntity s => eventArgs.Button == MouseButton.Left && HandleSignClick(s), - TileSpecMapEntity ts => eventArgs.Button == MouseButton.Left && HandleTileSpecClick(ts), - _ => throw new ArgumentException() - }; - } + return entity switch + { + DomainCharacter c => GetCharacterRendererArea(c.ID), + DomainNPC n => GetNPCRendererArea(n.Index), + SignMapEntity or TileSpecMapEntity => GetObjectBounds(entity), + _ => throw new ArgumentException() + }; + } - private Rectangle GetEntityBounds(IMapEntity entity) - { - return entity switch + private Rectangle GetCharacterRendererArea(int characterId) { - DomainCharacter c => GetCharacterRendererArea(c.ID), - DomainNPC n => GetNPCRendererArea(n.Index), - SignMapEntity or TileSpecMapEntity => GetObjectBounds(entity), - _ => throw new ArgumentException() - }; - } + return _characterRendererProvider.MainCharacterRenderer.Match( + some: mcr => mcr.Character.ID == characterId ? mcr.DrawArea : RendererDrawAreaOrEmpty(characterId), + none: () => RendererDrawAreaOrEmpty(characterId)); - private Rectangle GetCharacterRendererArea(int characterId) - { - return _characterRendererProvider.MainCharacterRenderer.Match( - some: mcr => mcr.Character.ID == characterId ? mcr.DrawArea : RendererDrawAreaOrEmpty(characterId), - none: () => RendererDrawAreaOrEmpty(characterId)); + Rectangle RendererDrawAreaOrEmpty(int id) => _characterRendererProvider.CharacterRenderers.ContainsKey(characterId) + ? _characterRendererProvider.CharacterRenderers[characterId].DrawArea + : Rectangle.Empty; + } - Rectangle RendererDrawAreaOrEmpty(int id) => _characterRendererProvider.CharacterRenderers.ContainsKey(characterId) - ? _characterRendererProvider.CharacterRenderers[characterId].DrawArea + private Rectangle GetNPCRendererArea(int npcIndex) + { + return _npcRendererProvider.NPCRenderers.ContainsKey(npcIndex) + ? _npcRendererProvider.NPCRenderers[npcIndex].DrawArea : Rectangle.Empty; - } - - private Rectangle GetNPCRendererArea(int npcIndex) - { - return _npcRendererProvider.NPCRenderers.ContainsKey(npcIndex) - ? _npcRendererProvider.NPCRenderers[npcIndex].DrawArea - : Rectangle.Empty; - } - - private Rectangle GetObjectBounds(IMapEntity entity) - { - var gfx = _currentMapProvider.CurrentMap.GFX[MapLayer.Objects][entity.Y, entity.X]; - return gfx > 0 - ? _mapObjectBoundsCalculator.GetMapObjectBounds(entity.X, entity.Y, gfx) - // if there is no map object GFX at the sign's position, use the default tile coordinates - : new Rectangle( - _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(entity.X, entity.Y).ToPoint(), - new Point(64, 32)); - } + } - private bool HandleCharacterClick(DomainCharacter c, MouseButton button) - { - switch (button) + private Rectangle GetObjectBounds(IMapEntity entity) { - case MouseButton.Left: return _mapInteractionController.LeftClick(c); - case MouseButton.Right: _mapInteractionController.RightClick(c); break; - default: return false; + var gfx = _currentMapProvider.CurrentMap.GFX[MapLayer.Objects][entity.Y, entity.X]; + return gfx > 0 + ? _mapObjectBoundsCalculator.GetMapObjectBounds(entity.X, entity.Y, gfx) + // if there is no map object GFX at the sign's position, use the default tile coordinates + : new Rectangle( + _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(entity.X, entity.Y).ToPoint(), + new Point(64, 32)); } - return true; - } - - private bool HandleNPCClick(DomainNPC n, Point currentMousePosition) - { - var renderer = _npcRendererProvider.NPCRenderers[n.Index]; - - if (_spellSlotDataProvider.SpellIsPrepared) + private bool HandleCharacterClick(DomainCharacter c, MouseButton button) { - _mapInteractionController.LeftClick(n); + switch (button) + { + case MouseButton.Left: return _mapInteractionController.LeftClick(c); + case MouseButton.Right: _mapInteractionController.RightClick(c); break; + default: return false; + } + + return true; } - else if (renderer.IsClickablePixel(currentMousePosition)) + + private bool HandleNPCClick(DomainNPC n, Point currentMousePosition) { - _npcInteractionController.ShowNPCDialog(n); - } + var renderer = _npcRendererProvider.NPCRenderers[n.Index]; - return true; - } + if (_spellSlotDataProvider.SpellIsPrepared) + { + _mapInteractionController.LeftClick(n); + } + else if (renderer.IsClickablePixel(currentMousePosition)) + { + _npcInteractionController.ShowNPCDialog(n); + } - private bool HandleSignClick(SignMapEntity s) - { - var cellState = new MapCellState + return true; + } + + private bool HandleSignClick(SignMapEntity s) { - Sign = Option.Some(new Sign(s)), - Coordinate = new MapCoordinate(s.X, s.Y) - }; + var cellState = new MapCellState + { + Sign = Option.Some(new Sign(s)), + Coordinate = new MapCoordinate(s.X, s.Y) + }; - _mapInteractionController.LeftClick(cellState); + _mapInteractionController.LeftClick(cellState); - return true; - } + return true; + } - private bool HandleTileSpecClick(TileSpecMapEntity ts) - { - var cellState = new MapCellState + private bool HandleTileSpecClick(TileSpecMapEntity ts) { - Coordinate = new MapCoordinate(ts.X, ts.Y), - TileSpec = _currentMapProvider.CurrentMap.Tiles[ts.Y, ts.X] - }; + var cellState = new MapCellState + { + Coordinate = new MapCoordinate(ts.X, ts.Y), + TileSpec = _currentMapProvider.CurrentMap.Tiles[ts.Y, ts.X] + }; - _mapInteractionController.LeftClick(cellState); + _mapInteractionController.LeftClick(cellState); - return false; + return false; + } } -} -public interface IClickDispatcher : IGameComponent -{ - int DrawOrder { get; set; } + public interface IClickDispatcher : IGameComponent + { + int DrawOrder { get; set; } + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs b/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs index 77ddc36f7..1fd6e2c43 100644 --- a/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs +++ b/EndlessClient/Rendering/Map/ClickDispatcherFactory.cs @@ -7,78 +7,79 @@ using EOLib.Domain.Character; using EOLib.Domain.Map; -namespace EndlessClient.Rendering.Map; - -[AutoMappedType] -public class ClickDispatcherFactory : IClickDispatcherFactory +namespace EndlessClient.Rendering.Map { - private readonly IHudControlProvider _hudControlProvider; + [AutoMappedType] + public class ClickDispatcherFactory : IClickDispatcherFactory + { + private readonly IHudControlProvider _hudControlProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IMapCellStateProvider _mapCellStateProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly INPCRendererProvider _npcRendererProvider; - private readonly ISpellSlotDataProvider _spellSlotDataProvider; - private readonly IContextMenuRepository _contextMenuRepository; - private readonly IMapObjectBoundsCalculator _mapObjectBoundsCalculator; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IMapInteractionController _mapInteractionController; - private readonly INPCInteractionController _npcInteractionController; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IMapCellStateProvider _mapCellStateProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly INPCRendererProvider _npcRendererProvider; + private readonly ISpellSlotDataProvider _spellSlotDataProvider; + private readonly IContextMenuRepository _contextMenuRepository; + private readonly IMapObjectBoundsCalculator _mapObjectBoundsCalculator; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IMapInteractionController _mapInteractionController; + private readonly INPCInteractionController _npcInteractionController; - public ClickDispatcherFactory(IHudControlProvider hudControlProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterProvider characterProvider, - IMapCellStateProvider mapCellStateProvider, - ICharacterRendererProvider characterRendererProvider, - INPCRendererProvider npcRendererProvider, - ISpellSlotDataProvider spellSlotDataProvider, - IContextMenuRepository contextMenuRepository, - IMapObjectBoundsCalculator mapObjectBoundsCalculator, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IMapInteractionController mapInteractionController, - INPCInteractionController npcInteractionController) - { - _hudControlProvider = hudControlProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _characterProvider = characterProvider; - _mapCellStateProvider = mapCellStateProvider; - _characterRendererProvider = characterRendererProvider; - _npcRendererProvider = npcRendererProvider; - _spellSlotDataProvider = spellSlotDataProvider; - _contextMenuRepository = contextMenuRepository; - _mapObjectBoundsCalculator = mapObjectBoundsCalculator; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _mapInteractionController = mapInteractionController; - _npcInteractionController = npcInteractionController; + public ClickDispatcherFactory(IHudControlProvider hudControlProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterProvider characterProvider, + IMapCellStateProvider mapCellStateProvider, + ICharacterRendererProvider characterRendererProvider, + INPCRendererProvider npcRendererProvider, + ISpellSlotDataProvider spellSlotDataProvider, + IContextMenuRepository contextMenuRepository, + IMapObjectBoundsCalculator mapObjectBoundsCalculator, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IMapInteractionController mapInteractionController, + INPCInteractionController npcInteractionController) + { + _hudControlProvider = hudControlProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _characterProvider = characterProvider; + _mapCellStateProvider = mapCellStateProvider; + _characterRendererProvider = characterRendererProvider; + _npcRendererProvider = npcRendererProvider; + _spellSlotDataProvider = spellSlotDataProvider; + _contextMenuRepository = contextMenuRepository; + _mapObjectBoundsCalculator = mapObjectBoundsCalculator; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _mapInteractionController = mapInteractionController; + _npcInteractionController = npcInteractionController; + } + + public IClickDispatcher Create() + { + return new ClickDispatcher(_hudControlProvider, + _clientWindowSizeProvider, + _currentMapProvider, + _currentMapStateProvider, + _characterProvider, + _mapCellStateProvider, + _characterRendererProvider, + _npcRendererProvider, + _spellSlotDataProvider, + _contextMenuRepository, + _mapObjectBoundsCalculator, + _gridDrawCoordinateCalculator, + _mapInteractionController, + _npcInteractionController); + } } - public IClickDispatcher Create() + public interface IClickDispatcherFactory { - return new ClickDispatcher(_hudControlProvider, - _clientWindowSizeProvider, - _currentMapProvider, - _currentMapStateProvider, - _characterProvider, - _mapCellStateProvider, - _characterRendererProvider, - _npcRendererProvider, - _spellSlotDataProvider, - _contextMenuRepository, - _mapObjectBoundsCalculator, - _gridDrawCoordinateCalculator, - _mapInteractionController, - _npcInteractionController); + IClickDispatcher Create(); } -} - -public interface IClickDispatcherFactory -{ - IClickDispatcher Create(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs b/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs index 68b1a0e58..52fc59fd5 100644 --- a/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs +++ b/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs @@ -12,142 +12,143 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.Map; - -[AutoMappedType(IsSingleton = true)] -public class DynamicMapObjectUpdater : IDynamicMapObjectUpdater +namespace EndlessClient.Rendering.Map { - private const int DOOR_CLOSE_TIME_MS = 3000; - - private readonly ICharacterProvider _characterProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IConfigurationProvider _configurationProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly ISfxPlayer _sfxPlayer; - - private readonly List<(Warp Door, DateTime OpenTime)> _cachedDoorState; - private IMapFile _cachedMap; - private List _ambientSounds; - - public DynamicMapObjectUpdater(ICharacterProvider characterProvider, - ICharacterRendererProvider characterRendererProvider, - ICurrentMapStateRepository currentMapStateRepository, - ICurrentMapProvider currentMapProvider, - IConfigurationProvider configurationProvider, - IUserInputProvider userInputProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType(IsSingleton = true)] + public class DynamicMapObjectUpdater : IDynamicMapObjectUpdater { - _characterProvider = characterProvider; - _characterRendererProvider = characterRendererProvider; - _currentMapStateRepository = currentMapStateRepository; - _currentMapProvider = currentMapProvider; - _configurationProvider = configurationProvider; - _userInputProvider = userInputProvider; - _sfxPlayer = sfxPlayer; - - _cachedDoorState = new List<(Warp Door, DateTime OpenTime)>(); - _ambientSounds = new List(); - } - - public void UpdateMapObjects(GameTime gameTime) - { - // todo: this should probably be part of currentMapStateRepository instead of tracked here - if (_cachedMap != _currentMapProvider.CurrentMap) + private const int DOOR_CLOSE_TIME_MS = 3000; + + private readonly ICharacterProvider _characterProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IConfigurationProvider _configurationProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly ISfxPlayer _sfxPlayer; + + private readonly List<(Warp Door, DateTime OpenTime)> _cachedDoorState; + private IMapFile _cachedMap; + private List _ambientSounds; + + public DynamicMapObjectUpdater(ICharacterProvider characterProvider, + ICharacterRendererProvider characterRendererProvider, + ICurrentMapStateRepository currentMapStateRepository, + ICurrentMapProvider currentMapProvider, + IConfigurationProvider configurationProvider, + IUserInputProvider userInputProvider, + ISfxPlayer sfxPlayer) { - _ambientSounds = new List(_currentMapProvider.CurrentMap.GetTileSpecs(TileSpec.AmbientSource)); - _cachedMap = _currentMapProvider.CurrentMap; + _characterProvider = characterProvider; + _characterRendererProvider = characterRendererProvider; + _currentMapStateRepository = currentMapStateRepository; + _currentMapProvider = currentMapProvider; + _configurationProvider = configurationProvider; + _userInputProvider = userInputProvider; + _sfxPlayer = sfxPlayer; + + _cachedDoorState = new List<(Warp Door, DateTime OpenTime)>(); + _ambientSounds = new List(); } - var now = DateTime.Now; - OpenNewDoors(now); - CloseExpiredDoors(now); + public void UpdateMapObjects(GameTime gameTime) + { + // todo: this should probably be part of currentMapStateRepository instead of tracked here + if (_cachedMap != _currentMapProvider.CurrentMap) + { + _ambientSounds = new List(_currentMapProvider.CurrentMap.GetTileSpecs(TileSpec.AmbientSource)); + _cachedMap = _currentMapProvider.CurrentMap; + } - UpdateAmbientNoiseVolume(); + var now = DateTime.Now; + OpenNewDoors(now); + CloseExpiredDoors(now); - HideStackedCharacterNames(); - } + UpdateAmbientNoiseVolume(); - private void OpenNewDoors(DateTime now) - { - var newDoors = _currentMapStateRepository.OpenDoors.Where(x => _cachedDoorState.All(d => d.Door != x)); - foreach (var door in newDoors) - { - _cachedDoorState.Add((door, now)); - _sfxPlayer.PlaySfx(SoundEffectID.DoorOpen); + HideStackedCharacterNames(); } - } - private void CloseExpiredDoors(DateTime now) - { - var expiredDoors = _cachedDoorState.Where(x => (now - x.OpenTime).TotalMilliseconds > DOOR_CLOSE_TIME_MS).ToList(); - foreach (var door in expiredDoors) + private void OpenNewDoors(DateTime now) { - _cachedDoorState.Remove(door); - if (_currentMapStateRepository.OpenDoors.Contains(door.Door)) + var newDoors = _currentMapStateRepository.OpenDoors.Where(x => _cachedDoorState.All(d => d.Door != x)); + foreach (var door in newDoors) { - _currentMapStateRepository.OpenDoors.Remove(door.Door); - _sfxPlayer.PlaySfx(SoundEffectID.DoorClose); + _cachedDoorState.Add((door, now)); + _sfxPlayer.PlaySfx(SoundEffectID.DoorOpen); } } - } - private void UpdateAmbientNoiseVolume() - { - if (_cachedMap.Properties.AmbientNoise <= 0 || !_configurationProvider.SoundEnabled) - return; - - // the algorithm in EO main seems to scale volume with distance to the closest ambient source - // distance is the sum of the components of the vector from character position to closest ambient source - // this is scaled from 0-25, with 0 being on top of the tile and 25 being too far away to hear the ambient sound from it - var props = _characterProvider.MainCharacter.RenderProperties; - var charCoord = props.CurrentAction == CharacterActionState.Walking ? props.DestinationCoordinates() : props.Coordinates(); - var shortestDistance = int.MaxValue; - foreach (var coordinate in _ambientSounds) + private void CloseExpiredDoors(DateTime now) { - var distance = Math.Abs(charCoord.X - coordinate.X) + Math.Abs(charCoord.Y - coordinate.Y); - if (distance < shortestDistance) - shortestDistance = distance; + var expiredDoors = _cachedDoorState.Where(x => (now - x.OpenTime).TotalMilliseconds > DOOR_CLOSE_TIME_MS).ToList(); + foreach (var door in expiredDoors) + { + _cachedDoorState.Remove(door); + if (_currentMapStateRepository.OpenDoors.Contains(door.Door)) + { + _currentMapStateRepository.OpenDoors.Remove(door.Door); + _sfxPlayer.PlaySfx(SoundEffectID.DoorClose); + } + } } - _sfxPlayer.SetLoopingSfxVolume(Math.Max((25 - shortestDistance) / 25f, 0)); - } - private void HideStackedCharacterNames() - { - var characters = _characterRendererProvider.CharacterRenderers.Values - .Where(x => x.DrawArea.Contains(_userInputProvider.CurrentMouseState.Position)) - .GroupBy(x => x.Character.RenderProperties.Coordinates()); + private void UpdateAmbientNoiseVolume() + { + if (_cachedMap.Properties.AmbientNoise <= 0 || !_configurationProvider.SoundEnabled) + return; + + // the algorithm in EO main seems to scale volume with distance to the closest ambient source + // distance is the sum of the components of the vector from character position to closest ambient source + // this is scaled from 0-25, with 0 being on top of the tile and 25 being too far away to hear the ambient sound from it + var props = _characterProvider.MainCharacter.RenderProperties; + var charCoord = props.CurrentAction == CharacterActionState.Walking ? props.DestinationCoordinates() : props.Coordinates(); + var shortestDistance = int.MaxValue; + foreach (var coordinate in _ambientSounds) + { + var distance = Math.Abs(charCoord.X - coordinate.X) + Math.Abs(charCoord.Y - coordinate.Y); + if (distance < shortestDistance) + shortestDistance = distance; + } + _sfxPlayer.SetLoopingSfxVolume(Math.Max((25 - shortestDistance) / 25f, 0)); + } - foreach (var grouping in characters) + private void HideStackedCharacterNames() { - if (grouping.Count() > 1) + var characters = _characterRendererProvider.CharacterRenderers.Values + .Where(x => x.DrawArea.Contains(_userInputProvider.CurrentMouseState.Position)) + .GroupBy(x => x.Character.RenderProperties.Coordinates()); + + foreach (var grouping in characters) { - var isFirst = true; - foreach (var character in grouping.Reverse()) + if (grouping.Count() > 1) { - if (isFirst) - { - character.ShowName(); - } - else + var isFirst = true; + foreach (var character in grouping.Reverse()) { - character.HideName(); + if (isFirst) + { + character.ShowName(); + } + else + { + character.HideName(); + } + + isFirst = false; } - - isFirst = false; } - } - else - { - foreach (var character in grouping) - character.ShowName(); + else + { + foreach (var character in grouping) + character.ShowName(); + } } } } -} -public interface IDynamicMapObjectUpdater -{ - void UpdateMapObjects(GameTime gameTime); + public interface IDynamicMapObjectUpdater + { + void UpdateMapObjects(GameTime gameTime); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs b/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs index ed116105e..0182979a0 100644 --- a/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs +++ b/EndlessClient/Rendering/Map/IMapItemGraphicProvider.cs @@ -1,8 +1,9 @@ using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Map; - -public interface IMapItemGraphicProvider +namespace EndlessClient.Rendering.Map { - Texture2D GetItemGraphic(int id, int amount); + public interface IMapItemGraphicProvider + { + Texture2D GetItemGraphic(int id, int amount); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs b/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs index da21e211c..7e29d6466 100644 --- a/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs +++ b/EndlessClient/Rendering/Map/IMapRenderDistanceCalculator.cs @@ -1,8 +1,9 @@ using EOLib.IO.Map; -namespace EndlessClient.Rendering.Map; - -public interface IMapRenderDistanceCalculator +namespace EndlessClient.Rendering.Map { - MapRenderBounds CalculateRenderBounds(EOLib.Domain.Character.Character character, IMapFile currentMap); + public interface IMapRenderDistanceCalculator + { + MapRenderBounds CalculateRenderBounds(EOLib.Domain.Character.Character character, IMapFile currentMap); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/IMapRenderer.cs b/EndlessClient/Rendering/Map/IMapRenderer.cs index 8e2e5f870..00db8ffe2 100644 --- a/EndlessClient/Rendering/Map/IMapRenderer.cs +++ b/EndlessClient/Rendering/Map/IMapRenderer.cs @@ -1,23 +1,24 @@ using EOLib.Domain.Map; using Microsoft.Xna.Framework; -namespace EndlessClient.Rendering.Map; - -public interface IMapRenderer : IGameComponent, IDrawable +namespace EndlessClient.Rendering.Map { - MapCoordinate GridCoordinates { get; } + public interface IMapRenderer : IGameComponent, IDrawable + { + MapCoordinate GridCoordinates { get; } - bool MouseOver { get; } + bool MouseOver { get; } - void StartMapTransition(); + void StartMapTransition(); - void StartEarthquake(int strength); + void StartEarthquake(int strength); - void RedrawGroundLayer(); + void RedrawGroundLayer(); - void RenderEffect(MapCoordinate location, int effectId); + void RenderEffect(MapCoordinate location, int effectId); - void AnimateMouseClick(); + void AnimateMouseClick(); - void ClearTransientRenderables(); + void ClearTransientRenderables(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapChangedActions.cs b/EndlessClient/Rendering/Map/MapChangedActions.cs index 074746873..984c225f8 100644 --- a/EndlessClient/Rendering/Map/MapChangedActions.cs +++ b/EndlessClient/Rendering/Map/MapChangedActions.cs @@ -18,237 +18,238 @@ using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using System.Linq; -namespace EndlessClient.Rendering.Map; - -[MappedType(BaseType = typeof(IMapChangedActions))] -[MappedType(BaseType = typeof(IMapChangedNotifier))] -public class MapChangedActions : IMapChangedNotifier, IMapChangedActions +namespace EndlessClient.Rendering.Map { - private readonly ICharacterStateCache _characterStateCache; - private readonly INPCStateCache _npcStateCache; - private readonly INPCSpriteDataCache _npcSpriteDataCache; - private readonly ICharacterRendererRepository _characterRendererRepository; - private readonly INPCRendererRepository _npcRendererRepository; - private readonly IENFFileProvider _enfFileProvider; - private readonly IHudControlProvider _hudControlProvider; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IConfigurationProvider _configurationProvider; - private readonly IActiveDialogProvider _dialogProvider; - private readonly IMfxPlayer _mfxPlayer; - private readonly ISfxPlayer _sfxPlayer; - private readonly IChatController _chatController; - - public MapChangedActions(ICharacterStateCache characterStateCache, - INPCStateCache npcStateCache, - INPCSpriteDataCache npcSpriteDataCache, - ICharacterRendererRepository characterRendererRepository, - INPCRendererRepository npcRendererRepository, - IENFFileProvider enfFileProvider, - IHudControlProvider hudControlProvider, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateRepository currentMapStateRepository, - IConfigurationProvider configurationProvider, - IActiveDialogProvider dialogProvider, - IMfxPlayer mfxPlayer, - ISfxPlayer sfxPlayer, - IChatController chatController) - { - _characterStateCache = characterStateCache; - _npcStateCache = npcStateCache; - _npcSpriteDataCache = npcSpriteDataCache; - _characterRendererRepository = characterRendererRepository; - _npcRendererRepository = npcRendererRepository; - _enfFileProvider = enfFileProvider; - _hudControlProvider = hudControlProvider; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _currentMapProvider = currentMapProvider; - _currentMapStateRepository = currentMapStateRepository; - _configurationProvider = configurationProvider; - _dialogProvider = dialogProvider; - _mfxPlayer = mfxPlayer; - _sfxPlayer = sfxPlayer; - _chatController = chatController; - } - - public void ActiveCharacterEnterMapForLogin() - { - ShowMapNameIfAvailable(differentMapID: true); - ShowMapTransition(showMapTransition: true); - PlayBackgroundMusic(differentMapID: true); - PlayAmbientNoise(differentMapID: true); - ShowPkWarning(differentMapId: true); - } + [MappedType(BaseType = typeof(IMapChangedActions))] + [MappedType(BaseType = typeof(IMapChangedNotifier))] + public class MapChangedActions : IMapChangedNotifier, IMapChangedActions + { + private readonly ICharacterStateCache _characterStateCache; + private readonly INPCStateCache _npcStateCache; + private readonly INPCSpriteDataCache _npcSpriteDataCache; + private readonly ICharacterRendererRepository _characterRendererRepository; + private readonly INPCRendererRepository _npcRendererRepository; + private readonly IENFFileProvider _enfFileProvider; + private readonly IHudControlProvider _hudControlProvider; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IConfigurationProvider _configurationProvider; + private readonly IActiveDialogProvider _dialogProvider; + private readonly IMfxPlayer _mfxPlayer; + private readonly ISfxPlayer _sfxPlayer; + private readonly IChatController _chatController; + + public MapChangedActions(ICharacterStateCache characterStateCache, + INPCStateCache npcStateCache, + INPCSpriteDataCache npcSpriteDataCache, + ICharacterRendererRepository characterRendererRepository, + INPCRendererRepository npcRendererRepository, + IENFFileProvider enfFileProvider, + IHudControlProvider hudControlProvider, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateRepository currentMapStateRepository, + IConfigurationProvider configurationProvider, + IActiveDialogProvider dialogProvider, + IMfxPlayer mfxPlayer, + ISfxPlayer sfxPlayer, + IChatController chatController) + { + _characterStateCache = characterStateCache; + _npcStateCache = npcStateCache; + _npcSpriteDataCache = npcSpriteDataCache; + _characterRendererRepository = characterRendererRepository; + _npcRendererRepository = npcRendererRepository; + _enfFileProvider = enfFileProvider; + _hudControlProvider = hudControlProvider; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _currentMapProvider = currentMapProvider; + _currentMapStateRepository = currentMapStateRepository; + _configurationProvider = configurationProvider; + _dialogProvider = dialogProvider; + _mfxPlayer = mfxPlayer; + _sfxPlayer = sfxPlayer; + _chatController = chatController; + } - public void NotifyMapChanged(WarpEffect warpAnimation, bool differentMapID) - { - StopAllAnimations(); - ClearCharacterRenderersAndCache(); - ClearNPCRenderersAndCache(); - ClearOpenDoors(); - ShowMapNameIfAvailable(differentMapID); - ShowPkWarning(differentMapID); - ShowMapTransition(differentMapID); - ShowWarpBubbles(warpAnimation); - PlayBackgroundMusic(differentMapID); - PlayAmbientNoise(differentMapID); - - if (!differentMapID) - RedrawGroundLayer(); + public void ActiveCharacterEnterMapForLogin() + { + ShowMapNameIfAvailable(differentMapID: true); + ShowMapTransition(showMapTransition: true); + PlayBackgroundMusic(differentMapID: true); + PlayAmbientNoise(differentMapID: true); + ShowPkWarning(differentMapId: true); + } - CloseAllDialogs(); + public void NotifyMapChanged(WarpEffect warpAnimation, bool differentMapID) + { + StopAllAnimations(); + ClearCharacterRenderersAndCache(); + ClearNPCRenderersAndCache(); + ClearOpenDoors(); + ShowMapNameIfAvailable(differentMapID); + ShowPkWarning(differentMapID); + ShowMapTransition(differentMapID); + ShowWarpBubbles(warpAnimation); + PlayBackgroundMusic(differentMapID); + PlayAmbientNoise(differentMapID); + + if (!differentMapID) + RedrawGroundLayer(); + + CloseAllDialogs(); + + _chatController.ClearAndWarnIfJailAndGlobal(); + } - _chatController.ClearAndWarnIfJailAndGlobal(); - } + public void NotifyMapMutation() + { + ClearOpenDoors(); - public void NotifyMapMutation() - { - ClearOpenDoors(); + ShowMapTransition(showMapTransition: true); - ShowMapTransition(showMapTransition: true); + RedrawGroundLayer(); - RedrawGroundLayer(); + var localChatData = new ChatData(ChatTab.Local, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), _localizedStringFinder.GetString(EOResourceID.SERVER_MESSAGE_MAP_MUTATION), ChatIcon.Exclamation, ChatColor.Server); + var systemChatData = new ChatData(ChatTab.System, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), _localizedStringFinder.GetString(EOResourceID.SERVER_MESSAGE_MAP_MUTATION), ChatIcon.Exclamation, ChatColor.Server); + _chatRepository.AllChat[ChatTab.Local].Add(localChatData); + _chatRepository.AllChat[ChatTab.System].Add(systemChatData); - var localChatData = new ChatData(ChatTab.Local, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), _localizedStringFinder.GetString(EOResourceID.SERVER_MESSAGE_MAP_MUTATION), ChatIcon.Exclamation, ChatColor.Server); - var systemChatData = new ChatData(ChatTab.System, _localizedStringFinder.GetString(EOResourceID.STRING_SERVER), _localizedStringFinder.GetString(EOResourceID.SERVER_MESSAGE_MAP_MUTATION), ChatIcon.Exclamation, ChatColor.Server); - _chatRepository.AllChat[ChatTab.Local].Add(localChatData); - _chatRepository.AllChat[ChatTab.System].Add(systemChatData); + _sfxPlayer.PlaySfx(SoundEffectID.MapMutation); + } - _sfxPlayer.PlaySfx(SoundEffectID.MapMutation); - } + private void StopAllAnimations() + { + var characterAnimator = _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator); + characterAnimator.StopAllCharacterAnimations(); - private void StopAllAnimations() - { - var characterAnimator = _hudControlProvider.GetComponent(HudControlIdentifier.CharacterAnimator); - characterAnimator.StopAllCharacterAnimations(); + var npcAnimator = _hudControlProvider.GetComponent(HudControlIdentifier.NPCAnimator); + npcAnimator.StopAllAnimations(); + } - var npcAnimator = _hudControlProvider.GetComponent(HudControlIdentifier.NPCAnimator); - npcAnimator.StopAllAnimations(); - } + private void ClearCharacterRenderersAndCache() + { + _characterRendererRepository.MainCharacterRenderer.MatchSome(x => x.StopShout()); - private void ClearCharacterRenderersAndCache() - { - _characterRendererRepository.MainCharacterRenderer.MatchSome(x => x.StopShout()); + foreach (var characterRenderer in _characterRendererRepository.CharacterRenderers) + characterRenderer.Value.Dispose(); + _characterRendererRepository.CharacterRenderers.Clear(); + _characterStateCache.ClearAllOtherCharacterStates(); + } - foreach (var characterRenderer in _characterRendererRepository.CharacterRenderers) - characterRenderer.Value.Dispose(); - _characterRendererRepository.CharacterRenderers.Clear(); - _characterStateCache.ClearAllOtherCharacterStates(); - } + private void ClearNPCRenderersAndCache() + { + var currentMapNpcGraphics = _currentMapStateRepository.NPCs.Select(x => _enfFileProvider.ENFFile[x.ID].Graphic).ToList(); + var priorMapNpcGraphics = _npcRendererRepository.NPCRenderers.Select(x => _enfFileProvider.ENFFile[x.Value.NPC.ID].Graphic); - private void ClearNPCRenderersAndCache() - { - var currentMapNpcGraphics = _currentMapStateRepository.NPCs.Select(x => _enfFileProvider.ENFFile[x.ID].Graphic).ToList(); - var priorMapNpcGraphics = _npcRendererRepository.NPCRenderers.Select(x => _enfFileProvider.ENFFile[x.Value.NPC.ID].Graphic); + foreach (var evict in priorMapNpcGraphics.Except(currentMapNpcGraphics)) + _npcSpriteDataCache.MarkForEviction(evict); - foreach (var evict in priorMapNpcGraphics.Except(currentMapNpcGraphics)) - _npcSpriteDataCache.MarkForEviction(evict); + foreach (var unevict in currentMapNpcGraphics) + _npcSpriteDataCache.UnmarkForEviction(unevict); - foreach (var unevict in currentMapNpcGraphics) - _npcSpriteDataCache.UnmarkForEviction(unevict); + foreach (var npcRenderer in _npcRendererRepository.NPCRenderers) + npcRenderer.Value.Dispose(); + _npcRendererRepository.NPCRenderers.Clear(); + _npcStateCache.Reset(); + } - foreach (var npcRenderer in _npcRendererRepository.NPCRenderers) - npcRenderer.Value.Dispose(); - _npcRendererRepository.NPCRenderers.Clear(); - _npcStateCache.Reset(); - } + private void ClearOpenDoors() + { + _currentMapStateRepository.OpenDoors.Clear(); + } - private void ClearOpenDoors() - { - _currentMapStateRepository.OpenDoors.Clear(); - } + private void ShowMapNameIfAvailable(bool differentMapID) + { + if (!differentMapID || string.IsNullOrWhiteSpace(_currentMapProvider.CurrentMap.Properties.Name)) + return; - private void ShowMapNameIfAvailable(bool differentMapID) - { - if (!differentMapID || string.IsNullOrWhiteSpace(_currentMapProvider.CurrentMap.Properties.Name)) - return; + var message = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_YOU_ENTERED); + message = string.Format(message + " {0}", _currentMapProvider.CurrentMap.Properties.Name); - var message = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_YOU_ENTERED); - message = string.Format(message + " {0}", _currentMapProvider.CurrentMap.Properties.Name); + var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.NoteLeftArrow); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } - var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.NoteLeftArrow); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } + private void ShowPkWarning(bool differentMapId) + { + if (!differentMapId || !_currentMapProvider.CurrentMap.Properties.PKAvailable) + return; - private void ShowPkWarning(bool differentMapId) - { - if (!differentMapId || !_currentMapProvider.CurrentMap.Properties.PKAvailable) - return; + var message = _localizedStringFinder.GetString(EOResourceID.CAUTION_THIS_IS_A_PK_ZONE); + var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.NoteLeftArrow); + _chatRepository.AllChat[ChatTab.System].Add(chatData); - var message = _localizedStringFinder.GetString(EOResourceID.CAUTION_THIS_IS_A_PK_ZONE); - var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.NoteLeftArrow); - _chatRepository.AllChat[ChatTab.System].Add(chatData); + _sfxPlayer.PlaySfx(SoundEffectID.EnterPkMap); + } - _sfxPlayer.PlaySfx(SoundEffectID.EnterPkMap); - } + private void ShowMapTransition(bool showMapTransition) + { + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + mapRenderer.ClearTransientRenderables(); - private void ShowMapTransition(bool showMapTransition) - { - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - mapRenderer.ClearTransientRenderables(); + if (showMapTransition) + { + mapRenderer.StartMapTransition(); + } + } - if (showMapTransition) + private void ShowWarpBubbles(WarpEffect animation) { - mapRenderer.StartMapTransition(); + _characterRendererRepository.MainCharacterRenderer.MatchSome(r => + { + if (animation == WarpEffect.Admin) + r.PlayEffect((int)HardCodedEffect.WarpArrive); + }); } - } - private void ShowWarpBubbles(WarpEffect animation) - { - _characterRendererRepository.MainCharacterRenderer.MatchSome(r => + private void RedrawGroundLayer() { - if (animation == WarpEffect.Admin) - r.PlayEffect((int)HardCodedEffect.WarpArrive); - }); - } - - private void RedrawGroundLayer() - { - var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); - mapRenderer.RedrawGroundLayer(); - } + var mapRenderer = _hudControlProvider.GetComponent(HudControlIdentifier.MapRenderer); + mapRenderer.RedrawGroundLayer(); + } - private void PlayBackgroundMusic(bool differentMapID) - { - if (!_configurationProvider.MusicEnabled || !differentMapID) - return; - - var music = _currentMapProvider.CurrentMap.Properties.Music; - var musicControl = _currentMapProvider.CurrentMap.Properties.Control; - if (music > 0) - _mfxPlayer.PlayBackgroundMusic(_currentMapProvider.CurrentMap.Properties.Music, musicControl); - else - _mfxPlayer.StopBackgroundMusic(); - } + private void PlayBackgroundMusic(bool differentMapID) + { + if (!_configurationProvider.MusicEnabled || !differentMapID) + return; + + var music = _currentMapProvider.CurrentMap.Properties.Music; + var musicControl = _currentMapProvider.CurrentMap.Properties.Control; + if (music > 0) + _mfxPlayer.PlayBackgroundMusic(_currentMapProvider.CurrentMap.Properties.Music, musicControl); + else + _mfxPlayer.StopBackgroundMusic(); + } - private void PlayAmbientNoise(bool differentMapID) - { - if (!_configurationProvider.SoundEnabled || !differentMapID) - return; + private void PlayAmbientNoise(bool differentMapID) + { + if (!_configurationProvider.SoundEnabled || !differentMapID) + return; + + var noise = _currentMapProvider.CurrentMap.Properties.AmbientNoise; + if (noise > 0) + { + _sfxPlayer.StopLoopingSfx(); + _sfxPlayer.PlayLoopingSfx((SoundEffectID)noise); + } + else + _sfxPlayer.StopLoopingSfx(); + } - var noise = _currentMapProvider.CurrentMap.Properties.AmbientNoise; - if (noise > 0) + private void CloseAllDialogs() { - _sfxPlayer.StopLoopingSfx(); - _sfxPlayer.PlayLoopingSfx((SoundEffectID)noise); + foreach (var dlg in _dialogProvider.ActiveDialogs) + dlg.MatchSome(x => ((BaseEODialog)x).Close()); } - else - _sfxPlayer.StopLoopingSfx(); } - private void CloseAllDialogs() + public interface IMapChangedActions { - foreach (var dlg in _dialogProvider.ActiveDialogs) - dlg.MatchSome(x => ((BaseEODialog)x).Close()); + void ActiveCharacterEnterMapForLogin(); } -} - -public interface IMapChangedActions -{ - void ActiveCharacterEnterMapForLogin(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs b/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs index bf1e7ab44..a5049694a 100644 --- a/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs +++ b/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs @@ -8,120 +8,121 @@ using EOLib.Graphics; using System.Collections.Generic; -namespace EndlessClient.Rendering.Map; - -[MappedType(BaseType = typeof(IMapEntityRendererProvider), IsSingleton = true)] -public class MapEntityRendererProvider : IMapEntityRendererProvider +namespace EndlessClient.Rendering.Map { - public IMapEntityRenderer GroundRenderer { get; } + [MappedType(BaseType = typeof(IMapEntityRendererProvider), IsSingleton = true)] + public class MapEntityRendererProvider : IMapEntityRendererProvider + { + public IMapEntityRenderer GroundRenderer { get; } - public IReadOnlyList BaseRenderers { get; } + public IReadOnlyList BaseRenderers { get; } - public IReadOnlyList MapEntityRenderers { get; } + public IReadOnlyList MapEntityRenderers { get; } - public MapEntityRendererProvider(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - ICurrentMapStateProvider currentMapStateProvider, - IMapItemGraphicProvider mapItemGraphicProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - IConfigurationProvider configurationProvider, - ICharacterRendererProvider characterRendererProvider, - INPCRendererProvider npcRendererProvider) - { - GroundRenderer = - new GroundLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider); - - BaseRenderers = new List + public MapEntityRendererProvider(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + ICurrentMapStateProvider currentMapStateProvider, + IMapItemGraphicProvider mapItemGraphicProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + IConfigurationProvider configurationProvider, + ICharacterRendererProvider characterRendererProvider, + INPCRendererProvider npcRendererProvider) { - new AnimatedGroundLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new MapItemLayerRenderer(characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - currentMapStateProvider, - mapItemGraphicProvider) - }; + GroundRenderer = + new GroundLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider); - MapEntityRenderers = new List - { - new ShadowLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - configurationProvider), - new OverlayLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new MapObjectLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - currentMapStateProvider), - new MainCharacterEntityRenderer(characterProvider, - characterRendererProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - transparent: false), - new DownWallLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, + BaseRenderers = new List + { + new AnimatedGroundLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new MapItemLayerRenderer(characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + currentMapStateProvider, + mapItemGraphicProvider) + }; + + MapEntityRenderers = new List + { + new ShadowLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + configurationProvider), + new OverlayLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new MapObjectLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + currentMapStateProvider), + new MainCharacterEntityRenderer(characterProvider, + characterRendererProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + transparent: false), + new DownWallLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + currentMapStateProvider), + new RightWallLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + currentMapStateProvider), + new OtherCharacterEntityRenderer(characterProvider, + characterRendererProvider, + currentMapStateProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new NPCEntityRenderer(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider, + npcRendererProvider, currentMapStateProvider), - new RightWallLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - currentMapStateProvider), - new OtherCharacterEntityRenderer(characterProvider, - characterRendererProvider, - currentMapStateProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new NPCEntityRenderer(characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - npcRendererProvider, - currentMapStateProvider), - new Overlay2LayerRenderer(nativeGraphicsManager, + new Overlay2LayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new RoofLayerRenderer(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider), - new RoofLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new RoofLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new OnTopLayerRenderer(nativeGraphicsManager, - currentMapProvider, - characterProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider), - new MainCharacterEntityRenderer(characterProvider, - characterRendererProvider, - gridDrawCoordinateCalculator, - clientWindowSizeProvider, - transparent: true) - }; + new RoofLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new OnTopLayerRenderer(nativeGraphicsManager, + currentMapProvider, + characterProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider), + new MainCharacterEntityRenderer(characterProvider, + characterRendererProvider, + gridDrawCoordinateCalculator, + clientWindowSizeProvider, + transparent: true) + }; + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs b/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs index d5b9799fc..ef4fab820 100644 --- a/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs +++ b/EndlessClient/Rendering/Map/MapItemGraphicProvider.cs @@ -4,33 +4,34 @@ using EOLib.IO.Repositories; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Map; - -[AutoMappedType] -public class MapItemGraphicProvider : IMapItemGraphicProvider +namespace EndlessClient.Rendering.Map { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IEIFFileProvider _eifFileProvider; - - public MapItemGraphicProvider(INativeGraphicsManager nativeGraphicsManager, IEIFFileProvider eifFileProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _eifFileProvider = eifFileProvider; - } - - public Texture2D GetItemGraphic(int id, int amount) + [AutoMappedType] + public class MapItemGraphicProvider : IMapItemGraphicProvider { - var item = _eifFileProvider.EIFFile[id]; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IEIFFileProvider _eifFileProvider; - if (item.Type == ItemType.Money) + public MapItemGraphicProvider(INativeGraphicsManager nativeGraphicsManager, IEIFFileProvider eifFileProvider) { - var gfx = amount >= 100000 ? 4 : ( - amount >= 10000 ? 3 : ( - amount >= 100 ? 2 : ( - amount >= 2 ? 1 : 0))); - return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 269 + 2 * gfx, true); + _nativeGraphicsManager = nativeGraphicsManager; + _eifFileProvider = eifFileProvider; } - return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 2 * item.Graphic - 1, true); + public Texture2D GetItemGraphic(int id, int amount) + { + var item = _eifFileProvider.EIFFile[id]; + + if (item.Type == ItemType.Money) + { + var gfx = amount >= 100000 ? 4 : ( + amount >= 10000 ? 3 : ( + amount >= 100 ? 2 : ( + amount >= 2 ? 1 : 0))); + return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 269 + 2 * gfx, true); + } + + return _nativeGraphicsManager.TextureFromResource(GFXTypes.Items, 2 * item.Graphic - 1, true); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs b/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs index fdeb30b07..1a6625b4a 100644 --- a/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs +++ b/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs @@ -5,39 +5,40 @@ using Microsoft.Xna.Framework; using System.Linq; -namespace EndlessClient.Rendering.Map; - -[AutoMappedType] -public class MapObjectBoundsCalculator : IMapObjectBoundsCalculator +namespace EndlessClient.Rendering.Map { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICharacterProvider _characterProvider; - private readonly IRenderOffsetCalculator _renderOffsetCalculator; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - - public MapObjectBoundsCalculator(INativeGraphicsManager nativeGraphicsManager, - ICharacterProvider characterProvider, - IRenderOffsetCalculator renderOffsetCalculator, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) + [AutoMappedType] + public class MapObjectBoundsCalculator : IMapObjectBoundsCalculator { - _nativeGraphicsManager = nativeGraphicsManager; - _characterProvider = characterProvider; - _renderOffsetCalculator = renderOffsetCalculator; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICharacterProvider _characterProvider; + private readonly IRenderOffsetCalculator _renderOffsetCalculator; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + + public MapObjectBoundsCalculator(INativeGraphicsManager nativeGraphicsManager, + ICharacterProvider characterProvider, + IRenderOffsetCalculator renderOffsetCalculator, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) + { + _nativeGraphicsManager = nativeGraphicsManager; + _characterProvider = characterProvider; + _renderOffsetCalculator = renderOffsetCalculator; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + } + + public Rectangle GetMapObjectBounds(int gridX, int gridY, int gfxNum) + { + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapObjects, gfxNum, transparent: true); + var drawPosition = _gridDrawCoordinateCalculator.CalculateDrawCoordinatesFromGridUnits(gridX, gridY); + // see: MapObjectLayerRenderer + // todo: more centralized way of representing this + drawPosition -= new Vector2(gfx.Width / 2, gfx.Height - 32); + return gfx.Bounds.WithPosition(drawPosition); + } } - public Rectangle GetMapObjectBounds(int gridX, int gridY, int gfxNum) + public interface IMapObjectBoundsCalculator { - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapObjects, gfxNum, transparent: true); - var drawPosition = _gridDrawCoordinateCalculator.CalculateDrawCoordinatesFromGridUnits(gridX, gridY); - // see: MapObjectLayerRenderer - // todo: more centralized way of representing this - drawPosition -= new Vector2(gfx.Width / 2, gfx.Height - 32); - return gfx.Bounds.WithPosition(drawPosition); + Rectangle GetMapObjectBounds(int gridX, int gridY, int gfxNum); } -} - -public interface IMapObjectBoundsCalculator -{ - Rectangle GetMapObjectBounds(int gridX, int gridY, int gfxNum); } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapRenderBounds.cs b/EndlessClient/Rendering/Map/MapRenderBounds.cs index 229186a9c..cfc199502 100644 --- a/EndlessClient/Rendering/Map/MapRenderBounds.cs +++ b/EndlessClient/Rendering/Map/MapRenderBounds.cs @@ -1,18 +1,19 @@ -namespace EndlessClient.Rendering.Map; - -public struct MapRenderBounds +namespace EndlessClient.Rendering.Map { - public int FirstRow { get; private set; } - public int LastRow { get; private set; } - public int FirstCol { get; private set; } - public int LastCol { get; private set; } - - public MapRenderBounds(int firstRow, int lastRow, int firstCol, int lastCol) - : this() + public struct MapRenderBounds { - FirstRow = firstRow; - LastRow = lastRow; - FirstCol = firstCol; - LastCol = lastCol; + public int FirstRow { get; private set; } + public int LastRow { get; private set; } + public int FirstCol { get; private set; } + public int LastCol { get; private set; } + + public MapRenderBounds(int firstRow, int lastRow, int firstCol, int lastCol) + : this() + { + FirstRow = firstRow; + LastRow = lastRow; + FirstCol = firstCol; + LastCol = lastCol; + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs b/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs index f62eb6b93..85a850863 100644 --- a/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs +++ b/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs @@ -2,29 +2,30 @@ using EOLib.IO.Map; using System; -namespace EndlessClient.Rendering.Map; - -[AutoMappedType] -public class MapRenderDistanceCalculator : IMapRenderDistanceCalculator +namespace EndlessClient.Rendering.Map { - private const int DEFAULT_BOUNDS_DISTANCE = 22; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - - public MapRenderDistanceCalculator(IClientWindowSizeProvider clientWindowSizeProvider) + [AutoMappedType] + public class MapRenderDistanceCalculator : IMapRenderDistanceCalculator { - _clientWindowSizeProvider = clientWindowSizeProvider; - } + private const int DEFAULT_BOUNDS_DISTANCE = 22; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - public MapRenderBounds CalculateRenderBounds(EOLib.Domain.Character.Character character, IMapFile currentMap) - { - var boundsDistanceX = (int)Math.Ceiling((_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Width / 640.0 : 1) * DEFAULT_BOUNDS_DISTANCE); - var boundsDistanceY = (int)Math.Ceiling((_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Width / 320.0 : 1) * DEFAULT_BOUNDS_DISTANCE); + public MapRenderDistanceCalculator(IClientWindowSizeProvider clientWindowSizeProvider) + { + _clientWindowSizeProvider = clientWindowSizeProvider; + } + + public MapRenderBounds CalculateRenderBounds(EOLib.Domain.Character.Character character, IMapFile currentMap) + { + var boundsDistanceX = (int)Math.Ceiling((_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Width / 640.0 : 1) * DEFAULT_BOUNDS_DISTANCE); + var boundsDistanceY = (int)Math.Ceiling((_clientWindowSizeProvider.Resizable ? _clientWindowSizeProvider.Width / 320.0 : 1) * DEFAULT_BOUNDS_DISTANCE); - var firstRow = Math.Max(character.RenderProperties.MapY - boundsDistanceY, 0); - var lastRow = Math.Min(character.RenderProperties.MapY + boundsDistanceY, currentMap.Properties.Height); - var firstCol = Math.Max(character.RenderProperties.MapX - boundsDistanceX, 0); - var lastCol = Math.Min(character.RenderProperties.MapX + boundsDistanceX, currentMap.Properties.Width); + var firstRow = Math.Max(character.RenderProperties.MapY - boundsDistanceY, 0); + var lastRow = Math.Min(character.RenderProperties.MapY + boundsDistanceY, currentMap.Properties.Height); + var firstCol = Math.Max(character.RenderProperties.MapX - boundsDistanceX, 0); + var lastCol = Math.Min(character.RenderProperties.MapX + boundsDistanceX, currentMap.Properties.Width); - return new MapRenderBounds(firstRow, lastRow, firstCol, lastCol); + return new MapRenderBounds(firstRow, lastRow, firstCol, lastCol); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapRenderLayer.cs b/EndlessClient/Rendering/Map/MapRenderLayer.cs index 22fdd3e36..52478bc5c 100644 --- a/EndlessClient/Rendering/Map/MapRenderLayer.cs +++ b/EndlessClient/Rendering/Map/MapRenderLayer.cs @@ -1,19 +1,20 @@ -namespace EndlessClient.Rendering.Map; - -public enum MapRenderLayer +namespace EndlessClient.Rendering.Map { - Ground, - Item, - Overlay, - Shadows, - MainCharacter, - DownWall, - RightWall, - Objects, - OtherCharacters, - Npc, - Overlay2, - Roof, - OnTop, - MainCharacterTransparent + public enum MapRenderLayer + { + Ground, + Item, + Overlay, + Shadows, + MainCharacter, + DownWall, + RightWall, + Objects, + OtherCharacters, + Npc, + Overlay2, + Roof, + OnTop, + MainCharacterTransparent + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MapRenderer.cs b/EndlessClient/Rendering/Map/MapRenderer.cs index 23185857a..60c66eaaa 100644 --- a/EndlessClient/Rendering/Map/MapRenderer.cs +++ b/EndlessClient/Rendering/Map/MapRenderer.cs @@ -18,566 +18,567 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.Map; - -public class MapRenderer : DrawableGameComponent, IMapRenderer +namespace EndlessClient.Rendering.Map { - private const double TRANSITION_TIME_MS = 60.0; - - private readonly object _rt_locker_ = new object(); - - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IEffectRendererFactory _effectRendererFactory; - private readonly IMapEntityRendererProvider _mapEntityRendererProvider; - private readonly ICharacterProvider _characterProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IContentProvider _contentProvider; - private readonly IMapRenderDistanceCalculator _mapRenderDistanceCalculator; - private readonly ICharacterRendererUpdater _characterRendererUpdater; - private readonly INPCRendererUpdater _npcRendererUpdater; - private readonly IDynamicMapObjectUpdater _dynamicMapObjectUpdater; - private readonly IConfigurationProvider _configurationProvider; - private readonly IMouseCursorRenderer _mouseCursorRenderer; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IClientWindowSizeRepository _clientWindowSizeRepository; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - - private RenderTarget2D _mapBaseTarget, _mapObjectTarget; - private SpriteBatch _sb; - private MapTransitionState _mapTransitionState = MapTransitionState.Default; - private IReadOnlyList _lastMapChecksum; - private bool _groundDrawn; - - private Option _quakeState; - - private IDictionary _mapGridEffectRenderers; - - public bool MouseOver + public class MapRenderer : DrawableGameComponent, IMapRenderer { - get + private const double TRANSITION_TIME_MS = 60.0; + + private readonly object _rt_locker_ = new object(); + + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IEffectRendererFactory _effectRendererFactory; + private readonly IMapEntityRendererProvider _mapEntityRendererProvider; + private readonly ICharacterProvider _characterProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IContentProvider _contentProvider; + private readonly IMapRenderDistanceCalculator _mapRenderDistanceCalculator; + private readonly ICharacterRendererUpdater _characterRendererUpdater; + private readonly INPCRendererUpdater _npcRendererUpdater; + private readonly IDynamicMapObjectUpdater _dynamicMapObjectUpdater; + private readonly IConfigurationProvider _configurationProvider; + private readonly IMouseCursorRenderer _mouseCursorRenderer; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IClientWindowSizeRepository _clientWindowSizeRepository; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + + private RenderTarget2D _mapBaseTarget, _mapObjectTarget; + private SpriteBatch _sb; + private MapTransitionState _mapTransitionState = MapTransitionState.Default; + private IReadOnlyList _lastMapChecksum; + private bool _groundDrawn; + + private Option _quakeState; + + private IDictionary _mapGridEffectRenderers; + + public bool MouseOver { - var ms = Mouse.GetState(); - return Game.IsActive && ms.X > 0 && ms.Y > 0 && - ms.X < _clientWindowSizeRepository.Width && - ms.Y < (_clientWindowSizeRepository.Resizable ? _clientWindowSizeRepository.Height : _clientWindowSizeRepository.Height * 2 / 3); + get + { + var ms = Mouse.GetState(); + return Game.IsActive && ms.X > 0 && ms.Y > 0 && + ms.X < _clientWindowSizeRepository.Width && + ms.Y < (_clientWindowSizeRepository.Resizable ? _clientWindowSizeRepository.Height : _clientWindowSizeRepository.Height * 2 / 3); + } } - } - - public MapCoordinate GridCoordinates => _mouseCursorRenderer.GridCoordinates; - - public MapRenderer(IEndlessGame endlessGame, - IRenderTargetFactory renderTargetFactory, - IEffectRendererFactory effectRendererFactory, - IMapEntityRendererProvider mapEntityRendererProvider, - ICharacterProvider characterProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - IContentProvider contentProvider, - IMapRenderDistanceCalculator mapRenderDistanceCalculator, - ICharacterRendererUpdater characterRendererUpdater, - INPCRendererUpdater npcRendererUpdater, - IDynamicMapObjectUpdater dynamicMapObjectUpdater, - IConfigurationProvider configurationProvider, - IMouseCursorRenderer mouseCursorRenderer, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeRepository clientWindowSizeRepository, - IFixedTimeStepRepository fixedTimeStepRepository) - : base((Game)endlessGame) - { - _renderTargetFactory = renderTargetFactory; - _effectRendererFactory = effectRendererFactory; - _mapEntityRendererProvider = mapEntityRendererProvider; - _characterProvider = characterProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _contentProvider = contentProvider; - _mapRenderDistanceCalculator = mapRenderDistanceCalculator; - _characterRendererUpdater = characterRendererUpdater; - _npcRendererUpdater = npcRendererUpdater; - _dynamicMapObjectUpdater = dynamicMapObjectUpdater; - _configurationProvider = configurationProvider; - _mouseCursorRenderer = mouseCursorRenderer; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _clientWindowSizeRepository = clientWindowSizeRepository; - _fixedTimeStepRepository = fixedTimeStepRepository; - _mapGridEffectRenderers = new Dictionary(); - } - public override void Initialize() - { - _clientWindowSizeRepository.GameWindowSizeChanged += ResizeGameWindow; + public MapCoordinate GridCoordinates => _mouseCursorRenderer.GridCoordinates; + + public MapRenderer(IEndlessGame endlessGame, + IRenderTargetFactory renderTargetFactory, + IEffectRendererFactory effectRendererFactory, + IMapEntityRendererProvider mapEntityRendererProvider, + ICharacterProvider characterProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + IContentProvider contentProvider, + IMapRenderDistanceCalculator mapRenderDistanceCalculator, + ICharacterRendererUpdater characterRendererUpdater, + INPCRendererUpdater npcRendererUpdater, + IDynamicMapObjectUpdater dynamicMapObjectUpdater, + IConfigurationProvider configurationProvider, + IMouseCursorRenderer mouseCursorRenderer, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeRepository clientWindowSizeRepository, + IFixedTimeStepRepository fixedTimeStepRepository) + : base((Game)endlessGame) + { + _renderTargetFactory = renderTargetFactory; + _effectRendererFactory = effectRendererFactory; + _mapEntityRendererProvider = mapEntityRendererProvider; + _characterProvider = characterProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _contentProvider = contentProvider; + _mapRenderDistanceCalculator = mapRenderDistanceCalculator; + _characterRendererUpdater = characterRendererUpdater; + _npcRendererUpdater = npcRendererUpdater; + _dynamicMapObjectUpdater = dynamicMapObjectUpdater; + _configurationProvider = configurationProvider; + _mouseCursorRenderer = mouseCursorRenderer; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _clientWindowSizeRepository = clientWindowSizeRepository; + _fixedTimeStepRepository = fixedTimeStepRepository; + _mapGridEffectRenderers = new Dictionary(); + } - _mapBaseTarget = _renderTargetFactory.CreateRenderTarget(); - _mapObjectTarget = _renderTargetFactory.CreateRenderTarget(); - _sb = new SpriteBatch(Game.GraphicsDevice); + public override void Initialize() + { + _clientWindowSizeRepository.GameWindowSizeChanged += ResizeGameWindow; - _mouseCursorRenderer.Initialize(); + _mapBaseTarget = _renderTargetFactory.CreateRenderTarget(); + _mapObjectTarget = _renderTargetFactory.CreateRenderTarget(); + _sb = new SpriteBatch(Game.GraphicsDevice); - DrawOrder = -10; + _mouseCursorRenderer.Initialize(); - base.Initialize(); - } + DrawOrder = -10; - public override void Update(GameTime gameTime) - { - if (_currentMapStateProvider.IsSleepWarp) return; + base.Initialize(); + } - if (_lastMapChecksum == null || !_lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) + public override void Update(GameTime gameTime) { - // The dimensions of the map are 0-based in the properties. Adjust to 1-based for RT creation - var widthPlus1 = _currentMapProvider.CurrentMap.Properties.Width + 1; - var heightPlus1 = _currentMapProvider.CurrentMap.Properties.Height + 1; + if (_currentMapStateProvider.IsSleepWarp) return; - lock (_rt_locker_) + if (_lastMapChecksum == null || !_lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) { - _mapBaseTarget.Dispose(); - _mapBaseTarget = _renderTargetFactory.CreateRenderTarget( - (widthPlus1 + heightPlus1) * 32, - (widthPlus1 + heightPlus1) * 16); - _groundDrawn = false; - } - } + // The dimensions of the map are 0-based in the properties. Adjust to 1-based for RT creation + var widthPlus1 = _currentMapProvider.CurrentMap.Properties.Width + 1; + var heightPlus1 = _currentMapProvider.CurrentMap.Properties.Height + 1; - if (Visible) - { - _characterRendererUpdater.UpdateCharacters(gameTime); - _npcRendererUpdater.UpdateNPCs(gameTime); - _dynamicMapObjectUpdater.UpdateMapObjects(gameTime); + lock (_rt_locker_) + { + _mapBaseTarget.Dispose(); + _mapBaseTarget = _renderTargetFactory.CreateRenderTarget( + (widthPlus1 + heightPlus1) * 32, + (widthPlus1 + heightPlus1) * 16); + _groundDrawn = false; + } + } - if (MouseOver) - _mouseCursorRenderer.Update(gameTime); + if (Visible) + { + _characterRendererUpdater.UpdateCharacters(gameTime); + _npcRendererUpdater.UpdateNPCs(gameTime); + _dynamicMapObjectUpdater.UpdateMapObjects(gameTime); - UpdateQuakeState(); + if (MouseOver) + _mouseCursorRenderer.Update(gameTime); - foreach (var target in _mapGridEffectRenderers.Values) - target.Update(); + UpdateQuakeState(); - if (_fixedTimeStepRepository.IsWalkUpdateFrame || _mapTransitionState.StartTime.HasValue) - { - DrawGroundLayerToRenderTarget(); + foreach (var target in _mapGridEffectRenderers.Values) + target.Update(); - if (_fixedTimeStepRepository.IsWalkUpdateFrame) + if (_fixedTimeStepRepository.IsWalkUpdateFrame || _mapTransitionState.StartTime.HasValue) { - DrawMapToRenderTarget(); + DrawGroundLayerToRenderTarget(); + + if (_fixedTimeStepRepository.IsWalkUpdateFrame) + { + DrawMapToRenderTarget(); + } } } - } - - _lastMapChecksum = _currentMapProvider.CurrentMap.Properties.Checksum; - base.Update(gameTime); - } + _lastMapChecksum = _currentMapProvider.CurrentMap.Properties.Checksum; - public override void Draw(GameTime gameTime) - { - if (!Visible) - return; + base.Update(gameTime); + } - if (_currentMapStateProvider.IsSleepWarp) + public override void Draw(GameTime gameTime) { - lock (_rt_locker_) - { - GraphicsDevice.SetRenderTarget(_mapBaseTarget); - GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); - GraphicsDevice.SetRenderTarget(null); - } + if (!Visible) + return; - _sb.Begin(); - _sb.Draw(_mapBaseTarget, new Vector2(0, 0), Color.White); - _sb.DrawString(_contentProvider.Fonts[Constants.FontSize08], "zzzzz..", new Vector2(_clientWindowSizeRepository.Width / 2 - 15, _clientWindowSizeRepository.Height / 3), Color.White); - _sb.End(); - - // This implementation relies on MapWarpTime being reset in InputHandlerBase - _currentMapStateProvider.MapWarpTime.MatchSome(x => + if (_currentMapStateProvider.IsSleepWarp) { - if ((DateTime.Now - x).TotalSeconds >= 5) + lock (_rt_locker_) { - _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), 1); + GraphicsDevice.SetRenderTarget(_mapBaseTarget); + GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); + GraphicsDevice.SetRenderTarget(null); } - }); - } - else - { - DrawToSpriteBatch(_sb, gameTime); - } - base.Draw(gameTime); - } + _sb.Begin(); + _sb.Draw(_mapBaseTarget, new Vector2(0, 0), Color.White); + _sb.DrawString(_contentProvider.Fonts[Constants.FontSize08], "zzzzz..", new Vector2(_clientWindowSizeRepository.Width / 2 - 15, _clientWindowSizeRepository.Height / 3), Color.White); + _sb.End(); - public void StartMapTransition() - { - _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), 1); - } - - public void StartEarthquake(int strength) - { - _quakeState = Option.Some(new MapQuakeState(strength)); - } + // This implementation relies on MapWarpTime being reset in InputHandlerBase + _currentMapStateProvider.MapWarpTime.MatchSome(x => + { + if ((DateTime.Now - x).TotalSeconds >= 5) + { + _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), 1); + } + }); + } + else + { + DrawToSpriteBatch(_sb, gameTime); + } - public void RedrawGroundLayer() - { - _lastMapChecksum = null; - _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now - new TimeSpan(0, 5, 0)), 255); - } + base.Draw(gameTime); + } - public void RenderEffect(MapCoordinate coordinate, int effectId) - { - if (!_mapGridEffectRenderers.ContainsKey(coordinate)) + public void StartMapTransition() { - var renderer = _effectRendererFactory.Create(); - _mapGridEffectRenderers[coordinate] = renderer; + _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), 1); } - if (_mapGridEffectRenderers[coordinate].State == EffectState.Stopped) + public void StartEarthquake(int strength) { - _mapGridEffectRenderers[coordinate].PlayEffect(effectId + 1, coordinate); + _quakeState = Option.Some(new MapQuakeState(strength)); } - else + + public void RedrawGroundLayer() { - _mapGridEffectRenderers[coordinate].QueueEffect(effectId + 1, coordinate); + _lastMapChecksum = null; + _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now - new TimeSpan(0, 5, 0)), 255); } - } - public void AnimateMouseClick() => _mouseCursorRenderer.AnimateClick(); + public void RenderEffect(MapCoordinate coordinate, int effectId) + { + if (!_mapGridEffectRenderers.ContainsKey(coordinate)) + { + var renderer = _effectRendererFactory.Create(); + _mapGridEffectRenderers[coordinate] = renderer; + } - public void ClearTransientRenderables() - { - _mapGridEffectRenderers.Clear(); - _mouseCursorRenderer.ClearTransientRenderables(); - } + if (_mapGridEffectRenderers[coordinate].State == EffectState.Stopped) + { + _mapGridEffectRenderers[coordinate].PlayEffect(effectId + 1, coordinate); + } + else + { + _mapGridEffectRenderers[coordinate].QueueEffect(effectId + 1, coordinate); + } + } - private void UpdateQuakeState() - { - // when quake: - // 1. determine offset target - // 2. incrementally make offset approach closer to the target offset - // 3. when offset target reached, determine new target (random based on magnitude) - // 4. flip direction - // 5. keep going until specific number of "direction flips" has elapsed - - _quakeState.MatchSome(q => - { - var next = q.NextOffset(); + public void AnimateMouseClick() => _mouseCursorRenderer.AnimateClick(); - if (next.OffsetReached) - next = next.NextState(); + public void ClearTransientRenderables() + { + _mapGridEffectRenderers.Clear(); + _mouseCursorRenderer.ClearTransientRenderables(); + } - _quakeState = next.Done - ? Option.None() - : Option.Some(next); - }); - } + private void UpdateQuakeState() + { + // when quake: + // 1. determine offset target + // 2. incrementally make offset approach closer to the target offset + // 3. when offset target reached, determine new target (random based on magnitude) + // 4. flip direction + // 5. keep going until specific number of "direction flips" has elapsed + + _quakeState.MatchSome(q => + { + var next = q.NextOffset(); - private void DrawGroundLayerToRenderTarget() - { - if (_groundDrawn && !_mapTransitionState.StartTime.HasValue && _lastMapChecksum == _currentMapProvider.CurrentMap.Properties.Checksum) - return; + if (next.OffsetReached) + next = next.NextState(); - _groundDrawn = true; + _quakeState = next.Done + ? Option.None() + : Option.Some(next); + }); + } - lock (_rt_locker_) + private void DrawGroundLayerToRenderTarget() { - GraphicsDevice.SetRenderTarget(_mapBaseTarget); - _sb.Begin(); + if (_groundDrawn && !_mapTransitionState.StartTime.HasValue && _lastMapChecksum == _currentMapProvider.CurrentMap.Properties.Checksum) + return; - var renderBounds = new MapRenderBounds(0, _currentMapProvider.CurrentMap.Properties.Height, - 0, _currentMapProvider.CurrentMap.Properties.Width); + _groundDrawn = true; - var transitionComplete = true; - for (var row = renderBounds.FirstRow; row <= renderBounds.LastRow; row++) + lock (_rt_locker_) { - for (var col = renderBounds.FirstCol; col <= renderBounds.LastCol; ++col) - { - var alpha = GetAlphaForCoordinates(col, row, _characterProvider.MainCharacter); - transitionComplete &= alpha == 255; + GraphicsDevice.SetRenderTarget(_mapBaseTarget); + _sb.Begin(); + + var renderBounds = new MapRenderBounds(0, _currentMapProvider.CurrentMap.Properties.Height, + 0, _currentMapProvider.CurrentMap.Properties.Width); - if (_mapEntityRendererProvider.GroundRenderer.CanRender(row, col)) - _mapEntityRendererProvider.GroundRenderer.RenderElementAt(_sb, row, col, alpha); + var transitionComplete = true; + for (var row = renderBounds.FirstRow; row <= renderBounds.LastRow; row++) + { + for (var col = renderBounds.FirstCol; col <= renderBounds.LastCol; ++col) + { + var alpha = GetAlphaForCoordinates(col, row, _characterProvider.MainCharacter); + transitionComplete &= alpha == 255; + + if (_mapEntityRendererProvider.GroundRenderer.CanRender(row, col)) + _mapEntityRendererProvider.GroundRenderer.RenderElementAt(_sb, row, col, alpha); + } } - } - if (transitionComplete) - _mapTransitionState = new MapTransitionState(Option.None(), 0); + if (transitionComplete) + _mapTransitionState = new MapTransitionState(Option.None(), 0); - _sb.End(); - GraphicsDevice.SetRenderTarget(null); + _sb.End(); + GraphicsDevice.SetRenderTarget(null); + } } - } - - private void DrawMapToRenderTarget() - { - var immutableCharacter = _characterProvider.MainCharacter; - var gfxToRenderLast = new SortedList>(); - lock (_rt_locker_) + private void DrawMapToRenderTarget() { - GraphicsDevice.SetRenderTarget(_mapObjectTarget); - GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); + var immutableCharacter = _characterProvider.MainCharacter; + var gfxToRenderLast = new SortedList>(); - _sb.Begin(); - - var renderBounds = _mapRenderDistanceCalculator.CalculateRenderBounds(immutableCharacter, _currentMapProvider.CurrentMap); + lock (_rt_locker_) + { + GraphicsDevice.SetRenderTarget(_mapObjectTarget); + GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); - var hitKeys = new HashSet(); + _sb.Begin(); - // render the grid diagonally. hack that fixes some layering issues due to not using a depth buffer for layers - // a better solution would be to use a depth buffer like eomap-js - for (var rowStart = renderBounds.FirstRow; rowStart <= renderBounds.LastRow; rowStart++) - { - var row = rowStart; - var col = renderBounds.FirstCol; + var renderBounds = _mapRenderDistanceCalculator.CalculateRenderBounds(immutableCharacter, _currentMapProvider.CurrentMap); - if (!hitKeys.Add(new MapCoordinate(col, row))) - continue; + var hitKeys = new HashSet(); - while (row >= 0) + // render the grid diagonally. hack that fixes some layering issues due to not using a depth buffer for layers + // a better solution would be to use a depth buffer like eomap-js + for (var rowStart = renderBounds.FirstRow; rowStart <= renderBounds.LastRow; rowStart++) { - RenderGridSpace(row, col); + var row = rowStart; + var col = renderBounds.FirstCol; - row--; - col++; - } - } + if (!hitKeys.Add(new MapCoordinate(col, row))) + continue; - for (var colStart = renderBounds.FirstCol; colStart <= renderBounds.LastCol; colStart++) - { - var row = renderBounds.LastRow; - var col = colStart; + while (row >= 0) + { + RenderGridSpace(row, col); - if (!hitKeys.Add(new MapCoordinate(col, row))) - continue; + row--; + col++; + } + } - while (col <= renderBounds.LastCol) + for (var colStart = renderBounds.FirstCol; colStart <= renderBounds.LastCol; colStart++) { - RenderGridSpace(row, col); - row--; - col++; + var row = renderBounds.LastRow; + var col = colStart; + + if (!hitKeys.Add(new MapCoordinate(col, row))) + continue; + + while (col <= renderBounds.LastCol) + { + RenderGridSpace(row, col); + row--; + col++; + } } - } - foreach (var kvp in gfxToRenderLast) - { - foreach (var (pointKey, renderer) in kvp.Value) + foreach (var kvp in gfxToRenderLast) { - var alpha = GetAlphaForCoordinates(pointKey.X, pointKey.Y, immutableCharacter); - renderer.RenderElementAt(_sb, pointKey.Y, pointKey.X, alpha); + foreach (var (pointKey, renderer) in kvp.Value) + { + var alpha = GetAlphaForCoordinates(pointKey.X, pointKey.Y, immutableCharacter); + renderer.RenderElementAt(_sb, pointKey.Y, pointKey.X, alpha); + } } - } - _sb.End(); - GraphicsDevice.SetRenderTarget(null); - } - - void RenderGridSpace(int row, int col) - { - var alpha = GetAlphaForCoordinates(col, row, immutableCharacter); + _sb.End(); + GraphicsDevice.SetRenderTarget(null); + } - for (int i = 0; i < _mapEntityRendererProvider.MapEntityRenderers.Count; i++) + void RenderGridSpace(int row, int col) { - var renderer = _mapEntityRendererProvider.MapEntityRenderers[i]; - - if (!renderer.CanRender(row, col)) - continue; + var alpha = GetAlphaForCoordinates(col, row, immutableCharacter); - if (renderer.ShouldRenderLast) + for (int i = 0; i < _mapEntityRendererProvider.MapEntityRenderers.Count; i++) { - var renderLaterKey = new MapCoordinate(col, row); - if (gfxToRenderLast.ContainsKey(renderer.RenderLayer)) - gfxToRenderLast[renderer.RenderLayer].Add((renderLaterKey, renderer)); + var renderer = _mapEntityRendererProvider.MapEntityRenderers[i]; + + if (!renderer.CanRender(row, col)) + continue; + + if (renderer.ShouldRenderLast) + { + var renderLaterKey = new MapCoordinate(col, row); + if (gfxToRenderLast.ContainsKey(renderer.RenderLayer)) + gfxToRenderLast[renderer.RenderLayer].Add((renderLaterKey, renderer)); + else + gfxToRenderLast.Add(renderer.RenderLayer, new List<(MapCoordinate, IMapEntityRenderer)> { (renderLaterKey, renderer) }); + } else - gfxToRenderLast.Add(renderer.RenderLayer, new List<(MapCoordinate, IMapEntityRenderer)> { (renderLaterKey, renderer) }); + renderer.RenderElementAt(_sb, row, col, alpha); } - else - renderer.RenderElementAt(_sb, row, col, alpha); } } - } - private void DrawToSpriteBatch(SpriteBatch spriteBatch, GameTime gameTime) - { - spriteBatch.Begin(); + private void DrawToSpriteBatch(SpriteBatch spriteBatch, GameTime gameTime) + { + spriteBatch.Begin(); - var drawLoc = _gridDrawCoordinateCalculator.CalculateGroundLayerRenderTargetDrawCoordinates(); - var offset = _quakeState.Map(GetOffset).ValueOr(0); + var drawLoc = _gridDrawCoordinateCalculator.CalculateGroundLayerRenderTargetDrawCoordinates(); + var offset = _quakeState.Map(GetOffset).ValueOr(0); - lock (_rt_locker_) - { - spriteBatch.Draw(_mapBaseTarget, drawLoc + new Vector2(offset, 0), Color.White); - DrawBaseLayers(spriteBatch); + lock (_rt_locker_) + { + spriteBatch.Draw(_mapBaseTarget, drawLoc + new Vector2(offset, 0), Color.White); + DrawBaseLayers(spriteBatch); - _mouseCursorRenderer.Draw(spriteBatch, new Vector2(offset, 0)); + _mouseCursorRenderer.Draw(spriteBatch, new Vector2(offset, 0)); - spriteBatch.Draw(_mapObjectTarget, new Vector2(offset, 0), Color.White); + spriteBatch.Draw(_mapObjectTarget, new Vector2(offset, 0), Color.White); - foreach (var target in _mapGridEffectRenderers.Values) - { - target.DrawBehindTarget(spriteBatch); - target.DrawInFrontOfTarget(spriteBatch); + foreach (var target in _mapGridEffectRenderers.Values) + { + target.DrawBehindTarget(spriteBatch); + target.DrawInFrontOfTarget(spriteBatch); + } + + spriteBatch.End(); } - spriteBatch.End(); + static float GetOffset(MapQuakeState quakeState) => quakeState.Offset; } - static float GetOffset(MapQuakeState quakeState) => quakeState.Offset; - } - - private void DrawBaseLayers(SpriteBatch spriteBatch) - { - var offset = _quakeState.Map(GetOffset).ValueOr(0); + private void DrawBaseLayers(SpriteBatch spriteBatch) + { + var offset = _quakeState.Map(GetOffset).ValueOr(0); - var renderBounds = _mapRenderDistanceCalculator.CalculateRenderBounds(_characterProvider.MainCharacter, _currentMapProvider.CurrentMap); + var renderBounds = _mapRenderDistanceCalculator.CalculateRenderBounds(_characterProvider.MainCharacter, _currentMapProvider.CurrentMap); - for (var row = renderBounds.FirstRow; row <= renderBounds.LastRow; row++) - { - for (var col = renderBounds.FirstCol; col <= renderBounds.LastCol; ++col) + for (var row = renderBounds.FirstRow; row <= renderBounds.LastRow; row++) { - var alpha = GetAlphaForCoordinates(col, row, _characterProvider.MainCharacter); - - for (int i = 0; i < _mapEntityRendererProvider.BaseRenderers.Count; i++) + for (var col = renderBounds.FirstCol; col <= renderBounds.LastCol; ++col) { - var renderer = _mapEntityRendererProvider.BaseRenderers[i]; - if (renderer.CanRender(row, col)) - renderer.RenderElementAt(spriteBatch, row, col, alpha, new Vector2(offset, 0)); + var alpha = GetAlphaForCoordinates(col, row, _characterProvider.MainCharacter); + + for (int i = 0; i < _mapEntityRendererProvider.BaseRenderers.Count; i++) + { + var renderer = _mapEntityRendererProvider.BaseRenderers[i]; + if (renderer.CanRender(row, col)) + renderer.RenderElementAt(spriteBatch, row, col, alpha, new Vector2(offset, 0)); + } } } - } - static float GetOffset(MapQuakeState quakeState) => quakeState.Offset; - } + static float GetOffset(MapQuakeState quakeState) => quakeState.Offset; + } - private int GetAlphaForCoordinates(int objX, int objY, EOLib.Domain.Character.Character character) - { - if (!_configurationProvider.ShowTransition) + private int GetAlphaForCoordinates(int objX, int objY, EOLib.Domain.Character.Character character) { - _mapTransitionState = new MapTransitionState(Option.None(), 0); - return 255; - } + if (!_configurationProvider.ShowTransition) + { + _mapTransitionState = new MapTransitionState(Option.None(), 0); + return 255; + } - //get the farther away of X or Y coordinate for the map object - var metric = Math.Max(Math.Abs(objX - character.RenderProperties.MapX), - Math.Abs(objY - character.RenderProperties.MapY)); + //get the farther away of X or Y coordinate for the map object + var metric = Math.Max(Math.Abs(objX - character.RenderProperties.MapX), + Math.Abs(objY - character.RenderProperties.MapY)); - int alpha = 0; - if (!_mapTransitionState.StartTime.HasValue || - metric < _mapTransitionState.TransitionMetric || - _mapTransitionState.TransitionMetric == 0) - { - alpha = 255; - } - else if (metric == _mapTransitionState.TransitionMetric) - { - alpha = _mapTransitionState.StartTime.Map(HandleStartTime).ValueOr(alpha); - } - else - alpha = 0; + int alpha = 0; + if (!_mapTransitionState.StartTime.HasValue || + metric < _mapTransitionState.TransitionMetric || + _mapTransitionState.TransitionMetric == 0) + { + alpha = 255; + } + else if (metric == _mapTransitionState.TransitionMetric) + { + alpha = _mapTransitionState.StartTime.Map(HandleStartTime).ValueOr(alpha); + } + else + alpha = 0; - return alpha; + return alpha; - int HandleStartTime(DateTime startTime) - { - var ms = (DateTime.Now - startTime).TotalMilliseconds; + int HandleStartTime(DateTime startTime) + { + var ms = (DateTime.Now - startTime).TotalMilliseconds; - if (ms / TRANSITION_TIME_MS >= 1) - _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), _mapTransitionState.TransitionMetric + 1); + if (ms / TRANSITION_TIME_MS >= 1) + _mapTransitionState = new MapTransitionState(Option.Some(DateTime.Now), _mapTransitionState.TransitionMetric + 1); - return (int)Math.Round(ms / TRANSITION_TIME_MS * 255); + return (int)Math.Round(ms / TRANSITION_TIME_MS * 255); + } } - } - private void ResizeGameWindow(object sender, EventArgs e) - { - lock (_rt_locker_) + private void ResizeGameWindow(object sender, EventArgs e) { - _mapObjectTarget.Dispose(); - _mapObjectTarget = _renderTargetFactory.CreateRenderTarget(_clientWindowSizeRepository.Width, _clientWindowSizeRepository.Height); + lock (_rt_locker_) + { + _mapObjectTarget.Dispose(); + _mapObjectTarget = _renderTargetFactory.CreateRenderTarget(_clientWindowSizeRepository.Width, _clientWindowSizeRepository.Height); + } } - } - protected override void Dispose(bool disposing) - { - if (disposing) + protected override void Dispose(bool disposing) { - lock (_rt_locker_) + if (disposing) { - _mapBaseTarget.Dispose(); - _mapObjectTarget.Dispose(); + lock (_rt_locker_) + { + _mapBaseTarget.Dispose(); + _mapObjectTarget.Dispose(); + } + _sb.Dispose(); + _mouseCursorRenderer.Dispose(); + + _npcRendererUpdater.Dispose(); + _characterRendererUpdater.Dispose(); } - _sb.Dispose(); - _mouseCursorRenderer.Dispose(); - _npcRendererUpdater.Dispose(); - _characterRendererUpdater.Dispose(); + base.Dispose(disposing); } - - base.Dispose(disposing); } -} -internal struct MapTransitionState -{ - internal static MapTransitionState Default => new MapTransitionState(Option.None(), 0); + internal struct MapTransitionState + { + internal static MapTransitionState Default => new MapTransitionState(Option.None(), 0); - internal Option StartTime { get; } + internal Option StartTime { get; } - internal int TransitionMetric { get; } + internal int TransitionMetric { get; } - internal MapTransitionState(Option startTime, int transitionMetric) - : this() - { - StartTime = startTime; - TransitionMetric = transitionMetric; + internal MapTransitionState(Option startTime, int transitionMetric) + : this() + { + StartTime = startTime; + TransitionMetric = transitionMetric; + } } -} -internal struct MapQuakeState -{ - private static readonly Random _random = new Random(); + internal struct MapQuakeState + { + private static readonly Random _random = new Random(); - internal static MapQuakeState Default => new MapQuakeState(); + internal static MapQuakeState Default => new MapQuakeState(); - internal int Magnitude { get; } + internal int Magnitude { get; } - internal float Offset { get; } + internal float Offset { get; } - internal float OffsetTarget { get; } + internal float OffsetTarget { get; } - internal bool OffsetReached => Math.Abs(Offset) >= Math.Abs(OffsetTarget); + internal bool OffsetReached => Math.Abs(Offset) >= Math.Abs(OffsetTarget); - internal int Flips { get; } + internal int Flips { get; } - internal int FlipsMax => Magnitude == 0 ? 0 : 10 + Magnitude * 2; + internal int FlipsMax => Magnitude == 0 ? 0 : 10 + Magnitude * 2; - internal bool Done => Flips >= FlipsMax; + internal bool Done => Flips >= FlipsMax; - internal MapQuakeState(int magnitude) - : this(magnitude, 0, 0) { } + internal MapQuakeState(int magnitude) + : this(magnitude, 0, 0) { } - private MapQuakeState(int magnitude, float offset, int flips) - : this(magnitude, offset, NewOffsetTarget(magnitude), flips) { } + private MapQuakeState(int magnitude, float offset, int flips) + : this(magnitude, offset, NewOffsetTarget(magnitude), flips) { } - private MapQuakeState(int magnitude, float offset, float offsetTarget, int flips) - { - Magnitude = magnitude; - Offset = offset; - OffsetTarget = offsetTarget; - Flips = flips; - } + private MapQuakeState(int magnitude, float offset, float offsetTarget, int flips) + { + Magnitude = magnitude; + Offset = offset; + OffsetTarget = offsetTarget; + Flips = flips; + } - internal MapQuakeState NextOffset() - { - var nextOffset = Offset + OffsetTarget / 4f; - return new MapQuakeState(Magnitude, nextOffset, OffsetTarget, Flips); - } + internal MapQuakeState NextOffset() + { + var nextOffset = Offset + OffsetTarget / 4f; + return new MapQuakeState(Magnitude, nextOffset, OffsetTarget, Flips); + } - internal MapQuakeState NextState() - { - var flip = -OffsetTarget / Math.Abs(OffsetTarget); - var offset = OffsetTarget + 1 * flip; - var nextOffsetTarget = NewOffsetTarget(Magnitude) * flip; + internal MapQuakeState NextState() + { + var flip = -OffsetTarget / Math.Abs(OffsetTarget); + var offset = OffsetTarget + 1 * flip; + var nextOffsetTarget = NewOffsetTarget(Magnitude) * flip; - return new MapQuakeState(Magnitude, offset, nextOffsetTarget, Flips + 1); - } + return new MapQuakeState(Magnitude, offset, nextOffsetTarget, Flips + 1); + } - private static float NewOffsetTarget(int magnitude) => 16 + 3 * _random.Next(0, (int)(magnitude * 1.5)); + private static float NewOffsetTarget(int magnitude) => 16 + 3 * _random.Next(0, (int)(magnitude * 1.5)); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MiniMapRenderer.cs b/EndlessClient/Rendering/Map/MiniMapRenderer.cs index 8ffc6ccac..56cdbc24b 100644 --- a/EndlessClient/Rendering/Map/MiniMapRenderer.cs +++ b/EndlessClient/Rendering/Map/MiniMapRenderer.cs @@ -11,272 +11,273 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering.Map; - -public class MiniMapRenderer : XNAControl +namespace EndlessClient.Rendering.Map { - private const int TileWidth = 28; - private const int TileHeight = 14; - - private enum MiniMapGfx + public class MiniMapRenderer : XNAControl { - UpLine = 0, - LeftLine = 1, - Corner = 2, - Solid = 3, //wall or obstacle - Green = 4, //other player - Red = 5, //attackable npc - Orange = 6, //you! - Blue = 7, //tile that you can interact with - Purple = 8, //npc - NUM_GRIDS = 9, - } + private const int TileWidth = 28; + private const int TileHeight = 14; - private readonly object _rt_locker_ = new object(); - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly Texture2D _miniMapTexture; - - private RenderTarget2D _miniMapTarget; - private IReadOnlyList _lastMapChecksum; - - public MiniMapRenderer(INativeGraphicsManager nativeGraphicsManager, - IRenderTargetFactory renderTargetFactory, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterProvider characterProvider, - IENFFileProvider enfFileProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) - { - _renderTargetFactory = renderTargetFactory; - _clientWindowSizeProvider = clientWindowSizeProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _characterProvider = characterProvider; - _enfFileProvider = enfFileProvider; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _miniMapTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 45, true); - } + private enum MiniMapGfx + { + UpLine = 0, + LeftLine = 1, + Corner = 2, + Solid = 3, //wall or obstacle + Green = 4, //other player + Red = 5, //attackable npc + Orange = 6, //you! + Blue = 7, //tile that you can interact with + Purple = 8, //npc + NUM_GRIDS = 9, + } - public override void Initialize() - { - Visible = true; - DrawOrder = 0; + private readonly object _rt_locker_ = new object(); + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly Texture2D _miniMapTexture; + + private RenderTarget2D _miniMapTarget; + private IReadOnlyList _lastMapChecksum; + + public MiniMapRenderer(INativeGraphicsManager nativeGraphicsManager, + IRenderTargetFactory renderTargetFactory, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterProvider characterProvider, + IENFFileProvider enfFileProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) + { + _renderTargetFactory = renderTargetFactory; + _clientWindowSizeProvider = clientWindowSizeProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _characterProvider = characterProvider; + _enfFileProvider = enfFileProvider; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _miniMapTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 45, true); + } - base.Initialize(); - } + public override void Initialize() + { + Visible = true; + DrawOrder = 0; - protected override bool ShouldDraw() - { - return _currentMapStateProvider.ShowMiniMap && base.ShouldDraw(); - } + base.Initialize(); + } - protected override void OnUpdateControl(GameTime gameTime) - { - if (_lastMapChecksum == null || !_lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) + protected override bool ShouldDraw() { - // The dimensions of the map are 0-based in the properties. Adjust to 1-based for RT creation - var widthPlus1 = _currentMapProvider.CurrentMap.Properties.Width + 1; - var heightPlus1 = _currentMapProvider.CurrentMap.Properties.Height + 1; + return _currentMapStateProvider.ShowMiniMap && base.ShouldDraw(); + } - lock (_rt_locker_) + protected override void OnUpdateControl(GameTime gameTime) + { + if (_lastMapChecksum == null || !_lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) { - _miniMapTarget?.Dispose(); - _miniMapTarget = _renderTargetFactory.CreateRenderTarget( - (widthPlus1 + heightPlus1) * TileWidth, - (widthPlus1 + heightPlus1) * TileHeight); + // The dimensions of the map are 0-based in the properties. Adjust to 1-based for RT creation + var widthPlus1 = _currentMapProvider.CurrentMap.Properties.Width + 1; + var heightPlus1 = _currentMapProvider.CurrentMap.Properties.Height + 1; + + lock (_rt_locker_) + { + _miniMapTarget?.Dispose(); + _miniMapTarget = _renderTargetFactory.CreateRenderTarget( + (widthPlus1 + heightPlus1) * TileWidth, + (widthPlus1 + heightPlus1) * TileHeight); + } + + DrawFixedMapElementsToRenderTarget(); } - DrawFixedMapElementsToRenderTarget(); - } - - _lastMapChecksum = _currentMapProvider.CurrentMap.Properties.Checksum; + _lastMapChecksum = _currentMapProvider.CurrentMap.Properties.Checksum; - base.OnUpdateControl(gameTime); - } + base.OnUpdateControl(gameTime); + } - protected override void OnDrawControl(GameTime gameTime) - { - lock (_rt_locker_) + protected override void OnDrawControl(GameTime gameTime) { - _spriteBatch.Begin(); + lock (_rt_locker_) + { + _spriteBatch.Begin(); - var baseTargetDrawLoc = _gridDrawCoordinateCalculator.CalculateGroundLayerRenderTargetDrawCoordinates(isMiniMap: true, TileWidth, TileHeight); - _spriteBatch.Draw(_miniMapTarget, baseTargetDrawLoc, Color.White); + var baseTargetDrawLoc = _gridDrawCoordinateCalculator.CalculateGroundLayerRenderTargetDrawCoordinates(isMiniMap: true, TileWidth, TileHeight); + _spriteBatch.Draw(_miniMapTarget, baseTargetDrawLoc, Color.White); - var entities = new IMapEntity[] { _characterProvider.MainCharacter } - .Concat(_currentMapStateProvider.Characters) - .Concat(_currentMapStateProvider.NPCs); + var entities = new IMapEntity[] { _characterProvider.MainCharacter } + .Concat(_currentMapStateProvider.Characters) + .Concat(_currentMapStateProvider.NPCs); - foreach (var entity in entities) - { - var loc = GetMiniMapDrawCoordinates(entity.X, entity.Y); - var miniMapRectSrc = GetSourceRectangleForEntity(entity); - DrawGridBox(loc, null, miniMapRectSrc); + foreach (var entity in entities) + { + var loc = GetMiniMapDrawCoordinates(entity.X, entity.Y); + var miniMapRectSrc = GetSourceRectangleForEntity(entity); + DrawGridBox(loc, null, miniMapRectSrc); + } + + _spriteBatch.End(); } - _spriteBatch.End(); + base.OnDrawControl(gameTime); } - base.OnDrawControl(gameTime); - } - - private (MiniMapGfx? EdgeGfx, Rectangle SourceRect) GetSourceRectangleForGridSpace(int col, int row) - { - var tileSpec = _currentMapProvider.CurrentMap.Tiles[row, col]; - - switch (tileSpec) + private (MiniMapGfx? EdgeGfx, Rectangle SourceRect) GetSourceRectangleForGridSpace(int col, int row) { - case TileSpec.Wall: - case TileSpec.FakeWall: - return (GetEdge(), GetSourceRect(MiniMapGfx.Solid)); - case TileSpec.BankVault: - case TileSpec.ChairAll: - case TileSpec.ChairDown: - case TileSpec.ChairLeft: - case TileSpec.ChairRight: - case TileSpec.ChairUp: - case TileSpec.ChairDownRight: - case TileSpec.ChairUpLeft: - case TileSpec.Chest: - case TileSpec.JammedDoor: - // Unknown TileSpecs 10-15 have been confirmed in the vanilla client to show a Blue ! on the minimap - case (TileSpec)10: - case (TileSpec)11: - case (TileSpec)12: - case (TileSpec)13: - case (TileSpec)14: - case (TileSpec)15: - return (GetEdge(), GetSourceRect(MiniMapGfx.Blue)); - case TileSpec.MapEdge: - return (null, Rectangle.Empty); - } + var tileSpec = _currentMapProvider.CurrentMap.Tiles[row, col]; - if (_currentMapProvider.CurrentMap.Warps[row, col] != null) - { - var doorType = _currentMapProvider.CurrentMap.Warps[row, col].DoorType; - return (GetEdge(), GetSourceRect(doorType != DoorSpec.NoDoor ? MiniMapGfx.Blue : MiniMapGfx.UpLine)); - } + switch (tileSpec) + { + case TileSpec.Wall: + case TileSpec.FakeWall: + return (GetEdge(), GetSourceRect(MiniMapGfx.Solid)); + case TileSpec.BankVault: + case TileSpec.ChairAll: + case TileSpec.ChairDown: + case TileSpec.ChairLeft: + case TileSpec.ChairRight: + case TileSpec.ChairUp: + case TileSpec.ChairDownRight: + case TileSpec.ChairUpLeft: + case TileSpec.Chest: + case TileSpec.JammedDoor: + // Unknown TileSpecs 10-15 have been confirmed in the vanilla client to show a Blue ! on the minimap + case (TileSpec)10: + case (TileSpec)11: + case (TileSpec)12: + case (TileSpec)13: + case (TileSpec)14: + case (TileSpec)15: + return (GetEdge(), GetSourceRect(MiniMapGfx.Blue)); + case TileSpec.MapEdge: + return (null, Rectangle.Empty); + } - return (GetEdge(), Rectangle.Empty); + if (_currentMapProvider.CurrentMap.Warps[row, col] != null) + { + var doorType = _currentMapProvider.CurrentMap.Warps[row, col].DoorType; + return (GetEdge(), GetSourceRect(doorType != DoorSpec.NoDoor ? MiniMapGfx.Blue : MiniMapGfx.UpLine)); + } - MiniMapGfx? GetEdge() - { - if (tileSpec == TileSpec.MapEdge) - return null; - - var tiles = _currentMapProvider.CurrentMap.Tiles; - - if (col - 1 >= 0 && tiles[row, col - 1] == TileSpec.MapEdge && - row - 1 >= 0 && tiles[row - 1, col] == TileSpec.MapEdge) - return null; - else if (col == 0 || (col - 1 >= 0 && tiles[row, col - 1] == TileSpec.MapEdge)) - return MiniMapGfx.UpLine; - else if (row == 0 || (row - 1 >= 0 && tiles[row - 1, col] == TileSpec.MapEdge)) - return MiniMapGfx.LeftLine; - else - return MiniMapGfx.Corner; - } - } + return (GetEdge(), Rectangle.Empty); - private Rectangle GetSourceRectangleForEntity(IMapEntity mapEntity) - { - if (_characterProvider.MainCharacter == mapEntity) - { - return GetSourceRect(MiniMapGfx.Orange); + MiniMapGfx? GetEdge() + { + if (tileSpec == TileSpec.MapEdge) + return null; + + var tiles = _currentMapProvider.CurrentMap.Tiles; + + if (col - 1 >= 0 && tiles[row, col - 1] == TileSpec.MapEdge && + row - 1 >= 0 && tiles[row - 1, col] == TileSpec.MapEdge) + return null; + else if (col == 0 || (col - 1 >= 0 && tiles[row, col - 1] == TileSpec.MapEdge)) + return MiniMapGfx.UpLine; + else if (row == 0 || (row - 1 >= 0 && tiles[row - 1, col] == TileSpec.MapEdge)) + return MiniMapGfx.LeftLine; + else + return MiniMapGfx.Corner; + } } - return mapEntity switch + private Rectangle GetSourceRectangleForEntity(IMapEntity mapEntity) { - EOLib.Domain.NPC.NPC n => GetNPCSourceRectangle(n), - EOLib.Domain.Character.Character c => GetSourceRect(MiniMapGfx.Green), - _ => Rectangle.Empty - }; + if (_characterProvider.MainCharacter == mapEntity) + { + return GetSourceRect(MiniMapGfx.Orange); + } - Rectangle GetNPCSourceRectangle(EOLib.Domain.NPC.NPC npc) - { - var npcType = _enfFileProvider.ENFFile[npc.ID].Type; - return GetSourceRect(npcType == NPCType.Aggressive || npcType == NPCType.Passive ? MiniMapGfx.Red : MiniMapGfx.Purple); + return mapEntity switch + { + EOLib.Domain.NPC.NPC n => GetNPCSourceRectangle(n), + EOLib.Domain.Character.Character c => GetSourceRect(MiniMapGfx.Green), + _ => Rectangle.Empty + }; + + Rectangle GetNPCSourceRectangle(EOLib.Domain.NPC.NPC npc) + { + var npcType = _enfFileProvider.ENFFile[npc.ID].Type; + return GetSourceRect(npcType == NPCType.Aggressive || npcType == NPCType.Passive ? MiniMapGfx.Red : MiniMapGfx.Purple); + } } - } - private void DrawFixedMapElementsToRenderTarget() - { - if (_lastMapChecksum != null && _lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) - return; + private void DrawFixedMapElementsToRenderTarget() + { + if (_lastMapChecksum != null && _lastMapChecksum.SequenceEqual(_currentMapProvider.CurrentMap.Properties.Checksum)) + return; - GraphicsDevice.SetRenderTarget(_miniMapTarget); - GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); - _spriteBatch.Begin(); + GraphicsDevice.SetRenderTarget(_miniMapTarget); + GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); + _spriteBatch.Begin(); - // the height is used to offset the 0 point of the grid, which is TileHeight units per tile in the height of the map - var height = _currentMapProvider.CurrentMap.Properties.Height + 1; + // the height is used to offset the 0 point of the grid, which is TileHeight units per tile in the height of the map + var height = _currentMapProvider.CurrentMap.Properties.Height + 1; - for (int row = 0; row <= _currentMapProvider.CurrentMap.Properties.Height; ++row) - { - for (int col = 0; col <= _currentMapProvider.CurrentMap.Properties.Width; ++col) + for (int row = 0; row <= _currentMapProvider.CurrentMap.Properties.Height; ++row) { - var drawLoc = _gridDrawCoordinateCalculator.CalculateRawRenderCoordinatesFromGridUnits(col, row, TileWidth, TileHeight) + new Vector2(TileHeight * height, 0); - var (edgeGfx, miniMapRectSrc) = GetSourceRectangleForGridSpace(col, row); - DrawGridBox(drawLoc, edgeGfx, miniMapRectSrc); + for (int col = 0; col <= _currentMapProvider.CurrentMap.Properties.Width; ++col) + { + var drawLoc = _gridDrawCoordinateCalculator.CalculateRawRenderCoordinatesFromGridUnits(col, row, TileWidth, TileHeight) + new Vector2(TileHeight * height, 0); + var (edgeGfx, miniMapRectSrc) = GetSourceRectangleForGridSpace(col, row); + DrawGridBox(drawLoc, edgeGfx, miniMapRectSrc); + } } - } - _spriteBatch.End(); - GraphicsDevice.SetRenderTarget(null); - } + _spriteBatch.End(); + GraphicsDevice.SetRenderTarget(null); + } - private void DrawGridBox(Vector2 loc, MiniMapGfx? edgeGfx, Rectangle gridSpaceSourceRect) - { - if (edgeGfx != null) + private void DrawGridBox(Vector2 loc, MiniMapGfx? edgeGfx, Rectangle gridSpaceSourceRect) { - var src = gridSpaceSourceRect.Equals(Rectangle.Empty) - ? GetSourceRect(MiniMapGfx.UpLine) - : gridSpaceSourceRect; + if (edgeGfx != null) + { + var src = gridSpaceSourceRect.Equals(Rectangle.Empty) + ? GetSourceRect(MiniMapGfx.UpLine) + : gridSpaceSourceRect; - _spriteBatch.Draw(_miniMapTexture, loc, - new Rectangle((int)edgeGfx * src.Width, 0, src.Width, src.Height), - Color.FromNonPremultiplied(255, 255, 255, 128)); - } + _spriteBatch.Draw(_miniMapTexture, loc, + new Rectangle((int)edgeGfx * src.Width, 0, src.Width, src.Height), + Color.FromNonPremultiplied(255, 255, 255, 128)); + } - if (!gridSpaceSourceRect.IsEmpty) - { - _spriteBatch.Draw(_miniMapTexture, loc, gridSpaceSourceRect, Color.FromNonPremultiplied(255, 255, 255, 128)); + if (!gridSpaceSourceRect.IsEmpty) + { + _spriteBatch.Draw(_miniMapTexture, loc, gridSpaceSourceRect, Color.FromNonPremultiplied(255, 255, 255, 128)); + } } - } - private Vector2 GetMiniMapDrawCoordinates(int x, int y) - { - var widthFactor = _clientWindowSizeProvider.Width / 2; - var heightFactor = _clientWindowSizeProvider.Resizable - ? _clientWindowSizeProvider.Height / 2 // 144 = 480 * .45, viewport height factor - : _clientWindowSizeProvider.Height * 3 / 10 - 2; + private Vector2 GetMiniMapDrawCoordinates(int x, int y) + { + var widthFactor = _clientWindowSizeProvider.Width / 2; + var heightFactor = _clientWindowSizeProvider.Resizable + ? _clientWindowSizeProvider.Height / 2 // 144 = 480 * .45, viewport height factor + : _clientWindowSizeProvider.Height * 3 / 10 - 2; - var tileWidthFactor = TileWidth / 2; - var tileHeightFactor = TileHeight / 2; + var tileWidthFactor = TileWidth / 2; + var tileHeightFactor = TileHeight / 2; - return new Vector2(x * tileWidthFactor - y * tileWidthFactor + widthFactor, - y * tileHeightFactor + x * tileHeightFactor + heightFactor) - GetCharacterOffset(); - } + return new Vector2(x * tileWidthFactor - y * tileWidthFactor + widthFactor, + y * tileHeightFactor + x * tileHeightFactor + heightFactor) - GetCharacterOffset(); + } - private Rectangle GetSourceRect(MiniMapGfx gfx) - { - var delta = _miniMapTexture.Width / (int)MiniMapGfx.NUM_GRIDS; - return new Rectangle((int)gfx * delta, 0, delta, _miniMapTexture.Height); - } + private Rectangle GetSourceRect(MiniMapGfx gfx) + { + var delta = _miniMapTexture.Width / (int)MiniMapGfx.NUM_GRIDS; + return new Rectangle((int)gfx * delta, 0, delta, _miniMapTexture.Height); + } - private Vector2 GetCharacterOffset() - { - var tileWidthFactor = TileWidth / 2; - var tileHeightFactor = TileHeight / 2; + private Vector2 GetCharacterOffset() + { + var tileWidthFactor = TileWidth / 2; + var tileHeightFactor = TileHeight / 2; - var (cx, cy) = (_characterProvider.MainCharacter.X, _characterProvider.MainCharacter.Y); - return new Vector2(cx * tileWidthFactor - cy * tileWidthFactor, cx * tileHeightFactor + cy * tileHeightFactor); + var (cx, cy) = (_characterProvider.MainCharacter.X, _characterProvider.MainCharacter.Y); + return new Vector2(cx * tileWidthFactor - cy * tileWidthFactor, cx * tileHeightFactor + cy * tileHeightFactor); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs b/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs index 2eadef11f..2bccedcba 100644 --- a/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs +++ b/EndlessClient/Rendering/Map/MiniMapRendererFactory.cs @@ -5,53 +5,54 @@ using EOLib.Graphics; using EOLib.IO.Repositories; -namespace EndlessClient.Rendering.Map; - -[AutoMappedType] -public class MiniMapRendererFactory : IMiniMapRendererFactory +namespace EndlessClient.Rendering.Map { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IRenderTargetFactory _renderTargetFactory; - - public MiniMapRendererFactory(INativeGraphicsManager nativeGraphicsManager, - IRenderTargetFactory renderTargetFactory, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapProvider currentMapProvider, - ICurrentMapStateProvider currentMapStateProvider, - ICharacterProvider characterProvider, - IENFFileProvider enfFileProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) + [AutoMappedType] + public class MiniMapRendererFactory : IMiniMapRendererFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _clientWindowSizeProvider = clientWindowSizeProvider; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - _characterProvider = characterProvider; - _enfFileProvider = enfFileProvider; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _renderTargetFactory = renderTargetFactory; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IRenderTargetFactory _renderTargetFactory; + + public MiniMapRendererFactory(INativeGraphicsManager nativeGraphicsManager, + IRenderTargetFactory renderTargetFactory, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapProvider currentMapProvider, + ICurrentMapStateProvider currentMapStateProvider, + ICharacterProvider characterProvider, + IENFFileProvider enfFileProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator) + { + _nativeGraphicsManager = nativeGraphicsManager; + _clientWindowSizeProvider = clientWindowSizeProvider; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + _characterProvider = characterProvider; + _enfFileProvider = enfFileProvider; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _renderTargetFactory = renderTargetFactory; + } + + public MiniMapRenderer Create() + { + return new MiniMapRenderer(_nativeGraphicsManager, + _renderTargetFactory, + _clientWindowSizeProvider, + _currentMapProvider, + _currentMapStateProvider, + _characterProvider, + _enfFileProvider, + _gridDrawCoordinateCalculator); + } } - public MiniMapRenderer Create() + public interface IMiniMapRendererFactory { - return new MiniMapRenderer(_nativeGraphicsManager, - _renderTargetFactory, - _clientWindowSizeProvider, - _currentMapProvider, - _currentMapStateProvider, - _characterProvider, - _enfFileProvider, - _gridDrawCoordinateCalculator); + MiniMapRenderer Create(); } -} - -public interface IMiniMapRendererFactory -{ - MiniMapRenderer Create(); } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs index ef919192d..f431effcb 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs @@ -5,81 +5,82 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public abstract class BaseMapEntityRenderer : IMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private static readonly Dictionary _layerOffsets; + public abstract class BaseMapEntityRenderer : IMapEntityRenderer + { + private static readonly Dictionary _layerOffsets; - private static DateTime _lastFrameTime = DateTime.Now; - protected static int _frameIndex = 0; + private static DateTime _lastFrameTime = DateTime.Now; + protected static int _frameIndex = 0; - static BaseMapEntityRenderer() - { - _layerOffsets = new Dictionary + static BaseMapEntityRenderer() { - { MapRenderLayer.Ground, Point.Zero }, - { MapRenderLayer.Item, new Point(0, 16) }, - { MapRenderLayer.Objects, new Point(-2, -2) }, - { MapRenderLayer.Overlay, new Point(-2, -2) }, - { MapRenderLayer.DownWall, new Point(0, -1) }, - { MapRenderLayer.RightWall, new Point(32, -1) }, - { MapRenderLayer.Roof, new Point(-32, -64) }, - { MapRenderLayer.OnTop, new Point(-32, -32) }, - { MapRenderLayer.Shadows, new Point(-24, -12) }, - { MapRenderLayer.Overlay2, new Point(-2, -2) }, - { MapRenderLayer.MainCharacter, Point.Zero }, - }; - } + _layerOffsets = new Dictionary + { + { MapRenderLayer.Ground, Point.Zero }, + { MapRenderLayer.Item, new Point(0, 16) }, + { MapRenderLayer.Objects, new Point(-2, -2) }, + { MapRenderLayer.Overlay, new Point(-2, -2) }, + { MapRenderLayer.DownWall, new Point(0, -1) }, + { MapRenderLayer.RightWall, new Point(32, -1) }, + { MapRenderLayer.Roof, new Point(-32, -64) }, + { MapRenderLayer.OnTop, new Point(-32, -32) }, + { MapRenderLayer.Shadows, new Point(-24, -12) }, + { MapRenderLayer.Overlay2, new Point(-2, -2) }, + { MapRenderLayer.MainCharacter, Point.Zero }, + }; + } - protected readonly ICharacterProvider _characterProvider; - protected readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + protected readonly ICharacterProvider _characterProvider; + protected readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - public abstract MapRenderLayer RenderLayer { get; } + public abstract MapRenderLayer RenderLayer { get; } - public bool ShouldRenderLast => RenderLayer == MapRenderLayer.Overlay2 || RenderLayer == MapRenderLayer.MainCharacterTransparent; + public bool ShouldRenderLast => RenderLayer == MapRenderLayer.Overlay2 || RenderLayer == MapRenderLayer.MainCharacterTransparent; - protected abstract int RenderDistance { get; } + protected abstract int RenderDistance { get; } - protected BaseMapEntityRenderer(ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _characterProvider = characterProvider; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _clientWindowSizeProvider = clientWindowSizeProvider; - } + protected BaseMapEntityRenderer(ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _characterProvider = characterProvider; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _clientWindowSizeProvider = clientWindowSizeProvider; + } - public virtual bool CanRender(int row, int col) - { - if (!ElementExistsAt(row, col)) - return false; + public virtual bool CanRender(int row, int col) + { + if (!ElementExistsAt(row, col)) + return false; - var props = _characterProvider.MainCharacter.RenderProperties; + var props = _characterProvider.MainCharacter.RenderProperties; - var rowDelta = Math.Abs(props.MapY - row); - var colDelta = Math.Abs(props.MapX - col); + var rowDelta = Math.Abs(props.MapY - row); + var colDelta = Math.Abs(props.MapX - col); - var renderDistanceScaledX = (int)Math.Ceiling(_clientWindowSizeProvider.Width / 640.0 * RenderDistance); - var renderDistanceScaledY = (int)Math.Ceiling(_clientWindowSizeProvider.Height / 480.0 * RenderDistance); + var renderDistanceScaledX = (int)Math.Ceiling(_clientWindowSizeProvider.Width / 640.0 * RenderDistance); + var renderDistanceScaledY = (int)Math.Ceiling(_clientWindowSizeProvider.Height / 480.0 * RenderDistance); - return rowDelta <= renderDistanceScaledX && colDelta <= renderDistanceScaledY; - } + return rowDelta <= renderDistanceScaledX && colDelta <= renderDistanceScaledY; + } - protected abstract bool ElementExistsAt(int row, int col); + protected abstract bool ElementExistsAt(int row, int col); - public virtual void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - if ((DateTime.Now - _lastFrameTime).TotalMilliseconds > 600) + public virtual void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) { - _lastFrameTime = DateTime.Now; - _frameIndex = (_frameIndex + 1) % 4; + if ((DateTime.Now - _lastFrameTime).TotalMilliseconds > 600) + { + _lastFrameTime = DateTime.Now; + _frameIndex = (_frameIndex + 1) % 4; + } } - } - protected virtual Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) - { - return _gridDrawCoordinateCalculator.CalculateDrawCoordinatesFromGridUnits(gridX, gridY) + _layerOffsets[RenderLayer].ToVector2(); + protected virtual Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) + { + return _gridDrawCoordinateCalculator.CalculateDrawCoordinatesFromGridUnits(gridX, gridY) + _layerOffsets[RenderLayer].ToVector2(); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs index d9c68e5fd..17182a148 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/GroundLayerRenderer.cs @@ -6,100 +6,101 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class GroundLayerRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - protected const int ANIMATED_TILE_MIN_WIDTH = 128; - - protected readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - - public override MapRenderLayer RenderLayer => MapRenderLayer.Ground; - - protected override int RenderDistance => 10; - - public GroundLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - } - - protected override Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) + public class GroundLayerRenderer : BaseMapEntityRenderer { - // the height is used to offset the 0 point of the grid, which is 32 units per tile in the height of the map - var height = CurrentMap.Properties.Height; - var offset = new Vector2(32 * height, 0); + protected const int ANIMATED_TILE_MIN_WIDTH = 128; - var basePosition = _gridDrawCoordinateCalculator.CalculateRawRenderCoordinatesFromGridUnits(gridX, gridY); - return basePosition + offset; - } - - public override bool CanRender(int row, int col) => ElementExistsAt(row, col); + protected readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; - protected override bool ElementExistsAt(int row, int col) - { - return (CurrentMap.Properties.FillTile > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) || - CurrentMap.GFX[MapLayer.GroundTile][row, col] > 0; - } + public override MapRenderLayer RenderLayer => MapRenderLayer.Ground; - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - base.RenderElementAt(spriteBatch, row, col, alpha); + protected override int RenderDistance => 10; - var pos = GetDrawCoordinatesFromGridUnits(col, row); + public GroundLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + } - int tileGFX; - Texture2D tileTexture; - if ((tileGFX = CurrentMap.Properties.FillTile) > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) + protected override Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) { - tileTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileGFX, true); + // the height is used to offset the 0 point of the grid, which is 32 units per tile in the height of the map + var height = CurrentMap.Properties.Height; + var offset = new Vector2(32 * height, 0); + + var basePosition = _gridDrawCoordinateCalculator.CalculateRawRenderCoordinatesFromGridUnits(gridX, gridY); + return basePosition + offset; } - else if ((tileGFX = CurrentMap.GFX[MapLayer.GroundTile][row, col]) > 0) + + public override bool CanRender(int row, int col) => ElementExistsAt(row, col); + + protected override bool ElementExistsAt(int row, int col) { - tileTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileGFX, true); + return (CurrentMap.Properties.FillTile > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) || + CurrentMap.GFX[MapLayer.GroundTile][row, col] > 0; } - else + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) { - return; + base.RenderElementAt(spriteBatch, row, col, alpha); + + var pos = GetDrawCoordinatesFromGridUnits(col, row); + + int tileGFX; + Texture2D tileTexture; + if ((tileGFX = CurrentMap.Properties.FillTile) > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) + { + tileTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileGFX, true); + } + else if ((tileGFX = CurrentMap.GFX[MapLayer.GroundTile][row, col]) > 0) + { + tileTexture = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileGFX, true); + } + else + { + return; + } + + var src = tileTexture.Width >= ANIMATED_TILE_MIN_WIDTH + ? new Rectangle?(new Rectangle((tileTexture.Width / 4) * _frameIndex, 0, tileTexture.Width / 4, tileTexture.Height)) + : null; + spriteBatch.Draw(tileTexture, pos + additionalOffset, src, Color.FromNonPremultiplied(255, 255, 255, alpha)); } - var src = tileTexture.Width >= ANIMATED_TILE_MIN_WIDTH - ? new Rectangle?(new Rectangle((tileTexture.Width / 4) * _frameIndex, 0, tileTexture.Width / 4, tileTexture.Height)) - : null; - spriteBatch.Draw(tileTexture, pos + additionalOffset, src, Color.FromNonPremultiplied(255, 255, 255, alpha)); + protected IMapFile CurrentMap => _currentMapProvider.CurrentMap; } - protected IMapFile CurrentMap => _currentMapProvider.CurrentMap; -} - -public class AnimatedGroundLayerRenderer : GroundLayerRenderer -{ - public AnimatedGroundLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + public class AnimatedGroundLayerRenderer : GroundLayerRenderer { - } + public AnimatedGroundLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + } - protected override bool ElementExistsAt(int row, int col) - { - int tileId; - var tileExists = ((tileId = CurrentMap.Properties.FillTile) > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) || - (tileId = CurrentMap.GFX[MapLayer.GroundTile][row, col]) > 0; + protected override bool ElementExistsAt(int row, int col) + { + int tileId; + var tileExists = ((tileId = CurrentMap.Properties.FillTile) > 0 && CurrentMap.GFX[MapLayer.GroundTile][row, col] < 0) || + (tileId = CurrentMap.GFX[MapLayer.GroundTile][row, col]) > 0; - return tileExists && _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileId, true).Width >= ANIMATED_TILE_MIN_WIDTH; - } + return tileExists && _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, tileId, true).Width >= ANIMATED_TILE_MIN_WIDTH; + } - protected override Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) - { - return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(gridX, gridY); + protected override Vector2 GetDrawCoordinatesFromGridUnits(int gridX, int gridY) + { + return _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(gridX, gridY); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs index 4d0ee8a12..9315a11a5 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs @@ -3,15 +3,16 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public interface IMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - MapRenderLayer RenderLayer { get; } + public interface IMapEntityRenderer + { + MapRenderLayer RenderLayer { get; } - bool ShouldRenderLast { get; } + bool ShouldRenderLast { get; } - bool CanRender(int row, int col); + bool CanRender(int row, int col); - void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalPixelOffset = default); + void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalPixelOffset = default); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs index cac29588d..90c1e5422 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRendererProvider.cs @@ -1,13 +1,14 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public interface IMapEntityRendererProvider +namespace EndlessClient.Rendering.MapEntityRenderers { - IMapEntityRenderer GroundRenderer { get; } + public interface IMapEntityRendererProvider + { + IMapEntityRenderer GroundRenderer { get; } - IReadOnlyList BaseRenderers { get; } + IReadOnlyList BaseRenderers { get; } - IReadOnlyList MapEntityRenderers { get; } + IReadOnlyList MapEntityRenderers { get; } + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs index d0f5e3627..f45bc97d2 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MainCharacterEntityRenderer.cs @@ -5,48 +5,49 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class MainCharacterEntityRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly bool _transparent; - - public MainCharacterEntityRenderer(ICharacterProvider characterProvider, - ICharacterRendererProvider characterRendererProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - bool transparent) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + public class MainCharacterEntityRenderer : BaseMapEntityRenderer { - _characterRendererProvider = characterRendererProvider; - _transparent = transparent; - } + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly bool _transparent; - public override MapRenderLayer RenderLayer => - _transparent ? MapRenderLayer.MainCharacterTransparent : MapRenderLayer.MainCharacter; - - protected override int RenderDistance => 1; - - protected override bool ElementExistsAt(int row, int col) - { - var rp = _characterProvider.MainCharacter.RenderProperties; - if (rp.CurrentAction != CharacterActionState.Walking) + public MainCharacterEntityRenderer(ICharacterProvider characterProvider, + ICharacterRendererProvider characterRendererProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + bool transparent) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) { - return row == rp.MapY && col == rp.MapX; + _characterRendererProvider = characterRendererProvider; + _transparent = transparent; } - else + + public override MapRenderLayer RenderLayer => + _transparent ? MapRenderLayer.MainCharacterTransparent : MapRenderLayer.MainCharacter; + + protected override int RenderDistance => 1; + + protected override bool ElementExistsAt(int row, int col) { - return row == rp.GetDestinationY() && col == rp.GetDestinationX(); + var rp = _characterProvider.MainCharacter.RenderProperties; + if (rp.CurrentAction != CharacterActionState.Walking) + { + return row == rp.MapY && col == rp.MapX; + } + else + { + return row == rp.GetDestinationY() && col == rp.GetDestinationX(); + } } - } - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) { - cr.Transparent = _transparent; - cr.DrawToSpriteBatch(spriteBatch); - }); + _characterRendererProvider.MainCharacterRenderer.MatchSome(cr => + { + cr.Transparent = _transparent; + cr.DrawToSpriteBatch(spriteBatch); + }); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs index a1f0403de..8b7819708 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs @@ -6,46 +6,47 @@ using System; using System.Linq; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class MapItemLayerRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - - public override MapRenderLayer RenderLayer => MapRenderLayer.Item; - - protected override int RenderDistance => 16; - - public MapItemLayerRenderer(ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapStateProvider currentMapStateProvider, - IMapItemGraphicProvider mapItemGraphicProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + public class MapItemLayerRenderer : BaseMapEntityRenderer { - _currentMapStateProvider = currentMapStateProvider; - _mapItemGraphicProvider = mapItemGraphicProvider; - } + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly IMapItemGraphicProvider _mapItemGraphicProvider; - protected override bool ElementExistsAt(int row, int col) - { - return _currentMapStateProvider.MapItems.ContainsKey(new MapCoordinate(col, row)); - } + public override MapRenderLayer RenderLayer => MapRenderLayer.Item; - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - var items = _currentMapStateProvider.MapItems[new MapCoordinate(col, row)]; + protected override int RenderDistance => 16; + + public MapItemLayerRenderer(ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapStateProvider currentMapStateProvider, + IMapItemGraphicProvider mapItemGraphicProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _currentMapStateProvider = currentMapStateProvider; + _mapItemGraphicProvider = mapItemGraphicProvider; + } - foreach (var item in items.OrderBy(item => item.UniqueID)) + protected override bool ElementExistsAt(int row, int col) { - var itemPos = GetDrawCoordinatesFromGridUnits(col, row); - var itemTexture = _mapItemGraphicProvider.GetItemGraphic(item.ItemID, item.Amount); + return _currentMapStateProvider.MapItems.ContainsKey(new MapCoordinate(col, row)); + } - spriteBatch.Draw(itemTexture, - new Vector2(itemPos.X - (int)Math.Round(itemTexture.Width / 2.0), - itemPos.Y - (int)Math.Round(itemTexture.Height / 2.0)) + additionalOffset, - Color.FromNonPremultiplied(255, 255, 255, alpha)); + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + var items = _currentMapStateProvider.MapItems[new MapCoordinate(col, row)]; + + foreach (var item in items.OrderBy(item => item.UniqueID)) + { + var itemPos = GetDrawCoordinatesFromGridUnits(col, row); + var itemTexture = _mapItemGraphicProvider.GetItemGraphic(item.ItemID, item.Amount); + + spriteBatch.Draw(itemTexture, + new Vector2(itemPos.X - (int)Math.Round(itemTexture.Width / 2.0), + itemPos.Y - (int)Math.Round(itemTexture.Height / 2.0)) + additionalOffset, + Color.FromNonPremultiplied(255, 255, 255, alpha)); + } } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs index 36b8ec6b4..3677dffa8 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs @@ -11,81 +11,82 @@ using System.Linq; using DomainCharacter = EOLib.Domain.Character.Character; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class MapObjectLayerRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private const int TIMED_SPIKE_DURATION_MS = 1000; + public class MapObjectLayerRenderer : BaseMapEntityRenderer + { + private const int TIMED_SPIKE_DURATION_MS = 1000; - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; - public override MapRenderLayer RenderLayer => MapRenderLayer.Objects; + public override MapRenderLayer RenderLayer => MapRenderLayer.Objects; - protected override int RenderDistance => 22; + protected override int RenderDistance => 22; - public MapObjectLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapStateProvider currentMapStateProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; - } + public MapObjectLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapStateProvider currentMapStateProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + } - protected override bool ElementExistsAt(int row, int col) - { - return MapFile.GFX[MapLayer.Objects][row, col] > 0; - } + protected override bool ElementExistsAt(int row, int col) + { + return MapFile.GFX[MapLayer.Objects][row, col] > 0; + } - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - if (MapFile.Tiles[row, col] == TileSpec.SpikesTrap) + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) { - var loc = new MapCoordinate(col, row); - var mainCharacterAt = CharacterAt(_characterProvider.MainCharacter, loc); - if (!mainCharacterAt && _currentMapStateProvider.Characters.ContainsKey(loc)) + if (MapFile.Tiles[row, col] == TileSpec.SpikesTrap) { - var anyOtherCharactersAt = _currentMapStateProvider.Characters[loc].Any(x => CharacterAt(x, loc)); - if (!anyOtherCharactersAt) + var loc = new MapCoordinate(col, row); + var mainCharacterAt = CharacterAt(_characterProvider.MainCharacter, loc); + if (!mainCharacterAt && _currentMapStateProvider.Characters.ContainsKey(loc)) + { + var anyOtherCharactersAt = _currentMapStateProvider.Characters[loc].Any(x => CharacterAt(x, loc)); + if (!anyOtherCharactersAt) + { + return; + } + } + else if (!mainCharacterAt) { return; } } - else if (!mainCharacterAt) + else if (MapFile.Tiles[row, col] == TileSpec.SpikesTimed) { - return; + var shouldRender = _currentMapStateProvider.LastTimedSpikeEvent + .Map(time => (DateTime.Now - time).TotalMilliseconds <= TIMED_SPIKE_DURATION_MS) + .ValueOr(false); + if (!shouldRender) + return; } - } - else if (MapFile.Tiles[row, col] == TileSpec.SpikesTimed) - { - var shouldRender = _currentMapStateProvider.LastTimedSpikeEvent - .Map(time => (DateTime.Now - time).TotalMilliseconds <= TIMED_SPIKE_DURATION_MS) - .ValueOr(false); - if (!shouldRender) - return; - } - int gfxNum = MapFile.GFX[MapLayer.Objects][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapObjects, gfxNum, true); + int gfxNum = MapFile.GFX[MapLayer.Objects][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapObjects, gfxNum, true); - var pos = GetDrawCoordinatesFromGridUnits(col, row); - pos -= new Vector2(gfx.Width / 2, gfx.Height - 32); + var pos = GetDrawCoordinatesFromGridUnits(col, row); + pos -= new Vector2(gfx.Width / 2, gfx.Height - 32); - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); + } - private IMapFile MapFile => _currentMapProvider.CurrentMap; + private IMapFile MapFile => _currentMapProvider.CurrentMap; - private static bool CharacterAt(DomainCharacter c, MapCoordinate tile) - { - return c.RenderProperties.CurrentAction != CharacterActionState.Walking - ? tile == c.RenderProperties.Coordinates() - : tile == c.RenderProperties.DestinationCoordinates(); + private static bool CharacterAt(DomainCharacter c, MapCoordinate tile) + { + return c.RenderProperties.CurrentAction != CharacterActionState.Walking + ? tile == c.RenderProperties.Coordinates() + : tile == c.RenderProperties.DestinationCoordinates(); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs index 2551ba8d5..ac63c5438 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs @@ -6,50 +6,51 @@ using Microsoft.Xna.Framework.Graphics; using System.Linq; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class NPCEntityRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private readonly INPCRendererProvider _npcRendererProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - - public NPCEntityRenderer(ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - INPCRendererProvider npcRendererProvider, - ICurrentMapStateProvider currentMapStateProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + public class NPCEntityRenderer : BaseMapEntityRenderer { - _npcRendererProvider = npcRendererProvider; - _currentMapStateProvider = currentMapStateProvider; - } - - public override MapRenderLayer RenderLayer => MapRenderLayer.Npc; + private readonly INPCRendererProvider _npcRendererProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + + public NPCEntityRenderer(ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + INPCRendererProvider npcRendererProvider, + ICurrentMapStateProvider currentMapStateProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _npcRendererProvider = npcRendererProvider; + _currentMapStateProvider = currentMapStateProvider; + } - protected override int RenderDistance => 16; + public override MapRenderLayer RenderLayer => MapRenderLayer.Npc; - protected override bool ElementExistsAt(int row, int col) - { - var coordinate = new MapCoordinate(col, row); - return _currentMapStateProvider.NPCs.ContainsKey(coordinate) || _npcRendererProvider.DyingNPCs.ContainsKey(coordinate); - } + protected override int RenderDistance => 16; - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - var coordinate = new MapCoordinate(col, row); - var indicesToRender = _npcRendererProvider.DyingNPCs.ContainsKey(coordinate) - ? _currentMapStateProvider.NPCs.ContainsKey(coordinate) - ? Enumerable.Repeat(_npcRendererProvider.DyingNPCs[coordinate], 1).Concat(_currentMapStateProvider.NPCs[coordinate].Select(n => n.Index)) - : Enumerable.Repeat(_npcRendererProvider.DyingNPCs[coordinate], 1) - : _currentMapStateProvider.NPCs[coordinate].Select(n => n.Index); - - foreach (var index in indicesToRender) + protected override bool ElementExistsAt(int row, int col) { - if (!_npcRendererProvider.NPCRenderers.ContainsKey(index) || - _npcRendererProvider.NPCRenderers[index] == null) - continue; + var coordinate = new MapCoordinate(col, row); + return _currentMapStateProvider.NPCs.ContainsKey(coordinate) || _npcRendererProvider.DyingNPCs.ContainsKey(coordinate); + } - _npcRendererProvider.NPCRenderers[index].DrawToSpriteBatch(spriteBatch); + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + var coordinate = new MapCoordinate(col, row); + var indicesToRender = _npcRendererProvider.DyingNPCs.ContainsKey(coordinate) + ? _currentMapStateProvider.NPCs.ContainsKey(coordinate) + ? Enumerable.Repeat(_npcRendererProvider.DyingNPCs[coordinate], 1).Concat(_currentMapStateProvider.NPCs[coordinate].Select(n => n.Index)) + : Enumerable.Repeat(_npcRendererProvider.DyingNPCs[coordinate], 1) + : _currentMapStateProvider.NPCs[coordinate].Select(n => n.Index); + + foreach (var index in indicesToRender) + { + if (!_npcRendererProvider.NPCRenderers.ContainsKey(index) || + _npcRendererProvider.NPCRenderers[index] == null) + continue; + + _npcRendererProvider.NPCRenderers[index].DrawToSpriteBatch(spriteBatch); + } } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs index cce88a4dc..32a32620f 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/OnTopLayerRenderer.cs @@ -6,41 +6,42 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class OnTopLayerRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - - public override MapRenderLayer RenderLayer => MapRenderLayer.OnTop; - - protected override int RenderDistance => 12; - - public OnTopLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - } - - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.OverlayTile][row, col] > 0; - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + public class OnTopLayerRenderer : BaseMapEntityRenderer { - int gfxNum = CurrentMap.GFX[MapLayer.OverlayTile][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, gfxNum, true); - - var pos = GetDrawCoordinatesFromGridUnits(col, row); - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; + + public override MapRenderLayer RenderLayer => MapRenderLayer.OnTop; + + protected override int RenderDistance => 12; + + public OnTopLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + } + + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.OverlayTile][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + int gfxNum = CurrentMap.GFX[MapLayer.OverlayTile][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapTiles, gfxNum, true); + + var pos = GetDrawCoordinatesFromGridUnits(col, row); + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); + } + + private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } - - private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs index ab6b1b444..25dd1a64e 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs @@ -6,44 +6,45 @@ using Microsoft.Xna.Framework.Graphics; using System.Linq; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class OtherCharacterEntityRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; - - public OtherCharacterEntityRenderer(ICharacterProvider characterProvider, - ICharacterRendererProvider characterRendererProvider, - ICurrentMapStateProvider currentMapStateProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + public class OtherCharacterEntityRenderer : BaseMapEntityRenderer { - _characterRendererProvider = characterRendererProvider; - _currentMapStateProvider = currentMapStateProvider; - } + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + + public OtherCharacterEntityRenderer(ICharacterProvider characterProvider, + ICharacterRendererProvider characterRendererProvider, + ICurrentMapStateProvider currentMapStateProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _characterRendererProvider = characterRendererProvider; + _currentMapStateProvider = currentMapStateProvider; + } - public override MapRenderLayer RenderLayer => MapRenderLayer.OtherCharacters; + public override MapRenderLayer RenderLayer => MapRenderLayer.OtherCharacters; - protected override int RenderDistance => 16; + protected override int RenderDistance => 16; - protected override bool ElementExistsAt(int row, int col) - { - return _currentMapStateProvider.Characters.ContainsKey(new MapCoordinate(col, row)); - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - var toRender = _currentMapStateProvider.Characters[new MapCoordinate(col, row)]; + protected override bool ElementExistsAt(int row, int col) + { + return _currentMapStateProvider.Characters.ContainsKey(new MapCoordinate(col, row)); + } - foreach (var id in toRender.Select(x => x.ID)) + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) { - if (!_characterRendererProvider.CharacterRenderers.ContainsKey(id) || - _characterRendererProvider.CharacterRenderers[id] == null) - return; + var toRender = _currentMapStateProvider.Characters[new MapCoordinate(col, row)]; + + foreach (var id in toRender.Select(x => x.ID)) + { + if (!_characterRendererProvider.CharacterRenderers.ContainsKey(id) || + _characterRendererProvider.CharacterRenderers[id] == null) + return; - _characterRendererProvider.CharacterRenderers[id].DrawToSpriteBatch(spriteBatch); + _characterRendererProvider.CharacterRenderers[id].DrawToSpriteBatch(spriteBatch); + } } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs index 3845c7d4f..e23dc5240 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/Overlay2LayerRenderer.cs @@ -6,43 +6,44 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class Overlay2LayerRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; + public class Overlay2LayerRenderer : BaseMapEntityRenderer + { + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; - public override MapRenderLayer RenderLayer => MapRenderLayer.Overlay2; + public override MapRenderLayer RenderLayer => MapRenderLayer.Overlay2; - protected override int RenderDistance => 12; + protected override int RenderDistance => 12; - public Overlay2LayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - } + public Overlay2LayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + } - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.Overlay2][row, col] > 0; - } + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.Overlay2][row, col] > 0; + } - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - int gfxNum = CurrentMap.GFX[MapLayer.Overlay2][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapOverlay, gfxNum, true); + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + int gfxNum = CurrentMap.GFX[MapLayer.Overlay2][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapOverlay, gfxNum, true); - var pos = GetDrawCoordinatesFromGridUnits(col, row); - pos -= new Vector2((float)System.Math.Floor(gfx.Width / 2f), gfx.Height - 32); + var pos = GetDrawCoordinatesFromGridUnits(col, row); + pos -= new Vector2((float)System.Math.Floor(gfx.Width / 2f), gfx.Height - 32); - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); + } - private IMapFile CurrentMap => _currentMapProvider.CurrentMap; + private IMapFile CurrentMap => _currentMapProvider.CurrentMap; + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs index ad170a8ce..b6ff7111e 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/OverlayLayerRenderer.cs @@ -6,43 +6,44 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class OverlayLayerRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; + public class OverlayLayerRenderer : BaseMapEntityRenderer + { + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; - public override MapRenderLayer RenderLayer => MapRenderLayer.Overlay; + public override MapRenderLayer RenderLayer => MapRenderLayer.Overlay; - protected override int RenderDistance => 14; + protected override int RenderDistance => 14; - public OverlayLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - } + public OverlayLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + } - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.OverlayObjects][row, col] > 0; - } + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.OverlayObjects][row, col] > 0; + } - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - int gfxNum = CurrentMap.GFX[MapLayer.OverlayObjects][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapOverlay, gfxNum, true); + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + int gfxNum = CurrentMap.GFX[MapLayer.OverlayObjects][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapOverlay, gfxNum, true); - var pos = GetDrawCoordinatesFromGridUnits(col, row); - pos -= new Vector2(gfx.Width / 2, gfx.Height - 32); + var pos = GetDrawCoordinatesFromGridUnits(col, row); + pos -= new Vector2(gfx.Width / 2, gfx.Height - 32); - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); + } - private IMapFile CurrentMap => _currentMapProvider.CurrentMap; + private IMapFile CurrentMap => _currentMapProvider.CurrentMap; + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs index ada554756..b42cff2e9 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/RoofLayerRenderer.cs @@ -6,41 +6,42 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class RoofLayerRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - - public override MapRenderLayer RenderLayer => MapRenderLayer.Roof; - - protected override int RenderDistance => 12; - - public RoofLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - } - - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.Roof][row, col] > 0; - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + public class RoofLayerRenderer : BaseMapEntityRenderer { - int gfxNum = CurrentMap.GFX[MapLayer.Roof][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapWallTop, gfxNum, true); - - var pos = GetDrawCoordinatesFromGridUnits(col, row); - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; + + public override MapRenderLayer RenderLayer => MapRenderLayer.Roof; + + protected override int RenderDistance => 12; + + public RoofLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + } + + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.Roof][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + int gfxNum = CurrentMap.GFX[MapLayer.Roof][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapWallTop, gfxNum, true); + + var pos = GetDrawCoordinatesFromGridUnits(col, row); + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, alpha)); + } + + private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } - - private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs index 64d45c991..d6ca67d0f 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/ShadowLayerRenderer.cs @@ -7,51 +7,52 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public class ShadowLayerRenderer : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IConfigurationProvider _configurationProvider; - - public override MapRenderLayer RenderLayer => MapRenderLayer.Shadows; - - protected override int RenderDistance => 16; - - public ShadowLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - IConfigurationProvider configurationProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - _configurationProvider = configurationProvider; - } - - public override bool CanRender(int row, int col) - { - return _configurationProvider.ShowShadows && base.CanRender(row, col); - } - - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.Shadow][row, col] > 0; - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + public class ShadowLayerRenderer : BaseMapEntityRenderer { - int gfxNum = CurrentMap.GFX[MapLayer.Shadow][row, col]; - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.Shadows, gfxNum, true); - - var pos = GetDrawCoordinatesFromGridUnits(col, row); - pos = new Vector2(pos.X - 32, pos.Y); - - spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, 255 / 5)); + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IConfigurationProvider _configurationProvider; + + public override MapRenderLayer RenderLayer => MapRenderLayer.Shadows; + + protected override int RenderDistance => 16; + + public ShadowLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + IConfigurationProvider configurationProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + _configurationProvider = configurationProvider; + } + + public override bool CanRender(int row, int col) + { + return _configurationProvider.ShowShadows && base.CanRender(row, col); + } + + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.Shadow][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + int gfxNum = CurrentMap.GFX[MapLayer.Shadow][row, col]; + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.Shadows, gfxNum, true); + + var pos = GetDrawCoordinatesFromGridUnits(col, row); + pos = new Vector2(pos.X - 32, pos.Y); + + spriteBatch.Draw(gfx, pos + additionalOffset, Color.FromNonPremultiplied(255, 255, 255, 255 / 5)); + } + + private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } - - private IMapFile CurrentMap => _currentMapProvider.CurrentMap; } \ No newline at end of file diff --git a/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs index 6d5260106..eb8687289 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs @@ -7,104 +7,105 @@ using Microsoft.Xna.Framework.Graphics; using System.Linq; -namespace EndlessClient.Rendering.MapEntityRenderers; - -public abstract class WallLayerRendererBase : BaseMapEntityRenderer +namespace EndlessClient.Rendering.MapEntityRenderers { - private const int WALL_FRAME_WIDTH = 68; - - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICurrentMapStateProvider _currentMapStateProvider; + public abstract class WallLayerRendererBase : BaseMapEntityRenderer + { + private const int WALL_FRAME_WIDTH = 68; + + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICurrentMapStateProvider _currentMapStateProvider; + + protected override int RenderDistance => 20; + + protected WallLayerRendererBase(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapStateProvider currentMapStateProvider) + : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) + { + _nativeGraphicsManager = nativeGraphicsManager; + _currentMapProvider = currentMapProvider; + _currentMapStateProvider = currentMapStateProvider; + } + + protected void DrawWall(SpriteBatch spriteBatch, int row, int col, int alpha, int gfxNum, Vector2 additionalOffset = default) + { + if (_currentMapStateProvider.OpenDoors.Any(openDoor => openDoor.X == col && openDoor.Y == row)) + gfxNum++; + + var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapWalls, gfxNum, true); + + var gfxWidthDelta = gfx.Width / 4; + var src = gfx.Width > WALL_FRAME_WIDTH + ? new Rectangle?(new Rectangle(gfxWidthDelta * _frameIndex, 0, gfxWidthDelta, gfx.Height)) + : null; + + var pos = GetDrawCoordinatesFromGridUnits(col, row); + pos -= new Vector2(32, gfx.Height - 32); + + spriteBatch.Draw(gfx, pos + additionalOffset, src, Color.FromNonPremultiplied(255, 255, 255, alpha)); + } + + protected IMapFile CurrentMap => _currentMapProvider.CurrentMap; + } - protected override int RenderDistance => 20; + public class DownWallLayerRenderer : WallLayerRendererBase + { + public override MapRenderLayer RenderLayer => MapRenderLayer.DownWall; - protected WallLayerRendererBase(INativeGraphicsManager nativeGraphicsManager, + public DownWallLayerRenderer(INativeGraphicsManager nativeGraphicsManager, ICurrentMapProvider currentMapProvider, ICharacterProvider characterProvider, IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, IClientWindowSizeProvider clientWindowSizeProvider, ICurrentMapStateProvider currentMapStateProvider) - : base(characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider) - { - _nativeGraphicsManager = nativeGraphicsManager; - _currentMapProvider = currentMapProvider; - _currentMapStateProvider = currentMapStateProvider; + : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider, currentMapStateProvider) + { + } + + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.WallRowsDown][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + base.RenderElementAt(spriteBatch, row, col, alpha, additionalOffset); + + var gfxNum = CurrentMap.GFX[MapLayer.WallRowsDown][row, col]; + DrawWall(spriteBatch, row, col, alpha, gfxNum, additionalOffset); + } } - protected void DrawWall(SpriteBatch spriteBatch, int row, int col, int alpha, int gfxNum, Vector2 additionalOffset = default) + public class RightWallLayerRenderer : WallLayerRendererBase { - if (_currentMapStateProvider.OpenDoors.Any(openDoor => openDoor.X == col && openDoor.Y == row)) - gfxNum++; - - var gfx = _nativeGraphicsManager.TextureFromResource(GFXTypes.MapWalls, gfxNum, true); - - var gfxWidthDelta = gfx.Width / 4; - var src = gfx.Width > WALL_FRAME_WIDTH - ? new Rectangle?(new Rectangle(gfxWidthDelta * _frameIndex, 0, gfxWidthDelta, gfx.Height)) - : null; - - var pos = GetDrawCoordinatesFromGridUnits(col, row); - pos -= new Vector2(32, gfx.Height - 32); - - spriteBatch.Draw(gfx, pos + additionalOffset, src, Color.FromNonPremultiplied(255, 255, 255, alpha)); - } - - protected IMapFile CurrentMap => _currentMapProvider.CurrentMap; -} - -public class DownWallLayerRenderer : WallLayerRendererBase -{ - public override MapRenderLayer RenderLayer => MapRenderLayer.DownWall; - - public DownWallLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapStateProvider currentMapStateProvider) - : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider, currentMapStateProvider) - { - } - - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.WallRowsDown][row, col] > 0; - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - base.RenderElementAt(spriteBatch, row, col, alpha, additionalOffset); - - var gfxNum = CurrentMap.GFX[MapLayer.WallRowsDown][row, col]; - DrawWall(spriteBatch, row, col, alpha, gfxNum, additionalOffset); - } -} - -public class RightWallLayerRenderer : WallLayerRendererBase -{ - public override MapRenderLayer RenderLayer => MapRenderLayer.RightWall; - - public RightWallLayerRenderer(INativeGraphicsManager nativeGraphicsManager, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IClientWindowSizeProvider clientWindowSizeProvider, - ICurrentMapStateProvider currentMapStateProvider) - : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider, currentMapStateProvider) - { - } - - protected override bool ElementExistsAt(int row, int col) - { - return CurrentMap.GFX[MapLayer.WallRowsRight][row, col] > 0; - } - - public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) - { - base.RenderElementAt(spriteBatch, row, col, alpha, additionalOffset); - - var gfxNum = CurrentMap.GFX[MapLayer.WallRowsRight][row, col]; - DrawWall(spriteBatch, row, col, alpha, gfxNum, additionalOffset); + public override MapRenderLayer RenderLayer => MapRenderLayer.RightWall; + + public RightWallLayerRenderer(INativeGraphicsManager nativeGraphicsManager, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IClientWindowSizeProvider clientWindowSizeProvider, + ICurrentMapStateProvider currentMapStateProvider) + : base(nativeGraphicsManager, currentMapProvider, characterProvider, gridDrawCoordinateCalculator, clientWindowSizeProvider, currentMapStateProvider) + { + } + + protected override bool ElementExistsAt(int row, int col) + { + return CurrentMap.GFX[MapLayer.WallRowsRight][row, col] > 0; + } + + public override void RenderElementAt(SpriteBatch spriteBatch, int row, int col, int alpha, Vector2 additionalOffset = default) + { + base.RenderElementAt(spriteBatch, row, col, alpha, additionalOffset); + + var gfxNum = CurrentMap.GFX[MapLayer.WallRowsRight][row, col]; + DrawWall(spriteBatch, row, col, alpha, gfxNum, additionalOffset); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs b/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs index 0350ebe36..c6dfe7e0d 100644 --- a/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs @@ -4,63 +4,64 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata; - -[AutoMappedType(IsSingleton = true)] -public class EffectMetadataProvider : IMetadataProvider +namespace EndlessClient.Rendering.Metadata { - public IReadOnlyDictionary DefaultMetadata => _metadata; + [AutoMappedType(IsSingleton = true)] + public class EffectMetadataProvider : IMetadataProvider + { + public IReadOnlyDictionary DefaultMetadata => _metadata; - private readonly Dictionary _metadata; - private readonly IGFXMetadataLoader _metadataLoader; + private readonly Dictionary _metadata; + private readonly IGFXMetadataLoader _metadataLoader; - public EffectMetadataProvider(IGFXMetadataLoader metadataLoader) - { - // source: https://docs.google.com/spreadsheets/d/1DQgN4r2cH6HA2ydn4M6CpUJlClWXXBemosYP57k_o5I/edit#gid=0 - // todo: flickering effects are off-by-one. Fix metadata in the GFX (EndlessClient.Binaries), here, and in EffectSpriteInfo where a -1 is applied to the random choice - _metadata = new Dictionary + public EffectMetadataProvider(IGFXMetadataLoader metadataLoader) { - { 1, new EffectMetadata(true, true, true, SoundEffectID.PotionOfFlamesEffect, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // small fire - { 2, new EffectMetadata(false, false, true, SoundEffectID.PotionOfLoveEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // hearts - { 3, new EffectMetadata(false, true, true, SoundEffectID.AdminWarp, 8, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin warp - { 4, new EffectMetadata(false, false, true, SoundEffectID.AdminWarp, 8, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin warp 2 - { 5, new EffectMetadata(false, false, true, SoundEffectID.PotionOfFireworksEffect, 7, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // celebrate - { 6, new EffectMetadata(false, true, true, SoundEffectID.PotionOfSparklesEffect, 5, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // schwing - { 7, new EffectMetadata(true, false, false, SoundEffectID.PotionOfEvilTerrorEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // evil - { 8, new EffectMetadata(true, false, false, SoundEffectID.PotionOfEvilTerrorEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // terror - { 9, new EffectMetadata(true, false, false, SoundEffectID.Water, 6, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // water splash - { 10, new EffectMetadata(false, true, true, SoundEffectID.Heal, 5, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // heal - { 11, new EffectMetadata(false, false, true, SoundEffectID.Thunder, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // small thunder - { 12, new EffectMetadata(false, false, true, 0, 4, 8, 0, 0, EffectAnimationType.Static, null, null, null) }, // snow - { 13, new EffectMetadata(true, true, false, SoundEffectID.UltimaBlastSpell, 4, 3, 0, 0, EffectAnimationType.Static, null, null, null) }, // ultima - { 14, new EffectMetadata(true, true, false, SoundEffectID.PotionOfFlamesEffect, 6, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // fire ball - { 15, new EffectMetadata(false, true, true, SoundEffectID.ShieldSpell, 6, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // shield - { 16, new EffectMetadata(true, false, true, SoundEffectID.RingOfFireSpell, 4, 3, 0, 0, EffectAnimationType.Static, null, null, null) }, // ring of fire - { 17, new EffectMetadata(false, true, true, SoundEffectID.IceBlastSpell1, 7, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // ice blast - { 18, new EffectMetadata(false, false, true, SoundEffectID.EnergyBallSpell, 7, 1, 0, 0, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(-10), null, null) }, // energy ball - { 19, new EffectMetadata(true, true, true, SoundEffectID.WhirlSpell, 4, 2, 0, -10, EffectAnimationType.Position, null, new PositionOffsetEffectMetadata(new[] { -20, 0, 20, 0 }, new[] { 0, 14, 0, -14 }), null) }, // whirl / tornado - { 20, new EffectMetadata(false, true, false, SoundEffectID.AuraSpell, 5, 3, 0, -12, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // aura - { 21, new EffectMetadata(false, false, true, SoundEffectID.BouldersSpell, 7, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // boulders - { 22, new EffectMetadata(true, true, false, SoundEffectID.HeavenSpell, 5, 4, 0, -114, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // heaven - { 23, new EffectMetadata(true, true, false, SoundEffectID.IceBlastSpell2, 6, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // blue flame - { 24, new EffectMetadata(true, true, false, SoundEffectID.HeavenSpell, 5, 4, 0, -114, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // dark beam - { 25, new EffectMetadata(false, false, true, SoundEffectID.AdminHide, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin hide - { 26, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark hand - { 27, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark skull - { 28, new EffectMetadata(false, false, true, SoundEffectID.FireBlastSpell, 4, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // fire blast - { 29, new EffectMetadata(false, false, true, SoundEffectID.TentaclesSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // tentacles - { 30, new EffectMetadata(true, false, true, SoundEffectID.PowerWindSpell, 6, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // power wind - { 31, new EffectMetadata(true, false, true, SoundEffectID.MagicWhirlSpell, 15, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // magic whirl - { 32, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 6, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark bite - { 33, new EffectMetadata(true, true, false, SoundEffectID.AuraSpell, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // shell - { 34, new EffectMetadata(true, true, false, SoundEffectID.EnergyBallSpell, 5, 1, 0, -44, EffectAnimationType.Static, null, null, null) } // green flame - }; - _metadataLoader = metadataLoader; - } + // source: https://docs.google.com/spreadsheets/d/1DQgN4r2cH6HA2ydn4M6CpUJlClWXXBemosYP57k_o5I/edit#gid=0 + // todo: flickering effects are off-by-one. Fix metadata in the GFX (EndlessClient.Binaries), here, and in EffectSpriteInfo where a -1 is applied to the random choice + _metadata = new Dictionary + { + { 1, new EffectMetadata(true, true, true, SoundEffectID.PotionOfFlamesEffect, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // small fire + { 2, new EffectMetadata(false, false, true, SoundEffectID.PotionOfLoveEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // hearts + { 3, new EffectMetadata(false, true, true, SoundEffectID.AdminWarp, 8, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin warp + { 4, new EffectMetadata(false, false, true, SoundEffectID.AdminWarp, 8, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin warp 2 + { 5, new EffectMetadata(false, false, true, SoundEffectID.PotionOfFireworksEffect, 7, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // celebrate + { 6, new EffectMetadata(false, true, true, SoundEffectID.PotionOfSparklesEffect, 5, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // schwing + { 7, new EffectMetadata(true, false, false, SoundEffectID.PotionOfEvilTerrorEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // evil + { 8, new EffectMetadata(true, false, false, SoundEffectID.PotionOfEvilTerrorEffect, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // terror + { 9, new EffectMetadata(true, false, false, SoundEffectID.Water, 6, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // water splash + { 10, new EffectMetadata(false, true, true, SoundEffectID.Heal, 5, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // heal + { 11, new EffectMetadata(false, false, true, SoundEffectID.Thunder, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // small thunder + { 12, new EffectMetadata(false, false, true, 0, 4, 8, 0, 0, EffectAnimationType.Static, null, null, null) }, // snow + { 13, new EffectMetadata(true, true, false, SoundEffectID.UltimaBlastSpell, 4, 3, 0, 0, EffectAnimationType.Static, null, null, null) }, // ultima + { 14, new EffectMetadata(true, true, false, SoundEffectID.PotionOfFlamesEffect, 6, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // fire ball + { 15, new EffectMetadata(false, true, true, SoundEffectID.ShieldSpell, 6, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // shield + { 16, new EffectMetadata(true, false, true, SoundEffectID.RingOfFireSpell, 4, 3, 0, 0, EffectAnimationType.Static, null, null, null) }, // ring of fire + { 17, new EffectMetadata(false, true, true, SoundEffectID.IceBlastSpell1, 7, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // ice blast + { 18, new EffectMetadata(false, false, true, SoundEffectID.EnergyBallSpell, 7, 1, 0, 0, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(-10), null, null) }, // energy ball + { 19, new EffectMetadata(true, true, true, SoundEffectID.WhirlSpell, 4, 2, 0, -10, EffectAnimationType.Position, null, new PositionOffsetEffectMetadata(new[] { -20, 0, 20, 0 }, new[] { 0, 14, 0, -14 }), null) }, // whirl / tornado + { 20, new EffectMetadata(false, true, false, SoundEffectID.AuraSpell, 5, 3, 0, -12, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // aura + { 21, new EffectMetadata(false, false, true, SoundEffectID.BouldersSpell, 7, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // boulders + { 22, new EffectMetadata(true, true, false, SoundEffectID.HeavenSpell, 5, 4, 0, -114, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // heaven + { 23, new EffectMetadata(true, true, false, SoundEffectID.IceBlastSpell2, 6, 1, 0, -160, EffectAnimationType.VerticalSliding, new VerticalSlidingEffectMetadata(30), null, null) }, // blue flame + { 24, new EffectMetadata(true, true, false, SoundEffectID.HeavenSpell, 5, 4, 0, -114, EffectAnimationType.Flickering, null, null, new RandomFlickeringEffectMetadata(3, 4)) }, // dark beam + { 25, new EffectMetadata(false, false, true, SoundEffectID.AdminHide, 4, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // admin hide + { 26, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark hand + { 27, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark skull + { 28, new EffectMetadata(false, false, true, SoundEffectID.FireBlastSpell, 4, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // fire blast + { 29, new EffectMetadata(false, false, true, SoundEffectID.TentaclesSpell, 5, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // tentacles + { 30, new EffectMetadata(true, false, true, SoundEffectID.PowerWindSpell, 6, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // power wind + { 31, new EffectMetadata(true, false, true, SoundEffectID.MagicWhirlSpell, 15, 1, 0, 0, EffectAnimationType.Static, null, null, null) }, // magic whirl + { 32, new EffectMetadata(true, true, false, SoundEffectID.DarkHandSpell, 6, 2, 0, 0, EffectAnimationType.Static, null, null, null) }, // dark bite + { 33, new EffectMetadata(true, true, false, SoundEffectID.AuraSpell, 4, 4, 0, 0, EffectAnimationType.Static, null, null, null) }, // shell + { 34, new EffectMetadata(true, true, false, SoundEffectID.EnergyBallSpell, 5, 1, 0, -44, EffectAnimationType.Static, null, null, null) } // green flame + }; + _metadataLoader = metadataLoader; + } - public EffectMetadata GetValueOrDefault(int graphic) - { - return _metadataLoader.GetMetadata(graphic) - .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : EffectMetadata.Default); + public EffectMetadata GetValueOrDefault(int graphic) + { + return _metadataLoader.GetMetadata(graphic) + .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : EffectMetadata.Default); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs b/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs index 6ece51a9c..0456b8f54 100644 --- a/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs +++ b/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs @@ -8,62 +8,63 @@ using System.Collections.Generic; using System.Text; -namespace EndlessClient.Rendering.Metadata; - -[AutoMappedType(IsSingleton = true)] -public class GFXMetadataLoader : IGFXMetadataLoader +namespace EndlessClient.Rendering.Metadata { - private readonly IPEFileCollection _peFileCollection; - private readonly Dictionary> _cache; + [AutoMappedType(IsSingleton = true)] + public class GFXMetadataLoader : IGFXMetadataLoader + { + private readonly IPEFileCollection _peFileCollection; + private readonly Dictionary> _cache; - private static readonly Dictionary _mapper; + private static readonly Dictionary _mapper; - static GFXMetadataLoader() - { - _mapper = new Dictionary + static GFXMetadataLoader() { - { typeof(EffectMetadata), GFXTypes.Spells }, - { typeof(NPCMetadata), GFXTypes.NPC }, - { typeof(ShieldMetadata), GFXTypes.MaleBack }, - { typeof(HatMetadata), GFXTypes.MaleHat }, - { typeof(WeaponMetadata), GFXTypes.MaleWeapons } - }; - } + _mapper = new Dictionary + { + { typeof(EffectMetadata), GFXTypes.Spells }, + { typeof(NPCMetadata), GFXTypes.NPC }, + { typeof(ShieldMetadata), GFXTypes.MaleBack }, + { typeof(HatMetadata), GFXTypes.MaleHat }, + { typeof(WeaponMetadata), GFXTypes.MaleWeapons } + }; + } - public GFXMetadataLoader(IPEFileCollection peFileCollection) - { - _peFileCollection = peFileCollection; - _cache = new Dictionary>(); - } + public GFXMetadataLoader(IPEFileCollection peFileCollection) + { + _peFileCollection = peFileCollection; + _cache = new Dictionary>(); + } - public Option GetMetadata(int graphic) - where TMetadata : class, IGFXMetadata - { - if (graphic == 0 || !_mapper.TryGetValue(typeof(TMetadata), out var gfxType)) - return Option.None(); + public Option GetMetadata(int graphic) + where TMetadata : class, IGFXMetadata + { + if (graphic == 0 || !_mapper.TryGetValue(typeof(TMetadata), out var gfxType)) + return Option.None(); - if (!_cache.ContainsKey(gfxType)) - _cache.Add(gfxType, new Dictionary()); - else if (_cache[gfxType].ContainsKey(graphic)) - return Option.Some(_cache[gfxType][graphic] as TMetadata).NotNull(); + if (!_cache.ContainsKey(gfxType)) + _cache.Add(gfxType, new Dictionary()); + else if (_cache[gfxType].ContainsKey(graphic)) + return Option.Some(_cache[gfxType][graphic] as TMetadata).NotNull(); - try - { - var rawMetadata = _peFileCollection[gfxType].GetResourceByID(ResourceType.RCData, graphic); - var metadataString = Encoding.Unicode.GetString(rawMetadata); - _cache[gfxType].Add(graphic, JsonConvert.DeserializeObject(metadataString)); + try + { + var rawMetadata = _peFileCollection[gfxType].GetResourceByID(ResourceType.RCData, graphic); + var metadataString = Encoding.Unicode.GetString(rawMetadata); + _cache[gfxType].Add(graphic, JsonConvert.DeserializeObject(metadataString)); - return (_cache[gfxType][graphic] as TMetadata).SomeNotNull(); - } - catch - { - return Option.None(); + return (_cache[gfxType][graphic] as TMetadata).SomeNotNull(); + } + catch + { + return Option.None(); + } } } -} -public interface IGFXMetadataLoader -{ - Option GetMetadata(int graphic) - where TMetadata : class, IGFXMetadata; + public interface IGFXMetadataLoader + { + Option GetMetadata(int graphic) + where TMetadata : class, IGFXMetadata; + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs b/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs index 6f90b3ac0..d1c783103 100644 --- a/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs @@ -2,67 +2,68 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata; - -[AutoMappedType(IsSingleton = true)] -public class HatMetadataProvider : IMetadataProvider +namespace EndlessClient.Rendering.Metadata { - public IReadOnlyDictionary DefaultMetadata => _metadata; + [AutoMappedType(IsSingleton = true)] + public class HatMetadataProvider : IMetadataProvider + { + public IReadOnlyDictionary DefaultMetadata => _metadata; - private readonly Dictionary _metadata; - private readonly IGFXMetadataLoader _metadataLoader; + private readonly Dictionary _metadata; + private readonly IGFXMetadataLoader _metadataLoader; - public HatMetadataProvider(IGFXMetadataLoader metadataLoader) - { - _metadata = new Dictionary + public HatMetadataProvider(IGFXMetadataLoader metadataLoader) { - { 7, new HatMetadata(HatMaskType.FaceMask) }, // bandana - { 8, new HatMetadata(HatMaskType.FaceMask) }, // bandana - { 9, new HatMetadata(HatMaskType.FaceMask) }, // bandana - { 10, new HatMetadata(HatMaskType.FaceMask) }, // bandana - { 11, new HatMetadata(HatMaskType.FaceMask) }, // bandana - { 12, new HatMetadata(HatMaskType.FaceMask) }, // purple scarf - { 13, new HatMetadata(HatMaskType.FaceMask) }, // red scarf - { 14, new HatMetadata(HatMaskType.FaceMask) }, // black scarf - { 15, new HatMetadata(HatMaskType.FaceMask) }, // dragon mask + _metadata = new Dictionary + { + { 7, new HatMetadata(HatMaskType.FaceMask) }, // bandana + { 8, new HatMetadata(HatMaskType.FaceMask) }, // bandana + { 9, new HatMetadata(HatMaskType.FaceMask) }, // bandana + { 10, new HatMetadata(HatMaskType.FaceMask) }, // bandana + { 11, new HatMetadata(HatMaskType.FaceMask) }, // bandana + { 12, new HatMetadata(HatMaskType.FaceMask) }, // purple scarf + { 13, new HatMetadata(HatMaskType.FaceMask) }, // red scarf + { 14, new HatMetadata(HatMaskType.FaceMask) }, // black scarf + { 15, new HatMetadata(HatMaskType.FaceMask) }, // dragon mask - { 16, new HatMetadata(HatMaskType.HideHair) }, // black hood - { 17, new HatMetadata(HatMaskType.HideHair) }, // brown hood - { 18, new HatMetadata(HatMaskType.HideHair) }, // blue hood - { 19, new HatMetadata(HatMaskType.HideHair) }, // green hood - { 20, new HatMetadata(HatMaskType.HideHair) }, // red hood - { 21, new HatMetadata(HatMaskType.HideHair) }, // chainmail hat + { 16, new HatMetadata(HatMaskType.HideHair) }, // black hood + { 17, new HatMetadata(HatMaskType.HideHair) }, // brown hood + { 18, new HatMetadata(HatMaskType.HideHair) }, // blue hood + { 19, new HatMetadata(HatMaskType.HideHair) }, // green hood + { 20, new HatMetadata(HatMaskType.HideHair) }, // red hood + { 21, new HatMetadata(HatMaskType.HideHair) }, // chainmail hat - { 25, new HatMetadata(HatMaskType.HideHair) }, // horned hat - { 26, new HatMetadata(HatMaskType.HideHair) }, // merchant hat - { 28, new HatMetadata(HatMaskType.HideHair) }, // helmy - { 30, new HatMetadata(HatMaskType.HideHair) }, // eloff helmet - { 31, new HatMetadata(HatMaskType.HideHair) }, // air hat + { 25, new HatMetadata(HatMaskType.HideHair) }, // horned hat + { 26, new HatMetadata(HatMaskType.HideHair) }, // merchant hat + { 28, new HatMetadata(HatMaskType.HideHair) }, // helmy + { 30, new HatMetadata(HatMaskType.HideHair) }, // eloff helmet + { 31, new HatMetadata(HatMaskType.HideHair) }, // air hat - { 32, new HatMetadata(HatMaskType.FaceMask) }, // frog head - { 33, new HatMetadata(HatMaskType.FaceMask) }, // pilotte + { 32, new HatMetadata(HatMaskType.FaceMask) }, // frog head + { 33, new HatMetadata(HatMaskType.FaceMask) }, // pilotte - { 34, new HatMetadata(HatMaskType.HideHair) }, // beruta - { 35, new HatMetadata(HatMaskType.HideHair) }, // pirate hat - { 36, new HatMetadata(HatMaskType.HideHair) }, // lotus helmet - { 37, new HatMetadata(HatMaskType.HideHair) }, // kitty hat - { 38, new HatMetadata(HatMaskType.HideHair) }, // hula hula hat + { 34, new HatMetadata(HatMaskType.HideHair) }, // beruta + { 35, new HatMetadata(HatMaskType.HideHair) }, // pirate hat + { 36, new HatMetadata(HatMaskType.HideHair) }, // lotus helmet + { 37, new HatMetadata(HatMaskType.HideHair) }, // kitty hat + { 38, new HatMetadata(HatMaskType.HideHair) }, // hula hula hat - { 40, new HatMetadata(HatMaskType.HideHair) }, // gob helm - { 41, new HatMetadata(HatMaskType.HideHair) }, // horned gob helm - { 44, new HatMetadata(HatMaskType.HideHair) }, // helmet of darkness - { 46, new HatMetadata(HatMaskType.HideHair) }, // flad hat - { 47, new HatMetadata(HatMaskType.HideHair) }, // cook hat + { 40, new HatMetadata(HatMaskType.HideHair) }, // gob helm + { 41, new HatMetadata(HatMaskType.HideHair) }, // horned gob helm + { 44, new HatMetadata(HatMaskType.HideHair) }, // helmet of darkness + { 46, new HatMetadata(HatMaskType.HideHair) }, // flad hat + { 47, new HatMetadata(HatMaskType.HideHair) }, // cook hat - { 48, new HatMetadata(HatMaskType.FaceMask) }, // glasses - { 50, new HatMetadata(HatMaskType.FaceMask) }, // medic cap - }; - _metadataLoader = metadataLoader; - } + { 48, new HatMetadata(HatMaskType.FaceMask) }, // glasses + { 50, new HatMetadata(HatMaskType.FaceMask) }, // medic cap + }; + _metadataLoader = metadataLoader; + } - public HatMetadata GetValueOrDefault(int graphic) - { - return _metadataLoader.GetMetadata(graphic) - .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : HatMetadata.Default); + public HatMetadata GetValueOrDefault(int graphic) + { + return _metadataLoader.GetMetadata(graphic) + .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : HatMetadata.Default); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/IMetadataProvider.cs b/EndlessClient/Rendering/Metadata/IMetadataProvider.cs index 84c5501fd..f7075edab 100644 --- a/EndlessClient/Rendering/Metadata/IMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/IMetadataProvider.cs @@ -1,12 +1,13 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata; - -public interface IMetadataProvider - where TMetadata : IGFXMetadata +namespace EndlessClient.Rendering.Metadata { - IReadOnlyDictionary DefaultMetadata { get; } + public interface IMetadataProvider + where TMetadata : IGFXMetadata + { + IReadOnlyDictionary DefaultMetadata { get; } - TMetadata GetValueOrDefault(int graphic); + TMetadata GetValueOrDefault(int graphic); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs b/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs index 4414e5de4..1d529de90 100644 --- a/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/EffectMetadata.cs @@ -3,46 +3,47 @@ using EndlessClient.Rendering.Effects; using Newtonsoft.Json; -namespace EndlessClient.Rendering.Metadata.Models; - -[Record] -public sealed partial class EffectMetadata : IGFXMetadata +namespace EndlessClient.Rendering.Metadata.Models { - public static EffectMetadata Default { get; } = new Builder { HasInFrontLayer = true, Loops = 2, Frames = 4, AnimationType = EffectAnimationType.Static }.ToImmutable(); + [Record] + public sealed partial class EffectMetadata : IGFXMetadata + { + public static EffectMetadata Default { get; } = new Builder { HasInFrontLayer = true, Loops = 2, Frames = 4, AnimationType = EffectAnimationType.Static }.ToImmutable(); - [JsonProperty("hasLayer0")] - public bool HasBehindLayer { get; } + [JsonProperty("hasLayer0")] + public bool HasBehindLayer { get; } - [JsonProperty("hasLayer1")] - public bool HasTransparentLayer { get; } + [JsonProperty("hasLayer1")] + public bool HasTransparentLayer { get; } - [JsonProperty("hasLayer2")] - public bool HasInFrontLayer { get; } + [JsonProperty("hasLayer2")] + public bool HasInFrontLayer { get; } - [JsonProperty("sfx")] - public SoundEffectID SoundEffect { get; } + [JsonProperty("sfx")] + public SoundEffectID SoundEffect { get; } - [JsonProperty("frames")] - public int Frames { get; } + [JsonProperty("frames")] + public int Frames { get; } - [JsonProperty("loops")] - public int Loops { get; } + [JsonProperty("loops")] + public int Loops { get; } - [JsonProperty("xOffset")] - public int OffsetX { get; } + [JsonProperty("xOffset")] + public int OffsetX { get; } - [JsonProperty("yOffset")] - public int OffsetY { get; } + [JsonProperty("yOffset")] + public int OffsetY { get; } - [JsonProperty("type")] - public EffectAnimationType AnimationType { get; } + [JsonProperty("type")] + public EffectAnimationType AnimationType { get; } - [JsonProperty("verticalSlidingData")] - public VerticalSlidingEffectMetadata VerticalSlidingMetadata { get; } + [JsonProperty("verticalSlidingData")] + public VerticalSlidingEffectMetadata VerticalSlidingMetadata { get; } - [JsonProperty("positionData")] - public PositionOffsetEffectMetadata PositionOffsetMetadata { get; } + [JsonProperty("positionData")] + public PositionOffsetEffectMetadata PositionOffsetMetadata { get; } - [JsonProperty("flickeringData")] - public RandomFlickeringEffectMetadata RandomFlickeringMetadata { get; } + [JsonProperty("flickeringData")] + public RandomFlickeringEffectMetadata RandomFlickeringMetadata { get; } + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/HatMetadata.cs b/EndlessClient/Rendering/Metadata/Models/HatMetadata.cs index 7290a5325..f2413e944 100644 --- a/EndlessClient/Rendering/Metadata/Models/HatMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/HatMetadata.cs @@ -1,13 +1,14 @@ -namespace EndlessClient.Rendering.Metadata.Models; - -public enum HatMaskType +namespace EndlessClient.Rendering.Metadata.Models { - Standard, - FaceMask, - HideHair -} + public enum HatMaskType + { + Standard, + FaceMask, + HideHair + } -public record HatMetadata(HatMaskType ClipMode) : IGFXMetadata -{ - public static HatMetadata Default { get; } = new HatMetadata(HatMaskType.Standard); + public record HatMetadata(HatMaskType ClipMode) : IGFXMetadata + { + public static HatMetadata Default { get; } = new HatMetadata(HatMaskType.Standard); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs b/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs index ca4011e8d..afff2bc1d 100644 --- a/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/IGFXMetadata.cs @@ -1,5 +1,6 @@ -namespace EndlessClient.Rendering.Metadata.Models; - -public interface IGFXMetadata +namespace EndlessClient.Rendering.Metadata.Models { + public interface IGFXMetadata + { + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs b/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs index 33cbe1485..4cbe72b7d 100644 --- a/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/NPCMetadata.cs @@ -1,28 +1,29 @@ using Amadevus.RecordGenerator; using Newtonsoft.Json; -namespace EndlessClient.Rendering.Metadata.Models; - -[Record] -public sealed partial class NPCMetadata : IGFXMetadata +namespace EndlessClient.Rendering.Metadata.Models { - public static NPCMetadata Default { get; } = new Builder().ToImmutable(); + [Record] + public sealed partial class NPCMetadata : IGFXMetadata + { + public static NPCMetadata Default { get; } = new Builder().ToImmutable(); - [JsonProperty("xOffset")] - public int OffsetX { get; } + [JsonProperty("xOffset")] + public int OffsetX { get; } - [JsonProperty("yOffset")] - public int OffsetY { get; } + [JsonProperty("yOffset")] + public int OffsetY { get; } - [JsonProperty("xAttackOffset")] - public int AttackOffsetX { get; } + [JsonProperty("xAttackOffset")] + public int AttackOffsetX { get; } - [JsonProperty("yAttackOffset")] - public int AttackOffsetY { get; } + [JsonProperty("yAttackOffset")] + public int AttackOffsetY { get; } - [JsonProperty("hasAnimation")] - public bool HasStandingFrameAnimation { get; } + [JsonProperty("hasAnimation")] + public bool HasStandingFrameAnimation { get; } - [JsonProperty("nameHeight")] - public int NameLabelOffset { get; } + [JsonProperty("nameHeight")] + public int NameLabelOffset { get; } + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/ShieldMetadata.cs b/EndlessClient/Rendering/Metadata/Models/ShieldMetadata.cs index 399e6818c..27ff1776f 100644 --- a/EndlessClient/Rendering/Metadata/Models/ShieldMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/ShieldMetadata.cs @@ -1,6 +1,7 @@ -namespace EndlessClient.Rendering.Metadata.Models; - -public sealed record ShieldMetadata(bool IsShieldOnBack) : IGFXMetadata +namespace EndlessClient.Rendering.Metadata.Models { - public static ShieldMetadata Default { get; } = new ShieldMetadata(false); + public sealed record ShieldMetadata(bool IsShieldOnBack) : IGFXMetadata + { + public static ShieldMetadata Default { get; } = new ShieldMetadata(false); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/Models/WeaponMetadata.cs b/EndlessClient/Rendering/Metadata/Models/WeaponMetadata.cs index b11153cad..03392aec6 100644 --- a/EndlessClient/Rendering/Metadata/Models/WeaponMetadata.cs +++ b/EndlessClient/Rendering/Metadata/Models/WeaponMetadata.cs @@ -1,8 +1,9 @@ using EndlessClient.Audio; -namespace EndlessClient.Rendering.Metadata.Models; - -public record WeaponMetadata(int? Slash, SoundEffectID[] SFX, bool Ranged) : IGFXMetadata +namespace EndlessClient.Rendering.Metadata.Models { - public static WeaponMetadata Default { get; } = new WeaponMetadata(Slash: null, SFX: new[] { SoundEffectID.PunchAttack }, Ranged: false); + public record WeaponMetadata(int? Slash, SoundEffectID[] SFX, bool Ranged) : IGFXMetadata + { + public static WeaponMetadata Default { get; } = new WeaponMetadata(Slash: null, SFX: new[] { SoundEffectID.PunchAttack }, Ranged: false); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs b/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs index 0eca0a32e..b6009357f 100644 --- a/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs @@ -2,199 +2,200 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata; - -[AutoMappedType(IsSingleton = true)] -public class NPCMetadataProvider : IMetadataProvider +namespace EndlessClient.Rendering.Metadata { - public IReadOnlyDictionary DefaultMetadata => _metadata; + [AutoMappedType(IsSingleton = true)] + public class NPCMetadataProvider : IMetadataProvider + { + public IReadOnlyDictionary DefaultMetadata => _metadata; - private readonly Dictionary _metadata; - private readonly IGFXMetadataLoader _metadataLoader; + private readonly Dictionary _metadata; + private readonly IGFXMetadataLoader _metadataLoader; - public NPCMetadataProvider(IGFXMetadataLoader metadataLoader) - { - // source: https://docs.google.com/spreadsheets/d/1GMo3c2xcPW5Uv3pOsaIS2EwtVA_N0Qfwo9TCTDibUoI/edit#gid=0 - _metadata = new Dictionary + public NPCMetadataProvider(IGFXMetadataLoader metadataLoader) { - { 1, new NPCMetadata(0, 16, 0, 0, false, 4) }, // crow - { 2, new NPCMetadata(0, 18, -6, -3, false, 0) }, // rat - { 3, new NPCMetadata(0, 16, -8, -4, false, 0) }, // slime - { 4, new NPCMetadata(0, 18, -8, -4, false, 50) }, // mummy - { 5, new NPCMetadata(-2, 7, -8, -4, false, 20) }, // fox - { 6, new NPCMetadata(0, 8, -6, -3, false, 10) }, // snake - { 7, new NPCMetadata(-2, 6, -4, -2, false, 12) }, // goat - { 8, new NPCMetadata(0, 0, -2, -1, false, 75) }, // centaur - { 9, new NPCMetadata(-4, 6, -4, -2, false, 30) }, // undeath - { 10, new NPCMetadata(1, -1, -6, -3, false, 8) }, // spider - { 11, new NPCMetadata(0, 5, -4, -2, false, 40) }, // barbarian - { 12, new NPCMetadata(0, 15, -6, -3, false, 33) }, // cactus - { 13, new NPCMetadata(0, 13, 2, -2, false, 10) }, // penguin - { 14, new NPCMetadata(-4, 10, -2, -4, false, 53) }, // cyclops - { 15, new NPCMetadata(-1, 17, 0, 0, false, 40) }, // shop bob - { 16, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton - { 17, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton captain - { 18, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton sword - { 19, new NPCMetadata(0, 11, -6, -3, false, 49) }, // wingo - { 20, new NPCMetadata(0, 7, 0, 0, false, 40) }, // juweller - { 21, new NPCMetadata(-2, 17, -10, -5, false, 40) }, // pirate npc 1 - { 22, new NPCMetadata(0, 11, 0, 0, true, 45) }, // witch - { 23, new NPCMetadata(0, 17, 0, 0, false, 40) }, // babs - { 24, new NPCMetadata(0, 17, 0, 0, false, 40) }, // pirate npc 2 - { 25, new NPCMetadata(0, 6, 0, 0, true, 50) }, // blacksmith - { 26, new NPCMetadata(-2, 11, -6, -3, false, 0) }, // crab🦀 - { 27, new NPCMetadata(0, 9, 0, 0, true, 12) }, // remi - { 28, new NPCMetadata(-4, 16, 0, 0, true, 42) }, // guild bob - { 29, new NPCMetadata(0, 7, -6, -3, false, 0) }, // vyercil - { 30, new NPCMetadata(-10, 13, -8, -4, false, 42) }, // reaper - { 31, new NPCMetadata(0, 13, -8, -4, false, 42) }, // chaos spawn - { 32, new NPCMetadata(0, 17, 0, 0, false, 40) }, // blue hair npc - { 33, new NPCMetadata(0, 17, 0, 0, false, 40) }, // beard npc - { 34, new NPCMetadata(0, 17, 0, 0, false, 40) }, // long hair npc - { 35, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard red - { 36, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard purple - { 37, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard green - { 38, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // green blob - { 39, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // pink blob - { 40, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // red blob - { 41, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // cyan blob - { 42, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // orange blob - { 43, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // yellow blob - { 44, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // blue blob - { 45, new NPCMetadata(-1, 12, -6, -3, false, 40) }, // horse - { 46, new NPCMetadata(-3, 10, -6, -3, false, 42) }, // unicorn - { 47, new NPCMetadata(0, 10, -6, -3, false, 66) }, // birdman - { 48, new NPCMetadata(6, 10, -6, -3, false, 66) }, // birdman winged - { 49, new NPCMetadata(-9, 13, -6, -3, false, 68) }, // birdman captain - { 50, new NPCMetadata(4, 10, -6, -3, true, 82) }, // flying birdman - { 51, new NPCMetadata(0, 13, -10, -5, true, 59) }, // hell guardian - { 52, new NPCMetadata(0, 1, -4, -2, true, 48) }, // wolfman - { 53, new NPCMetadata(-2, 17, 0, 0, false, 40) }, // mommy npc - { 54, new NPCMetadata(0, 14, 0, 0, false, 28) }, // kid npc - { 55, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog green - { 56, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog turqoise - { 57, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog red - { 58, new NPCMetadata(0, 18, -8, -4, true, 42) }, // hornet - { 59, new NPCMetadata(0, 16, -8, -4, true, 44) }, // bat - { 60, new NPCMetadata(-3, 6, -6, -3, false, 10) }, // wurm - { 61, new NPCMetadata(0, 0, -12, -6, false, 10) }, // worm - { 62, new NPCMetadata(-3, 11, -8, -4, false, 10) }, // ant - { 63, new NPCMetadata(-3, 11, -8, -4, false, 10) }, // ant soldier - { 64, new NPCMetadata(0, 15, -12, -6, true, 41) }, // teawk - { 65, new NPCMetadata(3, 12, -8, -4, false, 23) }, // batmaso - { 66, new NPCMetadata(-1, 8, -10, -5, false, 53) }, // jesaur - { 67, new NPCMetadata(0, 12, -4, -2, false, 28) }, // hedgehog - { 68, new NPCMetadata(0, 6, -4, -2, false, 93) }, // ice golem - { 69, new NPCMetadata(0, 20, 0, 0, true, 48) }, // ice gem - { 70, new NPCMetadata(-1, 17, -8, -4, false, 18) }, // gnome - { 71, new NPCMetadata(-2, 10, -6, -3, false, 24) }, // gnome rider - { 72, new NPCMetadata(1, 14, 0, 0, false, 20) }, // rock - { 73, new NPCMetadata(-3, 13, -8, -4, false, 55) }, // golem - { 74, new NPCMetadata(0, 16, -4, -2, false, 22) }, // mushroom - { 75, new NPCMetadata(-1, 17, -6, -3, true, 37) }, // teawcus - { 76, new NPCMetadata(-1, 16, -4, -2, false, 41) }, // hula man - { 77, new NPCMetadata(-2, 10, 0, 0, false, 14) }, // snail - { 78, new NPCMetadata(-2, 10, 0, 0, false, 14) }, // bowtie snail - { 79, new NPCMetadata(0, 15, 0, 0, true, 41) }, // geggime - { 80, new NPCMetadata(0, 5, -8, -4, false, 31) }, // ewak - { 81, new NPCMetadata(-3, 15, -6, -3, true, 44) }, // azuorph - { 82, new NPCMetadata(-2, 18, 0, 0, false, 40) }, // sword guy npc - { 83, new NPCMetadata(-2, 17, 0, 0, false, 40) }, // purple hair npc - { 84, new NPCMetadata(-2, 18, 0, 0, false, 40) }, // green hair girl npc - { 85, new NPCMetadata(0, 18, -10, -5, true, 50) }, // wraith - { 86, new NPCMetadata(-2, 14, 0, 0, true, 43) }, // priest - { 87, new NPCMetadata(-4, 11, -8, -4, false, 40) }, // ninja - { 88, new NPCMetadata(1, 12, -10, -5, false, 54) }, // orc - { 89, new NPCMetadata(0, -4, 0, 0, true, 43) }, // octo - { 90, new NPCMetadata(1, 6, -8, -4, true, 54) }, // octo tentacle - { 91, new NPCMetadata(-14, 14, -3, -2, false, 64) }, // anundo leader - { 92, new NPCMetadata(0, 13, -6, -4, false, 21) }, // carnivo - { 93, new NPCMetadata(-9, 14, 0, 0, true, 55) }, // old king - { 94, new NPCMetadata(-9, 14, 0, 0, true, 50) }, // green hair king - { 95, new NPCMetadata(-7, 9, 0, 0, false, 32) }, // goblin - { 96, new NPCMetadata(-1, 18, -6, -3, true, 46) }, // optica - { 97, new NPCMetadata(-2, 14, -4, -2, false, 46) }, // bogo man - { 98, new NPCMetadata(-1, 20, -8, -4, true, 50) }, // butterfly - { 99, new NPCMetadata(0, 17, -6, -3, true, 68) }, // cursed mask - { 100, new NPCMetadata(0, 17, -6, -3, false, 30) }, // red imp - { 101, new NPCMetadata(0, 17, -6, -3, false, 30) }, // grey imp - { 102, new NPCMetadata(0, 15, 0, 0, true, 84) }, // vine tentacle - { 103, new NPCMetadata(0, 16, -10, -5, false, 48) }, // headless hunter - { 104, new NPCMetadata(0, 15, -8, -4, false, 60) }, // swamp monster - { 105, new NPCMetadata(0, 15, -8, -4, true, 70) }, // twin demons - { 106, new NPCMetadata(0, 13, -6, -3, false, 30) }, // dwarf - { 107, new NPCMetadata(-31, 4, -4, -2, false, 138) }, // apozen - { 108, new NPCMetadata(0, 6, -10, -5, false, 12) }, // mimic - { 109, new NPCMetadata(-2, 16, 0, 0, false, 43) }, // panda master npc - { 110, new NPCMetadata(-2, 17, -6, -3, true, 59) }, // crane - { 111, new NPCMetadata(0, 17, -6, -3, true, 17) }, // cyto 053 - { 112, new NPCMetadata(4, 6, -6, -3, true, 30) }, // sav 109 - { 113, new NPCMetadata(1, 7, 0, 0, false, 6) }, // robo tile - { 114, new NPCMetadata(0, 17, -4, -2, true, 44) }, // proto - { 115, new NPCMetadata(-6, 16, -6, -3, true, 42) }, // princess - { 116, new NPCMetadata(0, 18, 0, 0, true, 40) }, // scientist npc - { 117, new NPCMetadata(-2, 15, 0, 0, true, 32) }, // mechanic npc - { 118, new NPCMetadata(-6, 15, -4, -2, true, 47) }, // wise man - { 119, new NPCMetadata(-1, 13, -6, -3, false, 15) }, // sheep - { 120, new NPCMetadata(-3, 19, -8, -4, false, 19) }, // biter - { 121, new NPCMetadata(-1, 16, -2, -1, true, 10) }, // blocto - { 122, new NPCMetadata(0, 18, -8, -4, true, 58) }, // puppet - { 123, new NPCMetadata(0, 4, 0, 0, false, 65) }, // king wurm - { 124, new NPCMetadata(-4, 9, -10, -5, false, 71) }, // gnoll - { 125, new NPCMetadata(0, 0, 0, 0, false, 88) }, // bone spider - { 126, new NPCMetadata(0, 20, -10, -5, true, 58) }, // hell flyer - { 127, new NPCMetadata(-4, 12, -14, -5, true, 36) }, // shaman - { 128, new NPCMetadata(-5, 17, -4, -2, false, 36) }, // war bear - { 129, new NPCMetadata(0, 7, 0, 0, true, 32) }, // shark - { 130, new NPCMetadata(0, 15, -10, -5, false, 5) }, // turtle - { 131, new NPCMetadata(-1, 16, -8, -4, false, 16) }, // doll - { 132, new NPCMetadata(-2, 5, -8, -4, false, 40) }, // dark magician - { 133, new NPCMetadata(-2, 5, -6, -3, false, 47) }, // yeti - { 134, new NPCMetadata(0, 18, -10, -5, true, 80) }, // banshee - { 135, new NPCMetadata(0, 18, 0, 5, false, 41) }, // drone flyer - { 136, new NPCMetadata(-2, 19, -4, -2, false, 22) }, // butter - { 137, new NPCMetadata(0, 18, -8, -4, false, 45) }, // funky hair npc - { 138, new NPCMetadata(0, 18, -6, -3, false, 26) }, // flombie - { 139, new NPCMetadata(0, 17, -6, -3, false, 32) }, // gator - { 140, new NPCMetadata(0, 18, -2, -1, true, 65) }, // phoenix - { 141, new NPCMetadata(0, 16, -6, -3, false, 25) }, // bale - { 142, new NPCMetadata(0, 18, -2, -1, true, 20) }, // espring - { 143, new NPCMetadata(0, 16, -6, -3, false, 40) }, // old italian man npc - { 144, new NPCMetadata(-3, 8, 0, 0, false, 52) }, // rotveig - { 145, new NPCMetadata(0, 19, -6, -3, false, 48) }, // booba amazon npc - { 146, new NPCMetadata(0, 19, -6, -3, false, 69) }, // cacadem - { 147, new NPCMetadata(0, 10, 0, 0, false, 32) }, // flowie - { 148, new NPCMetadata(-4, 16, -6, -3, true, 37) }, // nutviper - { 149, new NPCMetadata(2, 6, 0, 0, false, 98) }, // dragon - { 150, new NPCMetadata(-1, 18, -6, -3, false, 48) }, // flyman - { 151, new NPCMetadata(-2, 1, -2, 1, false, 18) }, // vitamin - { 152, new NPCMetadata(0, 10, -8, -2, false, 27) }, // onigiri - { 153, new NPCMetadata(-2, 13, -6, -9, false, 39) }, // rabther - { 154, new NPCMetadata(0, 15, -6, -3, false, 13) }, // piglet - { 155, new NPCMetadata(0, 16, -6, -3, false, 18) }, // piglet with baby - { 156, new NPCMetadata(0, 15, -6, -3, false, 32) }, // tenba - { 157, new NPCMetadata(0, 6, -8, -4, true, 58) }, // funky hair cyborg - { 158, new NPCMetadata(0, 15, 0, 0, true, 74) }, // drummer - { 159, new NPCMetadata(-11, 18, 0, 0, true, 57) }, // guitarist - { 160, new NPCMetadata(-4, 18, 0, 0, true, 45) }, // wise man guitar - { 161, new NPCMetadata(0, 0, 0, 0, true, 65) }, // piano panda - { 162, new NPCMetadata(-1, 10, -8, -4, false, 15) }, // mini army - { 163, new NPCMetadata(0, 8, -6, -3, false, 12) }, // artist - { 164, new NPCMetadata(0, 15, -8, -4, false, 10) }, // hamster - { 165, new NPCMetadata(0, 13, 0, 0, false, 10) }, // mole - { 166, new NPCMetadata(0, 18, 0, 0, true, 32) }, // fish - { 167, new NPCMetadata(0, 14, -6, -3, false, 22) }, // lizzy - { 168, new NPCMetadata(0, 15, -8, -4, false, 15) }, // ape - { 169, new NPCMetadata(0, 4, -8, -4, false, 19) }, // taraduda - { 170, new NPCMetadata(0, 19, -8, -4, false, 17) }, // monkey - { 171, new NPCMetadata(0, 0, 0, 0, false, 0) }, // ancient wraith - }; - _metadataLoader = metadataLoader; - } + // source: https://docs.google.com/spreadsheets/d/1GMo3c2xcPW5Uv3pOsaIS2EwtVA_N0Qfwo9TCTDibUoI/edit#gid=0 + _metadata = new Dictionary + { + { 1, new NPCMetadata(0, 16, 0, 0, false, 4) }, // crow + { 2, new NPCMetadata(0, 18, -6, -3, false, 0) }, // rat + { 3, new NPCMetadata(0, 16, -8, -4, false, 0) }, // slime + { 4, new NPCMetadata(0, 18, -8, -4, false, 50) }, // mummy + { 5, new NPCMetadata(-2, 7, -8, -4, false, 20) }, // fox + { 6, new NPCMetadata(0, 8, -6, -3, false, 10) }, // snake + { 7, new NPCMetadata(-2, 6, -4, -2, false, 12) }, // goat + { 8, new NPCMetadata(0, 0, -2, -1, false, 75) }, // centaur + { 9, new NPCMetadata(-4, 6, -4, -2, false, 30) }, // undeath + { 10, new NPCMetadata(1, -1, -6, -3, false, 8) }, // spider + { 11, new NPCMetadata(0, 5, -4, -2, false, 40) }, // barbarian + { 12, new NPCMetadata(0, 15, -6, -3, false, 33) }, // cactus + { 13, new NPCMetadata(0, 13, 2, -2, false, 10) }, // penguin + { 14, new NPCMetadata(-4, 10, -2, -4, false, 53) }, // cyclops + { 15, new NPCMetadata(-1, 17, 0, 0, false, 40) }, // shop bob + { 16, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton + { 17, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton captain + { 18, new NPCMetadata(0, 14, -6, -3, false, 45) }, // skeleton sword + { 19, new NPCMetadata(0, 11, -6, -3, false, 49) }, // wingo + { 20, new NPCMetadata(0, 7, 0, 0, false, 40) }, // juweller + { 21, new NPCMetadata(-2, 17, -10, -5, false, 40) }, // pirate npc 1 + { 22, new NPCMetadata(0, 11, 0, 0, true, 45) }, // witch + { 23, new NPCMetadata(0, 17, 0, 0, false, 40) }, // babs + { 24, new NPCMetadata(0, 17, 0, 0, false, 40) }, // pirate npc 2 + { 25, new NPCMetadata(0, 6, 0, 0, true, 50) }, // blacksmith + { 26, new NPCMetadata(-2, 11, -6, -3, false, 0) }, // crab🦀 + { 27, new NPCMetadata(0, 9, 0, 0, true, 12) }, // remi + { 28, new NPCMetadata(-4, 16, 0, 0, true, 42) }, // guild bob + { 29, new NPCMetadata(0, 7, -6, -3, false, 0) }, // vyercil + { 30, new NPCMetadata(-10, 13, -8, -4, false, 42) }, // reaper + { 31, new NPCMetadata(0, 13, -8, -4, false, 42) }, // chaos spawn + { 32, new NPCMetadata(0, 17, 0, 0, false, 40) }, // blue hair npc + { 33, new NPCMetadata(0, 17, 0, 0, false, 40) }, // beard npc + { 34, new NPCMetadata(0, 17, 0, 0, false, 40) }, // long hair npc + { 35, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard red + { 36, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard purple + { 37, new NPCMetadata(-5, 17, -6, -3, false, 40) }, // aeven guard green + { 38, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // green blob + { 39, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // pink blob + { 40, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // red blob + { 41, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // cyan blob + { 42, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // orange blob + { 43, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // yellow blob + { 44, new NPCMetadata(-1, 12, -6, -3, false, 0) }, // blue blob + { 45, new NPCMetadata(-1, 12, -6, -3, false, 40) }, // horse + { 46, new NPCMetadata(-3, 10, -6, -3, false, 42) }, // unicorn + { 47, new NPCMetadata(0, 10, -6, -3, false, 66) }, // birdman + { 48, new NPCMetadata(6, 10, -6, -3, false, 66) }, // birdman winged + { 49, new NPCMetadata(-9, 13, -6, -3, false, 68) }, // birdman captain + { 50, new NPCMetadata(4, 10, -6, -3, true, 82) }, // flying birdman + { 51, new NPCMetadata(0, 13, -10, -5, true, 59) }, // hell guardian + { 52, new NPCMetadata(0, 1, -4, -2, true, 48) }, // wolfman + { 53, new NPCMetadata(-2, 17, 0, 0, false, 40) }, // mommy npc + { 54, new NPCMetadata(0, 14, 0, 0, false, 28) }, // kid npc + { 55, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog green + { 56, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog turqoise + { 57, new NPCMetadata(-3, 4, -3, -2, true, 13) }, // bullfrog red + { 58, new NPCMetadata(0, 18, -8, -4, true, 42) }, // hornet + { 59, new NPCMetadata(0, 16, -8, -4, true, 44) }, // bat + { 60, new NPCMetadata(-3, 6, -6, -3, false, 10) }, // wurm + { 61, new NPCMetadata(0, 0, -12, -6, false, 10) }, // worm + { 62, new NPCMetadata(-3, 11, -8, -4, false, 10) }, // ant + { 63, new NPCMetadata(-3, 11, -8, -4, false, 10) }, // ant soldier + { 64, new NPCMetadata(0, 15, -12, -6, true, 41) }, // teawk + { 65, new NPCMetadata(3, 12, -8, -4, false, 23) }, // batmaso + { 66, new NPCMetadata(-1, 8, -10, -5, false, 53) }, // jesaur + { 67, new NPCMetadata(0, 12, -4, -2, false, 28) }, // hedgehog + { 68, new NPCMetadata(0, 6, -4, -2, false, 93) }, // ice golem + { 69, new NPCMetadata(0, 20, 0, 0, true, 48) }, // ice gem + { 70, new NPCMetadata(-1, 17, -8, -4, false, 18) }, // gnome + { 71, new NPCMetadata(-2, 10, -6, -3, false, 24) }, // gnome rider + { 72, new NPCMetadata(1, 14, 0, 0, false, 20) }, // rock + { 73, new NPCMetadata(-3, 13, -8, -4, false, 55) }, // golem + { 74, new NPCMetadata(0, 16, -4, -2, false, 22) }, // mushroom + { 75, new NPCMetadata(-1, 17, -6, -3, true, 37) }, // teawcus + { 76, new NPCMetadata(-1, 16, -4, -2, false, 41) }, // hula man + { 77, new NPCMetadata(-2, 10, 0, 0, false, 14) }, // snail + { 78, new NPCMetadata(-2, 10, 0, 0, false, 14) }, // bowtie snail + { 79, new NPCMetadata(0, 15, 0, 0, true, 41) }, // geggime + { 80, new NPCMetadata(0, 5, -8, -4, false, 31) }, // ewak + { 81, new NPCMetadata(-3, 15, -6, -3, true, 44) }, // azuorph + { 82, new NPCMetadata(-2, 18, 0, 0, false, 40) }, // sword guy npc + { 83, new NPCMetadata(-2, 17, 0, 0, false, 40) }, // purple hair npc + { 84, new NPCMetadata(-2, 18, 0, 0, false, 40) }, // green hair girl npc + { 85, new NPCMetadata(0, 18, -10, -5, true, 50) }, // wraith + { 86, new NPCMetadata(-2, 14, 0, 0, true, 43) }, // priest + { 87, new NPCMetadata(-4, 11, -8, -4, false, 40) }, // ninja + { 88, new NPCMetadata(1, 12, -10, -5, false, 54) }, // orc + { 89, new NPCMetadata(0, -4, 0, 0, true, 43) }, // octo + { 90, new NPCMetadata(1, 6, -8, -4, true, 54) }, // octo tentacle + { 91, new NPCMetadata(-14, 14, -3, -2, false, 64) }, // anundo leader + { 92, new NPCMetadata(0, 13, -6, -4, false, 21) }, // carnivo + { 93, new NPCMetadata(-9, 14, 0, 0, true, 55) }, // old king + { 94, new NPCMetadata(-9, 14, 0, 0, true, 50) }, // green hair king + { 95, new NPCMetadata(-7, 9, 0, 0, false, 32) }, // goblin + { 96, new NPCMetadata(-1, 18, -6, -3, true, 46) }, // optica + { 97, new NPCMetadata(-2, 14, -4, -2, false, 46) }, // bogo man + { 98, new NPCMetadata(-1, 20, -8, -4, true, 50) }, // butterfly + { 99, new NPCMetadata(0, 17, -6, -3, true, 68) }, // cursed mask + { 100, new NPCMetadata(0, 17, -6, -3, false, 30) }, // red imp + { 101, new NPCMetadata(0, 17, -6, -3, false, 30) }, // grey imp + { 102, new NPCMetadata(0, 15, 0, 0, true, 84) }, // vine tentacle + { 103, new NPCMetadata(0, 16, -10, -5, false, 48) }, // headless hunter + { 104, new NPCMetadata(0, 15, -8, -4, false, 60) }, // swamp monster + { 105, new NPCMetadata(0, 15, -8, -4, true, 70) }, // twin demons + { 106, new NPCMetadata(0, 13, -6, -3, false, 30) }, // dwarf + { 107, new NPCMetadata(-31, 4, -4, -2, false, 138) }, // apozen + { 108, new NPCMetadata(0, 6, -10, -5, false, 12) }, // mimic + { 109, new NPCMetadata(-2, 16, 0, 0, false, 43) }, // panda master npc + { 110, new NPCMetadata(-2, 17, -6, -3, true, 59) }, // crane + { 111, new NPCMetadata(0, 17, -6, -3, true, 17) }, // cyto 053 + { 112, new NPCMetadata(4, 6, -6, -3, true, 30) }, // sav 109 + { 113, new NPCMetadata(1, 7, 0, 0, false, 6) }, // robo tile + { 114, new NPCMetadata(0, 17, -4, -2, true, 44) }, // proto + { 115, new NPCMetadata(-6, 16, -6, -3, true, 42) }, // princess + { 116, new NPCMetadata(0, 18, 0, 0, true, 40) }, // scientist npc + { 117, new NPCMetadata(-2, 15, 0, 0, true, 32) }, // mechanic npc + { 118, new NPCMetadata(-6, 15, -4, -2, true, 47) }, // wise man + { 119, new NPCMetadata(-1, 13, -6, -3, false, 15) }, // sheep + { 120, new NPCMetadata(-3, 19, -8, -4, false, 19) }, // biter + { 121, new NPCMetadata(-1, 16, -2, -1, true, 10) }, // blocto + { 122, new NPCMetadata(0, 18, -8, -4, true, 58) }, // puppet + { 123, new NPCMetadata(0, 4, 0, 0, false, 65) }, // king wurm + { 124, new NPCMetadata(-4, 9, -10, -5, false, 71) }, // gnoll + { 125, new NPCMetadata(0, 0, 0, 0, false, 88) }, // bone spider + { 126, new NPCMetadata(0, 20, -10, -5, true, 58) }, // hell flyer + { 127, new NPCMetadata(-4, 12, -14, -5, true, 36) }, // shaman + { 128, new NPCMetadata(-5, 17, -4, -2, false, 36) }, // war bear + { 129, new NPCMetadata(0, 7, 0, 0, true, 32) }, // shark + { 130, new NPCMetadata(0, 15, -10, -5, false, 5) }, // turtle + { 131, new NPCMetadata(-1, 16, -8, -4, false, 16) }, // doll + { 132, new NPCMetadata(-2, 5, -8, -4, false, 40) }, // dark magician + { 133, new NPCMetadata(-2, 5, -6, -3, false, 47) }, // yeti + { 134, new NPCMetadata(0, 18, -10, -5, true, 80) }, // banshee + { 135, new NPCMetadata(0, 18, 0, 5, false, 41) }, // drone flyer + { 136, new NPCMetadata(-2, 19, -4, -2, false, 22) }, // butter + { 137, new NPCMetadata(0, 18, -8, -4, false, 45) }, // funky hair npc + { 138, new NPCMetadata(0, 18, -6, -3, false, 26) }, // flombie + { 139, new NPCMetadata(0, 17, -6, -3, false, 32) }, // gator + { 140, new NPCMetadata(0, 18, -2, -1, true, 65) }, // phoenix + { 141, new NPCMetadata(0, 16, -6, -3, false, 25) }, // bale + { 142, new NPCMetadata(0, 18, -2, -1, true, 20) }, // espring + { 143, new NPCMetadata(0, 16, -6, -3, false, 40) }, // old italian man npc + { 144, new NPCMetadata(-3, 8, 0, 0, false, 52) }, // rotveig + { 145, new NPCMetadata(0, 19, -6, -3, false, 48) }, // booba amazon npc + { 146, new NPCMetadata(0, 19, -6, -3, false, 69) }, // cacadem + { 147, new NPCMetadata(0, 10, 0, 0, false, 32) }, // flowie + { 148, new NPCMetadata(-4, 16, -6, -3, true, 37) }, // nutviper + { 149, new NPCMetadata(2, 6, 0, 0, false, 98) }, // dragon + { 150, new NPCMetadata(-1, 18, -6, -3, false, 48) }, // flyman + { 151, new NPCMetadata(-2, 1, -2, 1, false, 18) }, // vitamin + { 152, new NPCMetadata(0, 10, -8, -2, false, 27) }, // onigiri + { 153, new NPCMetadata(-2, 13, -6, -9, false, 39) }, // rabther + { 154, new NPCMetadata(0, 15, -6, -3, false, 13) }, // piglet + { 155, new NPCMetadata(0, 16, -6, -3, false, 18) }, // piglet with baby + { 156, new NPCMetadata(0, 15, -6, -3, false, 32) }, // tenba + { 157, new NPCMetadata(0, 6, -8, -4, true, 58) }, // funky hair cyborg + { 158, new NPCMetadata(0, 15, 0, 0, true, 74) }, // drummer + { 159, new NPCMetadata(-11, 18, 0, 0, true, 57) }, // guitarist + { 160, new NPCMetadata(-4, 18, 0, 0, true, 45) }, // wise man guitar + { 161, new NPCMetadata(0, 0, 0, 0, true, 65) }, // piano panda + { 162, new NPCMetadata(-1, 10, -8, -4, false, 15) }, // mini army + { 163, new NPCMetadata(0, 8, -6, -3, false, 12) }, // artist + { 164, new NPCMetadata(0, 15, -8, -4, false, 10) }, // hamster + { 165, new NPCMetadata(0, 13, 0, 0, false, 10) }, // mole + { 166, new NPCMetadata(0, 18, 0, 0, true, 32) }, // fish + { 167, new NPCMetadata(0, 14, -6, -3, false, 22) }, // lizzy + { 168, new NPCMetadata(0, 15, -8, -4, false, 15) }, // ape + { 169, new NPCMetadata(0, 4, -8, -4, false, 19) }, // taraduda + { 170, new NPCMetadata(0, 19, -8, -4, false, 17) }, // monkey + { 171, new NPCMetadata(0, 0, 0, 0, false, 0) }, // ancient wraith + }; + _metadataLoader = metadataLoader; + } - public NPCMetadata GetValueOrDefault(int graphic) - { - return _metadataLoader.GetMetadata(graphic) - .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : NPCMetadata.Default); + public NPCMetadata GetValueOrDefault(int graphic) + { + return _metadataLoader.GetMetadata(graphic) + .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : NPCMetadata.Default); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs b/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs index 6199e292f..b5fbab4ac 100644 --- a/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs @@ -2,34 +2,35 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata; - -[AutoMappedType(IsSingleton = true)] -public class ShieldMetadataProvider : IMetadataProvider +namespace EndlessClient.Rendering.Metadata { - public IReadOnlyDictionary DefaultMetadata => _metadata; + [AutoMappedType(IsSingleton = true)] + public class ShieldMetadataProvider : IMetadataProvider + { + public IReadOnlyDictionary DefaultMetadata => _metadata; - private readonly Dictionary _metadata; - private readonly IGFXMetadataLoader _metadataLoader; + private readonly Dictionary _metadata; + private readonly IGFXMetadataLoader _metadataLoader; - public ShieldMetadataProvider(IGFXMetadataLoader metadataLoader) - { - _metadata = new Dictionary + public ShieldMetadataProvider(IGFXMetadataLoader metadataLoader) { - { 10, new ShieldMetadata(true) }, // good wings - { 11, new ShieldMetadata(true) }, // bag - { 14, new ShieldMetadata(true) }, // normal arrows - { 15, new ShieldMetadata(true) }, // frost arrows - { 16, new ShieldMetadata(true) }, // fire arrows - { 18, new ShieldMetadata(true) }, // good force wings - { 19, new ShieldMetadata(true) }, // fire force wings - }; - _metadataLoader = metadataLoader; - } + _metadata = new Dictionary + { + { 10, new ShieldMetadata(true) }, // good wings + { 11, new ShieldMetadata(true) }, // bag + { 14, new ShieldMetadata(true) }, // normal arrows + { 15, new ShieldMetadata(true) }, // frost arrows + { 16, new ShieldMetadata(true) }, // fire arrows + { 18, new ShieldMetadata(true) }, // good force wings + { 19, new ShieldMetadata(true) }, // fire force wings + }; + _metadataLoader = metadataLoader; + } - public ShieldMetadata GetValueOrDefault(int graphic) - { - return _metadataLoader.GetMetadata(graphic) - .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : ShieldMetadata.Default); + public ShieldMetadata GetValueOrDefault(int graphic) + { + return _metadataLoader.GetMetadata(graphic) + .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : ShieldMetadata.Default); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs b/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs index 20a3264c1..5aa1bf734 100644 --- a/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs @@ -3,102 +3,103 @@ using EndlessClient.Rendering.Metadata.Models; using System.Collections.Generic; -namespace EndlessClient.Rendering.Metadata; - -[AutoMappedType(IsSingleton = true)] -public class WeaponMetadataProvider : IMetadataProvider +namespace EndlessClient.Rendering.Metadata { - public IReadOnlyDictionary DefaultMetadata => _metadata; + [AutoMappedType(IsSingleton = true)] + public class WeaponMetadataProvider : IMetadataProvider + { + public IReadOnlyDictionary DefaultMetadata => _metadata; - private readonly Dictionary _metadata; - private readonly IGFXMetadataLoader _metadataLoader; + private readonly Dictionary _metadata; + private readonly IGFXMetadataLoader _metadataLoader; - public WeaponMetadataProvider(IGFXMetadataLoader metadataLoader) - { - _metadata = new Dictionary + public WeaponMetadataProvider(IGFXMetadataLoader metadataLoader) { - { 0, new WeaponMetadata(null, new[] { SoundEffectID.PunchAttack }, false) }, // fist - { 1, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // wood axe - { 2, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // sai - { 3, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dragon blade - { 4, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dagger - { 5, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // spear - { 6, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // saber - { 7, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // staff - { 8, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // book - { 9, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // mace - { 10, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // spirit star - { 11, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // throw axe - { 12, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dark katana - { 13, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // short sword - { 14, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // broadsword - { 15, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // broom - { 16, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ninchackus - { 17, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ancient star - { 18, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle axe - { 19, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ancient sword - { 20, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // luna staff - { 21, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lance - { 22, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // aura staff - { 23, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // forest staff - { 24, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // normal sword - { 25, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // jewel staff - { 26, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // thor's hammer - { 27, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // light katana - { 28, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // polearm - { 29, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // sickle - { 30, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // trident - { 31, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // warlock sword - { 32, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // whip - { 33, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ultima - { 34, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ice blade - { 35, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gold defender - { 36, new WeaponMetadata(4, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lotus sword - { 37, new WeaponMetadata(4, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // cristal sword - { 38, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // killing edge - { 39, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // dark blade - { 40, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // reaper scyth - { 41, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // crescent staff - { 42, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // bow - { 43, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // xbow - { 44, new WeaponMetadata(8, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // reaper - { 45, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // hockey stick - { 46, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // twin blades - { 47, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lefor mace - { 48, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // cava staff - { 49, new WeaponMetadata(0, new[] { SoundEffectID.Harp1,SoundEffectID.Harp2,SoundEffectID.Harp3}, true) }, // harp - { 50, new WeaponMetadata(0, new[] { SoundEffectID.Guitar1,SoundEffectID.Guitar2, SoundEffectID.Guitar3 }, true) }, // guitar - { 51, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle spear - { 52, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // flail - { 53, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // war axe - { 54, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gastro - { 55, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // ablo staff - { 56, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fluon sword - { 57, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // rapier - { 58, new WeaponMetadata(0, new[] { SoundEffectID.Gun }, true) }, // gun - { 59, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // knob staff - { 60, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fladdat staff - { 61, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gabrasto - { 62, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle spear 2 - { 63, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lens of truth - { 64, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // chopper - { 65, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // adger - { 66, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // chains - { 67, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // mitova - { 68, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // merhawk - { 69, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // kontra - { 70, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // jack spear - { 71, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // bazar staff - { 72, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // saw blade - { 73, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // scav bow - { 74, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fan - }; - _metadataLoader = metadataLoader; - } + _metadata = new Dictionary + { + { 0, new WeaponMetadata(null, new[] { SoundEffectID.PunchAttack }, false) }, // fist + { 1, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // wood axe + { 2, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // sai + { 3, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dragon blade + { 4, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dagger + { 5, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // spear + { 6, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // saber + { 7, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // staff + { 8, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // book + { 9, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // mace + { 10, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // spirit star + { 11, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // throw axe + { 12, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // dark katana + { 13, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // short sword + { 14, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // broadsword + { 15, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // broom + { 16, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ninchackus + { 17, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ancient star + { 18, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle axe + { 19, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ancient sword + { 20, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // luna staff + { 21, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lance + { 22, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // aura staff + { 23, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // forest staff + { 24, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // normal sword + { 25, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // jewel staff + { 26, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // thor's hammer + { 27, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // light katana + { 28, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // polearm + { 29, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // sickle + { 30, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // trident + { 31, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // warlock sword + { 32, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // whip + { 33, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ultima + { 34, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // ice blade + { 35, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gold defender + { 36, new WeaponMetadata(4, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lotus sword + { 37, new WeaponMetadata(4, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // cristal sword + { 38, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // killing edge + { 39, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // dark blade + { 40, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // reaper scyth + { 41, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // crescent staff + { 42, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // bow + { 43, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // xbow + { 44, new WeaponMetadata(8, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // reaper + { 45, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // hockey stick + { 46, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // twin blades + { 47, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lefor mace + { 48, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // cava staff + { 49, new WeaponMetadata(0, new[] { SoundEffectID.Harp1,SoundEffectID.Harp2,SoundEffectID.Harp3}, true) }, // harp + { 50, new WeaponMetadata(0, new[] { SoundEffectID.Guitar1,SoundEffectID.Guitar2, SoundEffectID.Guitar3 }, true) }, // guitar + { 51, new WeaponMetadata(5, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle spear + { 52, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // flail + { 53, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // war axe + { 54, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gastro + { 55, new WeaponMetadata(7, new[] { SoundEffectID.AlternateMeleeAttack }, false) }, // ablo staff + { 56, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fluon sword + { 57, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // rapier + { 58, new WeaponMetadata(0, new[] { SoundEffectID.Gun }, true) }, // gun + { 59, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // knob staff + { 60, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fladdat staff + { 61, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // gabrasto + { 62, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // battle spear 2 + { 63, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // lens of truth + { 64, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // chopper + { 65, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // adger + { 66, new WeaponMetadata(1, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // chains + { 67, new WeaponMetadata(2, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // mitova + { 68, new WeaponMetadata(3, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // merhawk + { 69, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // kontra + { 70, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // jack spear + { 71, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // bazar staff + { 72, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // saw blade + { 73, new WeaponMetadata(0, new[] { SoundEffectID.AttackBow }, true) }, // scav bow + { 74, new WeaponMetadata(0, new[] { SoundEffectID.MeleeWeaponAttack }, false) }, // fan + }; + _metadataLoader = metadataLoader; + } - public WeaponMetadata GetValueOrDefault(int graphic) - { - return _metadataLoader.GetMetadata(graphic) - .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : WeaponMetadata.Default); + public WeaponMetadata GetValueOrDefault(int graphic) + { + return _metadataLoader.GetMetadata(graphic) + .ValueOr(DefaultMetadata.TryGetValue(graphic, out var ret) ? ret : WeaponMetadata.Default); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/MouseCursorRenderer.cs b/EndlessClient/Rendering/MouseCursorRenderer.cs index 9f04a642c..f311a3a5b 100644 --- a/EndlessClient/Rendering/MouseCursorRenderer.cs +++ b/EndlessClient/Rendering/MouseCursorRenderer.cs @@ -17,301 +17,302 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering; - -public class MouseCursorRenderer : XNAControl, IMouseCursorRenderer +namespace EndlessClient.Rendering { - private enum CursorIndex - { - Standard = 0, - HoverNormal = 1, - HoverItem = 2, - ClickFirstFrame = 3, - ClickSecondFrame = 4, - NumberOfFramesInSheet = 5 - } - - private readonly Rectangle SingleCursorFrameArea; - - private readonly Texture2D _mouseCursorTexture; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IMapCellStateProvider _mapCellStateProvider; - private readonly IItemStringService _itemStringService; - private readonly IItemNameColorService _itemNameColorService; - private readonly IEIFFileProvider _eifFileProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly IUserInputProvider _userInputProvider; - private readonly IActiveDialogProvider _activeDialogProvider; - private readonly IContextMenuProvider _contextMenuProvider; - - private readonly XNALabel _mapItemText; - - private int _gridX, _gridY; - private CursorIndex _cursorIndex; - private bool _shouldDrawCursor; - - private Option _startClickTime; - private CursorIndex _clickFrame; - private int _clickAlpha; - private Option _clickCoordinate; - - public MapCoordinate GridCoordinates => new MapCoordinate(_gridX, _gridY); - - public MouseCursorRenderer(INativeGraphicsManager nativeGraphicsManager, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IMapCellStateProvider mapCellStateProvider, - IItemStringService itemStringService, - IItemNameColorService itemNameColorService, - IEIFFileProvider eifFileProvider, - ICurrentMapProvider currentMapProvider, - IUserInputProvider userInputProvider, - IActiveDialogProvider activeDialogProvider, - IContextMenuProvider contextMenuProvider) + public class MouseCursorRenderer : XNAControl, IMouseCursorRenderer { - _mouseCursorTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 24, true); - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _mapCellStateProvider = mapCellStateProvider; - _itemStringService = itemStringService; - _itemNameColorService = itemNameColorService; - _eifFileProvider = eifFileProvider; - _currentMapProvider = currentMapProvider; - _userInputProvider = userInputProvider; - _activeDialogProvider = activeDialogProvider; - _contextMenuProvider = contextMenuProvider; - - SingleCursorFrameArea = new Rectangle(0, 0, - _mouseCursorTexture.Width / (int)CursorIndex.NumberOfFramesInSheet, - _mouseCursorTexture.Height); - DrawArea = SingleCursorFrameArea; - - _mapItemText = new XNALabel(Constants.FontSize09) + private enum CursorIndex { - Visible = false, - Text = string.Empty, - ForeColor = Color.White, - AutoSize = false, - DrawOrder = 10 //todo: make a better provider for draw orders (see also HudControlsFactory) - }; - - _clickCoordinate = Option.None(); - } + Standard = 0, + HoverNormal = 1, + HoverItem = 2, + ClickFirstFrame = 3, + ClickSecondFrame = 4, + NumberOfFramesInSheet = 5 + } - public override void Initialize() - { - _mapItemText.AddControlToDefaultGame(); - } + private readonly Rectangle SingleCursorFrameArea; + + private readonly Texture2D _mouseCursorTexture; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IMapCellStateProvider _mapCellStateProvider; + private readonly IItemStringService _itemStringService; + private readonly IItemNameColorService _itemNameColorService; + private readonly IEIFFileProvider _eifFileProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly IUserInputProvider _userInputProvider; + private readonly IActiveDialogProvider _activeDialogProvider; + private readonly IContextMenuProvider _contextMenuProvider; + + private readonly XNALabel _mapItemText; + + private int _gridX, _gridY; + private CursorIndex _cursorIndex; + private bool _shouldDrawCursor; + + private Option _startClickTime; + private CursorIndex _clickFrame; + private int _clickAlpha; + private Option _clickCoordinate; + + public MapCoordinate GridCoordinates => new MapCoordinate(_gridX, _gridY); + + public MouseCursorRenderer(INativeGraphicsManager nativeGraphicsManager, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IMapCellStateProvider mapCellStateProvider, + IItemStringService itemStringService, + IItemNameColorService itemNameColorService, + IEIFFileProvider eifFileProvider, + ICurrentMapProvider currentMapProvider, + IUserInputProvider userInputProvider, + IActiveDialogProvider activeDialogProvider, + IContextMenuProvider contextMenuProvider) + { + _mouseCursorTexture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 24, true); + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _mapCellStateProvider = mapCellStateProvider; + _itemStringService = itemStringService; + _itemNameColorService = itemNameColorService; + _eifFileProvider = eifFileProvider; + _currentMapProvider = currentMapProvider; + _userInputProvider = userInputProvider; + _activeDialogProvider = activeDialogProvider; + _contextMenuProvider = contextMenuProvider; + + SingleCursorFrameArea = new Rectangle(0, 0, + _mouseCursorTexture.Width / (int)CursorIndex.NumberOfFramesInSheet, + _mouseCursorTexture.Height); + DrawArea = SingleCursorFrameArea; + + _mapItemText = new XNALabel(Constants.FontSize09) + { + Visible = false, + Text = string.Empty, + ForeColor = Color.White, + AutoSize = false, + DrawOrder = 10 //todo: make a better provider for draw orders (see also HudControlsFactory) + }; + + _clickCoordinate = Option.None(); + } - #region Update and Helpers + public override void Initialize() + { + _mapItemText.AddControlToDefaultGame(); + } - public override void Update(GameTime gameTime) - { - // prevents updates if there is a dialog - if (!ShouldUpdate() || _activeDialogProvider.ActiveDialogs.Any(x => x.HasValue) || - _contextMenuProvider.ContextMenu.HasValue) - return; + #region Update and Helpers - var gridPosition = _gridDrawCoordinateCalculator.CalculateGridCoordinatesFromDrawLocation(_userInputProvider.CurrentMouseState.Position.ToVector2()); - _gridX = gridPosition.X; - _gridY = gridPosition.Y; + public override void Update(GameTime gameTime) + { + // prevents updates if there is a dialog + if (!ShouldUpdate() || _activeDialogProvider.ActiveDialogs.Any(x => x.HasValue) || + _contextMenuProvider.ContextMenu.HasValue) + return; - UpdateDrawPostionBasedOnGridPosition(); + var gridPosition = _gridDrawCoordinateCalculator.CalculateGridCoordinatesFromDrawLocation(_userInputProvider.CurrentMouseState.Position.ToVector2()); + _gridX = gridPosition.X; + _gridY = gridPosition.Y; - var cellState = _mapCellStateProvider.GetCellStateAt(_gridX, _gridY); - UpdateCursorSourceRectangle(cellState); - } + UpdateDrawPostionBasedOnGridPosition(); - private void UpdateDrawPostionBasedOnGridPosition() - { - var drawPosition = _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(_gridX, _gridY); - DrawArea = new Rectangle((int)drawPosition.X, - (int)drawPosition.Y, - DrawArea.Width, - DrawArea.Height); - } + var cellState = _mapCellStateProvider.GetCellStateAt(_gridX, _gridY); + UpdateCursorSourceRectangle(cellState); + } - private void UpdateCursorSourceRectangle(IMapCellState cellState) - { - _shouldDrawCursor = true; - _cursorIndex = CursorIndex.Standard; - if (cellState.Character.HasValue || cellState.NPC.HasValue) - _cursorIndex = CursorIndex.HoverNormal; - else if (cellState.Sign.HasValue) - _shouldDrawCursor = false; - else if (cellState.Items.Any()) + private void UpdateDrawPostionBasedOnGridPosition() { - _cursorIndex = CursorIndex.HoverItem; - UpdateMapItemLabel(Option.Some(cellState.Items.First())); + var drawPosition = _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(_gridX, _gridY); + DrawArea = new Rectangle((int)drawPosition.X, + (int)drawPosition.Y, + DrawArea.Width, + DrawArea.Height); } - else if (cellState.TileSpec != TileSpec.None) - UpdateCursorIndexForTileSpec(cellState.TileSpec); - if (!cellState.Items.Any()) - UpdateMapItemLabel(Option.None()); - - if (_mapItemText.Visible) + private void UpdateCursorSourceRectangle(IMapCellState cellState) { - //relative to cursor DrawPosition, since this control is a parent of MapItemText - _mapItemText.DrawPosition = new Vector2(DrawArea.X + 32 - _mapItemText.ActualWidth / 2f, - DrawArea.Y + -_mapItemText.ActualHeight - 4); - } + _shouldDrawCursor = true; + _cursorIndex = CursorIndex.Standard; + if (cellState.Character.HasValue || cellState.NPC.HasValue) + _cursorIndex = CursorIndex.HoverNormal; + else if (cellState.Sign.HasValue) + _shouldDrawCursor = false; + else if (cellState.Items.Any()) + { + _cursorIndex = CursorIndex.HoverItem; + UpdateMapItemLabel(Option.Some(cellState.Items.First())); + } + else if (cellState.TileSpec != TileSpec.None) + UpdateCursorIndexForTileSpec(cellState.TileSpec); + + if (!cellState.Items.Any()) + UpdateMapItemLabel(Option.None()); - _startClickTime.MatchSome(st => + if (_mapItemText.Visible) { - _clickAlpha -= 5; + //relative to cursor DrawPosition, since this control is a parent of MapItemText + _mapItemText.DrawPosition = new Vector2(DrawArea.X + 32 - _mapItemText.ActualWidth / 2f, + DrawArea.Y + -_mapItemText.ActualHeight - 4); + } - if (st.ElapsedMilliseconds > 350) + _startClickTime.MatchSome(st => { - _startClickTime = Option.Some(Stopwatch.StartNew()); - _clickFrame++; + _clickAlpha -= 5; - if (_clickFrame != CursorIndex.ClickFirstFrame && _clickFrame != CursorIndex.ClickSecondFrame) + if (st.ElapsedMilliseconds > 350) { - _clickFrame = CursorIndex.Standard; - _startClickTime = Option.None(); - _clickCoordinate = Option.None(); + _startClickTime = Option.Some(Stopwatch.StartNew()); + _clickFrame++; + + if (_clickFrame != CursorIndex.ClickFirstFrame && _clickFrame != CursorIndex.ClickSecondFrame) + { + _clickFrame = CursorIndex.Standard; + _startClickTime = Option.None(); + _clickCoordinate = Option.None(); + } } - } - }); - } + }); + } - private void UpdateMapItemLabel(Option item) - { - item.Match( - some: i => - { - var data = _eifFileProvider.EIFFile[i.ItemID]; - var text = _itemStringService.GetStringForMapDisplay(data, i.Amount); + private void UpdateMapItemLabel(Option item) + { + item.Match( + some: i => + { + var data = _eifFileProvider.EIFFile[i.ItemID]; + var text = _itemStringService.GetStringForMapDisplay(data, i.Amount); - if (!_mapItemText.Visible || _mapItemText.Text != text) + if (!_mapItemText.Visible || _mapItemText.Text != text) + { + _mapItemText.Visible = true; + _mapItemText.Text = text; + _mapItemText.ResizeBasedOnText(); + _mapItemText.ForeColor = _itemNameColorService.GetColorForMapDisplay(data); + } + }, + none: () => { - _mapItemText.Visible = true; - _mapItemText.Text = text; - _mapItemText.ResizeBasedOnText(); - _mapItemText.ForeColor = _itemNameColorService.GetColorForMapDisplay(data); - } - }, - none: () => - { - _mapItemText.Visible = false; - _mapItemText.Text = string.Empty; - }); - } + _mapItemText.Visible = false; + _mapItemText.Text = string.Empty; + }); + } - private void UpdateCursorIndexForTileSpec(TileSpec tileSpec) - { - switch (tileSpec) + private void UpdateCursorIndexForTileSpec(TileSpec tileSpec) { - case TileSpec.Wall: - case TileSpec.JammedDoor: - case TileSpec.MapEdge: - case TileSpec.FakeWall: - case TileSpec.VultTypo: - _shouldDrawCursor = false; - break; - case TileSpec.Chest: - case TileSpec.BankVault: - case TileSpec.ChairDown: - case TileSpec.ChairLeft: - case TileSpec.ChairRight: - case TileSpec.ChairUp: - case TileSpec.ChairDownRight: - case TileSpec.ChairUpLeft: - case TileSpec.ChairAll: - case TileSpec.Board1: - case TileSpec.Board2: - case TileSpec.Board3: - case TileSpec.Board4: - case TileSpec.Board5: - case TileSpec.Board6: - case TileSpec.Board7: - case TileSpec.Board8: - case TileSpec.Jukebox: - _cursorIndex = CursorIndex.HoverNormal; - break; - case TileSpec.NPCBoundary: - case TileSpec.Jump: - case TileSpec.Water: - case TileSpec.Arena: - case TileSpec.AmbientSource: - case TileSpec.SpikesStatic: - case TileSpec.SpikesTrap: - case TileSpec.SpikesTimed: - case TileSpec.None: - _cursorIndex = CursorIndex.Standard; - break; - default: - _cursorIndex = CursorIndex.HoverNormal; - break; + switch (tileSpec) + { + case TileSpec.Wall: + case TileSpec.JammedDoor: + case TileSpec.MapEdge: + case TileSpec.FakeWall: + case TileSpec.VultTypo: + _shouldDrawCursor = false; + break; + case TileSpec.Chest: + case TileSpec.BankVault: + case TileSpec.ChairDown: + case TileSpec.ChairLeft: + case TileSpec.ChairRight: + case TileSpec.ChairUp: + case TileSpec.ChairDownRight: + case TileSpec.ChairUpLeft: + case TileSpec.ChairAll: + case TileSpec.Board1: + case TileSpec.Board2: + case TileSpec.Board3: + case TileSpec.Board4: + case TileSpec.Board5: + case TileSpec.Board6: + case TileSpec.Board7: + case TileSpec.Board8: + case TileSpec.Jukebox: + _cursorIndex = CursorIndex.HoverNormal; + break; + case TileSpec.NPCBoundary: + case TileSpec.Jump: + case TileSpec.Water: + case TileSpec.Arena: + case TileSpec.AmbientSource: + case TileSpec.SpikesStatic: + case TileSpec.SpikesTrap: + case TileSpec.SpikesTimed: + case TileSpec.None: + _cursorIndex = CursorIndex.Standard; + break; + default: + _cursorIndex = CursorIndex.HoverNormal; + break; + } } - } - - #endregion - public void Draw(SpriteBatch spriteBatch, Vector2 additionalOffset) - { - if (_contextMenuProvider.ContextMenu.HasValue) - return; + #endregion - if (_shouldDrawCursor && _gridX >= 0 && _gridY >= 0 && - _gridX <= _currentMapProvider.CurrentMap.Properties.Width && - _gridY <= _currentMapProvider.CurrentMap.Properties.Height) + public void Draw(SpriteBatch spriteBatch, Vector2 additionalOffset) { - spriteBatch.Draw(_mouseCursorTexture, - DrawPosition + additionalOffset, - new Rectangle(SingleCursorFrameArea.Width * (int)_cursorIndex, - 0, - SingleCursorFrameArea.Width, - SingleCursorFrameArea.Height), - Color.White); - } + if (_contextMenuProvider.ContextMenu.HasValue) + return; - if (_startClickTime.HasValue) - { - _clickCoordinate.MatchSome(c => + if (_shouldDrawCursor && _gridX >= 0 && _gridY >= 0 && + _gridX <= _currentMapProvider.CurrentMap.Properties.Width && + _gridY <= _currentMapProvider.CurrentMap.Properties.Height) { - var position = _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c); spriteBatch.Draw(_mouseCursorTexture, - position + additionalOffset, - SingleCursorFrameArea.WithPosition(new Vector2(SingleCursorFrameArea.Width * (int)_clickFrame, 0)), - Color.FromNonPremultiplied(255, 255, 255, _clickAlpha)); - }); + DrawPosition + additionalOffset, + new Rectangle(SingleCursorFrameArea.Width * (int)_cursorIndex, + 0, + SingleCursorFrameArea.Width, + SingleCursorFrameArea.Height), + Color.White); + } + + if (_startClickTime.HasValue) + { + _clickCoordinate.MatchSome(c => + { + var position = _gridDrawCoordinateCalculator.CalculateBaseLayerDrawCoordinatesFromGridUnits(c); + spriteBatch.Draw(_mouseCursorTexture, + position + additionalOffset, + SingleCursorFrameArea.WithPosition(new Vector2(SingleCursorFrameArea.Width * (int)_clickFrame, 0)), + Color.FromNonPremultiplied(255, 255, 255, _clickAlpha)); + }); + } } - } - public void AnimateClick() - { - if (_startClickTime.HasValue) - return; + public void AnimateClick() + { + if (_startClickTime.HasValue) + return; - _startClickTime = Option.Some(Stopwatch.StartNew()); - _clickFrame = CursorIndex.ClickFirstFrame; - _clickAlpha = 200; - _clickCoordinate = Option.Some(new MapCoordinate(_gridX, _gridY)); - } + _startClickTime = Option.Some(Stopwatch.StartNew()); + _clickFrame = CursorIndex.ClickFirstFrame; + _clickAlpha = 200; + _clickCoordinate = Option.Some(new MapCoordinate(_gridX, _gridY)); + } - public void ClearTransientRenderables() - { - _mapItemText.Visible = false; - _startClickTime = Option.None(); - } + public void ClearTransientRenderables() + { + _mapItemText.Visible = false; + _startClickTime = Option.None(); + } - protected override void Dispose(bool disposing) - { - if (disposing) + protected override void Dispose(bool disposing) { - _spriteBatch.Dispose(); - _mapItemText.Dispose(); + if (disposing) + { + _spriteBatch.Dispose(); + _mapItemText.Dispose(); + } } } -} -public interface IMouseCursorRenderer : IXNAControl, IDisposable -{ - MapCoordinate GridCoordinates { get; } + public interface IMouseCursorRenderer : IXNAControl, IDisposable + { + MapCoordinate GridCoordinates { get; } - void Draw(SpriteBatch spriteBatch, Vector2 additionalOffset); + void Draw(SpriteBatch spriteBatch, Vector2 additionalOffset); - void AnimateClick(); + void AnimateClick(); - void ClearTransientRenderables(); + void ClearTransientRenderables(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/INPCRenderer.cs b/EndlessClient/Rendering/NPC/INPCRenderer.cs index 238154a37..654c13446 100644 --- a/EndlessClient/Rendering/NPC/INPCRenderer.cs +++ b/EndlessClient/Rendering/NPC/INPCRenderer.cs @@ -2,17 +2,18 @@ using Microsoft.Xna.Framework.Graphics; using System; -namespace EndlessClient.Rendering.NPC; - -public interface INPCRenderer : IDrawable, IUpdateable, IGameComponent, IDisposable, IMapActor +namespace EndlessClient.Rendering.NPC { - EOLib.Domain.NPC.NPC NPC { get; set; } + public interface INPCRenderer : IDrawable, IUpdateable, IGameComponent, IDisposable, IMapActor + { + EOLib.Domain.NPC.NPC NPC { get; set; } - bool IsDead { get; } + bool IsDead { get; } - bool IsClickablePixel(Point currentMousePosition); + bool IsClickablePixel(Point currentMousePosition); - void DrawToSpriteBatch(SpriteBatch spriteBatch); + void DrawToSpriteBatch(SpriteBatch spriteBatch); - void StartDying(); + void StartDying(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCActions.cs b/EndlessClient/Rendering/NPC/NPCActions.cs index a8ef0ab5a..1a150be36 100644 --- a/EndlessClient/Rendering/NPC/NPCActions.cs +++ b/EndlessClient/Rendering/NPC/NPCActions.cs @@ -11,157 +11,158 @@ using EOLib.Localization; using Optional; -namespace EndlessClient.Rendering.NPC; - -[AutoMappedType] -public class NPCActions : INPCActionNotifier +namespace EndlessClient.Rendering.NPC { - private readonly IHudControlProvider _hudControlProvider; - private readonly INPCStateCache _npcStateCache; - private readonly INPCRendererRepository _npcRendererRepository; - private readonly ICharacterRendererRepository _characterRendererRepository; - private readonly IChatBubbleActions _chatBubbleActions; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IESFFileProvider _esfFileProvider; - private readonly ISfxPlayer _sfxPlayer; - - public NPCActions(IHudControlProvider hudControlProvider, - INPCStateCache npcStateCache, - INPCRendererRepository npcRendererRepository, - ICharacterRendererRepository characterRendererRepository, - IChatBubbleActions chatBubbleActions, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - IEIFFileProvider eifFileProvider, - IESFFileProvider esfFileProvider, - ISfxPlayer sfxPlayer) - { - _hudControlProvider = hudControlProvider; - _npcStateCache = npcStateCache; - _npcRendererRepository = npcRendererRepository; - _characterRendererRepository = characterRendererRepository; - _chatBubbleActions = chatBubbleActions; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _eifFileProvider = eifFileProvider; - _esfFileProvider = esfFileProvider; - _sfxPlayer = sfxPlayer; - } - - public void StartNPCWalkAnimation(int npcIndex) - { - if (!_hudControlProvider.IsInGame) - return; - - Animator.StartWalkAnimation(npcIndex); - } - - public void StartNPCAttackAnimation(int npcIndex) + [AutoMappedType] + public class NPCActions : INPCActionNotifier { - if (!_hudControlProvider.IsInGame) - return; + private readonly IHudControlProvider _hudControlProvider; + private readonly INPCStateCache _npcStateCache; + private readonly INPCRendererRepository _npcRendererRepository; + private readonly ICharacterRendererRepository _characterRendererRepository; + private readonly IChatBubbleActions _chatBubbleActions; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IESFFileProvider _esfFileProvider; + private readonly ISfxPlayer _sfxPlayer; + + public NPCActions(IHudControlProvider hudControlProvider, + INPCStateCache npcStateCache, + INPCRendererRepository npcRendererRepository, + ICharacterRendererRepository characterRendererRepository, + IChatBubbleActions chatBubbleActions, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + IEIFFileProvider eifFileProvider, + IESFFileProvider esfFileProvider, + ISfxPlayer sfxPlayer) + { + _hudControlProvider = hudControlProvider; + _npcStateCache = npcStateCache; + _npcRendererRepository = npcRendererRepository; + _characterRendererRepository = characterRendererRepository; + _chatBubbleActions = chatBubbleActions; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _eifFileProvider = eifFileProvider; + _esfFileProvider = esfFileProvider; + _sfxPlayer = sfxPlayer; + } - Animator.StartAttackAnimation(npcIndex); + public void StartNPCWalkAnimation(int npcIndex) + { + if (!_hudControlProvider.IsInGame) + return; - _sfxPlayer.PlaySfx(SoundEffectID.PunchAttack); - } + Animator.StartWalkAnimation(npcIndex); + } - public void RemoveNPCFromView(int npcIndex, int playerId, Option spellId, Option damage, bool showDeathAnimation) - { - //possible that the server might send a packet for the npc to be removed by the map switch is completed - if (!_hudControlProvider.IsInGame) - return; + public void StartNPCAttackAnimation(int npcIndex) + { + if (!_hudControlProvider.IsInGame) + return; - var hasRenderer = _npcRendererRepository.NPCRenderers.ContainsKey(npcIndex); + Animator.StartAttackAnimation(npcIndex); - _npcStateCache.RemoveStateByIndex(npcIndex); + _sfxPlayer.PlaySfx(SoundEffectID.PunchAttack); + } - if (hasRenderer) + public void RemoveNPCFromView(int npcIndex, int playerId, Option spellId, Option damage, bool showDeathAnimation) { - var renderer = _npcRendererRepository.NPCRenderers[npcIndex]; + //possible that the server might send a packet for the npc to be removed by the map switch is completed + if (!_hudControlProvider.IsInGame) + return; - if (!showDeathAnimation) - { - renderer.Dispose(); - _npcRendererRepository.NPCRenderers.Remove(npcIndex); - } - else - { - renderer.StartDying(); - _npcRendererRepository.DyingNPCs[new MapCoordinate(renderer.NPC.X, renderer.NPC.Y)] = npcIndex; + var hasRenderer = _npcRendererRepository.NPCRenderers.ContainsKey(npcIndex); - damage.MatchSome(d => renderer.ShowDamageCounter(d, 0, isHeal: false)); - } - } + _npcStateCache.RemoveStateByIndex(npcIndex); - spellId.MatchSome(spell => - { if (hasRenderer) { - var graphic = _esfFileProvider.ESFFile[spell].Graphic; - _npcRendererRepository.NPCRenderers[npcIndex].PlayEffect(graphic); - } + var renderer = _npcRendererRepository.NPCRenderers[npcIndex]; - ShoutSpellCast(playerId); - }); - } + if (!showDeathAnimation) + { + renderer.Dispose(); + _npcRendererRepository.NPCRenderers.Remove(npcIndex); + } + else + { + renderer.StartDying(); + _npcRendererRepository.DyingNPCs[new MapCoordinate(renderer.NPC.X, renderer.NPC.Y)] = npcIndex; + + damage.MatchSome(d => renderer.ShowDamageCounter(d, 0, isHeal: false)); + } + } - public void ShowNPCSpeechBubble(int npcIndex, string message) - { - _chatBubbleActions.ShowChatBubbleForNPC(npcIndex, message); - } + spellId.MatchSome(spell => + { + if (hasRenderer) + { + var graphic = _esfFileProvider.ESFFile[spell].Graphic; + _npcRendererRepository.NPCRenderers[npcIndex].PlayEffect(graphic); + } - public void NPCTakeDamage(int npcIndex, int fromPlayerId, int damageToNpc, int npcPctHealth, Option spellId) - { - var hasRenderer = _npcRendererRepository.NPCRenderers.ContainsKey(npcIndex); + ShoutSpellCast(playerId); + }); + } - if (hasRenderer) - _npcRendererRepository.NPCRenderers[npcIndex].ShowDamageCounter(damageToNpc, npcPctHealth, isHeal: false); + public void ShowNPCSpeechBubble(int npcIndex, string message) + { + _chatBubbleActions.ShowChatBubbleForNPC(npcIndex, message); + } - spellId.MatchSome(spell => + public void NPCTakeDamage(int npcIndex, int fromPlayerId, int damageToNpc, int npcPctHealth, Option spellId) { + var hasRenderer = _npcRendererRepository.NPCRenderers.ContainsKey(npcIndex); + if (hasRenderer) + _npcRendererRepository.NPCRenderers[npcIndex].ShowDamageCounter(damageToNpc, npcPctHealth, isHeal: false); + + spellId.MatchSome(spell => { - var renderer = _npcRendererRepository.NPCRenderers[npcIndex]; + if (hasRenderer) + { + var renderer = _npcRendererRepository.NPCRenderers[npcIndex]; - var graphic = _esfFileProvider.ESFFile[spell].Graphic; - renderer.PlayEffect(graphic); - } + var graphic = _esfFileProvider.ESFFile[spell].Graphic; + renderer.PlayEffect(graphic); + } - ShoutSpellCast(fromPlayerId); - }); - } + ShoutSpellCast(fromPlayerId); + }); + } - public void NPCDropItem(MapItem item) - { - // todo: not sure if it is better to do this here in a notifier or modify the chat repository in the packet handler - // however, I don't want to introduce a dependency on localized text in the packet handler - var itemName = _eifFileProvider.EIFFile[item.ItemID].Name; - var chatData = new ChatData(ChatTab.System, - string.Empty, - $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_THE_NPC_DROPPED)} {item.Amount} {itemName}", - ChatIcon.DownArrow); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } + public void NPCDropItem(MapItem item) + { + // todo: not sure if it is better to do this here in a notifier or modify the chat repository in the packet handler + // however, I don't want to introduce a dependency on localized text in the packet handler + var itemName = _eifFileProvider.EIFFile[item.ItemID].Name; + var chatData = new ChatData(ChatTab.System, + string.Empty, + $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_THE_NPC_DROPPED)} {item.Amount} {itemName}", + ChatIcon.DownArrow); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } - private void ShoutSpellCast(int playerId) - { - _characterRendererRepository.MainCharacterRenderer.Match( - some: r => - { - if (r.Character.ID == playerId) - r.ShoutSpellCast(); - else if (_characterRendererRepository.CharacterRenderers.ContainsKey(playerId)) - _characterRendererRepository.CharacterRenderers[playerId].ShoutSpellCast(); - }, - none: () => - { - if (_characterRendererRepository.CharacterRenderers.ContainsKey(playerId)) - _characterRendererRepository.CharacterRenderers[playerId].ShoutSpellCast(); - }); - } + private void ShoutSpellCast(int playerId) + { + _characterRendererRepository.MainCharacterRenderer.Match( + some: r => + { + if (r.Character.ID == playerId) + r.ShoutSpellCast(); + else if (_characterRendererRepository.CharacterRenderers.ContainsKey(playerId)) + _characterRendererRepository.CharacterRenderers[playerId].ShoutSpellCast(); + }, + none: () => + { + if (_characterRendererRepository.CharacterRenderers.ContainsKey(playerId)) + _characterRendererRepository.CharacterRenderers[playerId].ShoutSpellCast(); + }); + } - private INPCAnimator Animator => _hudControlProvider.GetComponent(HudControlIdentifier.NPCAnimator); + private INPCAnimator Animator => _hudControlProvider.GetComponent(HudControlIdentifier.NPCAnimator); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCAnimator.cs b/EndlessClient/Rendering/NPC/NPCAnimator.cs index db118c5ba..77124741a 100644 --- a/EndlessClient/Rendering/NPC/NPCAnimator.cs +++ b/EndlessClient/Rendering/NPC/NPCAnimator.cs @@ -8,138 +8,139 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.NPC; - -public class NPCAnimator : GameComponent, INPCAnimator +namespace EndlessClient.Rendering.NPC { - private const int TICKS_PER_ACTION_FRAME = 8; // 8 x10ms ticks per action frame + public class NPCAnimator : GameComponent, INPCAnimator + { + private const int TICKS_PER_ACTION_FRAME = 8; // 8 x10ms ticks per action frame - private readonly List _npcStartWalkingTimes; - private readonly List _npcStartAttackingTimes; - private readonly ICurrentMapStateRepository _currentMapStateRepository; - private readonly IFixedTimeStepRepository _fixedTimeStepRepository; + private readonly List _npcStartWalkingTimes; + private readonly List _npcStartAttackingTimes; + private readonly ICurrentMapStateRepository _currentMapStateRepository; + private readonly IFixedTimeStepRepository _fixedTimeStepRepository; - public NPCAnimator(IEndlessGameProvider gameProvider, - ICurrentMapStateRepository currentMapStateRepository, - IFixedTimeStepRepository fixedTimeStepRepository) - : base((Game)gameProvider.Game) - { - _currentMapStateRepository = currentMapStateRepository; - _fixedTimeStepRepository = fixedTimeStepRepository; - _npcStartWalkingTimes = new List(); - _npcStartAttackingTimes = new List(); - } + public NPCAnimator(IEndlessGameProvider gameProvider, + ICurrentMapStateRepository currentMapStateRepository, + IFixedTimeStepRepository fixedTimeStepRepository) + : base((Game)gameProvider.Game) + { + _currentMapStateRepository = currentMapStateRepository; + _fixedTimeStepRepository = fixedTimeStepRepository; + _npcStartWalkingTimes = new List(); + _npcStartAttackingTimes = new List(); + } - public override void Update(GameTime gameTime) - { - AnimateNPCWalking(); - AnimateNPCAttacking(); + public override void Update(GameTime gameTime) + { + AnimateNPCWalking(); + AnimateNPCAttacking(); - base.Update(gameTime); - } + base.Update(gameTime); + } - public void StartWalkAnimation(int npcIndex) - { - if (_npcStartWalkingTimes.Any(x => x.UniqueID == npcIndex)) - return; + public void StartWalkAnimation(int npcIndex) + { + if (_npcStartWalkingTimes.Any(x => x.UniqueID == npcIndex)) + return; - var startWalkingTimeAndID = new RenderFrameActionTime(npcIndex, _fixedTimeStepRepository.TickCount); + var startWalkingTimeAndID = new RenderFrameActionTime(npcIndex, _fixedTimeStepRepository.TickCount); - _npcStartWalkingTimes.Add(startWalkingTimeAndID); - } + _npcStartWalkingTimes.Add(startWalkingTimeAndID); + } - public void StartAttackAnimation(int npcIndex) - { - if (_npcStartAttackingTimes.Any(x => x.UniqueID == npcIndex)) - return; + public void StartAttackAnimation(int npcIndex) + { + if (_npcStartAttackingTimes.Any(x => x.UniqueID == npcIndex)) + return; - var startAttackingTimeAndID = new RenderFrameActionTime(npcIndex, _fixedTimeStepRepository.TickCount); + var startAttackingTimeAndID = new RenderFrameActionTime(npcIndex, _fixedTimeStepRepository.TickCount); - _npcStartAttackingTimes.Add(startAttackingTimeAndID); - } + _npcStartAttackingTimes.Add(startAttackingTimeAndID); + } - public void StopAllAnimations() - { - _npcStartWalkingTimes.Clear(); - } + public void StopAllAnimations() + { + _npcStartWalkingTimes.Clear(); + } - private void AnimateNPCWalking() - { - var npcsDoneWalking = new List(); - foreach (var pair in _npcStartWalkingTimes) + private void AnimateNPCWalking() { - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_ACTION_FRAME) + var npcsDoneWalking = new List(); + foreach (var pair in _npcStartWalkingTimes) { - var npc = _currentMapStateRepository.NPCs.SingleOrNone(x => x.Index == pair.UniqueID); - - npc.Match( - some: n => - { - var nextFrameNPC = AnimateOneWalkFrame(n); - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - - if (nextFrameNPC.Frame == NPCFrame.Standing) - npcsDoneWalking.Add(pair); - - _currentMapStateRepository.NPCs.Remove(n); - _currentMapStateRepository.NPCs.Add(nextFrameNPC); - }, - none: () => npcsDoneWalking.Add(pair)); + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_ACTION_FRAME) + { + var npc = _currentMapStateRepository.NPCs.SingleOrNone(x => x.Index == pair.UniqueID); + + npc.Match( + some: n => + { + var nextFrameNPC = AnimateOneWalkFrame(n); + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + + if (nextFrameNPC.Frame == NPCFrame.Standing) + npcsDoneWalking.Add(pair); + + _currentMapStateRepository.NPCs.Remove(n); + _currentMapStateRepository.NPCs.Add(nextFrameNPC); + }, + none: () => npcsDoneWalking.Add(pair)); + } } - } - _npcStartWalkingTimes.RemoveAll(npcsDoneWalking.Contains); - } + _npcStartWalkingTimes.RemoveAll(npcsDoneWalking.Contains); + } - private void AnimateNPCAttacking() - { - var npcsDoneAttacking = new List(); - foreach (var pair in _npcStartAttackingTimes) + private void AnimateNPCAttacking() { - if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_ACTION_FRAME) + var npcsDoneAttacking = new List(); + foreach (var pair in _npcStartAttackingTimes) { - var npc = _currentMapStateRepository.NPCs.SingleOrNone(x => x.Index == pair.UniqueID); + if ((_fixedTimeStepRepository.TickCount - pair.ActionTick) >= TICKS_PER_ACTION_FRAME) + { + var npc = _currentMapStateRepository.NPCs.SingleOrNone(x => x.Index == pair.UniqueID); - npc.Match( - some: n => - { - var nextFrameNPC = n.WithNextAttackFrame(); - pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); + npc.Match( + some: n => + { + var nextFrameNPC = n.WithNextAttackFrame(); + pair.UpdateActionStartTime(_fixedTimeStepRepository.TickCount); - if (nextFrameNPC.Frame == NPCFrame.Standing) - npcsDoneAttacking.Add(pair); + if (nextFrameNPC.Frame == NPCFrame.Standing) + npcsDoneAttacking.Add(pair); - _currentMapStateRepository.NPCs.Remove(n); - _currentMapStateRepository.NPCs.Add(nextFrameNPC); + _currentMapStateRepository.NPCs.Remove(n); + _currentMapStateRepository.NPCs.Add(nextFrameNPC); - }, - none: () => npcsDoneAttacking.Add(pair)); + }, + none: () => npcsDoneAttacking.Add(pair)); + } } + + _npcStartAttackingTimes.RemoveAll(npcsDoneAttacking.Contains); } - _npcStartAttackingTimes.RemoveAll(npcsDoneAttacking.Contains); - } + private static EOLib.Domain.NPC.NPC AnimateOneWalkFrame(EOLib.Domain.NPC.NPC npc) + { + var nextFrameNPC = npc.WithNextWalkFrame(); - private static EOLib.Domain.NPC.NPC AnimateOneWalkFrame(EOLib.Domain.NPC.NPC npc) - { - var nextFrameNPC = npc.WithNextWalkFrame(); + if (nextFrameNPC.IsActing(NPCActionState.Standing)) + { + nextFrameNPC = nextFrameNPC + .WithX(nextFrameNPC.GetDestinationX()) + .WithY(nextFrameNPC.GetDestinationY()); + } - if (nextFrameNPC.IsActing(NPCActionState.Standing)) - { - nextFrameNPC = nextFrameNPC - .WithX(nextFrameNPC.GetDestinationX()) - .WithY(nextFrameNPC.GetDestinationY()); + return nextFrameNPC; } - - return nextFrameNPC; } -} -public interface INPCAnimator : IGameComponent -{ - void StartWalkAnimation(int npcIndex); + public interface INPCAnimator : IGameComponent + { + void StartWalkAnimation(int npcIndex); - void StartAttackAnimation(int npcIndex); + void StartAttackAnimation(int npcIndex); - void StopAllAnimations(); + void StopAllAnimations(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCCache.cs b/EndlessClient/Rendering/NPC/NPCCache.cs index caa4a7830..65c527286 100644 --- a/EndlessClient/Rendering/NPC/NPCCache.cs +++ b/EndlessClient/Rendering/NPC/NPCCache.cs @@ -1,54 +1,55 @@ using AutomaticTypeMapper; using System.Collections.Generic; -namespace EndlessClient.Rendering.NPC; - -[MappedType(BaseType = typeof(INPCStateCache), IsSingleton = true)] -public class NPCStateCache : INPCStateCache +namespace EndlessClient.Rendering.NPC { - private readonly Dictionary _npcStates; - - public IReadOnlyDictionary NPCStates => _npcStates; - - public NPCStateCache() - { - _npcStates = new Dictionary(); - } - - public bool HasNPCStateWithIndex(int index) - { - return _npcStates.ContainsKey(index) && _npcStates[index] != null; - } - - public void UpdateNPCState(int index, EOLib.Domain.NPC.NPC npc) - { - if (!_npcStates.ContainsKey(index)) - _npcStates.Add(index, npc); - else - _npcStates[index] = npc; - } - - public void RemoveStateByIndex(int index) + [MappedType(BaseType = typeof(INPCStateCache), IsSingleton = true)] + public class NPCStateCache : INPCStateCache { - if (_npcStates.ContainsKey(index)) - _npcStates.Remove(index); + private readonly Dictionary _npcStates; + + public IReadOnlyDictionary NPCStates => _npcStates; + + public NPCStateCache() + { + _npcStates = new Dictionary(); + } + + public bool HasNPCStateWithIndex(int index) + { + return _npcStates.ContainsKey(index) && _npcStates[index] != null; + } + + public void UpdateNPCState(int index, EOLib.Domain.NPC.NPC npc) + { + if (!_npcStates.ContainsKey(index)) + _npcStates.Add(index, npc); + else + _npcStates[index] = npc; + } + + public void RemoveStateByIndex(int index) + { + if (_npcStates.ContainsKey(index)) + _npcStates.Remove(index); + } + + public void Reset() + { + _npcStates.Clear(); + } } - public void Reset() + public interface INPCStateCache { - _npcStates.Clear(); - } -} - -public interface INPCStateCache -{ - IReadOnlyDictionary NPCStates { get; } + IReadOnlyDictionary NPCStates { get; } - bool HasNPCStateWithIndex(int index); + bool HasNPCStateWithIndex(int index); - void UpdateNPCState(int index, EOLib.Domain.NPC.NPC npc); + void UpdateNPCState(int index, EOLib.Domain.NPC.NPC npc); - void RemoveStateByIndex(int index); + void RemoveStateByIndex(int index); - void Reset(); + void Reset(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRenderer.cs b/EndlessClient/Rendering/NPC/NPCRenderer.cs index 0d990b932..56befc44e 100644 --- a/EndlessClient/Rendering/NPC/NPCRenderer.cs +++ b/EndlessClient/Rendering/NPC/NPCRenderer.cs @@ -18,329 +18,330 @@ using System.Linq; using XNAControls; -namespace EndlessClient.Rendering.NPC; - -public class NPCRenderer : DrawableGameComponent, INPCRenderer +namespace EndlessClient.Rendering.NPC { - private static readonly object _rt_locker_ = new object(); - - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly INPCSpriteSheet _npcSpriteSheet; - private readonly INPCSpriteDataCache _npcSpriteDataCache; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IHealthBarRendererFactory _healthBarRendererFactory; - private readonly IChatBubbleFactory _chatBubbleFactory; - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IUserInputProvider _userInputProvider; - private readonly IEffectRenderer _effectRenderer; - private readonly IHealthBarRenderer _healthBarRenderer; + public class NPCRenderer : DrawableGameComponent, INPCRenderer + { + private static readonly object _rt_locker_ = new object(); - private RenderTarget2D _npcRenderTarget; - private SpriteBatch _spriteBatch; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly INPCSpriteSheet _npcSpriteSheet; + private readonly INPCSpriteDataCache _npcSpriteDataCache; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IHealthBarRendererFactory _healthBarRendererFactory; + private readonly IChatBubbleFactory _chatBubbleFactory; + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IUserInputProvider _userInputProvider; + private readonly IEffectRenderer _effectRenderer; + private readonly IHealthBarRenderer _healthBarRenderer; - private DateTime _lastStandingAnimation; - private int _fadeAwayAlpha; - private bool _isDying, _isBlankSprite; + private RenderTarget2D _npcRenderTarget; + private SpriteBatch _spriteBatch; - private XNALabel _nameLabel; - private IChatBubble _chatBubble; + private DateTime _lastStandingAnimation; + private int _fadeAwayAlpha; + private bool _isDying, _isBlankSprite; - public int NameLabelY { get; private set; } + private XNALabel _nameLabel; + private IChatBubble _chatBubble; - public int HorizontalCenter { get; private set; } + public int NameLabelY { get; private set; } - public bool IsAlive => !_isDying && !IsDead; + public int HorizontalCenter { get; private set; } - public Rectangle DrawArea { get; private set; } + public bool IsAlive => !_isDying && !IsDead; - public EOLib.Domain.NPC.NPC NPC { get; set; } + public Rectangle DrawArea { get; private set; } - public ISpellTargetable SpellTarget => NPC; + public EOLib.Domain.NPC.NPC NPC { get; set; } - public bool IsDead { get; private set; } + public ISpellTargetable SpellTarget => NPC; - public Rectangle EffectTargetArea { get; private set; } + public bool IsDead { get; private set; } - public NPCRenderer(IEndlessGameProvider endlessGameProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - IENFFileProvider enfFileProvider, - INPCSpriteSheet npcSpriteSheet, - INPCSpriteDataCache npcSpriteDataCache, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IHealthBarRendererFactory healthBarRendererFactory, - IChatBubbleFactory chatBubbleFactory, - IRenderTargetFactory renderTargetFactory, - IUserInputProvider userInputProvider, - IEffectRendererFactory effectRendererFactory, - EOLib.Domain.NPC.NPC initialNPC) - : base((Game)endlessGameProvider.Game) - { - NPC = initialNPC; - _clientWindowSizeProvider = clientWindowSizeProvider; - _enfFileProvider = enfFileProvider; - _npcSpriteSheet = npcSpriteSheet; - _npcSpriteDataCache = npcSpriteDataCache; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _healthBarRendererFactory = healthBarRendererFactory; - _chatBubbleFactory = chatBubbleFactory; - _renderTargetFactory = renderTargetFactory; - _userInputProvider = userInputProvider; - _effectRenderer = effectRendererFactory.Create(); - - DrawArea = GetStandingFrameRectangle(); - - _lastStandingAnimation = DateTime.Now; - _fadeAwayAlpha = 255; - - _clientWindowSizeProvider.GameWindowSizeChanged += RecreateRenderTarget; - - _healthBarRenderer = _healthBarRendererFactory.CreateHealthBarRenderer(this); - } + public Rectangle EffectTargetArea { get; private set; } - public override void Initialize() - { - UpdateDrawAreas(); - - _nameLabel = new XNALabel(Constants.FontSize08pt5) + public NPCRenderer(IEndlessGameProvider endlessGameProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + IENFFileProvider enfFileProvider, + INPCSpriteSheet npcSpriteSheet, + INPCSpriteDataCache npcSpriteDataCache, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IHealthBarRendererFactory healthBarRendererFactory, + IChatBubbleFactory chatBubbleFactory, + IRenderTargetFactory renderTargetFactory, + IUserInputProvider userInputProvider, + IEffectRendererFactory effectRendererFactory, + EOLib.Domain.NPC.NPC initialNPC) + : base((Game)endlessGameProvider.Game) { - Visible = false, - TextWidth = 89, - TextAlign = LabelAlignment.MiddleCenter, - ForeColor = Color.White, - AutoSize = true, - Text = _enfFileProvider.ENFFile[NPC.ID].Name, - DrawOrder = 30, - KeepInClientWindowBounds = false, - }; - _nameLabel.Initialize(); - - if (!_nameLabel.Game.Components.Contains(_nameLabel)) - _nameLabel.Game.Components.Add(_nameLabel); - - _nameLabel.DrawPosition = GetNameLabelPosition(); - - lock (_rt_locker_) - _npcRenderTarget = _renderTargetFactory.CreateRenderTarget(); - - _spriteBatch = new SpriteBatch(Game.GraphicsDevice); + NPC = initialNPC; + _clientWindowSizeProvider = clientWindowSizeProvider; + _enfFileProvider = enfFileProvider; + _npcSpriteSheet = npcSpriteSheet; + _npcSpriteDataCache = npcSpriteDataCache; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _healthBarRendererFactory = healthBarRendererFactory; + _chatBubbleFactory = chatBubbleFactory; + _renderTargetFactory = renderTargetFactory; + _userInputProvider = userInputProvider; + _effectRenderer = effectRendererFactory.Create(); + + DrawArea = GetStandingFrameRectangle(); + + _lastStandingAnimation = DateTime.Now; + _fadeAwayAlpha = 255; + + _clientWindowSizeProvider.GameWindowSizeChanged += RecreateRenderTarget; + + _healthBarRenderer = _healthBarRendererFactory.CreateHealthBarRenderer(this); + } - var graphic = _enfFileProvider.ENFFile[NPC.ID].Graphic; - _npcSpriteDataCache.Populate(graphic); - _isBlankSprite = _npcSpriteDataCache.IsBlankSprite(graphic); + public override void Initialize() + { + UpdateDrawAreas(); + + _nameLabel = new XNALabel(Constants.FontSize08pt5) + { + Visible = false, + TextWidth = 89, + TextAlign = LabelAlignment.MiddleCenter, + ForeColor = Color.White, + AutoSize = true, + Text = _enfFileProvider.ENFFile[NPC.ID].Name, + DrawOrder = 30, + KeepInClientWindowBounds = false, + }; + _nameLabel.Initialize(); + + if (!_nameLabel.Game.Components.Contains(_nameLabel)) + _nameLabel.Game.Components.Add(_nameLabel); - base.Initialize(); - } + _nameLabel.DrawPosition = GetNameLabelPosition(); - public override void Update(GameTime gameTime) - { - if (!Visible) return; + lock (_rt_locker_) + _npcRenderTarget = _renderTargetFactory.CreateRenderTarget(); - UpdateDrawAreas(); - UpdateStandingFrameAnimation(); - UpdateDeadState(); - DrawToRenderTarget(); + _spriteBatch = new SpriteBatch(Game.GraphicsDevice); - var currentMousePosition = _userInputProvider.CurrentMouseState.Position; + var graphic = _enfFileProvider.ENFFile[NPC.ID].Graphic; + _npcSpriteDataCache.Populate(graphic); + _isBlankSprite = _npcSpriteDataCache.IsBlankSprite(graphic); - if (DrawArea.Contains(currentMousePosition)) - { - var chatBubbleIsVisible = _chatBubble != null && _chatBubble.Visible; - _nameLabel.Visible = !_healthBarRenderer.Visible && !chatBubbleIsVisible && !_isDying && IsClickablePixel(currentMousePosition); - _nameLabel.DrawPosition = GetNameLabelPosition(); + base.Initialize(); } - else - { - _nameLabel.Visible = false; - } - - _effectRenderer.Update(); - _healthBarRenderer.Update(gameTime); - base.Update(gameTime); - } - - public bool IsClickablePixel(Point currentMousePosition) - { - var cachedTexture = _npcSpriteDataCache.GetData(_enfFileProvider.ENFFile[NPC.ID].Graphic, NPC.Frame); - if (!_isBlankSprite && cachedTexture.Length > 0 && _npcRenderTarget.Bounds.Contains(currentMousePosition)) + public override void Update(GameTime gameTime) { - var currentFrame = _npcSpriteSheet.GetNPCTexture(_enfFileProvider.ENFFile[NPC.ID].Graphic, NPC.Frame, NPC.Direction); - - var adjustedPos = currentMousePosition - DrawArea.Location; - var pixel = cachedTexture[adjustedPos.Y * currentFrame.Width + adjustedPos.X]; - - return pixel.A > 0; + if (!Visible) return; + + UpdateDrawAreas(); + UpdateStandingFrameAnimation(); + UpdateDeadState(); + DrawToRenderTarget(); + + var currentMousePosition = _userInputProvider.CurrentMouseState.Position; + + if (DrawArea.Contains(currentMousePosition)) + { + var chatBubbleIsVisible = _chatBubble != null && _chatBubble.Visible; + _nameLabel.Visible = !_healthBarRenderer.Visible && !chatBubbleIsVisible && !_isDying && IsClickablePixel(currentMousePosition); + _nameLabel.DrawPosition = GetNameLabelPosition(); + } + else + { + _nameLabel.Visible = false; + } + + _effectRenderer.Update(); + _healthBarRenderer.Update(gameTime); + + base.Update(gameTime); } - return true; - } + public bool IsClickablePixel(Point currentMousePosition) + { + var cachedTexture = _npcSpriteDataCache.GetData(_enfFileProvider.ENFFile[NPC.ID].Graphic, NPC.Frame); + if (!_isBlankSprite && cachedTexture.Length > 0 && _npcRenderTarget.Bounds.Contains(currentMousePosition)) + { + var currentFrame = _npcSpriteSheet.GetNPCTexture(_enfFileProvider.ENFFile[NPC.ID].Graphic, NPC.Frame, NPC.Direction); - public void DrawToSpriteBatch(SpriteBatch spriteBatch) - { - if (!Visible) return; + var adjustedPos = currentMousePosition - DrawArea.Location; + var pixel = cachedTexture[adjustedPos.Y * currentFrame.Width + adjustedPos.X]; - _effectRenderer.DrawBehindTarget(spriteBatch); - if (_npcRenderTarget != null) - spriteBatch.Draw(_npcRenderTarget, Vector2.Zero, Color.White); - _effectRenderer.DrawInFrontOfTarget(spriteBatch); + return pixel.A > 0; + } - _healthBarRenderer.DrawToSpriteBatch(spriteBatch); - } + return true; + } - public void StartDying() - { - _isDying = true; - } + public void DrawToSpriteBatch(SpriteBatch spriteBatch) + { + if (!Visible) return; - public void ShowDamageCounter(int damage, int percentHealth, bool isHeal) - { - var optionalDamage = damage.SomeWhen(d => d > 0); - _healthBarRenderer.SetDamage(optionalDamage, percentHealth, ShowChatBubble); - _chatBubble?.Hide(); + _effectRenderer.DrawBehindTarget(spriteBatch); + if (_npcRenderTarget != null) + spriteBatch.Draw(_npcRenderTarget, Vector2.Zero, Color.White); + _effectRenderer.DrawInFrontOfTarget(spriteBatch); - void ShowChatBubble() => _chatBubble?.Show(); - } + _healthBarRenderer.DrawToSpriteBatch(spriteBatch); + } - public void ShowChatBubble(string message, bool isGroupChat) - { - if (_chatBubble == null) - _chatBubble = _chatBubbleFactory.CreateChatBubble(this); - _chatBubble.SetMessage(message, isGroupChat: false); - } + public void StartDying() + { + _isDying = true; + } - #region Effects + public void ShowDamageCounter(int damage, int percentHealth, bool isHeal) + { + var optionalDamage = damage.SomeWhen(d => d > 0); + _healthBarRenderer.SetDamage(optionalDamage, percentHealth, ShowChatBubble); + _chatBubble?.Hide(); - public bool EffectIsPlaying() - { - return _effectRenderer.State == EffectState.Playing; - } + void ShowChatBubble() => _chatBubble?.Show(); + } - public void PlayEffect(int graphic) - { - _effectRenderer.PlayEffect(graphic, this); - } + public void ShowChatBubble(string message, bool isGroupChat) + { + if (_chatBubble == null) + _chatBubble = _chatBubbleFactory.CreateChatBubble(this); + _chatBubble.SetMessage(message, isGroupChat: false); + } - #endregion + #region Effects - private Rectangle GetStandingFrameRectangle() - { - var data = _enfFileProvider.ENFFile[NPC.ID]; - var baseFrame = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPCFrame.Standing, EODirection.Down); - return new Rectangle(0, 0, baseFrame.Width, baseFrame.Height); - } + public bool EffectIsPlaying() + { + return _effectRenderer.State == EffectState.Playing; + } - private void UpdateDrawAreas() - { - var data = _enfFileProvider.ENFFile[NPC.ID]; - var frameTexture = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPC.Frame, NPC.Direction); - var metaData = _npcSpriteSheet.GetNPCMetadata(data.Graphic); + public void PlayEffect(int graphic) + { + _effectRenderer.PlayEffect(graphic, this); + } - var isUpOrRight = NPC.IsFacing(EODirection.Up, EODirection.Right) ? -1 : 1; - var isDownOrRight = NPC.IsFacing(EODirection.Down, EODirection.Right) ? -1 : 1; + #endregion - int metaDataOffsetX, metaDataOffsetY; - if (NPC.Frame == NPCFrame.Attack2) + private Rectangle GetStandingFrameRectangle() { - metaDataOffsetX = metaData.AttackOffsetX * isUpOrRight + (metaData.OffsetX * isUpOrRight); - metaDataOffsetY = metaData.AttackOffsetY * isDownOrRight - metaData.OffsetY; + var data = _enfFileProvider.ENFFile[NPC.ID]; + var baseFrame = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPCFrame.Standing, EODirection.Down); + return new Rectangle(0, 0, baseFrame.Width, baseFrame.Height); } - else + + private void UpdateDrawAreas() { - metaDataOffsetX = metaData.OffsetX * isUpOrRight; - metaDataOffsetY = -metaData.OffsetY; + var data = _enfFileProvider.ENFFile[NPC.ID]; + var frameTexture = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPC.Frame, NPC.Direction); + var metaData = _npcSpriteSheet.GetNPCMetadata(data.Graphic); + + var isUpOrRight = NPC.IsFacing(EODirection.Up, EODirection.Right) ? -1 : 1; + var isDownOrRight = NPC.IsFacing(EODirection.Down, EODirection.Right) ? -1 : 1; + + int metaDataOffsetX, metaDataOffsetY; + if (NPC.Frame == NPCFrame.Attack2) + { + metaDataOffsetX = metaData.AttackOffsetX * isUpOrRight + (metaData.OffsetX * isUpOrRight); + metaDataOffsetY = metaData.AttackOffsetY * isDownOrRight - metaData.OffsetY; + } + else + { + metaDataOffsetX = metaData.OffsetX * isUpOrRight; + metaDataOffsetY = -metaData.OffsetY; + } + + var renderCoordinates = _gridDrawCoordinateCalculator.CalculateDrawCoordinates(NPC) + + new Vector2(metaDataOffsetX - frameTexture.Width / 2, metaDataOffsetY - (frameTexture.Height - 23)); + DrawArea = frameTexture.Bounds.WithPosition(renderCoordinates); + + var horizontalOffset = _npcSpriteSheet.GetNPCMetadata(data.Graphic).OffsetX * (NPC.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1); + HorizontalCenter = DrawArea.X + (DrawArea.Width / 2) + horizontalOffset; + + var nameLabelGridCoordinates = _gridDrawCoordinateCalculator.CalculateDrawCoordinates(NPC.WithX(NPC.X - 1).WithY(NPC.Y - 1)); + NameLabelY = (int)nameLabelGridCoordinates.Y - metaData.NameLabelOffset; + + EffectTargetArea = DrawArea.WithSize(DrawArea.Width + horizontalOffset * 2, DrawArea.Height); } - var renderCoordinates = _gridDrawCoordinateCalculator.CalculateDrawCoordinates(NPC) + - new Vector2(metaDataOffsetX - frameTexture.Width / 2, metaDataOffsetY - (frameTexture.Height - 23)); - DrawArea = frameTexture.Bounds.WithPosition(renderCoordinates); - - var horizontalOffset = _npcSpriteSheet.GetNPCMetadata(data.Graphic).OffsetX * (NPC.IsFacing(EODirection.Down, EODirection.Left) ? -1 : 1); - HorizontalCenter = DrawArea.X + (DrawArea.Width / 2) + horizontalOffset; + private void UpdateStandingFrameAnimation() + { + var now = DateTime.Now; - var nameLabelGridCoordinates = _gridDrawCoordinateCalculator.CalculateDrawCoordinates(NPC.WithX(NPC.X - 1).WithY(NPC.Y - 1)); - NameLabelY = (int)nameLabelGridCoordinates.Y - metaData.NameLabelOffset; + var data = _enfFileProvider.ENFFile[NPC.ID]; + var metaData = _npcSpriteSheet.GetNPCMetadata(data.Graphic); - EffectTargetArea = DrawArea.WithSize(DrawArea.Width + horizontalOffset * 2, DrawArea.Height); - } + if (!metaData.HasStandingFrameAnimation + || !NPC.IsActing(NPCActionState.Standing) + || (now - _lastStandingAnimation).TotalMilliseconds < 250) + return; - private void UpdateStandingFrameAnimation() - { - var now = DateTime.Now; + _lastStandingAnimation = now; + NPC = NPC.WithFrame(NPC.Frame == NPCFrame.Standing ? NPCFrame.StandingFrame1 : NPCFrame.Standing); + } - var data = _enfFileProvider.ENFFile[NPC.ID]; - var metaData = _npcSpriteSheet.GetNPCMetadata(data.Graphic); + private void UpdateDeadState() + { + if (!_isDying) return; - if (!metaData.HasStandingFrameAnimation - || !NPC.IsActing(NPCActionState.Standing) - || (now - _lastStandingAnimation).TotalMilliseconds < 250) - return; + if (_fadeAwayAlpha >= 3) + _fadeAwayAlpha -= 3; + IsDead = _fadeAwayAlpha <= 0 && !EffectIsPlaying(); + } - _lastStandingAnimation = now; - NPC = NPC.WithFrame(NPC.Frame == NPCFrame.Standing ? NPCFrame.StandingFrame1 : NPCFrame.Standing); - } + private void DrawToRenderTarget() + { + if (_npcRenderTarget == null) + return; - private void UpdateDeadState() - { - if (!_isDying) return; + var data = _enfFileProvider.ENFFile[NPC.ID]; + var texture = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPC.Frame, NPC.Direction); - if (_fadeAwayAlpha >= 3) - _fadeAwayAlpha -= 3; - IsDead = _fadeAwayAlpha <= 0 && !EffectIsPlaying(); - } + var color = Color.FromNonPremultiplied(255, 255, 255, _fadeAwayAlpha); + var effects = NPC.IsFacing(EODirection.Left, EODirection.Down) ? SpriteEffects.None : SpriteEffects.FlipHorizontally; - private void DrawToRenderTarget() - { - if (_npcRenderTarget == null) - return; + lock (_rt_locker_) + { + GraphicsDevice.SetRenderTarget(_npcRenderTarget); + GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 1, 0); - var data = _enfFileProvider.ENFFile[NPC.ID]; - var texture = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPC.Frame, NPC.Direction); + _spriteBatch.Begin(); + _spriteBatch.Draw(texture, DrawArea, null, color, 0, Vector2.Zero, effects, 1); + _spriteBatch.End(); - var color = Color.FromNonPremultiplied(255, 255, 255, _fadeAwayAlpha); - var effects = NPC.IsFacing(EODirection.Left, EODirection.Down) ? SpriteEffects.None : SpriteEffects.FlipHorizontally; + GraphicsDevice.SetRenderTarget(null); + } + } - lock (_rt_locker_) + private void RecreateRenderTarget(object sender, EventArgs e) { - GraphicsDevice.SetRenderTarget(_npcRenderTarget); - GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 1, 0); - - _spriteBatch.Begin(); - _spriteBatch.Draw(texture, DrawArea, null, color, 0, Vector2.Zero, effects, 1); - _spriteBatch.End(); - - GraphicsDevice.SetRenderTarget(null); + lock (_rt_locker_) + { + _npcRenderTarget.Dispose(); + _npcRenderTarget = _renderTargetFactory.CreateRenderTarget(); + } } - } - private void RecreateRenderTarget(object sender, EventArgs e) - { - lock (_rt_locker_) + private Vector2 GetNameLabelPosition() { - _npcRenderTarget.Dispose(); - _npcRenderTarget = _renderTargetFactory.CreateRenderTarget(); + return new Vector2(HorizontalCenter - (_nameLabel.ActualWidth / 2f), NameLabelY); } - } - - private Vector2 GetNameLabelPosition() - { - return new Vector2(HorizontalCenter - (_nameLabel.ActualWidth / 2f), NameLabelY); - } - protected override void Dispose(bool disposing) - { - if (disposing) + protected override void Dispose(bool disposing) { - _nameLabel.Dispose(); - _chatBubble?.Dispose(); - _spriteBatch?.Dispose(); + if (disposing) + { + _nameLabel.Dispose(); + _chatBubble?.Dispose(); + _spriteBatch?.Dispose(); - lock (_rt_locker_) - _npcRenderTarget?.Dispose(); + lock (_rt_locker_) + _npcRenderTarget?.Dispose(); - _clientWindowSizeProvider.GameWindowSizeChanged -= RecreateRenderTarget; - } + _clientWindowSizeProvider.GameWindowSizeChanged -= RecreateRenderTarget; + } - base.Dispose(disposing); + base.Dispose(disposing); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRendererFactory.cs b/EndlessClient/Rendering/NPC/NPCRendererFactory.cs index e362038de..882dab75b 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererFactory.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererFactory.cs @@ -7,66 +7,67 @@ using EndlessClient.Rendering.Sprites; using EOLib.IO.Repositories; -namespace EndlessClient.Rendering.NPC; - -[AutoMappedType] -public class NPCRendererFactory : INPCRendererFactory +namespace EndlessClient.Rendering.NPC { - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly IENFFileProvider _enfFileProvider; - private readonly INPCSpriteSheet _npcSpriteSheet; - private readonly INPCSpriteDataCache _npcSpriteDataCache; - private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; - private readonly IHealthBarRendererFactory _healthBarRendererFactory; - private readonly IChatBubbleFactory _chatBubbleFactory; - private readonly IRenderTargetFactory _renderTargetFactory; - private readonly IUserInputProvider _userInputProvider; - private readonly IEffectRendererFactory _effectRendererFactory; - - public NPCRendererFactory(IEndlessGameProvider endlessGameProvider, - IClientWindowSizeProvider clientWindowSizeProvider, - IENFFileProvider enfFileProvider, - INPCSpriteSheet npcSpriteSheet, - INPCSpriteDataCache npcSpriteDataCache, - IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, - IHealthBarRendererFactory healthBarRendererFactory, - IChatBubbleFactory chatBubbleFactory, - IRenderTargetFactory renderTargetFactory, - IUserInputProvider userInputProvider, - IEffectRendererFactory effectRendererFactory) + [AutoMappedType] + public class NPCRendererFactory : INPCRendererFactory { - _endlessGameProvider = endlessGameProvider; - _clientWindowSizeProvider = clientWindowSizeProvider; - _enfFileProvider = enfFileProvider; - _npcSpriteSheet = npcSpriteSheet; - _npcSpriteDataCache = npcSpriteDataCache; - _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; - _healthBarRendererFactory = healthBarRendererFactory; - _chatBubbleFactory = chatBubbleFactory; - _renderTargetFactory = renderTargetFactory; - _userInputProvider = userInputProvider; - _effectRendererFactory = effectRendererFactory; + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly IENFFileProvider _enfFileProvider; + private readonly INPCSpriteSheet _npcSpriteSheet; + private readonly INPCSpriteDataCache _npcSpriteDataCache; + private readonly IGridDrawCoordinateCalculator _gridDrawCoordinateCalculator; + private readonly IHealthBarRendererFactory _healthBarRendererFactory; + private readonly IChatBubbleFactory _chatBubbleFactory; + private readonly IRenderTargetFactory _renderTargetFactory; + private readonly IUserInputProvider _userInputProvider; + private readonly IEffectRendererFactory _effectRendererFactory; + + public NPCRendererFactory(IEndlessGameProvider endlessGameProvider, + IClientWindowSizeProvider clientWindowSizeProvider, + IENFFileProvider enfFileProvider, + INPCSpriteSheet npcSpriteSheet, + INPCSpriteDataCache npcSpriteDataCache, + IGridDrawCoordinateCalculator gridDrawCoordinateCalculator, + IHealthBarRendererFactory healthBarRendererFactory, + IChatBubbleFactory chatBubbleFactory, + IRenderTargetFactory renderTargetFactory, + IUserInputProvider userInputProvider, + IEffectRendererFactory effectRendererFactory) + { + _endlessGameProvider = endlessGameProvider; + _clientWindowSizeProvider = clientWindowSizeProvider; + _enfFileProvider = enfFileProvider; + _npcSpriteSheet = npcSpriteSheet; + _npcSpriteDataCache = npcSpriteDataCache; + _gridDrawCoordinateCalculator = gridDrawCoordinateCalculator; + _healthBarRendererFactory = healthBarRendererFactory; + _chatBubbleFactory = chatBubbleFactory; + _renderTargetFactory = renderTargetFactory; + _userInputProvider = userInputProvider; + _effectRendererFactory = effectRendererFactory; + } + + public INPCRenderer CreateRendererFor(EOLib.Domain.NPC.NPC npc) + { + return new NPCRenderer(_endlessGameProvider, + _clientWindowSizeProvider, + _enfFileProvider, + _npcSpriteSheet, + _npcSpriteDataCache, + _gridDrawCoordinateCalculator, + _healthBarRendererFactory, + _chatBubbleFactory, + _renderTargetFactory, + _userInputProvider, + _effectRendererFactory, + npc); + } } - public INPCRenderer CreateRendererFor(EOLib.Domain.NPC.NPC npc) + public interface INPCRendererFactory { - return new NPCRenderer(_endlessGameProvider, - _clientWindowSizeProvider, - _enfFileProvider, - _npcSpriteSheet, - _npcSpriteDataCache, - _gridDrawCoordinateCalculator, - _healthBarRendererFactory, - _chatBubbleFactory, - _renderTargetFactory, - _userInputProvider, - _effectRendererFactory, - npc); + INPCRenderer CreateRendererFor(EOLib.Domain.NPC.NPC npc); } -} - -public interface INPCRendererFactory -{ - INPCRenderer CreateRendererFor(EOLib.Domain.NPC.NPC npc); } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRendererRepository.cs b/EndlessClient/Rendering/NPC/NPCRendererRepository.cs index 611913026..d6f93a73c 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererRepository.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererRepository.cs @@ -3,45 +3,46 @@ using System; using System.Collections.Generic; -namespace EndlessClient.Rendering.NPC; - -public interface INPCRendererRepository : IDisposable +namespace EndlessClient.Rendering.NPC { - Dictionary NPCRenderers { get; set; } + public interface INPCRendererRepository : IDisposable + { + Dictionary NPCRenderers { get; set; } - Dictionary DyingNPCs { get; set; } -} + Dictionary DyingNPCs { get; set; } + } -public interface INPCRendererProvider -{ - IReadOnlyDictionary NPCRenderers { get; } + public interface INPCRendererProvider + { + IReadOnlyDictionary NPCRenderers { get; } - IReadOnlyDictionary DyingNPCs { get; } -} + IReadOnlyDictionary DyingNPCs { get; } + } -[AutoMappedType(IsSingleton = true)] -public class NPCRendererRepository : INPCRendererRepository, INPCRendererProvider -{ - public Dictionary NPCRenderers { get; set; } + [AutoMappedType(IsSingleton = true)] + public class NPCRendererRepository : INPCRendererRepository, INPCRendererProvider + { + public Dictionary NPCRenderers { get; set; } - public Dictionary DyingNPCs { get; set; } + public Dictionary DyingNPCs { get; set; } - IReadOnlyDictionary INPCRendererProvider.NPCRenderers => NPCRenderers; + IReadOnlyDictionary INPCRendererProvider.NPCRenderers => NPCRenderers; - IReadOnlyDictionary INPCRendererProvider.DyingNPCs => DyingNPCs; + IReadOnlyDictionary INPCRendererProvider.DyingNPCs => DyingNPCs; - public NPCRendererRepository() - { - NPCRenderers = new Dictionary(); - DyingNPCs = new Dictionary(); - } + public NPCRendererRepository() + { + NPCRenderers = new Dictionary(); + DyingNPCs = new Dictionary(); + } - public void Dispose() - { - foreach (var renderer in NPCRenderers.Values) - renderer.Dispose(); - NPCRenderers.Clear(); + public void Dispose() + { + foreach (var renderer in NPCRenderers.Values) + renderer.Dispose(); + NPCRenderers.Clear(); - DyingNPCs.Clear(); + DyingNPCs.Clear(); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs b/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs index 1f39ce3ca..be61aa056 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs @@ -5,128 +5,129 @@ using System; using System.Linq; -namespace EndlessClient.Rendering.NPC; - -[AutoMappedType] -public class NPCRendererUpdater : INPCRendererUpdater +namespace EndlessClient.Rendering.NPC { - private readonly ICurrentMapStateProvider _currentMapStateProvider; - private readonly INPCRendererRepository _npcRendererRepository; - private readonly INPCStateCache _npcStateCache; - private readonly INPCRendererFactory _npcRendererFactory; - - public NPCRendererUpdater(ICurrentMapStateProvider currentMapStateProvider, - INPCRendererRepository npcRendererRepository, - INPCStateCache npcStateCache, - INPCRendererFactory npcRendererFactory) + [AutoMappedType] + public class NPCRendererUpdater : INPCRendererUpdater { - _currentMapStateProvider = currentMapStateProvider; - _npcRendererRepository = npcRendererRepository; - _npcStateCache = npcStateCache; - _npcRendererFactory = npcRendererFactory; - } - - public void UpdateNPCs(GameTime gameTime) - { - CleanUpDeadNPCs(); - CleanUpRemovedNPCs(); - CreateAndCacheNPCRenderers(); - UpdateNPCRenderers(gameTime); - } - - private void CleanUpDeadNPCs() - { - var deadNPCs = _npcRendererRepository.NPCRenderers.Values.Where(x => x.IsDead).ToList(); - if (!deadNPCs.Any()) - return; - - foreach (var npc in deadNPCs) + private readonly ICurrentMapStateProvider _currentMapStateProvider; + private readonly INPCRendererRepository _npcRendererRepository; + private readonly INPCStateCache _npcStateCache; + private readonly INPCRendererFactory _npcRendererFactory; + + public NPCRendererUpdater(ICurrentMapStateProvider currentMapStateProvider, + INPCRendererRepository npcRendererRepository, + INPCStateCache npcStateCache, + INPCRendererFactory npcRendererFactory) { - npc.Dispose(); - _npcRendererRepository.NPCRenderers.Remove(npc.NPC.Index); - _npcRendererRepository.DyingNPCs.Remove(new MapCoordinate(npc.NPC.X, npc.NPC.Y)); - _npcStateCache.RemoveStateByIndex(npc.NPC.Index); + _currentMapStateProvider = currentMapStateProvider; + _npcRendererRepository = npcRendererRepository; + _npcStateCache = npcStateCache; + _npcRendererFactory = npcRendererFactory; } - } - private void CleanUpRemovedNPCs() - { - var removedNPCs = _npcRendererRepository.NPCRenderers.Values - .Where(x => x.IsAlive) - .Select(x => x.NPC.Index) - .Where(x => !_currentMapStateProvider.NPCs.Select(y => y.Index).Any(y => y == x)) - .ToList(); + public void UpdateNPCs(GameTime gameTime) + { + CleanUpDeadNPCs(); + CleanUpRemovedNPCs(); + CreateAndCacheNPCRenderers(); + UpdateNPCRenderers(gameTime); + } - foreach (var index in removedNPCs) + private void CleanUpDeadNPCs() { - if (!_npcRendererRepository.NPCRenderers.TryGetValue(index, out var renderer)) - continue; + var deadNPCs = _npcRendererRepository.NPCRenderers.Values.Where(x => x.IsDead).ToList(); + if (!deadNPCs.Any()) + return; + + foreach (var npc in deadNPCs) + { + npc.Dispose(); + _npcRendererRepository.NPCRenderers.Remove(npc.NPC.Index); + _npcRendererRepository.DyingNPCs.Remove(new MapCoordinate(npc.NPC.X, npc.NPC.Y)); + _npcStateCache.RemoveStateByIndex(npc.NPC.Index); + } + } - renderer.Dispose(); - _npcRendererRepository.NPCRenderers.Remove(index); - _npcStateCache.RemoveStateByIndex(index); + private void CleanUpRemovedNPCs() + { + var removedNPCs = _npcRendererRepository.NPCRenderers.Values + .Where(x => x.IsAlive) + .Select(x => x.NPC.Index) + .Where(x => !_currentMapStateProvider.NPCs.Select(y => y.Index).Any(y => y == x)) + .ToList(); + + foreach (var index in removedNPCs) + { + if (!_npcRendererRepository.NPCRenderers.TryGetValue(index, out var renderer)) + continue; + + renderer.Dispose(); + _npcRendererRepository.NPCRenderers.Remove(index); + _npcStateCache.RemoveStateByIndex(index); + } } - } - private void CreateAndCacheNPCRenderers() - { - foreach (var npc in _currentMapStateProvider.NPCs) + private void CreateAndCacheNPCRenderers() { - _npcStateCache.HasNPCStateWithIndex(npc.Index) - .SomeWhen(b => b) - .Map(_ => _npcStateCache.NPCStates[npc.Index]) - .Match( - some: n => - { - if (n != npc) + foreach (var npc in _currentMapStateProvider.NPCs) + { + _npcStateCache.HasNPCStateWithIndex(npc.Index) + .SomeWhen(b => b) + .Map(_ => _npcStateCache.NPCStates[npc.Index]) + .Match( + some: n => { - UpdateCachedNPC(npc); - } - }, - none: () => CreateAndCacheRendererForNPC(npc)); + if (n != npc) + { + UpdateCachedNPC(npc); + } + }, + none: () => CreateAndCacheRendererForNPC(npc)); + } } - } - private void CreateAndCacheRendererForNPC(EOLib.Domain.NPC.NPC npc) - { - _npcStateCache.UpdateNPCState(npc.Index, npc); + private void CreateAndCacheRendererForNPC(EOLib.Domain.NPC.NPC npc) + { + _npcStateCache.UpdateNPCState(npc.Index, npc); - var renderer = _npcRendererFactory.CreateRendererFor(npc); - renderer.Initialize(); + var renderer = _npcRendererFactory.CreateRendererFor(npc); + renderer.Initialize(); - if (_npcRendererRepository.NPCRenderers.ContainsKey(npc.Index) && - _npcRendererRepository.NPCRenderers[npc.Index] != null) - { - _npcRendererRepository.NPCRenderers[npc.Index].Dispose(); - _npcRendererRepository.NPCRenderers.Remove(npc.Index); + if (_npcRendererRepository.NPCRenderers.ContainsKey(npc.Index) && + _npcRendererRepository.NPCRenderers[npc.Index] != null) + { + _npcRendererRepository.NPCRenderers[npc.Index].Dispose(); + _npcRendererRepository.NPCRenderers.Remove(npc.Index); + } + + _npcRendererRepository.NPCRenderers.Add(npc.Index, renderer); } - _npcRendererRepository.NPCRenderers.Add(npc.Index, renderer); - } + private void UpdateCachedNPC(EOLib.Domain.NPC.NPC npc) + { + if (_npcRendererRepository.NPCRenderers.ContainsKey(npc.Index)) + { + _npcRendererRepository.NPCRenderers[npc.Index].NPC = npc; + _npcStateCache.UpdateNPCState(npc.Index, npc); + } + } - private void UpdateCachedNPC(EOLib.Domain.NPC.NPC npc) - { - if (_npcRendererRepository.NPCRenderers.ContainsKey(npc.Index)) + private void UpdateNPCRenderers(GameTime gameTime) { - _npcRendererRepository.NPCRenderers[npc.Index].NPC = npc; - _npcStateCache.UpdateNPCState(npc.Index, npc); + foreach (var renderer in _npcRendererRepository.NPCRenderers.Values) + renderer.Update(gameTime); } - } - private void UpdateNPCRenderers(GameTime gameTime) - { - foreach (var renderer in _npcRendererRepository.NPCRenderers.Values) - renderer.Update(gameTime); + public void Dispose() + { + _npcStateCache.Reset(); + _npcRendererRepository.Dispose(); + } } - public void Dispose() + public interface INPCRendererUpdater : IDisposable { - _npcStateCache.Reset(); - _npcRendererRepository.Dispose(); + void UpdateNPCs(GameTime gameTime); } -} - -public interface INPCRendererUpdater : IDisposable -{ - void UpdateNPCs(GameTime gameTime); } \ No newline at end of file diff --git a/EndlessClient/Rendering/PlayerStatusIconRenderer.cs b/EndlessClient/Rendering/PlayerStatusIconRenderer.cs index 298d71f52..7b984422f 100644 --- a/EndlessClient/Rendering/PlayerStatusIconRenderer.cs +++ b/EndlessClient/Rendering/PlayerStatusIconRenderer.cs @@ -7,96 +7,97 @@ using System; using XNAControls; -namespace EndlessClient.Rendering; - -public sealed class PlayerStatusIconRenderer : XNAControl +namespace EndlessClient.Rendering { - [Flags] - private enum StatusIconType - { - Weapon = 1, - Shield = 2, - Spell = 4, - PK = 8 - } - - private static readonly StatusIconType[] _orderedValues = + public sealed class PlayerStatusIconRenderer : XNAControl { - StatusIconType.PK, - StatusIconType.Spell, - StatusIconType.Weapon, - StatusIconType.Shield - }; + [Flags] + private enum StatusIconType + { + Weapon = 1, + Shield = 2, + Spell = 4, + PK = 8 + } - private readonly ICharacterProvider _characterProvider; - private readonly ISpellSlotDataProvider _spellSlotDataProvider; - private readonly ICurrentMapProvider _currentMapProvider; + private static readonly StatusIconType[] _orderedValues = + { + StatusIconType.PK, + StatusIconType.Spell, + StatusIconType.Weapon, + StatusIconType.Shield + }; - private readonly Texture2D _statusIcons; + private readonly ICharacterProvider _characterProvider; + private readonly ISpellSlotDataProvider _spellSlotDataProvider; + private readonly ICurrentMapProvider _currentMapProvider; - private StatusIconType _icons; + private readonly Texture2D _statusIcons; - public PlayerStatusIconRenderer(INativeGraphicsManager nativeGraphicsManager, - ICharacterProvider characterProvider, - ISpellSlotDataProvider spellSlotDataProvider, - ICurrentMapProvider currentMapProvider, - IClientWindowSizeProvider clientWindowSizeProvider) - { - _characterProvider = characterProvider; - _spellSlotDataProvider = spellSlotDataProvider; - _currentMapProvider = currentMapProvider; + private StatusIconType _icons; - _statusIcons = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 46, true); + public PlayerStatusIconRenderer(INativeGraphicsManager nativeGraphicsManager, + ICharacterProvider characterProvider, + ISpellSlotDataProvider spellSlotDataProvider, + ICurrentMapProvider currentMapProvider, + IClientWindowSizeProvider clientWindowSizeProvider) + { + _characterProvider = characterProvider; + _spellSlotDataProvider = spellSlotDataProvider; + _currentMapProvider = currentMapProvider; - DrawPosition = new Vector2(14, clientWindowSizeProvider.Height - _statusIcons.Height - 3); - clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => DrawPosition = new Vector2(14, clientWindowSizeProvider.Height - _statusIcons.Height - 3); - } + _statusIcons = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 46, true); - protected override void OnUpdateControl(GameTime gameTime) - { - var c = _characterProvider.MainCharacter; - - _icons = 0; - if (_currentMapProvider.CurrentMap.Properties.PKAvailable) - _icons |= StatusIconType.PK; - if (_spellSlotDataProvider.SelectedSpellSlot.HasValue) - _icons |= StatusIconType.Spell; - if (c.RenderProperties.WeaponGraphic > 0) - _icons |= StatusIconType.Weapon; - if (c.RenderProperties.ShieldGraphic > 0) - _icons |= StatusIconType.Shield; - - base.OnUpdateControl(gameTime); - } + DrawPosition = new Vector2(14, clientWindowSizeProvider.Height - _statusIcons.Height - 3); + clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => DrawPosition = new Vector2(14, clientWindowSizeProvider.Height - _statusIcons.Height - 3); + } - protected override void OnDrawControl(GameTime gt) - { - _spriteBatch.Begin(); + protected override void OnUpdateControl(GameTime gameTime) + { + var c = _characterProvider.MainCharacter; + + _icons = 0; + if (_currentMapProvider.CurrentMap.Properties.PKAvailable) + _icons |= StatusIconType.PK; + if (_spellSlotDataProvider.SelectedSpellSlot.HasValue) + _icons |= StatusIconType.Spell; + if (c.RenderProperties.WeaponGraphic > 0) + _icons |= StatusIconType.Weapon; + if (c.RenderProperties.ShieldGraphic > 0) + _icons |= StatusIconType.Shield; + + base.OnUpdateControl(gameTime); + } - int extraOffset = 0; - foreach (var icon in _orderedValues) + protected override void OnDrawControl(GameTime gt) { - if ((_icons & icon) > 0) + _spriteBatch.Begin(); + + int extraOffset = 0; + foreach (var icon in _orderedValues) { - _spriteBatch.Draw(_statusIcons, DrawPositionWithParentOffset + new Vector2(extraOffset, 0), GetSourceRectangle(icon), Color.FromNonPremultiplied(0x9e, 0x9f, 0x9e, 0xff)); - extraOffset += 24; + if ((_icons & icon) > 0) + { + _spriteBatch.Draw(_statusIcons, DrawPositionWithParentOffset + new Vector2(extraOffset, 0), GetSourceRectangle(icon), Color.FromNonPremultiplied(0x9e, 0x9f, 0x9e, 0xff)); + extraOffset += 24; + } } - } - _spriteBatch.End(); + _spriteBatch.End(); - base.OnDrawControl(gt); - } + base.OnDrawControl(gt); + } - private Rectangle GetSourceRectangle(StatusIconType type) - { - var widthDelta = _statusIcons.Width / 4; - var heightDelta = _statusIcons.Height / 2; + private Rectangle GetSourceRectangle(StatusIconType type) + { + var widthDelta = _statusIcons.Width / 4; + var heightDelta = _statusIcons.Height / 2; - //convert from power of two 'flag' value to base 10 index - var index = (int)Math.Log((int)type, 2); + //convert from power of two 'flag' value to base 10 index + var index = (int)Math.Log((int)type, 2); - var xOffset = widthDelta * index; - return new Rectangle(xOffset, 0, widthDelta, heightDelta); + var xOffset = widthDelta * index; + return new Rectangle(xOffset, 0, widthDelta, heightDelta); + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/PointComparer.cs b/EndlessClient/Rendering/PointComparer.cs index 43ce7f645..eadbb3f36 100644 --- a/EndlessClient/Rendering/PointComparer.cs +++ b/EndlessClient/Rendering/PointComparer.cs @@ -1,16 +1,17 @@ using Microsoft.Xna.Framework; using System.Collections.Generic; -namespace EndlessClient.Rendering; - -public class PointComparer : IComparer +namespace EndlessClient.Rendering { - public int Compare(Point a, Point b) + public class PointComparer : IComparer { - if (a.Y < b.Y || a.X < b.X) - return -1; - if (a.Y > b.Y || a.X > b.X) - return 1; - return 0; + public int Compare(Point a, Point b) + { + if (a.Y < b.Y || a.X < b.X) + return -1; + if (a.Y > b.Y || a.X > b.X) + return 1; + return 0; + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/RenderFrameActionTime.cs b/EndlessClient/Rendering/RenderFrameActionTime.cs index 3f32d6fa4..a4ee2626b 100644 --- a/EndlessClient/Rendering/RenderFrameActionTime.cs +++ b/EndlessClient/Rendering/RenderFrameActionTime.cs @@ -1,39 +1,40 @@ using System; -namespace EndlessClient.Rendering; - -public class RenderFrameActionTime +namespace EndlessClient.Rendering { - private Action _sfxCallback; + public class RenderFrameActionTime + { + private Action _sfxCallback; - public int UniqueID { get; private set; } + public int UniqueID { get; private set; } - public ulong ActionTick { get; private set; } + public ulong ActionTick { get; private set; } - public bool Replay { get; private set; } + public bool Replay { get; private set; } - public RenderFrameActionTime(int uniqueID, ulong ticks, Action sfxCallback = null) - { - UniqueID = uniqueID; - _sfxCallback = sfxCallback; - UpdateActionStartTime(ticks); - } + public RenderFrameActionTime(int uniqueID, ulong ticks, Action sfxCallback = null) + { + UniqueID = uniqueID; + _sfxCallback = sfxCallback; + UpdateActionStartTime(ticks); + } - public void UpdateActionStartTime(ulong ticks) - { - ActionTick = ticks; - } + public void UpdateActionStartTime(ulong ticks) + { + ActionTick = ticks; + } - public void SetReplay(Action sfxCallback = null) - { - _sfxCallback = sfxCallback; - Replay = true; - } + public void SetReplay(Action sfxCallback = null) + { + _sfxCallback = sfxCallback; + Replay = true; + } - public void ClearReplay() - { - Replay = false; - } + public void ClearReplay() + { + Replay = false; + } - public void SoundEffect() => _sfxCallback?.Invoke(); + public void SoundEffect() => _sfxCallback?.Invoke(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/RenderOffsetCalculator.cs b/EndlessClient/Rendering/RenderOffsetCalculator.cs index 47d44665e..6bbc5432a 100644 --- a/EndlessClient/Rendering/RenderOffsetCalculator.cs +++ b/EndlessClient/Rendering/RenderOffsetCalculator.cs @@ -5,92 +5,93 @@ using EOLib.Domain.Map; using EOLib.Domain.NPC; -namespace EndlessClient.Rendering; - -[MappedType(BaseType = typeof(IRenderOffsetCalculator))] -public class RenderOffsetCalculator : IRenderOffsetCalculator +namespace EndlessClient.Rendering { - private const int WidthFactor = 32; - private const int HeightFactor = 16; - private const int WalkWidthFactor = WidthFactor / 4; - private const int WalkHeightFactor = HeightFactor / 4; - - public int CalculateOffsetX(CharacterRenderProperties properties) - { - return properties.MapX * WidthFactor - properties.MapY * WidthFactor + CalculateWalkAdjustX(properties); - } - - public int CalculateWalkAdjustX(CharacterRenderProperties properties) - { - var multiplier = properties.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; - var walkAdjust = properties.IsActing(CharacterActionState.Walking) ? WalkWidthFactor * properties.ActualWalkFrame : 0; - return walkAdjust * multiplier; - } - - public int CalculateOffsetY(CharacterRenderProperties properties) + [MappedType(BaseType = typeof(IRenderOffsetCalculator))] + public class RenderOffsetCalculator : IRenderOffsetCalculator { - return properties.MapX * HeightFactor + properties.MapY * HeightFactor + CalculateWalkAdjustY(properties); + private const int WidthFactor = 32; + private const int HeightFactor = 16; + private const int WalkWidthFactor = WidthFactor / 4; + private const int WalkHeightFactor = HeightFactor / 4; + + public int CalculateOffsetX(CharacterRenderProperties properties) + { + return properties.MapX * WidthFactor - properties.MapY * WidthFactor + CalculateWalkAdjustX(properties); + } + + public int CalculateWalkAdjustX(CharacterRenderProperties properties) + { + var multiplier = properties.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; + var walkAdjust = properties.IsActing(CharacterActionState.Walking) ? WalkWidthFactor * properties.ActualWalkFrame : 0; + return walkAdjust * multiplier; + } + + public int CalculateOffsetY(CharacterRenderProperties properties) + { + return properties.MapX * HeightFactor + properties.MapY * HeightFactor + CalculateWalkAdjustY(properties); + } + + public int CalculateWalkAdjustY(CharacterRenderProperties properties) + { + var multiplier = properties.IsFacing(EODirection.Left, EODirection.Up) ? -1 : 1; + var walkAdjust = properties.IsActing(CharacterActionState.Walking) ? WalkHeightFactor * properties.ActualWalkFrame : 0; + return walkAdjust * multiplier; + } + + public int CalculateOffsetX(EOLib.Domain.NPC.NPC npc) + { + return npc.X * WidthFactor - npc.Y * WidthFactor + CalculateWalkAdjustX(npc); + } + + public int CalculateWalkAdjustX(EOLib.Domain.NPC.NPC npc) + { + var multiplier = npc.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; + var walkAdjust = npc.IsActing(NPCActionState.Walking) ? WalkWidthFactor * npc.GetWalkFrame() : 0; + + return walkAdjust * multiplier; + } + + public int CalculateOffsetY(EOLib.Domain.NPC.NPC npc) + { + return npc.X * HeightFactor + npc.Y * HeightFactor + CalculateWalkAdjustY(npc); + } + + public int CalculateWalkAdjustY(EOLib.Domain.NPC.NPC npc) + { + var multiplier = npc.IsFacing(EODirection.Left, EODirection.Up) ? -1 : 1; + var walkAdjust = npc.IsActing(NPCActionState.Walking) ? WalkHeightFactor * npc.GetWalkFrame() : 0; + + return walkAdjust * multiplier; + } + + public int CalculateOffsetX(MapCoordinate coordinate) + { + return coordinate.X * WidthFactor - coordinate.Y * WidthFactor; + } + + public int CalculateOffsetY(MapCoordinate coordinate) + { + return coordinate.X * HeightFactor + coordinate.Y * HeightFactor; + } } - public int CalculateWalkAdjustY(CharacterRenderProperties properties) + public interface IRenderOffsetCalculator { - var multiplier = properties.IsFacing(EODirection.Left, EODirection.Up) ? -1 : 1; - var walkAdjust = properties.IsActing(CharacterActionState.Walking) ? WalkHeightFactor * properties.ActualWalkFrame : 0; - return walkAdjust * multiplier; - } - - public int CalculateOffsetX(EOLib.Domain.NPC.NPC npc) - { - return npc.X * WidthFactor - npc.Y * WidthFactor + CalculateWalkAdjustX(npc); - } - - public int CalculateWalkAdjustX(EOLib.Domain.NPC.NPC npc) - { - var multiplier = npc.IsFacing(EODirection.Left, EODirection.Down) ? -1 : 1; - var walkAdjust = npc.IsActing(NPCActionState.Walking) ? WalkWidthFactor * npc.GetWalkFrame() : 0; - - return walkAdjust * multiplier; - } + int CalculateOffsetX(CharacterRenderProperties properties); + int CalculateWalkAdjustX(CharacterRenderProperties properties); - public int CalculateOffsetY(EOLib.Domain.NPC.NPC npc) - { - return npc.X * HeightFactor + npc.Y * HeightFactor + CalculateWalkAdjustY(npc); - } + int CalculateOffsetY(CharacterRenderProperties properties); + int CalculateWalkAdjustY(CharacterRenderProperties properties); - public int CalculateWalkAdjustY(EOLib.Domain.NPC.NPC npc) - { - var multiplier = npc.IsFacing(EODirection.Left, EODirection.Up) ? -1 : 1; - var walkAdjust = npc.IsActing(NPCActionState.Walking) ? WalkHeightFactor * npc.GetWalkFrame() : 0; + int CalculateOffsetX(EOLib.Domain.NPC.NPC npc); + int CalculateWalkAdjustX(EOLib.Domain.NPC.NPC npc); - return walkAdjust * multiplier; - } + int CalculateOffsetY(EOLib.Domain.NPC.NPC npc); + int CalculateWalkAdjustY(EOLib.Domain.NPC.NPC npc); - public int CalculateOffsetX(MapCoordinate coordinate) - { - return coordinate.X * WidthFactor - coordinate.Y * WidthFactor; - } + int CalculateOffsetX(MapCoordinate coordinate); - public int CalculateOffsetY(MapCoordinate coordinate) - { - return coordinate.X * HeightFactor + coordinate.Y * HeightFactor; + int CalculateOffsetY(MapCoordinate coordinate); } -} - -public interface IRenderOffsetCalculator -{ - int CalculateOffsetX(CharacterRenderProperties properties); - int CalculateWalkAdjustX(CharacterRenderProperties properties); - - int CalculateOffsetY(CharacterRenderProperties properties); - int CalculateWalkAdjustY(CharacterRenderProperties properties); - - int CalculateOffsetX(EOLib.Domain.NPC.NPC npc); - int CalculateWalkAdjustX(EOLib.Domain.NPC.NPC npc); - - int CalculateOffsetY(EOLib.Domain.NPC.NPC npc); - int CalculateWalkAdjustY(EOLib.Domain.NPC.NPC npc); - - int CalculateOffsetX(MapCoordinate coordinate); - - int CalculateOffsetY(MapCoordinate coordinate); } \ No newline at end of file diff --git a/EndlessClient/Rendering/RendererRepositoryResetter.cs b/EndlessClient/Rendering/RendererRepositoryResetter.cs index 996309c30..1a00ae3ab 100644 --- a/EndlessClient/Rendering/RendererRepositoryResetter.cs +++ b/EndlessClient/Rendering/RendererRepositoryResetter.cs @@ -3,38 +3,39 @@ using EndlessClient.Rendering.Chat; using EndlessClient.Rendering.NPC; -namespace EndlessClient.Rendering; - -[MappedType(BaseType = typeof(IRendererRepositoryResetter))] -public class RendererRepositoryResetter : IRendererRepositoryResetter +namespace EndlessClient.Rendering { - private readonly ICharacterRendererRepository _characterRendererRepository; - private readonly INPCRendererRepository _npcRendererRepository; - private readonly ICharacterStateCache _characterStateCache; - private readonly INPCStateCache _npcStateCache; - - public RendererRepositoryResetter(ICharacterRendererRepository characterRendererRepository, - INPCRendererRepository npcRendererRepository, - ICharacterStateCache characterStateCache, - INPCStateCache npcStateCache) + [MappedType(BaseType = typeof(IRendererRepositoryResetter))] + public class RendererRepositoryResetter : IRendererRepositoryResetter { - _characterRendererRepository = characterRendererRepository; - _npcRendererRepository = npcRendererRepository; - _characterStateCache = characterStateCache; - _npcStateCache = npcStateCache; - } + private readonly ICharacterRendererRepository _characterRendererRepository; + private readonly INPCRendererRepository _npcRendererRepository; + private readonly ICharacterStateCache _characterStateCache; + private readonly INPCStateCache _npcStateCache; - public void ResetRenderers() - { - _characterRendererRepository.Dispose(); - _npcRendererRepository.Dispose(); + public RendererRepositoryResetter(ICharacterRendererRepository characterRendererRepository, + INPCRendererRepository npcRendererRepository, + ICharacterStateCache characterStateCache, + INPCStateCache npcStateCache) + { + _characterRendererRepository = characterRendererRepository; + _npcRendererRepository = npcRendererRepository; + _characterStateCache = characterStateCache; + _npcStateCache = npcStateCache; + } - _characterStateCache.Reset(); - _npcStateCache.Reset(); + public void ResetRenderers() + { + _characterRendererRepository.Dispose(); + _npcRendererRepository.Dispose(); + + _characterStateCache.Reset(); + _npcStateCache.Reset(); + } } -} -public interface IRendererRepositoryResetter -{ - void ResetRenderers(); + public interface IRendererRepositoryResetter + { + void ResetRenderers(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs b/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs index 39adf29d0..90c79b724 100644 --- a/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs +++ b/EndlessClient/Rendering/Sprites/ArmorShieldSpriteType.cs @@ -1,20 +1,21 @@ -namespace EndlessClient.Rendering.Sprites; - -public enum ArmorShieldSpriteType +namespace EndlessClient.Rendering.Sprites { - //dir1/dir2 - Standing = 1, //1/2 - ShieldItemOnBack_AttackingWithBow = 3, - WalkFrame1 = 3, //3/7 - WalkFrame2 = 4, //4/8 - WalkFrame3 = 5, //5/9 - WalkFrame4 = 6, //6/10 - SpellCast = 11, //11/12 - PunchFrame1 = 13, //13/15 - PunchFrame2 = 14, //14/16 + public enum ArmorShieldSpriteType + { + //dir1/dir2 + Standing = 1, //1/2 + ShieldItemOnBack_AttackingWithBow = 3, + WalkFrame1 = 3, //3/7 + WalkFrame2 = 4, //4/8 + WalkFrame3 = 5, //5/9 + WalkFrame4 = 6, //6/10 + SpellCast = 11, //11/12 + PunchFrame1 = 13, //13/15 + PunchFrame2 = 14, //14/16 - //not valid for shields: - SitChair = 17, //17/18 - SitGround = 19, //19/20 - Bow = 21, //21/22 + //not valid for shields: + SitChair = 17, //17/18 + SitGround = 19, //19/20 + Bow = 21, //21/22 + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/BootsSpriteType.cs b/EndlessClient/Rendering/Sprites/BootsSpriteType.cs index 34b0522cf..e06c886e3 100644 --- a/EndlessClient/Rendering/Sprites/BootsSpriteType.cs +++ b/EndlessClient/Rendering/Sprites/BootsSpriteType.cs @@ -1,13 +1,14 @@ -namespace EndlessClient.Rendering.Sprites; - -public enum BootsSpriteType +namespace EndlessClient.Rendering.Sprites { - Standing = 1, //1/2 - WalkFrame1 = 3, //3/7 - WalkFrame2 = 4, //4/8 - WalkFrame3 = 5, //5/9 - WalkFrame4 = 6, //6/10 - Attack = 11, //11/12 - SitChair = 13, //13/14 - SitGround = 15, //15/16 + public enum BootsSpriteType + { + Standing = 1, //1/2 + WalkFrame1 = 3, //3/7 + WalkFrame2 = 4, //4/8 + WalkFrame3 = 5, //5/9 + WalkFrame4 = 6, //6/10 + Attack = 11, //11/12 + SitChair = 13, //13/14 + SitGround = 15, //15/16 + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs b/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs index 531a996ca..e4f920f79 100644 --- a/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs +++ b/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs @@ -9,102 +9,173 @@ using System; using System.Linq; -namespace EndlessClient.Rendering.Sprites; - -[MappedType(BaseType = typeof(ICharacterSpriteCalculator))] -public class CharacterSpriteCalculator : ICharacterSpriteCalculator +namespace EndlessClient.Rendering.Sprites { - private readonly INativeGraphicsManager _gfxManager; - private readonly IMetadataProvider _shieldMetadataProvider; - private readonly IMetadataProvider _hatMetadataProvider; - private readonly IMetadataProvider _weaponMetadataProvider; - - public CharacterSpriteCalculator(INativeGraphicsManager gfxManager, - IMetadataProvider shieldMetadataProvider, - IMetadataProvider hatMetadataProvider, - IMetadataProvider weaponMetadataProvider) + [MappedType(BaseType = typeof(ICharacterSpriteCalculator))] + public class CharacterSpriteCalculator : ICharacterSpriteCalculator { - _gfxManager = gfxManager; - _shieldMetadataProvider = shieldMetadataProvider; - _hatMetadataProvider = hatMetadataProvider; - _weaponMetadataProvider = weaponMetadataProvider; - } + private readonly INativeGraphicsManager _gfxManager; + private readonly IMetadataProvider _shieldMetadataProvider; + private readonly IMetadataProvider _hatMetadataProvider; + private readonly IMetadataProvider _weaponMetadataProvider; + + public CharacterSpriteCalculator(INativeGraphicsManager gfxManager, + IMetadataProvider shieldMetadataProvider, + IMetadataProvider hatMetadataProvider, + IMetadataProvider weaponMetadataProvider) + { + _gfxManager = gfxManager; + _shieldMetadataProvider = shieldMetadataProvider; + _hatMetadataProvider = hatMetadataProvider; + _weaponMetadataProvider = weaponMetadataProvider; + } - public ISpriteSheet GetBootsTexture(CharacterRenderProperties characterRenderProperties) - { - if (characterRenderProperties.BootsGraphic == 0) - return new EmptySpriteSheet(); + public ISpriteSheet GetBootsTexture(CharacterRenderProperties characterRenderProperties) + { + if (characterRenderProperties.BootsGraphic == 0) + return new EmptySpriteSheet(); - var type = BootsSpriteType.Standing; - var currentAction = characterRenderProperties.CurrentAction; - if (currentAction == CharacterActionState.Emote && characterRenderProperties.SitState != SitState.Standing) - currentAction = CharacterActionState.Sitting; + var type = BootsSpriteType.Standing; + var currentAction = characterRenderProperties.CurrentAction; + if (currentAction == CharacterActionState.Emote && characterRenderProperties.SitState != SitState.Standing) + currentAction = CharacterActionState.Sitting; - switch (currentAction) - { - case CharacterActionState.Walking: - switch (characterRenderProperties.RenderWalkFrame) - { - case 1: type = BootsSpriteType.WalkFrame1; break; - case 2: type = BootsSpriteType.WalkFrame2; break; - case 3: type = BootsSpriteType.WalkFrame3; break; - case 4: type = BootsSpriteType.WalkFrame4; break; - } - break; - case CharacterActionState.Attacking: - if (!BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame == 2 || - BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame == 1) - type = BootsSpriteType.Attack; - break; - case CharacterActionState.Sitting: - switch (characterRenderProperties.SitState) - { - case SitState.Chair: type = BootsSpriteType.SitChair; break; - case SitState.Floor: type = BootsSpriteType.SitGround; break; - } - break; + switch (currentAction) + { + case CharacterActionState.Walking: + switch (characterRenderProperties.RenderWalkFrame) + { + case 1: type = BootsSpriteType.WalkFrame1; break; + case 2: type = BootsSpriteType.WalkFrame2; break; + case 3: type = BootsSpriteType.WalkFrame3; break; + case 4: type = BootsSpriteType.WalkFrame4; break; + } + break; + case CharacterActionState.Attacking: + if (!BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame == 2 || + BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame == 1) + type = BootsSpriteType.Attack; + break; + case CharacterActionState.Sitting: + switch (characterRenderProperties.SitState) + { + case SitState.Chair: type = BootsSpriteType.SitChair; break; + case SitState.Floor: type = BootsSpriteType.SitGround; break; + } + break; + } + + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleShoes : GFXTypes.MaleShoes; + + var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var baseBootGraphic = GetBaseBootGraphic(characterRenderProperties.BootsGraphic); + var gfxNumber = baseBootGraphic + (int)type + offset; + + return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); } - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleShoes : GFXTypes.MaleShoes; + public ISpriteSheet GetArmorTexture(CharacterRenderProperties characterRenderProperties) + { + if (characterRenderProperties.ArmorGraphic == 0) + return new EmptySpriteSheet(); - var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var baseBootGraphic = GetBaseBootGraphic(characterRenderProperties.BootsGraphic); - var gfxNumber = baseBootGraphic + (int)type + offset; + var type = ArmorShieldSpriteType.Standing; + var currentAction = characterRenderProperties.CurrentAction; + if (currentAction == CharacterActionState.Emote && characterRenderProperties.SitState != SitState.Standing) + currentAction = CharacterActionState.Sitting; - return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); - } + switch (currentAction) + { + case CharacterActionState.Walking: + switch (characterRenderProperties.RenderWalkFrame) + { + case 1: type = ArmorShieldSpriteType.WalkFrame1; break; + case 2: type = ArmorShieldSpriteType.WalkFrame2; break; + case 3: type = ArmorShieldSpriteType.WalkFrame3; break; + case 4: type = ArmorShieldSpriteType.WalkFrame4; break; + } + break; + case CharacterActionState.Attacking: + if (BowIsEquipped(characterRenderProperties)) + { + switch (characterRenderProperties.RenderAttackFrame) + { + case 1: type = ArmorShieldSpriteType.Bow; break; + case 2: type = ArmorShieldSpriteType.Standing; break; + } + } + else + { + switch (characterRenderProperties.RenderAttackFrame) + { + case 1: type = ArmorShieldSpriteType.PunchFrame1; break; + case 2: type = ArmorShieldSpriteType.PunchFrame2; break; + } + } + break; + case CharacterActionState.SpellCast: + type = ArmorShieldSpriteType.SpellCast; + break; + case CharacterActionState.Sitting: + switch (characterRenderProperties.SitState) + { + case SitState.Chair: + type = ArmorShieldSpriteType.SitChair; + break; + case SitState.Floor: + type = ArmorShieldSpriteType.SitGround; + break; + } + break; + } - public ISpriteSheet GetArmorTexture(CharacterRenderProperties characterRenderProperties) - { - if (characterRenderProperties.ArmorGraphic == 0) - return new EmptySpriteSheet(); + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleArmor : GFXTypes.MaleArmor; + + var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var baseArmorValue = GetBaseArmorGraphic(characterRenderProperties.ArmorGraphic); + var gfxNumber = baseArmorValue + (int)type + offset; - var type = ArmorShieldSpriteType.Standing; - var currentAction = characterRenderProperties.CurrentAction; - if (currentAction == CharacterActionState.Emote && characterRenderProperties.SitState != SitState.Standing) - currentAction = CharacterActionState.Sitting; + return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + } - switch (currentAction) + public ISpriteSheet GetHatTexture(CharacterRenderProperties characterRenderProperties) { - case CharacterActionState.Walking: - switch (characterRenderProperties.RenderWalkFrame) - { - case 1: type = ArmorShieldSpriteType.WalkFrame1; break; - case 2: type = ArmorShieldSpriteType.WalkFrame2; break; - case 3: type = ArmorShieldSpriteType.WalkFrame3; break; - case 4: type = ArmorShieldSpriteType.WalkFrame4; break; - } - break; - case CharacterActionState.Attacking: - if (BowIsEquipped(characterRenderProperties)) + if (characterRenderProperties.HatGraphic == 0) + return new EmptySpriteSheet(); + + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleHat : GFXTypes.MaleHat; + + var offset = 2 * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var baseHatValue = GetBaseHatGraphic(characterRenderProperties.HatGraphic); + var gfxNumber = baseHatValue + 1 + offset; + + var actualMetadata = _hatMetadataProvider.GetValueOrDefault(characterRenderProperties.HatGraphic); + return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, transparent: true, fullTransparent: actualMetadata.ClipMode != HatMaskType.Standard)); + } + + public ISpriteSheet GetShieldTexture(CharacterRenderProperties characterRenderProperties) + { + if (characterRenderProperties.ShieldGraphic == 0) + return new EmptySpriteSheet(); + + var type = ArmorShieldSpriteType.Standing; + var offset = GetBaseOffsetFromDirection(characterRenderProperties.Direction); + + // front shields have one size gfx, back arrows/wings have another size. + var actualMetadata = _shieldMetadataProvider.GetValueOrDefault(characterRenderProperties.ShieldGraphic); + if (!actualMetadata.IsShieldOnBack) + { + if (characterRenderProperties.CurrentAction == CharacterActionState.Walking) { - switch (characterRenderProperties.RenderAttackFrame) + switch (characterRenderProperties.RenderWalkFrame) { - case 1: type = ArmorShieldSpriteType.Bow; break; - case 2: type = ArmorShieldSpriteType.Standing; break; + case 1: type = ArmorShieldSpriteType.WalkFrame1; break; + case 2: type = ArmorShieldSpriteType.WalkFrame2; break; + case 3: type = ArmorShieldSpriteType.WalkFrame3; break; + case 4: type = ArmorShieldSpriteType.WalkFrame4; break; } } - else + else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking) { switch (characterRenderProperties.RenderAttackFrame) { @@ -112,422 +183,352 @@ public ISpriteSheet GetArmorTexture(CharacterRenderProperties characterRenderPro case 2: type = ArmorShieldSpriteType.PunchFrame2; break; } } - break; - case CharacterActionState.SpellCast: - type = ArmorShieldSpriteType.SpellCast; - break; - case CharacterActionState.Sitting: - switch (characterRenderProperties.SitState) + else if (characterRenderProperties.CurrentAction == CharacterActionState.SpellCast) { - case SitState.Chair: - type = ArmorShieldSpriteType.SitChair; - break; - case SitState.Floor: - type = ArmorShieldSpriteType.SitGround; - break; + type = ArmorShieldSpriteType.SpellCast; } - break; + else if (characterRenderProperties.SitState != SitState.Standing) + { + return new EmptySpriteSheet(); + } + + offset *= GetOffsetBasedOnState(type); + } + else + { + //different gfx numbering scheme for shield items worn on the back: + // Standing = 1/2 + // Attacking = 3/4 + // Extra = 5 (unused?) + if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking) + type = ArmorShieldSpriteType.ShieldItemOnBack_AttackingWithBow; + } + + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleBack : GFXTypes.MaleBack; + + var baseShieldValue = GetBaseShieldGraphic(characterRenderProperties.ShieldGraphic); + var gfxNumber = baseShieldValue + (int)type + offset; + return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); } - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleArmor : GFXTypes.MaleArmor; + public ISpriteSheet[] GetWeaponTextures(CharacterRenderProperties characterRenderProperties) + { + var retTextures = new ISpriteSheet[] { new EmptySpriteSheet(), new EmptySpriteSheet() }; + if (characterRenderProperties.WeaponGraphic == 0) + return retTextures; - var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var baseArmorValue = GetBaseArmorGraphic(characterRenderProperties.ArmorGraphic); - var gfxNumber = baseArmorValue + (int)type + offset; + var type = WeaponSpriteType.Standing; + switch (characterRenderProperties.CurrentAction) + { + case CharacterActionState.Walking: + switch (characterRenderProperties.RenderWalkFrame) + { + case 1: type = WeaponSpriteType.WalkFrame1; break; + case 2: type = WeaponSpriteType.WalkFrame2; break; + case 3: type = WeaponSpriteType.WalkFrame3; break; + case 4: type = WeaponSpriteType.WalkFrame4; break; + } + break; + case CharacterActionState.Attacking: + if (BowIsEquipped(characterRenderProperties)) + { + switch (characterRenderProperties.RenderAttackFrame) + { + case 1: type = WeaponSpriteType.Shooting; break; + case 2: type = WeaponSpriteType.Standing; break; + } + } + else + { + switch (characterRenderProperties.RenderAttackFrame) + { + case 1: type = WeaponSpriteType.SwingFrame1; break; + case 2: + type = characterRenderProperties.Direction == EODirection.Down + || characterRenderProperties.Direction == EODirection.Right + ? WeaponSpriteType.SwingFrame2Spec : WeaponSpriteType.SwingFrame2; + break; + } + } + break; + case CharacterActionState.SpellCast: + type = WeaponSpriteType.SpellCast; + break; + case CharacterActionState.Sitting: + return retTextures; //no weapon when sitting + } - return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); - } + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleWeapons : GFXTypes.MaleWeapons; - public ISpriteSheet GetHatTexture(CharacterRenderProperties characterRenderProperties) - { - if (characterRenderProperties.HatGraphic == 0) - return new EmptySpriteSheet(); + var baseWeaponValue = GetBaseWeaponGraphic(characterRenderProperties.WeaponGraphic); - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleHat : GFXTypes.MaleHat; + if (type == WeaponSpriteType.SwingFrame2Spec) + { + // SwingFrame2Spec is rendered in front of the character + var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var gfxNumber = baseWeaponValue + (int)type + offset; + retTextures[0] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + + // SwingFrame2 is rendered behind the character + type = WeaponSpriteType.SwingFrame2; + offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + gfxNumber = baseWeaponValue + (int)type + offset; + retTextures[1] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + } + else + { + var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var gfxNumber = baseWeaponValue + (int)type + offset; - var offset = 2 * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var baseHatValue = GetBaseHatGraphic(characterRenderProperties.HatGraphic); - var gfxNumber = baseHatValue + 1 + offset; + retTextures[0] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + } - var actualMetadata = _hatMetadataProvider.GetValueOrDefault(characterRenderProperties.HatGraphic); - return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, transparent: true, fullTransparent: actualMetadata.ClipMode != HatMaskType.Standard)); - } + return retTextures; + } - public ISpriteSheet GetShieldTexture(CharacterRenderProperties characterRenderProperties) - { - if (characterRenderProperties.ShieldGraphic == 0) - return new EmptySpriteSheet(); + public ISpriteSheet GetWeaponSlash(CharacterRenderProperties characterRenderProperties) + { + const int NUM_SLASHES = 9; - var type = ArmorShieldSpriteType.Standing; - var offset = GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var metadata = _weaponMetadataProvider.GetValueOrDefault(characterRenderProperties.WeaponGraphic); + if (!metadata.Slash.HasValue || metadata.Ranged || characterRenderProperties.RenderAttackFrame != 2) + return new EmptySpriteSheet(); - // front shields have one size gfx, back arrows/wings have another size. - var actualMetadata = _shieldMetadataProvider.GetValueOrDefault(characterRenderProperties.ShieldGraphic); - if (!actualMetadata.IsShieldOnBack) + var sheet = _gfxManager.TextureFromResource(GFXTypes.PostLoginUI, 40, transparent: true); + return new SpriteSheet(sheet, + new Rectangle(sheet.Width / 4 * (int)characterRenderProperties.Direction, + sheet.Height / NUM_SLASHES * metadata.Slash.Value, + sheet.Width / 4, + sheet.Height / NUM_SLASHES)); + } + + public ISpriteSheet GetSkinTexture(CharacterRenderProperties characterRenderProperties) { - if (characterRenderProperties.CurrentAction == CharacterActionState.Walking) + const int SheetRows = 7; + var sheetColumns = 4; + var gfxNum = 1; + + if (characterRenderProperties.CurrentAction == CharacterActionState.Walking && characterRenderProperties.RenderWalkFrame > 0) { - switch (characterRenderProperties.RenderWalkFrame) - { - case 1: type = ArmorShieldSpriteType.WalkFrame1; break; - case 2: type = ArmorShieldSpriteType.WalkFrame2; break; - case 3: type = ArmorShieldSpriteType.WalkFrame3; break; - case 4: type = ArmorShieldSpriteType.WalkFrame4; break; - } + gfxNum = 2; + sheetColumns = 16; } - else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking) + else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && characterRenderProperties.RenderAttackFrame > 0) { - switch (characterRenderProperties.RenderAttackFrame) + if (!BowIsEquipped(characterRenderProperties)) + { + gfxNum = 3; + sheetColumns = 8; + } + else if (characterRenderProperties.RenderAttackFrame == 1) //only 1 frame of bow/gun animation { - case 1: type = ArmorShieldSpriteType.PunchFrame1; break; - case 2: type = ArmorShieldSpriteType.PunchFrame2; break; + gfxNum = 7; //4 columns in this one too } } else if (characterRenderProperties.CurrentAction == CharacterActionState.SpellCast) { - type = ArmorShieldSpriteType.SpellCast; + gfxNum = 4; } else if (characterRenderProperties.SitState != SitState.Standing) { - return new EmptySpriteSheet(); + if (characterRenderProperties.SitState == SitState.Floor) gfxNum = 6; + else if (characterRenderProperties.SitState == SitState.Chair) gfxNum = 5; } - offset *= GetOffsetBasedOnState(type); - } - else - { - //different gfx numbering scheme for shield items worn on the back: - // Standing = 1/2 - // Attacking = 3/4 - // Extra = 5 (unused?) - if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking) - type = ArmorShieldSpriteType.ShieldItemOnBack_AttackingWithBow; - } + var texture = _gfxManager.TextureFromResource(GFXTypes.SkinSprites, gfxNum, true); - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleBack : GFXTypes.MaleBack; + var rotated = characterRenderProperties.Direction == EODirection.Left || + characterRenderProperties.Direction == EODirection.Up; - var baseShieldValue = GetBaseShieldGraphic(characterRenderProperties.ShieldGraphic); - var gfxNumber = baseShieldValue + (int)type + offset; - return new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); - } + var heightDelta = texture.Height / SheetRows; + var widthDelta = texture.Width / sheetColumns; + var sectionDelta = texture.Width / 4; - public ISpriteSheet[] GetWeaponTextures(CharacterRenderProperties characterRenderProperties) - { - var retTextures = new ISpriteSheet[] { new EmptySpriteSheet(), new EmptySpriteSheet() }; - if (characterRenderProperties.WeaponGraphic == 0) - return retTextures; + var walkExtra = characterRenderProperties.RenderWalkFrame > 0 ? widthDelta * (characterRenderProperties.RenderWalkFrame - 1) : 0; + walkExtra = !BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame > 0 ? widthDelta * (characterRenderProperties.RenderAttackFrame - 1) : walkExtra; - var type = WeaponSpriteType.Standing; - switch (characterRenderProperties.CurrentAction) - { - case CharacterActionState.Walking: - switch (characterRenderProperties.RenderWalkFrame) + // Fix offsets for skins - the source rectangles are not at an evenly spaced interval + if (characterRenderProperties.Gender == 1) + { + if (characterRenderProperties.CurrentAction == CharacterActionState.Walking && !rotated) { - case 1: type = WeaponSpriteType.WalkFrame1; break; - case 2: type = WeaponSpriteType.WalkFrame2; break; - case 3: type = WeaponSpriteType.WalkFrame3; break; - case 4: type = WeaponSpriteType.WalkFrame4; break; + walkExtra += 1; } - break; - case CharacterActionState.Attacking: - if (BowIsEquipped(characterRenderProperties)) + else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && + characterRenderProperties.RenderAttackFrame == 1) { - switch (characterRenderProperties.RenderAttackFrame) - { - case 1: type = WeaponSpriteType.Shooting; break; - case 2: type = WeaponSpriteType.Standing; break; - } + // This condition needs some shifting, but this must be done in SkinRenderLocationCalculator since it is a shift of the loaded sprite } - else + } + else if (characterRenderProperties.Gender == 0) + { + if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && characterRenderProperties.RenderAttackFrame > 0) { - switch (characterRenderProperties.RenderAttackFrame) - { - case 1: type = WeaponSpriteType.SwingFrame1; break; - case 2: - type = characterRenderProperties.Direction == EODirection.Down - || characterRenderProperties.Direction == EODirection.Right - ? WeaponSpriteType.SwingFrame2Spec : WeaponSpriteType.SwingFrame2; - break; - } + walkExtra += 1; } - break; - case CharacterActionState.SpellCast: - type = WeaponSpriteType.SpellCast; - break; - case CharacterActionState.Sitting: - return retTextures; //no weapon when sitting - } - - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleWeapons : GFXTypes.MaleWeapons; - - var baseWeaponValue = GetBaseWeaponGraphic(characterRenderProperties.WeaponGraphic); + } - if (type == WeaponSpriteType.SwingFrame2Spec) - { - // SwingFrame2Spec is rendered in front of the character - var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var gfxNumber = baseWeaponValue + (int)type + offset; - retTextures[0] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); - - // SwingFrame2 is rendered behind the character - type = WeaponSpriteType.SwingFrame2; - offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - gfxNumber = baseWeaponValue + (int)type + offset; - retTextures[1] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); - } - else - { - var offset = GetOffsetBasedOnState(type) * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var gfxNumber = baseWeaponValue + (int)type + offset; + var sourceArea = new Rectangle( + characterRenderProperties.Gender * widthDelta * (sheetColumns / 2) + (rotated ? sectionDelta : 0) + walkExtra, + characterRenderProperties.Race * heightDelta, + widthDelta, + heightDelta); - retTextures[0] = new SpriteSheet(_gfxManager.TextureFromResource(gfxFile, gfxNumber, true)); + return new SpriteSheet(texture, sourceArea); } - return retTextures; - } + public ISpriteSheet GetHairTexture(CharacterRenderProperties characterRenderProperties) + { + // Use dummy rectangle for no hair so hats are still correctly aligned + var hairStyle = characterRenderProperties.HairStyle == 0 ? 1 : characterRenderProperties.HairStyle; - public ISpriteSheet GetWeaponSlash(CharacterRenderProperties characterRenderProperties) - { - const int NUM_SLASHES = 9; - - var metadata = _weaponMetadataProvider.GetValueOrDefault(characterRenderProperties.WeaponGraphic); - if (!metadata.Slash.HasValue || metadata.Ranged || characterRenderProperties.RenderAttackFrame != 2) - return new EmptySpriteSheet(); - - var sheet = _gfxManager.TextureFromResource(GFXTypes.PostLoginUI, 40, transparent: true); - return new SpriteSheet(sheet, - new Rectangle(sheet.Width / 4 * (int)characterRenderProperties.Direction, - sheet.Height / NUM_SLASHES * metadata.Slash.Value, - sheet.Width / 4, - sheet.Height / NUM_SLASHES)); - } + var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleHair : GFXTypes.MaleHair; + var offset = 2 * GetBaseOffsetFromDirection(characterRenderProperties.Direction); + var gfxNumber = GetBaseHairGraphic(hairStyle, characterRenderProperties.HairColor) + 2 + offset; - public ISpriteSheet GetSkinTexture(CharacterRenderProperties characterRenderProperties) - { - const int SheetRows = 7; - var sheetColumns = 4; - var gfxNum = 1; + var hairTexture = _gfxManager.TextureFromResource(gfxFile, gfxNumber, true); - if (characterRenderProperties.CurrentAction == CharacterActionState.Walking && characterRenderProperties.RenderWalkFrame > 0) - { - gfxNum = 2; - sheetColumns = 16; + return characterRenderProperties.HairStyle == 0 + ? (ISpriteSheet)new EmptySpriteSheet(new Rectangle(0, 0, hairTexture.Width, hairTexture.Height)) + : new SpriteSheet(hairTexture); } - else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && characterRenderProperties.RenderAttackFrame > 0) + + public ISpriteSheet GetFaceTexture(CharacterRenderProperties characterRenderProperties) { - if (!BowIsEquipped(characterRenderProperties)) - { - gfxNum = 3; - sheetColumns = 8; - } - else if (characterRenderProperties.RenderAttackFrame == 1) //only 1 frame of bow/gun animation + if (characterRenderProperties.EmoteFrame < 0 || + characterRenderProperties.Emote == Emote.Trade || + characterRenderProperties.Emote == Emote.LevelUp) { - gfxNum = 7; //4 columns in this one too + return new EmptySpriteSheet(); } - } - else if (characterRenderProperties.CurrentAction == CharacterActionState.SpellCast) - { - gfxNum = 4; - } - else if (characterRenderProperties.SitState != SitState.Standing) - { - if (characterRenderProperties.SitState == SitState.Floor) gfxNum = 6; - else if (characterRenderProperties.SitState == SitState.Chair) gfxNum = 5; - } - var texture = _gfxManager.TextureFromResource(GFXTypes.SkinSprites, gfxNum, true); + //14 rows (7 female - 7 male) / 11 columns + const int ROWS = 14; + const int COLS = 11; - var rotated = characterRenderProperties.Direction == EODirection.Left || - characterRenderProperties.Direction == EODirection.Up; + var texture = _gfxManager.TextureFromResource(GFXTypes.SkinSprites, 8, true); - var heightDelta = texture.Height / SheetRows; - var widthDelta = texture.Width / sheetColumns; - var sectionDelta = texture.Width / 4; + var widthDelta = texture.Width / COLS; + var heightDelta = texture.Height / ROWS; + var genderOffset = texture.Height / 2 * characterRenderProperties.Gender; + //'playful' is the last face in the gfx (ndx 10), even though it has enum value of 14 (ndx 13) + var emote = characterRenderProperties.Emote == Emote.Playful || + characterRenderProperties.Emote == Emote.Drunk + ? 10 : (int)characterRenderProperties.Emote - 1; - var walkExtra = characterRenderProperties.RenderWalkFrame > 0 ? widthDelta * (characterRenderProperties.RenderWalkFrame - 1) : 0; - walkExtra = !BowIsEquipped(characterRenderProperties) && characterRenderProperties.RenderAttackFrame > 0 ? widthDelta * (characterRenderProperties.RenderAttackFrame - 1) : walkExtra; + var sourceRectangle = new Rectangle(widthDelta * emote, heightDelta * characterRenderProperties.Race + genderOffset, widthDelta, heightDelta); - // Fix offsets for skins - the source rectangles are not at an evenly spaced interval - if (characterRenderProperties.Gender == 1) - { - if (characterRenderProperties.CurrentAction == CharacterActionState.Walking && !rotated) - { - walkExtra += 1; - } - else if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && - characterRenderProperties.RenderAttackFrame == 1) - { - // This condition needs some shifting, but this must be done in SkinRenderLocationCalculator since it is a shift of the loaded sprite - } + return new SpriteSheet(texture, sourceRectangle); } - else if (characterRenderProperties.Gender == 0) + + public ISpriteSheet GetEmoteTexture(CharacterRenderProperties characterRenderProperties) { - if (characterRenderProperties.CurrentAction == CharacterActionState.Attacking && characterRenderProperties.RenderAttackFrame > 0) - { - walkExtra += 1; - } - } + if (characterRenderProperties.Emote == 0 || characterRenderProperties.EmoteFrame < 0) + return new EmptySpriteSheet(); - var sourceArea = new Rectangle( - characterRenderProperties.Gender * widthDelta * (sheetColumns / 2) + (rotated ? sectionDelta : 0) + walkExtra, - characterRenderProperties.Race * heightDelta, - widthDelta, - heightDelta); + const int NUM_EMOTES = 15; + const int NUM_FRAMES = 4; - return new SpriteSheet(texture, sourceArea); - } + var emoteValue = Enum.GetName(typeof(Emote), characterRenderProperties.Emote) ?? ""; + var convertedValuesDictionary = Enum.GetNames(typeof(EmoteSpriteType)) + .ToDictionary(x => x, x => (EmoteSpriteType)Enum.Parse(typeof(EmoteSpriteType), x)); + var convertedEmote = (int)convertedValuesDictionary[emoteValue]; - public ISpriteSheet GetHairTexture(CharacterRenderProperties characterRenderProperties) - { - // Use dummy rectangle for no hair so hats are still correctly aligned - var hairStyle = characterRenderProperties.HairStyle == 0 ? 1 : characterRenderProperties.HairStyle; + var emoteTexture = _gfxManager.TextureFromResource(GFXTypes.PostLoginUI, 38, true); - var gfxFile = characterRenderProperties.Gender == 0 ? GFXTypes.FemaleHair : GFXTypes.MaleHair; - var offset = 2 * GetBaseOffsetFromDirection(characterRenderProperties.Direction); - var gfxNumber = GetBaseHairGraphic(hairStyle, characterRenderProperties.HairColor) + 2 + offset; + var eachSet = emoteTexture.Width / NUM_EMOTES; + var eachFrame = emoteTexture.Width / (NUM_EMOTES * NUM_FRAMES); + var startX = convertedEmote * eachSet + characterRenderProperties.EmoteFrame * eachFrame; - var hairTexture = _gfxManager.TextureFromResource(gfxFile, gfxNumber, true); + var emoteRect = new Rectangle(startX, 0, eachFrame, emoteTexture.Height); - return characterRenderProperties.HairStyle == 0 - ? (ISpriteSheet)new EmptySpriteSheet(new Rectangle(0, 0, hairTexture.Width, hairTexture.Height)) - : new SpriteSheet(hairTexture); - } + return new SpriteSheet(emoteTexture, emoteRect); + } - public ISpriteSheet GetFaceTexture(CharacterRenderProperties characterRenderProperties) - { - if (characterRenderProperties.EmoteFrame < 0 || - characterRenderProperties.Emote == Emote.Trade || - characterRenderProperties.Emote == Emote.LevelUp) + private int GetBaseBootGraphic(int bootsGraphic) { - return new EmptySpriteSheet(); + return (bootsGraphic - 1) * 40; } - //14 rows (7 female - 7 male) / 11 columns - const int ROWS = 14; - const int COLS = 11; - - var texture = _gfxManager.TextureFromResource(GFXTypes.SkinSprites, 8, true); - - var widthDelta = texture.Width / COLS; - var heightDelta = texture.Height / ROWS; - var genderOffset = texture.Height / 2 * characterRenderProperties.Gender; - //'playful' is the last face in the gfx (ndx 10), even though it has enum value of 14 (ndx 13) - var emote = characterRenderProperties.Emote == Emote.Playful || - characterRenderProperties.Emote == Emote.Drunk - ? 10 : (int)characterRenderProperties.Emote - 1; - - var sourceRectangle = new Rectangle(widthDelta * emote, heightDelta * characterRenderProperties.Race + genderOffset, widthDelta, heightDelta); - - return new SpriteSheet(texture, sourceRectangle); - } - - public ISpriteSheet GetEmoteTexture(CharacterRenderProperties characterRenderProperties) - { - if (characterRenderProperties.Emote == 0 || characterRenderProperties.EmoteFrame < 0) - return new EmptySpriteSheet(); - - const int NUM_EMOTES = 15; - const int NUM_FRAMES = 4; - - var emoteValue = Enum.GetName(typeof(Emote), characterRenderProperties.Emote) ?? ""; - var convertedValuesDictionary = Enum.GetNames(typeof(EmoteSpriteType)) - .ToDictionary(x => x, x => (EmoteSpriteType)Enum.Parse(typeof(EmoteSpriteType), x)); - var convertedEmote = (int)convertedValuesDictionary[emoteValue]; - - var emoteTexture = _gfxManager.TextureFromResource(GFXTypes.PostLoginUI, 38, true); - - var eachSet = emoteTexture.Width / NUM_EMOTES; - var eachFrame = emoteTexture.Width / (NUM_EMOTES * NUM_FRAMES); - var startX = convertedEmote * eachSet + characterRenderProperties.EmoteFrame * eachFrame; - - var emoteRect = new Rectangle(startX, 0, eachFrame, emoteTexture.Height); - - return new SpriteSheet(emoteTexture, emoteRect); - } - - private int GetBaseBootGraphic(int bootsGraphic) - { - return (bootsGraphic - 1) * 40; - } - - private int GetBaseArmorGraphic(int armorGraphic) - { - return (armorGraphic - 1) * 50; - } + private int GetBaseArmorGraphic(int armorGraphic) + { + return (armorGraphic - 1) * 50; + } - private int GetBaseHatGraphic(int hatGraphic) - { - return (hatGraphic - 1) * 10; - } + private int GetBaseHatGraphic(int hatGraphic) + { + return (hatGraphic - 1) * 10; + } - private int GetBaseShieldGraphic(int shieldGraphic) - { - return (shieldGraphic - 1) * 50; - } + private int GetBaseShieldGraphic(int shieldGraphic) + { + return (shieldGraphic - 1) * 50; + } - private int GetBaseWeaponGraphic(int weaponGraphic) - { - return (weaponGraphic - 1) * 100; - } + private int GetBaseWeaponGraphic(int weaponGraphic) + { + return (weaponGraphic - 1) * 100; + } - private int GetBaseHairGraphic(int hairStyle, int hairColor) - { - return (hairStyle - 1) * 40 + hairColor * 4; - } + private int GetBaseHairGraphic(int hairStyle, int hairColor) + { + return (hairStyle - 1) * 40 + hairColor * 4; + } - private int GetBaseOffsetFromDirection(EODirection direction) - { - return direction == EODirection.Down || - direction == EODirection.Right ? 0 : 1; - } + private int GetBaseOffsetFromDirection(EODirection direction) + { + return direction == EODirection.Down || + direction == EODirection.Right ? 0 : 1; + } - private int GetOffsetBasedOnState(BootsSpriteType type) - { - switch (type) + private int GetOffsetBasedOnState(BootsSpriteType type) { - case BootsSpriteType.WalkFrame1: - case BootsSpriteType.WalkFrame2: - case BootsSpriteType.WalkFrame3: - case BootsSpriteType.WalkFrame4: - return 4; + switch (type) + { + case BootsSpriteType.WalkFrame1: + case BootsSpriteType.WalkFrame2: + case BootsSpriteType.WalkFrame3: + case BootsSpriteType.WalkFrame4: + return 4; + } + return 1; } - return 1; - } - private int GetOffsetBasedOnState(ArmorShieldSpriteType type) - { - switch (type) + private int GetOffsetBasedOnState(ArmorShieldSpriteType type) { - case ArmorShieldSpriteType.WalkFrame1: - case ArmorShieldSpriteType.WalkFrame2: - case ArmorShieldSpriteType.WalkFrame3: - case ArmorShieldSpriteType.WalkFrame4: - return 4; - case ArmorShieldSpriteType.PunchFrame1: - case ArmorShieldSpriteType.PunchFrame2: - return 2; + switch (type) + { + case ArmorShieldSpriteType.WalkFrame1: + case ArmorShieldSpriteType.WalkFrame2: + case ArmorShieldSpriteType.WalkFrame3: + case ArmorShieldSpriteType.WalkFrame4: + return 4; + case ArmorShieldSpriteType.PunchFrame1: + case ArmorShieldSpriteType.PunchFrame2: + return 2; + } + return 1; } - return 1; - } - private int GetOffsetBasedOnState(WeaponSpriteType type) - { - switch (type) + private int GetOffsetBasedOnState(WeaponSpriteType type) { - case WeaponSpriteType.WalkFrame1: - case WeaponSpriteType.WalkFrame2: - case WeaponSpriteType.WalkFrame3: - case WeaponSpriteType.WalkFrame4: - return 4; - case WeaponSpriteType.SwingFrame1: - case WeaponSpriteType.SwingFrame2: - return 2; + switch (type) + { + case WeaponSpriteType.WalkFrame1: + case WeaponSpriteType.WalkFrame2: + case WeaponSpriteType.WalkFrame3: + case WeaponSpriteType.WalkFrame4: + return 4; + case WeaponSpriteType.SwingFrame1: + case WeaponSpriteType.SwingFrame2: + return 2; + } + return 1; } - return 1; - } - private bool BowIsEquipped(CharacterRenderProperties characterRenderProperties) - { - return _weaponMetadataProvider.GetValueOrDefault(characterRenderProperties.WeaponGraphic).Ranged; + private bool BowIsEquipped(CharacterRenderProperties characterRenderProperties) + { + return _weaponMetadataProvider.GetValueOrDefault(characterRenderProperties.WeaponGraphic).Ranged; + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs b/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs index 78ce76c8d..12edf2cba 100644 --- a/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs +++ b/EndlessClient/Rendering/Sprites/EmoteSpriteType.cs @@ -1,20 +1,21 @@ -namespace EndlessClient.Rendering.Sprites; - -public enum EmoteSpriteType +namespace EndlessClient.Rendering.Sprites { - Happy = 0, - Sad = 1, - Surprised = 2, - Confused = 3, - Moon = 4, - Angry = 5, - Hearts = 6, - Depressed = 7, - Embarassed = 8, - Suicidal = 9, - Drunk = 10, - Trade = 11, - LevelUp = 12, - Playful = 13, - MusicNotes = 14, + public enum EmoteSpriteType + { + Happy = 0, + Sad = 1, + Surprised = 2, + Confused = 3, + Moon = 4, + Angry = 5, + Hearts = 6, + Depressed = 7, + Embarassed = 8, + Suicidal = 9, + Drunk = 10, + Trade = 11, + LevelUp = 12, + Playful = 13, + MusicNotes = 14, + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs b/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs index af18adf02..5d8308eaf 100644 --- a/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs @@ -2,29 +2,30 @@ using Microsoft.Xna.Framework.Graphics; using System.Linq; -namespace EndlessClient.Rendering.Sprites; - -public class EmptySpriteSheet : ISpriteSheet +namespace EndlessClient.Rendering.Sprites { - public bool HasTexture => false; - public Texture2D SheetTexture => null; - public Rectangle SourceRectangle { get; } + public class EmptySpriteSheet : ISpriteSheet + { + public bool HasTexture => false; + public Texture2D SheetTexture => null; + public Rectangle SourceRectangle { get; } - public EmptySpriteSheet() - : this(Rectangle.Empty) { } + public EmptySpriteSheet() + : this(Rectangle.Empty) { } - public EmptySpriteSheet(Rectangle sourceRectangle) - { - SourceRectangle = sourceRectangle; - } + public EmptySpriteSheet(Rectangle sourceRectangle) + { + SourceRectangle = sourceRectangle; + } - public T[] GetSourceTextureData() where T : struct - { - return Enumerable.Empty().ToArray(); - } + public T[] GetSourceTextureData() where T : struct + { + return Enumerable.Empty().ToArray(); + } - public Texture2D GetSourceTexture() - { - return SheetTexture; + public Texture2D GetSourceTexture() + { + return SheetTexture; + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs b/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs index a6cfea869..f50db921c 100644 --- a/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs +++ b/EndlessClient/Rendering/Sprites/ICharacterSpriteCalculator.cs @@ -1,18 +1,19 @@ using EOLib.Domain.Character; -namespace EndlessClient.Rendering.Sprites; - -public interface ICharacterSpriteCalculator +namespace EndlessClient.Rendering.Sprites { - ISpriteSheet GetBootsTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetArmorTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetHatTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetShieldTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet[] GetWeaponTextures(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetWeaponSlash(CharacterRenderProperties characterRenderProperties); + public interface ICharacterSpriteCalculator + { + ISpriteSheet GetBootsTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetArmorTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetHatTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetShieldTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet[] GetWeaponTextures(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetWeaponSlash(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetSkinTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetHairTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetFaceTexture(CharacterRenderProperties characterRenderProperties); - ISpriteSheet GetEmoteTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetSkinTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetHairTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetFaceTexture(CharacterRenderProperties characterRenderProperties); + ISpriteSheet GetEmoteTexture(CharacterRenderProperties characterRenderProperties); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/ISpriteSheet.cs b/EndlessClient/Rendering/Sprites/ISpriteSheet.cs index 34784ea20..10e7863a6 100644 --- a/EndlessClient/Rendering/Sprites/ISpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/ISpriteSheet.cs @@ -1,17 +1,18 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Sprites; - -public interface ISpriteSheet +namespace EndlessClient.Rendering.Sprites { - bool HasTexture { get; } + public interface ISpriteSheet + { + bool HasTexture { get; } - Texture2D SheetTexture { get; } + Texture2D SheetTexture { get; } - Rectangle SourceRectangle { get; } + Rectangle SourceRectangle { get; } - T[] GetSourceTextureData() where T : struct; + T[] GetSourceTextureData() where T : struct; - Texture2D GetSourceTexture(); + Texture2D GetSourceTexture(); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs b/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs index eb4007a53..5909e4f48 100644 --- a/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs +++ b/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs @@ -6,112 +6,113 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Rendering.Sprites; - -[AutoMappedType(IsSingleton = true)] -public class NPCSpriteDataCache : INPCSpriteDataCache +namespace EndlessClient.Rendering.Sprites { - private const int CACHE_SIZE = 32; - - private readonly INPCSpriteSheet _npcSpriteSheet; + [AutoMappedType(IsSingleton = true)] + public class NPCSpriteDataCache : INPCSpriteDataCache + { + private const int CACHE_SIZE = 32; - private readonly Dictionary>> _spriteData; - private readonly List _lru; - private readonly HashSet _reclaimable; + private readonly INPCSpriteSheet _npcSpriteSheet; - public NPCSpriteDataCache(INPCSpriteSheet npcSpriteSheet) - { - _npcSpriteSheet = npcSpriteSheet; - _spriteData = new Dictionary>>(CACHE_SIZE); - _lru = new List(CACHE_SIZE); - _reclaimable = new HashSet(CACHE_SIZE); - } + private readonly Dictionary>> _spriteData; + private readonly List _lru; + private readonly HashSet _reclaimable; - public void Populate(int graphic) - { - if (_spriteData.ContainsKey(graphic)) - return; + public NPCSpriteDataCache(INPCSpriteSheet npcSpriteSheet) + { + _npcSpriteSheet = npcSpriteSheet; + _spriteData = new Dictionary>>(CACHE_SIZE); + _lru = new List(CACHE_SIZE); + _reclaimable = new HashSet(CACHE_SIZE); + } - if (_lru.Count >= CACHE_SIZE && _reclaimable.Count > 0) + public void Populate(int graphic) { - // find and "reclaim" the first available candidate based on the order they were added to the LRU - // 'reclaimable' candidates are updated when the map changes - // candidates will never be NPCs that are on the current map - // a map with >= CACHE_SIZE different NPCs will cause problems here - for (int i = 0; i < _lru.Count; i++) + if (_spriteData.ContainsKey(graphic)) + return; + + if (_lru.Count >= CACHE_SIZE && _reclaimable.Count > 0) { - var candidate = _lru[i]; - if (_reclaimable.Contains(candidate)) + // find and "reclaim" the first available candidate based on the order they were added to the LRU + // 'reclaimable' candidates are updated when the map changes + // candidates will never be NPCs that are on the current map + // a map with >= CACHE_SIZE different NPCs will cause problems here + for (int i = 0; i < _lru.Count; i++) { - _spriteData.Remove(candidate); - _reclaimable.Remove(candidate); - _lru.RemoveAt(i); - break; + var candidate = _lru[i]; + if (_reclaimable.Contains(candidate)) + { + _spriteData.Remove(candidate); + _reclaimable.Remove(candidate); + _lru.RemoveAt(i); + break; + } } } - } - _spriteData[graphic] = new Dictionary>(); - _reclaimable.Remove(graphic); - _lru.Add(graphic); + _spriteData[graphic] = new Dictionary>(); + _reclaimable.Remove(graphic); + _lru.Add(graphic); - foreach (NPCFrame frame in Enum.GetValues(typeof(NPCFrame))) - { - var text = _npcSpriteSheet.GetNPCTexture(graphic, frame, EODirection.Down); - var data = Array.Empty(); - - if (text != null) + foreach (NPCFrame frame in Enum.GetValues(typeof(NPCFrame))) { - data = new Color[text.Width * text.Height]; - text.GetData(data); - } + var text = _npcSpriteSheet.GetNPCTexture(graphic, frame, EODirection.Down); + var data = Array.Empty(); - _spriteData[graphic][frame] = data; - } - } + if (text != null) + { + data = new Color[text.Width * text.Height]; + text.GetData(data); + } - public void MarkForEviction(int graphic) - { - _reclaimable.Add(graphic); - } + _spriteData[graphic][frame] = data; + } + } - public void UnmarkForEviction(int graphic) - { - _reclaimable.Remove(graphic); - } + public void MarkForEviction(int graphic) + { + _reclaimable.Add(graphic); + } - public ReadOnlySpan GetData(int graphic, NPCFrame frame) - { - if (!_spriteData.ContainsKey(graphic)) + public void UnmarkForEviction(int graphic) { - Populate(graphic); + _reclaimable.Remove(graphic); } - return _spriteData[graphic][frame].Span; - } + public ReadOnlySpan GetData(int graphic, NPCFrame frame) + { + if (!_spriteData.ContainsKey(graphic)) + { + Populate(graphic); + } - public bool IsBlankSprite(int graphic) - { - if (!_spriteData.ContainsKey(graphic)) + return _spriteData[graphic][frame].Span; + } + + public bool IsBlankSprite(int graphic) { - Populate(graphic); + if (!_spriteData.ContainsKey(graphic)) + { + Populate(graphic); + } + + return _spriteData[graphic][NPCFrame.Standing].Span.ToArray().All(AlphaIsZero); } - return _spriteData[graphic][NPCFrame.Standing].Span.ToArray().All(AlphaIsZero); + private static bool AlphaIsZero(Color input) => input.A == 0; } - private static bool AlphaIsZero(Color input) => input.A == 0; -} - -public interface INPCSpriteDataCache -{ - void Populate(int graphic); + public interface INPCSpriteDataCache + { + void Populate(int graphic); - void MarkForEviction(int graphic); + void MarkForEviction(int graphic); - void UnmarkForEviction(int graphic); + void UnmarkForEviction(int graphic); - ReadOnlySpan GetData(int graphic, NPCFrame frame); + ReadOnlySpan GetData(int graphic, NPCFrame frame); - bool IsBlankSprite(int graphic); + bool IsBlankSprite(int graphic); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/NPCSpriteSheet.cs b/EndlessClient/Rendering/Sprites/NPCSpriteSheet.cs index 392641645..2c0d0ef27 100644 --- a/EndlessClient/Rendering/Sprites/NPCSpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/NPCSpriteSheet.cs @@ -6,67 +6,68 @@ using EOLib.Graphics; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Sprites; - -[AutoMappedType] -public class NPCSpriteSheet : INPCSpriteSheet +namespace EndlessClient.Rendering.Sprites { - private readonly INativeGraphicsManager _gfxManager; - private readonly IMetadataProvider _npcMetadataProvider; - - public NPCSpriteSheet(INativeGraphicsManager gfxManager, - IMetadataProvider npcMetadataProvider) + [AutoMappedType] + public class NPCSpriteSheet : INPCSpriteSheet { - _gfxManager = gfxManager; - _npcMetadataProvider = npcMetadataProvider; - } + private readonly INativeGraphicsManager _gfxManager; + private readonly IMetadataProvider _npcMetadataProvider; - public Texture2D GetNPCTexture(int baseGraphic, NPCFrame whichFrame, EODirection direction) - { - int offset; - switch (whichFrame) + public NPCSpriteSheet(INativeGraphicsManager gfxManager, + IMetadataProvider npcMetadataProvider) { - case NPCFrame.Standing: - offset = direction == EODirection.Down || direction == EODirection.Right ? 1 : 3; - break; - case NPCFrame.StandingFrame1: - offset = direction == EODirection.Down || direction == EODirection.Right ? 2 : 4; - break; - case NPCFrame.WalkFrame1: - offset = direction == EODirection.Down || direction == EODirection.Right ? 5 : 9; - break; - case NPCFrame.WalkFrame2: - offset = direction == EODirection.Down || direction == EODirection.Right ? 6 : 10; - break; - case NPCFrame.WalkFrame3: - offset = direction == EODirection.Down || direction == EODirection.Right ? 7 : 11; - break; - case NPCFrame.WalkFrame4: - offset = direction == EODirection.Down || direction == EODirection.Right ? 8 : 12; - break; - case NPCFrame.Attack1: - offset = direction == EODirection.Down || direction == EODirection.Right ? 13 : 15; - break; - case NPCFrame.Attack2: - offset = direction == EODirection.Down || direction == EODirection.Right ? 14 : 16; - break; - default: - return null; + _gfxManager = gfxManager; + _npcMetadataProvider = npcMetadataProvider; } - var baseGfx = (baseGraphic - 1) * 40; - return _gfxManager.TextureFromResource(GFXTypes.NPC, baseGfx + offset, true); - } + public Texture2D GetNPCTexture(int baseGraphic, NPCFrame whichFrame, EODirection direction) + { + int offset; + switch (whichFrame) + { + case NPCFrame.Standing: + offset = direction == EODirection.Down || direction == EODirection.Right ? 1 : 3; + break; + case NPCFrame.StandingFrame1: + offset = direction == EODirection.Down || direction == EODirection.Right ? 2 : 4; + break; + case NPCFrame.WalkFrame1: + offset = direction == EODirection.Down || direction == EODirection.Right ? 5 : 9; + break; + case NPCFrame.WalkFrame2: + offset = direction == EODirection.Down || direction == EODirection.Right ? 6 : 10; + break; + case NPCFrame.WalkFrame3: + offset = direction == EODirection.Down || direction == EODirection.Right ? 7 : 11; + break; + case NPCFrame.WalkFrame4: + offset = direction == EODirection.Down || direction == EODirection.Right ? 8 : 12; + break; + case NPCFrame.Attack1: + offset = direction == EODirection.Down || direction == EODirection.Right ? 13 : 15; + break; + case NPCFrame.Attack2: + offset = direction == EODirection.Down || direction == EODirection.Right ? 14 : 16; + break; + default: + return null; + } - public NPCMetadata GetNPCMetadata(int graphic) - { - return _npcMetadataProvider.GetValueOrDefault(graphic); + var baseGfx = (baseGraphic - 1) * 40; + return _gfxManager.TextureFromResource(GFXTypes.NPC, baseGfx + offset, true); + } + + public NPCMetadata GetNPCMetadata(int graphic) + { + return _npcMetadataProvider.GetValueOrDefault(graphic); + } } -} -public interface INPCSpriteSheet -{ - Texture2D GetNPCTexture(int baseGraphic, NPCFrame whichFrame, EODirection direction); + public interface INPCSpriteSheet + { + Texture2D GetNPCTexture(int baseGraphic, NPCFrame whichFrame, EODirection direction); - NPCMetadata GetNPCMetadata(int graphic); + NPCMetadata GetNPCMetadata(int graphic); + } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/SpriteSheet.cs b/EndlessClient/Rendering/Sprites/SpriteSheet.cs index ab46df8a3..4e44ea418 100644 --- a/EndlessClient/Rendering/Sprites/SpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/SpriteSheet.cs @@ -1,50 +1,51 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace EndlessClient.Rendering.Sprites; - -public class SpriteSheet : ISpriteSheet +namespace EndlessClient.Rendering.Sprites { - public bool HasTexture => true; + public class SpriteSheet : ISpriteSheet + { + public bool HasTexture => true; - public Texture2D SheetTexture { get; } + public Texture2D SheetTexture { get; } - public Rectangle SourceRectangle { get; } + public Rectangle SourceRectangle { get; } - public SpriteSheet(Texture2D texture) - { - SheetTexture = texture; - SourceRectangle = new Rectangle(0, 0, texture.Width, texture.Height); - } + public SpriteSheet(Texture2D texture) + { + SheetTexture = texture; + SourceRectangle = new Rectangle(0, 0, texture.Width, texture.Height); + } - public SpriteSheet(Texture2D texture, Rectangle sourceArea) - { - SheetTexture = texture; - SourceRectangle = sourceArea; - } + public SpriteSheet(Texture2D texture, Rectangle sourceArea) + { + SheetTexture = texture; + SourceRectangle = sourceArea; + } - public T[] GetSourceTextureData() where T : struct - { - var data = new T[SourceRectangle.Width * SourceRectangle.Height]; - if (!SheetTexture.Bounds.Contains(SourceRectangle)) - return data; + public T[] GetSourceTextureData() where T : struct + { + var data = new T[SourceRectangle.Width * SourceRectangle.Height]; + if (!SheetTexture.Bounds.Contains(SourceRectangle)) + return data; - SheetTexture.GetData(0, SourceRectangle, data, 0, data.Length); + SheetTexture.GetData(0, SourceRectangle, data, 0, data.Length); - return data; - } + return data; + } - /// - /// Get a new texture containing the data from SheetTexture within the bounds of SourceRectangle. Must be disposed. - /// - /// New texture containing just the image specified by the SourceRectangle property. - public Texture2D GetSourceTexture() - { - var colorData = GetSourceTextureData(); + /// + /// Get a new texture containing the data from SheetTexture within the bounds of SourceRectangle. Must be disposed. + /// + /// New texture containing just the image specified by the SourceRectangle property. + public Texture2D GetSourceTexture() + { + var colorData = GetSourceTextureData(); - var retText = new Texture2D(SheetTexture.GraphicsDevice, SourceRectangle.Width, SourceRectangle.Height); - retText.SetData(colorData); + var retText = new Texture2D(SheetTexture.GraphicsDevice, SourceRectangle.Width, SourceRectangle.Height); + retText.SetData(colorData); - return retText; + return retText; + } } } \ No newline at end of file diff --git a/EndlessClient/Rendering/Sprites/WeaponSpriteType.cs b/EndlessClient/Rendering/Sprites/WeaponSpriteType.cs index 1feb9532a..2c75f97f5 100644 --- a/EndlessClient/Rendering/Sprites/WeaponSpriteType.cs +++ b/EndlessClient/Rendering/Sprites/WeaponSpriteType.cs @@ -1,16 +1,17 @@ -namespace EndlessClient.Rendering.Sprites; - -public enum WeaponSpriteType +namespace EndlessClient.Rendering.Sprites { - Standing = 1, //1/2 - WalkFrame1 = 3, //3/7 - WalkFrame2 = 4, //4/8 - WalkFrame3 = 5, //5/9 - WalkFrame4 = 6, //6/10 - SpellCast = 11, //11/12 - SwingFrame1 = 13, //13/15 - SwingFrame2 = 14, //14/16 - SwingFrame2Spec = 17, //17 - special frame rendered on top of the character in certain directions - //invalid for non-ranged weapons: - Shooting = 18, //18/19 AND 21/22 have same gfx + public enum WeaponSpriteType + { + Standing = 1, //1/2 + WalkFrame1 = 3, //3/7 + WalkFrame2 = 4, //4/8 + WalkFrame3 = 5, //5/9 + WalkFrame4 = 6, //6/10 + SpellCast = 11, //11/12 + SwingFrame1 = 13, //13/15 + SwingFrame2 = 14, //14/16 + SwingFrame2Spec = 17, //17 - special frame rendered on top of the character in certain directions + //invalid for non-ranged weapons: + Shooting = 18, //18/19 AND 21/22 have same gfx + } } \ No newline at end of file diff --git a/EndlessClient/Services/FriendIgnoreListService.cs b/EndlessClient/Services/FriendIgnoreListService.cs index 466c75ca7..6aa0ced90 100644 --- a/EndlessClient/Services/FriendIgnoreListService.cs +++ b/EndlessClient/Services/FriendIgnoreListService.cs @@ -3,87 +3,88 @@ using System.IO; using System.Linq; -namespace EndlessClient.Services; - -[AutoMappedType] -public class FriendIgnoreListService : IFriendIgnoreListService +namespace EndlessClient.Services { - public IReadOnlyList LoadList(string path) - { - return Load(path); - } - - public void SaveFriends(string path, IReadOnlyList contents) - { - Save(isIgnore: false, path, contents); - } - - public void SaveIgnored(string path, IReadOnlyList contents) - { - Save(isIgnore: true, path, contents); - } - - public void SaveNewFriend(string path, string name) - { - if (!File.Exists(path) || string.IsNullOrWhiteSpace(File.ReadAllText(path))) - Save(isIgnore: false, path, new[] { name }); - else - File.AppendAllLines(path, new[] { name }); - } - - public void SaveNewIgnore(string path, string name) - { - if (!File.Exists(path) || string.IsNullOrWhiteSpace(File.ReadAllText(path))) - Save(isIgnore: true, path, new[] { name }); - else - File.AppendAllLines(path, new[] { name }); - } - - private static List Load(string fileName) + [AutoMappedType] + public class FriendIgnoreListService : IFriendIgnoreListService { - if (!File.Exists(fileName)) - return new List(); + public IReadOnlyList LoadList(string path) + { + return Load(path); + } - List allLines; - try + public void SaveFriends(string path, IReadOnlyList contents) { - allLines = new List(File.ReadAllLines(fileName)); + Save(isIgnore: false, path, contents); } - catch (IOException) + + public void SaveIgnored(string path, IReadOnlyList contents) { - return new List(); + Save(isIgnore: true, path, contents); } - allLines.RemoveAll(s => s.StartsWith("#") || string.IsNullOrWhiteSpace(s)); + public void SaveNewFriend(string path, string name) + { + if (!File.Exists(path) || string.IsNullOrWhiteSpace(File.ReadAllText(path))) + Save(isIgnore: false, path, new[] { name }); + else + File.AppendAllLines(path, new[] { name }); + } - return allLines.Select(Capitalize).Distinct().ToList(); - } + public void SaveNewIgnore(string path, string name) + { + if (!File.Exists(path) || string.IsNullOrWhiteSpace(File.ReadAllText(path))) + Save(isIgnore: true, path, new[] { name }); + else + File.AppendAllLines(path, new[] { name }); + } - private static void Save(bool isIgnore, string fileName, IEnumerable lines) - { - using (var sw = new StreamWriter(fileName)) + private static List Load(string fileName) { - string friendOrIgnore = isIgnore ? "ignore" : "friend"; - sw.WriteLine($"# Endless Online 0.28 [ {friendOrIgnore} list ]\n"); - sw.WriteLine($"# List of {friendOrIgnore}{(isIgnore ? "d" : "")} characters, use a new line for each name\n\n"); + if (!File.Exists(fileName)) + return new List(); + + List allLines; + try + { + allLines = new List(File.ReadAllLines(fileName)); + } + catch (IOException) + { + return new List(); + } + + allLines.RemoveAll(s => s.StartsWith("#") || string.IsNullOrWhiteSpace(s)); + + return allLines.Select(Capitalize).Distinct().ToList(); + } - foreach (string s in lines) - sw.WriteLine(Capitalize(s)); + private static void Save(bool isIgnore, string fileName, IEnumerable lines) + { + using (var sw = new StreamWriter(fileName)) + { + string friendOrIgnore = isIgnore ? "ignore" : "friend"; + sw.WriteLine($"# Endless Online 0.28 [ {friendOrIgnore} list ]\n"); + sw.WriteLine($"# List of {friendOrIgnore}{(isIgnore ? "d" : "")} characters, use a new line for each name\n\n"); + + foreach (string s in lines) + sw.WriteLine(Capitalize(s)); + } } - } - private static string Capitalize(string input) => char.ToUpper(input[0]) + input.Substring(1).ToLower(); -} + private static string Capitalize(string input) => char.ToUpper(input[0]) + input.Substring(1).ToLower(); + } -public interface IFriendIgnoreListService -{ - IReadOnlyList LoadList(string path); + public interface IFriendIgnoreListService + { + IReadOnlyList LoadList(string path); - void SaveFriends(string path, IReadOnlyList contents); + void SaveFriends(string path, IReadOnlyList contents); - void SaveIgnored(string path, IReadOnlyList contents); + void SaveIgnored(string path, IReadOnlyList contents); - void SaveNewFriend(string path, string name); + void SaveNewFriend(string path, string name); - void SaveNewIgnore(string path, string name); + void SaveNewIgnore(string path, string name); + } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/ArenaEventSubscriber.cs b/EndlessClient/Subscribers/ArenaEventSubscriber.cs index 5eb1b54e5..d8cd83401 100644 --- a/EndlessClient/Subscribers/ArenaEventSubscriber.cs +++ b/EndlessClient/Subscribers/ArenaEventSubscriber.cs @@ -13,94 +13,95 @@ using EOLib.Localization; using System.Collections.Generic; -namespace EndlessClient.Subscribers; - -[AutoMappedType] -public class ArenaEventSubscriber : IArenaNotifier +namespace EndlessClient.Subscribers { - private readonly IHudControlProvider _hudControlProvider; - private readonly ICurrentMapProvider _currentMapProvider; - private readonly ICharacterProvider _characterProvider; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IServerMessageHandler _serverMessageHandler; - - public ArenaEventSubscriber(IHudControlProvider hudControlProvider, - ICurrentMapProvider currentMapProvider, - ICharacterProvider characterProvider, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - IServerMessageHandler serverMessageHandler) - { - _hudControlProvider = hudControlProvider; - _currentMapProvider = currentMapProvider; - _characterProvider = characterProvider; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _serverMessageHandler = serverMessageHandler; - } - - public void NotifyArenaBusy() - { - var message = _localizedStringFinder.GetString(EOResourceID.ARENA_ROUND_DELAYED_STILL_PLAYERS); - _serverMessageHandler.AddServerMessage(message, SoundEffectID.ArenaTickSound); - } - - public void NotifyArenaStart(int players) + [AutoMappedType] + public class ArenaEventSubscriber : IArenaNotifier { - var message = _localizedStringFinder.GetString(EOResourceID.ARENA_PLAYERS_LAUNCHED); - _serverMessageHandler.AddServerMessage($"{players}{message}"); + private readonly IHudControlProvider _hudControlProvider; + private readonly ICurrentMapProvider _currentMapProvider; + private readonly ICharacterProvider _characterProvider; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IServerMessageHandler _serverMessageHandler; - var coord = _characterProvider.MainCharacter.RenderProperties.Coordinates(); - if (AdjacentToArenaTile(coord, _currentMapProvider.CurrentMap.Tiles)) + public ArenaEventSubscriber(IHudControlProvider hudControlProvider, + ICurrentMapProvider currentMapProvider, + ICharacterProvider characterProvider, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + IServerMessageHandler serverMessageHandler) { - var periodicEmoter = _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler); - periodicEmoter.StartArenaBlockTimer(); + _hudControlProvider = hudControlProvider; + _currentMapProvider = currentMapProvider; + _characterProvider = characterProvider; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _serverMessageHandler = serverMessageHandler; } - } - public void NotifyArenaKill(int killCount, string killer, string victim) - { - var message = $"{victim} {_localizedStringFinder.GetString(EOResourceID.ARENA_WAS_ELIMINATED_BY)}{killer}"; + public void NotifyArenaBusy() + { + var message = _localizedStringFinder.GetString(EOResourceID.ARENA_ROUND_DELAYED_STILL_PLAYERS); + _serverMessageHandler.AddServerMessage(message, SoundEffectID.ArenaTickSound); + } - if (killCount > 1) + public void NotifyArenaStart(int players) { - var killed = _localizedStringFinder.GetString(EOResourceID.ARENA_KILLED); - var players = _localizedStringFinder.GetString(EOResourceID.ARENA_PLAYERS); - message = $"{message}, {killer} {killed}{killCount}{players}"; + var message = _localizedStringFinder.GetString(EOResourceID.ARENA_PLAYERS_LAUNCHED); + _serverMessageHandler.AddServerMessage($"{players}{message}"); + + var coord = _characterProvider.MainCharacter.RenderProperties.Coordinates(); + if (AdjacentToArenaTile(coord, _currentMapProvider.CurrentMap.Tiles)) + { + var periodicEmoter = _hudControlProvider.GetComponent(HudControlIdentifier.PeriodicEmoteHandler); + periodicEmoter.StartArenaBlockTimer(); + } } - var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.Skeleton, log: false, filter: false); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } + public void NotifyArenaKill(int killCount, string killer, string victim) + { + var message = $"{victim} {_localizedStringFinder.GetString(EOResourceID.ARENA_WAS_ELIMINATED_BY)}{killer}"; - public void NotifyArenaWin(string winner) - { - var message = _localizedStringFinder.GetString(EOResourceID.ARENA_WON_EVENT); - _serverMessageHandler.AddServerMessage($"{winner}{message}", SoundEffectID.ArenaWin, ChatIcon.Trophy); - } + if (killCount > 1) + { + var killed = _localizedStringFinder.GetString(EOResourceID.ARENA_KILLED); + var players = _localizedStringFinder.GetString(EOResourceID.ARENA_PLAYERS); + message = $"{message}, {killer} {killed}{killCount}{players}"; + } - private static bool AdjacentToArenaTile(MapCoordinate coord, IReadOnlyMatrix tiles) - { - var check = new[] + var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.Skeleton, log: false, filter: false); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } + + public void NotifyArenaWin(string winner) { - coord, - new MapCoordinate(coord.X - 1, coord.Y), - new MapCoordinate(coord.X, coord.Y - 1), - new MapCoordinate(coord.X + 1, coord.Y), - new MapCoordinate(coord.X, coord.Y + 1), - }; + var message = _localizedStringFinder.GetString(EOResourceID.ARENA_WON_EVENT); + _serverMessageHandler.AddServerMessage($"{winner}{message}", SoundEffectID.ArenaWin, ChatIcon.Trophy); + } - foreach (var checkCoord in check) + private static bool AdjacentToArenaTile(MapCoordinate coord, IReadOnlyMatrix tiles) { - if (checkCoord.X >= 0 && checkCoord.X <= tiles.Cols && - checkCoord.Y >= 0 && checkCoord.Y <= tiles.Rows && - tiles[checkCoord.Y, checkCoord.X] == TileSpec.Arena) + var check = new[] { - return true; + coord, + new MapCoordinate(coord.X - 1, coord.Y), + new MapCoordinate(coord.X, coord.Y - 1), + new MapCoordinate(coord.X + 1, coord.Y), + new MapCoordinate(coord.X, coord.Y + 1), + }; + + foreach (var checkCoord in check) + { + if (checkCoord.X >= 0 && checkCoord.X <= tiles.Cols && + checkCoord.Y >= 0 && checkCoord.Y <= tiles.Rows && + tiles[checkCoord.Y, checkCoord.X] == TileSpec.Arena) + { + return true; + } } - } - return false; + return false; + } } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/JukeboxEventSubscriber.cs b/EndlessClient/Subscribers/JukeboxEventSubscriber.cs index fa8b3d3c2..1fda5fe85 100644 --- a/EndlessClient/Subscribers/JukeboxEventSubscriber.cs +++ b/EndlessClient/Subscribers/JukeboxEventSubscriber.cs @@ -3,21 +3,22 @@ using EOLib.Domain.Notifiers; using EOLib.Localization; -namespace EndlessClient.Subscribers; - -[AutoMappedType] -public class JukeboxEventSubscriber : IJukeboxNotifier +namespace EndlessClient.Subscribers { - private readonly IEOMessageBoxFactory _messageBoxFactory; - - public JukeboxEventSubscriber(IEOMessageBoxFactory messageBoxFactory) + [AutoMappedType] + public class JukeboxEventSubscriber : IJukeboxNotifier { - _messageBoxFactory = messageBoxFactory; - } + private readonly IEOMessageBoxFactory _messageBoxFactory; - public void JukeboxUnavailable() - { - var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.JUKEBOX_REQUESTED_RECENTLY); - dlg.ShowDialog(); + public JukeboxEventSubscriber(IEOMessageBoxFactory messageBoxFactory) + { + _messageBoxFactory = messageBoxFactory; + } + + public void JukeboxUnavailable() + { + var dlg = _messageBoxFactory.CreateMessageBox(DialogResourceID.JUKEBOX_REQUESTED_RECENTLY); + dlg.ShowDialog(); + } } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/LockerEventSubscriber.cs b/EndlessClient/Subscribers/LockerEventSubscriber.cs index 41623b15e..dd2c27600 100644 --- a/EndlessClient/Subscribers/LockerEventSubscriber.cs +++ b/EndlessClient/Subscribers/LockerEventSubscriber.cs @@ -3,27 +3,28 @@ using EOLib.Domain.Notifiers; using EOLib.Localization; -namespace EndlessClient.Subscribers; - -[AutoMappedType] -public class LockerEventSubscriber : ILockerEventNotifier +namespace EndlessClient.Subscribers { - private readonly IEOMessageBoxFactory _messageBoxFactory; - private readonly ILocalizedStringFinder _localizedStringFinder; - - public LockerEventSubscriber(IEOMessageBoxFactory messageBoxFactory, - ILocalizedStringFinder localizedStringFinder) + [AutoMappedType] + public class LockerEventSubscriber : ILockerEventNotifier { - _messageBoxFactory = messageBoxFactory; - _localizedStringFinder = localizedStringFinder; - } + private readonly IEOMessageBoxFactory _messageBoxFactory; + private readonly ILocalizedStringFinder _localizedStringFinder; - public void NotifyLockerFull(int maxItems) - { - var message = _localizedStringFinder.GetString(DialogResourceID.LOCKER_FULL_DIFF_ITEMS_MAX + 1); - var caption = _localizedStringFinder.GetString(DialogResourceID.LOCKER_FULL_DIFF_ITEMS_MAX); + public LockerEventSubscriber(IEOMessageBoxFactory messageBoxFactory, + ILocalizedStringFinder localizedStringFinder) + { + _messageBoxFactory = messageBoxFactory; + _localizedStringFinder = localizedStringFinder; + } + + public void NotifyLockerFull(int maxItems) + { + var message = _localizedStringFinder.GetString(DialogResourceID.LOCKER_FULL_DIFF_ITEMS_MAX + 1); + var caption = _localizedStringFinder.GetString(DialogResourceID.LOCKER_FULL_DIFF_ITEMS_MAX); - var dlg = _messageBoxFactory.CreateMessageBox(message.Replace("25", $"{maxItems}"), caption); - dlg.ShowDialog(); + var dlg = _messageBoxFactory.CreateMessageBox(message.Replace("25", $"{maxItems}"), caption); + dlg.ShowDialog(); + } } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/MainCharacterEventSubscriber.cs b/EndlessClient/Subscribers/MainCharacterEventSubscriber.cs index 25d17d935..f315a7336 100644 --- a/EndlessClient/Subscribers/MainCharacterEventSubscriber.cs +++ b/EndlessClient/Subscribers/MainCharacterEventSubscriber.cs @@ -6,80 +6,81 @@ using EOLib.IO.Repositories; using EOLib.Localization; -namespace EndlessClient.Subscribers; - -[MappedType(BaseType = typeof(IMainCharacterEventNotifier))] -public class MainCharacterEventSubscriber : IMainCharacterEventNotifier +namespace EndlessClient.Subscribers { - private readonly IStatusLabelSetter _statusLabelSetter; - private readonly IChatRepository _chatRepository; - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IPubFileProvider _pubFileProvider; - private readonly ICharacterRendererProvider _characterRendererProvider; - - public MainCharacterEventSubscriber(IStatusLabelSetter statusLabelSetter, - IChatRepository chatRepository, - ILocalizedStringFinder localizedStringFinder, - IPubFileProvider pubFileProvider, - ICharacterRendererProvider characterRendererProvider) - { - _statusLabelSetter = statusLabelSetter; - _chatRepository = chatRepository; - _localizedStringFinder = localizedStringFinder; - _pubFileProvider = pubFileProvider; - _characterRendererProvider = characterRendererProvider; - } - - public void NotifyGainedExp(int expDifference) - { - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, - EOResourceID.STATUS_LABEL_YOU_GAINED_EXP, - $" {expDifference} EXP"); - - var youGained = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_YOU_GAINED_EXP); - var message = $"{youGained} {expDifference} EXP"; - - var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.Star); - _chatRepository.AllChat[ChatTab.System].Add(chatData); - } - - public void NotifyTakeDamage(int damageTaken, int playerPercentHealth, bool isHeal) - { - if (isHeal && damageTaken == 0) return; - - _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.ShowDamageCounter(damageTaken, playerPercentHealth, isHeal)); - } - - public void TakeItemFromMap(int id, int amountTaken) + [MappedType(BaseType = typeof(IMainCharacterEventNotifier))] + public class MainCharacterEventSubscriber : IMainCharacterEventNotifier { - var rec = _pubFileProvider.EIFFile[id]; - - var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_PICKUP_YOU_PICKED_UP)} {amountTaken} {rec.Name}"; - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.UpArrow)); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_YOU_PICKED_UP, - $" {amountTaken} {rec.Name}"); - } - - public void DropItem(int id, int amountDropped) - { - var rec = _pubFileProvider.EIFFile[id]; - - var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_DROP_YOU_DROPPED)} {amountDropped} {rec.Name}"; - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.DownArrow)); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_DROP_YOU_DROPPED, - $" {amountDropped} {rec.Name}"); - } - - public void JunkItem(int id, int amountRemoved) - { - var rec = _pubFileProvider.EIFFile[id]; - - var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_JUNK_YOU_JUNKED)} {amountRemoved} {rec.Name}"; - _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.DownArrow)); - - _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_JUNK_YOU_JUNKED, - $" {amountRemoved} {rec.Name}"); + private readonly IStatusLabelSetter _statusLabelSetter; + private readonly IChatRepository _chatRepository; + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IPubFileProvider _pubFileProvider; + private readonly ICharacterRendererProvider _characterRendererProvider; + + public MainCharacterEventSubscriber(IStatusLabelSetter statusLabelSetter, + IChatRepository chatRepository, + ILocalizedStringFinder localizedStringFinder, + IPubFileProvider pubFileProvider, + ICharacterRendererProvider characterRendererProvider) + { + _statusLabelSetter = statusLabelSetter; + _chatRepository = chatRepository; + _localizedStringFinder = localizedStringFinder; + _pubFileProvider = pubFileProvider; + _characterRendererProvider = characterRendererProvider; + } + + public void NotifyGainedExp(int expDifference) + { + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, + EOResourceID.STATUS_LABEL_YOU_GAINED_EXP, + $" {expDifference} EXP"); + + var youGained = _localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_YOU_GAINED_EXP); + var message = $"{youGained} {expDifference} EXP"; + + var chatData = new ChatData(ChatTab.System, string.Empty, message, ChatIcon.Star); + _chatRepository.AllChat[ChatTab.System].Add(chatData); + } + + public void NotifyTakeDamage(int damageTaken, int playerPercentHealth, bool isHeal) + { + if (isHeal && damageTaken == 0) return; + + _characterRendererProvider.MainCharacterRenderer.MatchSome(r => r.ShowDamageCounter(damageTaken, playerPercentHealth, isHeal)); + } + + public void TakeItemFromMap(int id, int amountTaken) + { + var rec = _pubFileProvider.EIFFile[id]; + + var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_PICKUP_YOU_PICKED_UP)} {amountTaken} {rec.Name}"; + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.UpArrow)); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_PICKUP_YOU_PICKED_UP, + $" {amountTaken} {rec.Name}"); + } + + public void DropItem(int id, int amountDropped) + { + var rec = _pubFileProvider.EIFFile[id]; + + var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_DROP_YOU_DROPPED)} {amountDropped} {rec.Name}"; + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.DownArrow)); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_DROP_YOU_DROPPED, + $" {amountDropped} {rec.Name}"); + } + + public void JunkItem(int id, int amountRemoved) + { + var rec = _pubFileProvider.EIFFile[id]; + + var chatMessage = $"{_localizedStringFinder.GetString(EOResourceID.STATUS_LABEL_ITEM_JUNK_YOU_JUNKED)} {amountRemoved} {rec.Name}"; + _chatRepository.AllChat[ChatTab.System].Add(new ChatData(ChatTab.System, string.Empty, chatMessage, ChatIcon.DownArrow)); + + _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_JUNK_YOU_JUNKED, + $" {amountRemoved} {rec.Name}"); + } } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs b/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs index 42b40c081..de1ebbe6f 100644 --- a/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs +++ b/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs @@ -9,69 +9,70 @@ using System; using System.Linq; -namespace EndlessClient.Subscribers; - -[MappedType(BaseType = typeof(IOtherCharacterEventNotifier))] -public class OtherCharacterEventSubscriber : IOtherCharacterEventNotifier +namespace EndlessClient.Subscribers { - private readonly IChatBubbleActions _chatBubbleActions; - private readonly ICharacterRendererProvider _characterRendererProvider; - private readonly IFriendIgnoreListService _friendIgnoreListService; - private readonly IConfigurationProvider _configurationProvider; - private readonly IChatProcessor _chatProcessor; - - public OtherCharacterEventSubscriber(IChatBubbleActions chatBubbleActions, - ICharacterRendererProvider characterRendererProvider, - IFriendIgnoreListService friendIgnoreListService, - IConfigurationProvider configurationProvider, - IChatProcessor chatProcessor) + [MappedType(BaseType = typeof(IOtherCharacterEventNotifier))] + public class OtherCharacterEventSubscriber : IOtherCharacterEventNotifier { - _chatBubbleActions = chatBubbleActions; - _characterRendererProvider = characterRendererProvider; - _friendIgnoreListService = friendIgnoreListService; - _configurationProvider = configurationProvider; - _chatProcessor = chatProcessor; - } + private readonly IChatBubbleActions _chatBubbleActions; + private readonly ICharacterRendererProvider _characterRendererProvider; + private readonly IFriendIgnoreListService _friendIgnoreListService; + private readonly IConfigurationProvider _configurationProvider; + private readonly IChatProcessor _chatProcessor; - public void OtherCharacterTakeDamage(int characterID, int playerPercentHealth, int damageTaken, bool isHeal) - { - if (!_characterRendererProvider.CharacterRenderers.ContainsKey(characterID) || - (isHeal && damageTaken == 0)) - return; + public OtherCharacterEventSubscriber(IChatBubbleActions chatBubbleActions, + ICharacterRendererProvider characterRendererProvider, + IFriendIgnoreListService friendIgnoreListService, + IConfigurationProvider configurationProvider, + IChatProcessor chatProcessor) + { + _chatBubbleActions = chatBubbleActions; + _characterRendererProvider = characterRendererProvider; + _friendIgnoreListService = friendIgnoreListService; + _configurationProvider = configurationProvider; + _chatProcessor = chatProcessor; + } - _characterRendererProvider.CharacterRenderers[characterID].ShowDamageCounter(damageTaken, playerPercentHealth, isHeal); - } + public void OtherCharacterTakeDamage(int characterID, int playerPercentHealth, int damageTaken, bool isHeal) + { + if (!_characterRendererProvider.CharacterRenderers.ContainsKey(characterID) || + (isHeal && damageTaken == 0)) + return; - public void OtherCharacterSaySomething(int characterID, string message) - { - SaySomethingShared(isGroupChat: false, characterID: characterID, message: message); - } + _characterRendererProvider.CharacterRenderers[characterID].ShowDamageCounter(damageTaken, playerPercentHealth, isHeal); + } - public void OtherCharacterSaySomethingToGroup(int characterID, string message) - { - SaySomethingShared(isGroupChat: true, characterID: characterID, message: message); - } + public void OtherCharacterSaySomething(int characterID, string message) + { + SaySomethingShared(isGroupChat: false, characterID: characterID, message: message); + } - public void AdminAnnounce(string message) - { - _chatBubbleActions.ShowChatBubbleForMainCharacter(message); - } + public void OtherCharacterSaySomethingToGroup(int characterID, string message) + { + SaySomethingShared(isGroupChat: true, characterID: characterID, message: message); + } - private void SaySomethingShared(int characterID, string message, bool isGroupChat) - { - if (_characterRendererProvider.CharacterRenderers.TryGetValue(characterID, out var characterRenderer) || - _characterRendererProvider.MainCharacterRenderer.HasValue) + public void AdminAnnounce(string message) + { + _chatBubbleActions.ShowChatBubbleForMainCharacter(message); + } + + private void SaySomethingShared(int characterID, string message, bool isGroupChat) { - _characterRendererProvider.MainCharacterRenderer.MatchSome(x => characterRenderer = x); + if (_characterRendererProvider.CharacterRenderers.TryGetValue(characterID, out var characterRenderer) || + _characterRendererProvider.MainCharacterRenderer.HasValue) + { + _characterRendererProvider.MainCharacterRenderer.MatchSome(x => characterRenderer = x); - var name = characterRenderer.Character.Name; + var name = characterRenderer.Character.Name; - var ignoreList = _friendIgnoreListService.LoadList(Constants.IgnoreListFile); - if (ignoreList.Any(x => x.Equals(name, StringComparison.InvariantCultureIgnoreCase)) || - (_configurationProvider.StrictFilterEnabled && !_chatProcessor.FilterCurses(message).ShowChat)) - return; + var ignoreList = _friendIgnoreListService.LoadList(Constants.IgnoreListFile); + if (ignoreList.Any(x => x.Equals(name, StringComparison.InvariantCultureIgnoreCase)) || + (_configurationProvider.StrictFilterEnabled && !_chatProcessor.FilterCurses(message).ShowChat)) + return; - characterRenderer.ShowChatBubble(message, isGroupChat); + characterRenderer.ShowChatBubble(message, isGroupChat); + } } } } \ No newline at end of file diff --git a/EndlessClient/Subscribers/ServerRebootEventSubscriber.cs b/EndlessClient/Subscribers/ServerRebootEventSubscriber.cs index a6e191217..13d066d9c 100644 --- a/EndlessClient/Subscribers/ServerRebootEventSubscriber.cs +++ b/EndlessClient/Subscribers/ServerRebootEventSubscriber.cs @@ -5,29 +5,30 @@ using EOLib.Domain.Notifiers; using EOLib.Localization; -namespace EndlessClient.Subscribers; - -[AutoMappedType] -public class ServerRebootEventNotifier : IServerRebootNotifier +namespace EndlessClient.Subscribers { - private readonly ILocalizedStringFinder _localizedStringFinder; - private readonly IServerMessageHandler _serverMessageHandler; - private readonly IStatusLabelSetter _statusLabelSetter; - - public ServerRebootEventNotifier(ILocalizedStringFinder localizedStringFinder, - IServerMessageHandler serverMessageHandler, - IStatusLabelSetter statusLabelSetter, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class ServerRebootEventNotifier : IServerRebootNotifier { - _localizedStringFinder = localizedStringFinder; - _serverMessageHandler = serverMessageHandler; - _statusLabelSetter = statusLabelSetter; - } + private readonly ILocalizedStringFinder _localizedStringFinder; + private readonly IServerMessageHandler _serverMessageHandler; + private readonly IStatusLabelSetter _statusLabelSetter; - public void NotifyServerReboot() - { - var message = _localizedStringFinder.GetString(EOResourceID.REBOOT_SEQUENCE_STARTED); - _serverMessageHandler.AddServerMessage(message, SoundEffectID.Reboot); - _statusLabelSetter.ShowWarning(message); + public ServerRebootEventNotifier(ILocalizedStringFinder localizedStringFinder, + IServerMessageHandler serverMessageHandler, + IStatusLabelSetter statusLabelSetter, + ISfxPlayer sfxPlayer) + { + _localizedStringFinder = localizedStringFinder; + _serverMessageHandler = serverMessageHandler; + _statusLabelSetter = statusLabelSetter; + } + + public void NotifyServerReboot() + { + var message = _localizedStringFinder.GetString(EOResourceID.REBOOT_SEQUENCE_STARTED); + _serverMessageHandler.AddServerMessage(message, SoundEffectID.Reboot); + _statusLabelSetter.ShowWarning(message); + } } } \ No newline at end of file diff --git a/EndlessClient/Test/CharacterStateTest.cs b/EndlessClient/Test/CharacterStateTest.cs index f0025092e..8770a745e 100644 --- a/EndlessClient/Test/CharacterStateTest.cs +++ b/EndlessClient/Test/CharacterStateTest.cs @@ -15,291 +15,292 @@ using System.Collections.Generic; using System.Linq; -namespace EndlessClient.Test; - -public class CharacterStateTest : DrawableGameComponent +namespace EndlessClient.Test { - private enum DisplayState - { - Standing, - SitChair, - SitFloor, - Attack1, - Attack2, - Walk1, - Walk2, - Walk3, - SpellCast, - AttackingAnimation, - WalkingAnimation, - SpellCastAnimation - } - - private static readonly List _allDisplayStates; - - static CharacterStateTest() + public class CharacterStateTest : DrawableGameComponent { - _allDisplayStates = ((DisplayState[])Enum.GetValues(typeof(DisplayState))).ToList(); - } - - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IMetadataProvider _weaponMetadataProvider; + private enum DisplayState + { + Standing, + SitChair, + SitFloor, + Attack1, + Attack2, + Walk1, + Walk2, + Walk3, + SpellCast, + AttackingAnimation, + WalkingAnimation, + SpellCastAnimation + } - private CharacterRenderProperties _baseProperties; - private readonly Dictionary _itemIndices; - private readonly List _renderersForDifferentStates; + private static readonly List _allDisplayStates; - private KeyboardState _previousState, _currentState; + static CharacterStateTest() + { + _allDisplayStates = ((DisplayState[])Enum.GetValues(typeof(DisplayState))).ToList(); + } - private bool _isBowEquipped; - private int _lastGraphic; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IMetadataProvider _weaponMetadataProvider; - private DateTime _lastWalk, _lastAttack, _lastSpell; + private CharacterRenderProperties _baseProperties; + private readonly Dictionary _itemIndices; + private readonly List _renderersForDifferentStates; - public CharacterStateTest(IEndlessGame baseGame, - ICharacterRendererFactory characterRendererFactory, - IEIFFileProvider eifFileProvider, - IMetadataProvider weaponMetadataProvider) - : base((Game)baseGame) - { - _characterRendererFactory = characterRendererFactory; - _eifFileProvider = eifFileProvider; - _weaponMetadataProvider = weaponMetadataProvider; + private KeyboardState _previousState, _currentState; - _itemIndices = ((ItemType[])Enum.GetValues(typeof(ItemType))).ToDictionary(k => k, v => 0); - _renderersForDifferentStates = new List(12); - } + private bool _isBowEquipped; + private int _lastGraphic; - public override void Initialize() - { - DrawOrder = 0; + private DateTime _lastWalk, _lastAttack, _lastSpell; - _baseProperties = new CharacterRenderProperties.Builder().ToImmutable(); - foreach (var displayState in _allDisplayStates) + public CharacterStateTest(IEndlessGame baseGame, + ICharacterRendererFactory characterRendererFactory, + IEIFFileProvider eifFileProvider, + IMetadataProvider weaponMetadataProvider) + : base((Game)baseGame) { - var props = GetRenderPropertiesForState(displayState); - _renderersForDifferentStates.Add(_characterRendererFactory.CreateCharacterRenderer(Character.Default.WithRenderProperties(props), isUiControl: false)); - _renderersForDifferentStates.OfType().Last().DrawOrder = 10; + _characterRendererFactory = characterRendererFactory; + _eifFileProvider = eifFileProvider; + _weaponMetadataProvider = weaponMetadataProvider; + + _itemIndices = ((ItemType[])Enum.GetValues(typeof(ItemType))).ToDictionary(k => k, v => 0); + _renderersForDifferentStates = new List(12); } - _renderersForDifferentStates.ForEach(Game.Components.Add); + public override void Initialize() + { + DrawOrder = 0; - _currentState = _previousState = Keyboard.GetState(); - _lastWalk = _lastAttack = _lastSpell = DateTime.Now; + _baseProperties = new CharacterRenderProperties.Builder().ToImmutable(); + foreach (var displayState in _allDisplayStates) + { + var props = GetRenderPropertiesForState(displayState); + _renderersForDifferentStates.Add(_characterRendererFactory.CreateCharacterRenderer(Character.Default.WithRenderProperties(props), isUiControl: false)); + _renderersForDifferentStates.OfType().Last().DrawOrder = 10; + } - base.Initialize(); - } + _renderersForDifferentStates.ForEach(Game.Components.Add); - protected override void LoadContent() - { - RefreshDisplayedCharacters(); + _currentState = _previousState = Keyboard.GetState(); + _lastWalk = _lastAttack = _lastSpell = DateTime.Now; - foreach (var displayState in _allDisplayStates) - { - var characterRenderer = _renderersForDifferentStates[(int)displayState]; - characterRenderer.SetAbsoluteScreenPosition(50 + 640 / 4 * ((int)displayState % 4), - 30 + 480 / 3 * ((int)displayState / 4)); + base.Initialize(); } - base.LoadContent(); - } + protected override void LoadContent() + { + RefreshDisplayedCharacters(); - //standing = 0 - //sitting: chair floor - //attacking: 0 1 2 +animated (0-1-2-0) - //walking: 0 1 2 3 +animated (0-1-2-3-0) - //spellcast: 0 1 +animated (0-1-0) + foreach (var displayState in _allDisplayStates) + { + var characterRenderer = _renderersForDifferentStates[(int)displayState]; + characterRenderer.SetAbsoluteScreenPosition(50 + 640 / 4 * ((int)displayState % 4), + 30 + 480 / 3 * ((int)displayState / 4)); + } - public override void Update(GameTime gameTime) - { - _currentState = Keyboard.GetState(); + base.LoadContent(); + } - var increment = ShiftPressed ? -1 : 1; + //standing = 0 + //sitting: chair floor + //attacking: 0 1 2 +animated (0-1-2-0) + //walking: 0 1 2 3 +animated (0-1-2-3-0) + //spellcast: 0 1 +animated (0-1-0) - var update = false; - if (KeyPressed(Keys.D1)) - { - _baseProperties = _baseProperties.WithGender((_baseProperties.Gender + increment) % 2); - update = true; - } - else if (KeyPressed(Keys.D2)) + public override void Update(GameTime gameTime) { - if (CtrlPressed) + _currentState = Keyboard.GetState(); + + var increment = ShiftPressed ? -1 : 1; + + var update = false; + if (KeyPressed(Keys.D1)) { - const int NUM_HAIR_COLORS = 10; - if (_baseProperties.HairColor + increment < 0) _baseProperties = _baseProperties.WithHairColor(NUM_HAIR_COLORS); - _baseProperties = _baseProperties.WithHairColor((_baseProperties.HairColor + increment) % NUM_HAIR_COLORS); + _baseProperties = _baseProperties.WithGender((_baseProperties.Gender + increment) % 2); + update = true; } - else + else if (KeyPressed(Keys.D2)) { - const int NUM_HAIR_STYLES = 21; - if (_baseProperties.HairStyle + increment < 0) _baseProperties = _baseProperties.WithHairColor(NUM_HAIR_STYLES); - _baseProperties = _baseProperties.WithHairStyle((_baseProperties.HairStyle + increment) % NUM_HAIR_STYLES); + if (CtrlPressed) + { + const int NUM_HAIR_COLORS = 10; + if (_baseProperties.HairColor + increment < 0) _baseProperties = _baseProperties.WithHairColor(NUM_HAIR_COLORS); + _baseProperties = _baseProperties.WithHairColor((_baseProperties.HairColor + increment) % NUM_HAIR_COLORS); + } + else + { + const int NUM_HAIR_STYLES = 21; + if (_baseProperties.HairStyle + increment < 0) _baseProperties = _baseProperties.WithHairColor(NUM_HAIR_STYLES); + _baseProperties = _baseProperties.WithHairStyle((_baseProperties.HairStyle + increment) % NUM_HAIR_STYLES); + } + update = true; } - update = true; - } - else if (KeyPressed(Keys.D3)) - { - _baseProperties = _baseProperties.WithHatGraphic(GetNextItemGraphicMatching(ItemType.Hat, _baseProperties.HatGraphic)); - update = true; - } - else if (KeyPressed(Keys.D4)) - { - _baseProperties = _baseProperties.WithArmorGraphic(GetNextItemGraphicMatching(ItemType.Armor, _baseProperties.ArmorGraphic)); - update = true; - } - else if (KeyPressed(Keys.D5)) - { - _baseProperties = _baseProperties.WithBootsGraphic(GetNextItemGraphicMatching(ItemType.Boots, _baseProperties.BootsGraphic)); - update = true; - } - else if (KeyPressed(Keys.D6) && !_isBowEquipped) - { - var nextGraphic = GetNextItemGraphicMatching(ItemType.Weapon, _baseProperties.WeaponGraphic); - _baseProperties = _baseProperties.WithWeaponGraphic(nextGraphic); - update = true; - } - else if (KeyPressed(Keys.D7)) - { - _baseProperties = _baseProperties.WithShieldGraphic(GetNextItemGraphicMatching(ItemType.Shield, _baseProperties.ShieldGraphic)); - update = true; - } - else if (KeyPressed(Keys.D8)) - { - if ((int)_baseProperties.Direction + increment < 0) _baseProperties = _baseProperties.WithDirection((EODirection)4); - _baseProperties = _baseProperties.WithDirection((EODirection)(((int)_baseProperties.Direction + increment) % 4)); - update = true; - } - else if (KeyPressed(Keys.Space)) - { - if (!_isBowEquipped) + else if (KeyPressed(Keys.D3)) + { + _baseProperties = _baseProperties.WithHatGraphic(GetNextItemGraphicMatching(ItemType.Hat, _baseProperties.HatGraphic)); + update = true; + } + else if (KeyPressed(Keys.D4)) + { + _baseProperties = _baseProperties.WithArmorGraphic(GetNextItemGraphicMatching(ItemType.Armor, _baseProperties.ArmorGraphic)); + update = true; + } + else if (KeyPressed(Keys.D5)) + { + _baseProperties = _baseProperties.WithBootsGraphic(GetNextItemGraphicMatching(ItemType.Boots, _baseProperties.BootsGraphic)); + update = true; + } + else if (KeyPressed(Keys.D6) && !_isBowEquipped) + { + var nextGraphic = GetNextItemGraphicMatching(ItemType.Weapon, _baseProperties.WeaponGraphic); + _baseProperties = _baseProperties.WithWeaponGraphic(nextGraphic); + update = true; + } + else if (KeyPressed(Keys.D7)) + { + _baseProperties = _baseProperties.WithShieldGraphic(GetNextItemGraphicMatching(ItemType.Shield, _baseProperties.ShieldGraphic)); + update = true; + } + else if (KeyPressed(Keys.D8)) { - _lastGraphic = _baseProperties.WeaponGraphic; - var firstBowWeapon = EIFFile.First(x => x.Type == ItemType.Weapon && x.SubType == ItemSubType.Ranged); - _baseProperties = _baseProperties.WithWeaponGraphic(firstBowWeapon.DollGraphic); + if ((int)_baseProperties.Direction + increment < 0) _baseProperties = _baseProperties.WithDirection((EODirection)4); + _baseProperties = _baseProperties.WithDirection((EODirection)(((int)_baseProperties.Direction + increment) % 4)); + update = true; } - else + else if (KeyPressed(Keys.Space)) { - _baseProperties = _baseProperties.WithWeaponGraphic(_lastGraphic); + if (!_isBowEquipped) + { + _lastGraphic = _baseProperties.WeaponGraphic; + var firstBowWeapon = EIFFile.First(x => x.Type == ItemType.Weapon && x.SubType == ItemSubType.Ranged); + _baseProperties = _baseProperties.WithWeaponGraphic(firstBowWeapon.DollGraphic); + } + else + { + _baseProperties = _baseProperties.WithWeaponGraphic(_lastGraphic); + } + + _isBowEquipped = !_isBowEquipped; + update = true; } - _isBowEquipped = !_isBowEquipped; - update = true; - } + if (update) + RefreshDisplayedCharacters(); - if (update) - RefreshDisplayedCharacters(); + _previousState = _currentState; + + var now = DateTime.Now; + if ((now - _lastWalk).TotalMilliseconds > 500) + { + var rend = _renderersForDifferentStates[(int)DisplayState.WalkingAnimation]; + rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextWalkFrame(false)); + _lastWalk = now; + } - _previousState = _currentState; + if ((now - _lastAttack).TotalMilliseconds > 500) + { + var rend = _renderersForDifferentStates[(int)DisplayState.AttackingAnimation]; + var isRanged = _weaponMetadataProvider.GetValueOrDefault(rend.Character.RenderProperties.WeaponGraphic).Ranged; + rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextAttackFrame(isRanged)); + _lastAttack = now; + } - var now = DateTime.Now; - if ((now - _lastWalk).TotalMilliseconds > 500) - { - var rend = _renderersForDifferentStates[(int)DisplayState.WalkingAnimation]; - rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextWalkFrame(false)); - _lastWalk = now; + if ((now - _lastSpell).TotalMilliseconds > 500) + { + var rend = _renderersForDifferentStates[(int)DisplayState.SpellCastAnimation]; + rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextSpellCastFrame()); + _lastSpell = now; + } + + base.Update(gameTime); } - if ((now - _lastAttack).TotalMilliseconds > 500) + public override void Draw(GameTime gameTime) { - var rend = _renderersForDifferentStates[(int)DisplayState.AttackingAnimation]; - var isRanged = _weaponMetadataProvider.GetValueOrDefault(rend.Character.RenderProperties.WeaponGraphic).Ranged; - rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextAttackFrame(isRanged)); - _lastAttack = now; + GraphicsDevice.Clear(Color.White); + + base.Draw(gameTime); } - if ((now - _lastSpell).TotalMilliseconds > 500) + private CharacterRenderProperties GetRenderPropertiesForState(DisplayState displayState) { - var rend = _renderersForDifferentStates[(int)DisplayState.SpellCastAnimation]; - rend.Character = rend.Character.WithRenderProperties(rend.Character.RenderProperties.WithNextSpellCastFrame()); - _lastSpell = now; + var isRanged = _weaponMetadataProvider.GetValueOrDefault(_baseProperties.WeaponGraphic).Ranged; + switch (displayState) + { + case DisplayState.Standing: + return _baseProperties; + case DisplayState.SitChair: + return _baseProperties.WithSitState(SitState.Chair); + case DisplayState.SitFloor: + return _baseProperties.WithSitState(SitState.Floor); + case DisplayState.Attack1: + return _baseProperties.WithNextAttackFrame(isRanged); + case DisplayState.Attack2: + return _baseProperties.WithNextAttackFrame(isRanged).WithNextAttackFrame(isRanged); + case DisplayState.Walk1: + return _baseProperties.WithNextWalkFrame(); + case DisplayState.Walk2: + return _baseProperties.WithNextWalkFrame().WithNextWalkFrame(); + case DisplayState.Walk3: + return _baseProperties.WithNextWalkFrame().WithNextWalkFrame().WithNextWalkFrame(); + case DisplayState.SpellCast: + return _baseProperties.WithNextSpellCastFrame(); + //create a clone of the properties for animation + case DisplayState.WalkingAnimation: + case DisplayState.SpellCastAnimation: + case DisplayState.AttackingAnimation: + return _baseProperties.ToBuilder().ToImmutable(); + default: + throw new ArgumentOutOfRangeException(); + } } - base.Update(gameTime); - } - - public override void Draw(GameTime gameTime) - { - GraphicsDevice.Clear(Color.White); - - base.Draw(gameTime); - } - - private CharacterRenderProperties GetRenderPropertiesForState(DisplayState displayState) - { - var isRanged = _weaponMetadataProvider.GetValueOrDefault(_baseProperties.WeaponGraphic).Ranged; - switch (displayState) + private void RefreshDisplayedCharacters() { - case DisplayState.Standing: - return _baseProperties; - case DisplayState.SitChair: - return _baseProperties.WithSitState(SitState.Chair); - case DisplayState.SitFloor: - return _baseProperties.WithSitState(SitState.Floor); - case DisplayState.Attack1: - return _baseProperties.WithNextAttackFrame(isRanged); - case DisplayState.Attack2: - return _baseProperties.WithNextAttackFrame(isRanged).WithNextAttackFrame(isRanged); - case DisplayState.Walk1: - return _baseProperties.WithNextWalkFrame(); - case DisplayState.Walk2: - return _baseProperties.WithNextWalkFrame().WithNextWalkFrame(); - case DisplayState.Walk3: - return _baseProperties.WithNextWalkFrame().WithNextWalkFrame().WithNextWalkFrame(); - case DisplayState.SpellCast: - return _baseProperties.WithNextSpellCastFrame(); - //create a clone of the properties for animation - case DisplayState.WalkingAnimation: - case DisplayState.SpellCastAnimation: - case DisplayState.AttackingAnimation: - return _baseProperties.ToBuilder().ToImmutable(); - default: - throw new ArgumentOutOfRangeException(); + foreach (var displayState in _allDisplayStates) + { + var props = GetRenderPropertiesForState(displayState); + _renderersForDifferentStates[(int)displayState].Character = Character.Default.WithRenderProperties(props); + } } - } - private void RefreshDisplayedCharacters() - { - foreach (var displayState in _allDisplayStates) + private bool KeyPressed(Keys key) { - var props = GetRenderPropertiesForState(displayState); - _renderersForDifferentStates[(int)displayState].Character = Character.Default.WithRenderProperties(props); + return _previousState.IsKeyDown(key) && _currentState.IsKeyUp(key); } - } - private bool KeyPressed(Keys key) - { - return _previousState.IsKeyDown(key) && _currentState.IsKeyUp(key); - } + private bool ShiftPressed => _previousState.IsKeyDown(Keys.LeftShift) || _previousState.IsKeyDown(Keys.RightShift); - private bool ShiftPressed => _previousState.IsKeyDown(Keys.LeftShift) || _previousState.IsKeyDown(Keys.RightShift); + private bool CtrlPressed => _previousState.IsKeyDown(Keys.LeftControl) || _previousState.IsKeyDown(Keys.RightControl); - private bool CtrlPressed => _previousState.IsKeyDown(Keys.LeftControl) || _previousState.IsKeyDown(Keys.RightControl); + private int GetNextItemGraphicMatching(ItemType type, int currentGraphic) + { + var increment = ShiftPressed ? -1 : 1; + var matchingItems = EIFFile.Where(x => x.Type == type).OrderBy(x => x.ID).ToList(); + _itemIndices[type] = (_itemIndices[type] + increment) % matchingItems.Count; - private int GetNextItemGraphicMatching(ItemType type, int currentGraphic) - { - var increment = ShiftPressed ? -1 : 1; - var matchingItems = EIFFile.Where(x => x.Type == type).OrderBy(x => x.ID).ToList(); - _itemIndices[type] = (_itemIndices[type] + increment) % matchingItems.Count; + if (_itemIndices[type] + increment < 0) + { + _itemIndices[type] = 0; + return 0; + } - if (_itemIndices[type] + increment < 0) - { - _itemIndices[type] = 0; - return 0; + return matchingItems[_itemIndices[type]].DollGraphic; } - return matchingItems[_itemIndices[type]].DollGraphic; - } - - private IPubFile EIFFile => _eifFileProvider.EIFFile; + private IPubFile EIFFile => _eifFileProvider.EIFFile; - protected override void Dispose(bool disposing) - { - if (disposing) + protected override void Dispose(bool disposing) { - _renderersForDifferentStates.ForEach(x => x.Dispose()); + if (disposing) + { + _renderersForDifferentStates.ForEach(x => x.Dispose()); + } + base.Dispose(disposing); } - base.Dispose(disposing); } } \ No newline at end of file diff --git a/EndlessClient/Test/TestModeLauncher.cs b/EndlessClient/Test/TestModeLauncher.cs index d0b7d55b9..b6d5e8f96 100644 --- a/EndlessClient/Test/TestModeLauncher.cs +++ b/EndlessClient/Test/TestModeLauncher.cs @@ -5,47 +5,48 @@ using EndlessClient.Rendering.Metadata.Models; using EOLib.IO.Repositories; -namespace EndlessClient.Test; - -[AutoMappedType] -public class TestModeLauncher : ITestModeLauncher +namespace EndlessClient.Test { - private readonly IEndlessGameProvider _endlessGameProvider; - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly IEIFFileProvider _eifFileProvider; - private readonly IGameStateProvider _gameStateProvider; - private readonly IMetadataProvider _weaponMetadataProvider; - - public TestModeLauncher(IEndlessGameProvider endlessGameProvider, - ICharacterRendererFactory characterRendererFactory, - IEIFFileProvider eifFileProvider, - IGameStateProvider gameStateProvider, - IMetadataProvider weaponMetadataProvider) + [AutoMappedType] + public class TestModeLauncher : ITestModeLauncher { - _endlessGameProvider = endlessGameProvider; - _characterRendererFactory = characterRendererFactory; - _eifFileProvider = eifFileProvider; - _gameStateProvider = gameStateProvider; - _weaponMetadataProvider = weaponMetadataProvider; - } + private readonly IEndlessGameProvider _endlessGameProvider; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly IEIFFileProvider _eifFileProvider; + private readonly IGameStateProvider _gameStateProvider; + private readonly IMetadataProvider _weaponMetadataProvider; - public void LaunchTestMode() - { - if (_gameStateProvider.CurrentState != GameStates.None) - return; + public TestModeLauncher(IEndlessGameProvider endlessGameProvider, + ICharacterRendererFactory characterRendererFactory, + IEIFFileProvider eifFileProvider, + IGameStateProvider gameStateProvider, + IMetadataProvider weaponMetadataProvider) + { + _endlessGameProvider = endlessGameProvider; + _characterRendererFactory = characterRendererFactory; + _eifFileProvider = eifFileProvider; + _gameStateProvider = gameStateProvider; + _weaponMetadataProvider = weaponMetadataProvider; + } - var testMode = new CharacterStateTest( - _endlessGameProvider.Game, - _characterRendererFactory, - _eifFileProvider, - _weaponMetadataProvider); + public void LaunchTestMode() + { + if (_gameStateProvider.CurrentState != GameStates.None) + return; - _endlessGameProvider.Game.Components.Clear(); - _endlessGameProvider.Game.Components.Add(testMode); + var testMode = new CharacterStateTest( + _endlessGameProvider.Game, + _characterRendererFactory, + _eifFileProvider, + _weaponMetadataProvider); + + _endlessGameProvider.Game.Components.Clear(); + _endlessGameProvider.Game.Components.Add(testMode); + } } -} -public interface ITestModeLauncher -{ - void LaunchTestMode(); + public interface ITestModeLauncher + { + void LaunchTestMode(); + } } \ No newline at end of file diff --git a/EndlessClient/UIControls/BlinkingLabel.cs b/EndlessClient/UIControls/BlinkingLabel.cs index a875471e0..1b845f448 100644 --- a/EndlessClient/UIControls/BlinkingLabel.cs +++ b/EndlessClient/UIControls/BlinkingLabel.cs @@ -2,52 +2,53 @@ using System; using XNAControls; -namespace EndlessClient.UIControls; - -public class BlinkingLabel : XNALabel +namespace EndlessClient.UIControls { - /// - /// Get or Set the rate of blinking in milliseconds - /// - public int? BlinkRate { get; set; } - - private DateTime? _callbackStartTime; - private int _callbackDueTime; - private DateTime _lastToggleTime; - private Action _callback; - - public BlinkingLabel(string spriteFontContentName) - : base(spriteFontContentName) + public class BlinkingLabel : XNALabel { - _lastToggleTime = DateTime.Now; - } - - /// - /// Sets some action that is invoked after the specified amount of time - /// - /// Time to wait before invoking (in milliseconds) - /// Action to invoke - public void SetCallback(int dueTime, Action a) - { - _callbackDueTime = dueTime; - _callbackStartTime = DateTime.Now; - _callback = a; - } - - public override void Update(GameTime gameTime) - { - if (_callbackStartTime.HasValue && (DateTime.Now - _callbackStartTime.Value).TotalMilliseconds > _callbackDueTime) + /// + /// Get or Set the rate of blinking in milliseconds + /// + public int? BlinkRate { get; set; } + + private DateTime? _callbackStartTime; + private int _callbackDueTime; + private DateTime _lastToggleTime; + private Action _callback; + + public BlinkingLabel(string spriteFontContentName) + : base(spriteFontContentName) { - _callback(); - _callbackStartTime = null; + _lastToggleTime = DateTime.Now; } - if (BlinkRate.HasValue && (DateTime.Now - _lastToggleTime).TotalMilliseconds > BlinkRate) + /// + /// Sets some action that is invoked after the specified amount of time + /// + /// Time to wait before invoking (in milliseconds) + /// Action to invoke + public void SetCallback(int dueTime, Action a) { - _lastToggleTime = DateTime.Now; - Visible = !Visible; + _callbackDueTime = dueTime; + _callbackStartTime = DateTime.Now; + _callback = a; } - base.Update(gameTime); + public override void Update(GameTime gameTime) + { + if (_callbackStartTime.HasValue && (DateTime.Now - _callbackStartTime.Value).TotalMilliseconds > _callbackDueTime) + { + _callback(); + _callbackStartTime = null; + } + + if (BlinkRate.HasValue && (DateTime.Now - _lastToggleTime).TotalMilliseconds > BlinkRate) + { + _lastToggleTime = DateTime.Now; + Visible = !Visible; + } + + base.Update(gameTime); + } } } \ No newline at end of file diff --git a/EndlessClient/UIControls/CharacterControl.cs b/EndlessClient/UIControls/CharacterControl.cs index 054ed5905..fd68673cc 100644 --- a/EndlessClient/UIControls/CharacterControl.cs +++ b/EndlessClient/UIControls/CharacterControl.cs @@ -4,58 +4,59 @@ using Microsoft.Xna.Framework; using XNAControls; -namespace EndlessClient.UIControls; - -public class CharacterControl : XNAControl +namespace EndlessClient.UIControls { - public CharacterRenderProperties RenderProperties + public class CharacterControl : XNAControl { - get { return _characterRenderer.Character.RenderProperties; } - - protected set + public CharacterRenderProperties RenderProperties { - _characterRenderer.Character = _characterRenderer.Character.WithRenderProperties(value); + get { return _characterRenderer.Character.RenderProperties; } + + protected set + { + _characterRenderer.Character = _characterRenderer.Character.WithRenderProperties(value); + } } - } - protected readonly ICharacterRenderer _characterRenderer; + protected readonly ICharacterRenderer _characterRenderer; - public CharacterControl(Character character, - ICharacterRendererFactory characterRendererFactory) - { - _characterRenderer = characterRendererFactory.CreateCharacterRenderer(character, isUiControl: true); - } + public CharacterControl(Character character, + ICharacterRendererFactory characterRendererFactory) + { + _characterRenderer = characterRendererFactory.CreateCharacterRenderer(character, isUiControl: true); + } - public override void Initialize() - { - _characterRenderer.Initialize(); - _characterRenderer.SetAbsoluteScreenPosition(DrawAreaWithParentOffset.X, DrawAreaWithParentOffset.Y); + public override void Initialize() + { + _characterRenderer.Initialize(); + _characterRenderer.SetAbsoluteScreenPosition(DrawAreaWithParentOffset.X, DrawAreaWithParentOffset.Y); - base.Initialize(); - } + base.Initialize(); + } - protected override bool ShouldUpdate() - { - return Visible; - } + protected override bool ShouldUpdate() + { + return Visible; + } - protected override void OnUpdateControl(GameTime gameTime) - { - _characterRenderer.Update(gameTime); - base.OnUpdateControl(gameTime); - } + protected override void OnUpdateControl(GameTime gameTime) + { + _characterRenderer.Update(gameTime); + base.OnUpdateControl(gameTime); + } - protected override void OnDrawControl(GameTime gameTime) - { - _characterRenderer.Draw(gameTime); - base.OnDrawControl(gameTime); - } + protected override void OnDrawControl(GameTime gameTime) + { + _characterRenderer.Draw(gameTime); + base.OnDrawControl(gameTime); + } - protected override void Dispose(bool disposing) - { - if (disposing) - _characterRenderer.Dispose(); + protected override void Dispose(bool disposing) + { + if (disposing) + _characterRenderer.Dispose(); - base.Dispose(disposing); + base.Dispose(disposing); + } } } \ No newline at end of file diff --git a/EndlessClient/UIControls/CharacterInfoPanel.cs b/EndlessClient/UIControls/CharacterInfoPanel.cs index 6ec22efb0..df74d5481 100644 --- a/EndlessClient/UIControls/CharacterInfoPanel.cs +++ b/EndlessClient/UIControls/CharacterInfoPanel.cs @@ -15,238 +15,239 @@ using System.Threading.Tasks; using XNAControls; -namespace EndlessClient.UIControls; - -public class CharacterInfoPanel : XNAControl +namespace EndlessClient.UIControls { - private readonly INativeGraphicsManager _gfxManager; - private readonly Character _character; - private readonly ILoginController _loginController; - private readonly ICharacterManagementController _characterManagementController; - private readonly IRendererRepositoryResetter _rendererRepositoryResetter; - private readonly CharacterControl _characterControl; - private readonly ISpriteSheet _adminGraphic; - private readonly IUserInputProvider _userInputProvider; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - private readonly Texture2D _backgroundImage; - - private readonly IXNAButton _loginButton, _deleteButton; - private readonly IXNALabel _nameLabel, _levelLabel; - - private readonly int _characterIndex; - - private Task _activeTask; - - //top left - 334, 36 + ndx*124 - protected CharacterInfoPanel(int characterIndex, - INativeGraphicsManager gfxManager, - IEODialogButtonService dialogButtonService) - { - _characterIndex = characterIndex; - _gfxManager = gfxManager; - DrawPosition = new Vector2(334, 36 + characterIndex * 124); - - _loginButton = new XNAButton(dialogButtonService.SmallButtonSheet, - new Vector2(161, 57), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Login), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Login)); - _loginButton.OnClick += (o, e) => AsyncButtonClick(() => _loginController.LoginToCharacter(_character)); - _loginButton.SetParentControl(this); - - _deleteButton = new XNAButton(dialogButtonService.SmallButtonSheet, - new Vector2(161, 85), - dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Delete), - dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Delete)); - _deleteButton.OnClick += (o, e) => AsyncButtonClick(() => _characterManagementController.DeleteCharacter(_character)); - _deleteButton.SetParentControl(this); - - _backgroundImage = _gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 11); - SetSize(_backgroundImage.Width, _backgroundImage.Height); - } + public class CharacterInfoPanel : XNAControl + { + private readonly INativeGraphicsManager _gfxManager; + private readonly Character _character; + private readonly ILoginController _loginController; + private readonly ICharacterManagementController _characterManagementController; + private readonly IRendererRepositoryResetter _rendererRepositoryResetter; + private readonly CharacterControl _characterControl; + private readonly ISpriteSheet _adminGraphic; + private readonly IUserInputProvider _userInputProvider; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; + private readonly Texture2D _backgroundImage; + + private readonly IXNAButton _loginButton, _deleteButton; + private readonly IXNALabel _nameLabel, _levelLabel; + + private readonly int _characterIndex; + + private Task _activeTask; + + //top left - 334, 36 + ndx*124 + protected CharacterInfoPanel(int characterIndex, + INativeGraphicsManager gfxManager, + IEODialogButtonService dialogButtonService) + { + _characterIndex = characterIndex; + _gfxManager = gfxManager; + DrawPosition = new Vector2(334, 36 + characterIndex * 124); + + _loginButton = new XNAButton(dialogButtonService.SmallButtonSheet, + new Vector2(161, 57), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Login), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Login)); + _loginButton.OnClick += (o, e) => AsyncButtonClick(() => _loginController.LoginToCharacter(_character)); + _loginButton.SetParentControl(this); + + _deleteButton = new XNAButton(dialogButtonService.SmallButtonSheet, + new Vector2(161, 85), + dialogButtonService.GetSmallDialogButtonOutSource(SmallButton.Delete), + dialogButtonService.GetSmallDialogButtonOverSource(SmallButton.Delete)); + _deleteButton.OnClick += (o, e) => AsyncButtonClick(() => _characterManagementController.DeleteCharacter(_character)); + _deleteButton.SetParentControl(this); + + _backgroundImage = _gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 11); + SetSize(_backgroundImage.Width, _backgroundImage.Height); + } - public CharacterInfoPanel(int characterIndex, - Character character, - INativeGraphicsManager gfxManager, - IEODialogButtonService dialogButtonService, - ILoginController loginController, - ICharacterManagementController characterManagementController, - ICharacterRendererFactory rendererFactory, - IRendererRepositoryResetter rendererRepositoryResetter, - IUserInputProvider userInputProvider, - IXnaControlSoundMapper xnaControlSoundMapper) - : this(characterIndex, gfxManager, dialogButtonService) - { - _character = character; - _loginController = loginController; - _characterManagementController = characterManagementController; - _rendererRepositoryResetter = rendererRepositoryResetter; - _userInputProvider = userInputProvider; - _xnaControlSoundMapper = xnaControlSoundMapper; - - _characterControl = new CharacterControl(character, rendererFactory) - { - DrawPosition = new Vector2(68, 28) - }; - _characterControl.SetParentControl(this); - - _nameLabel = new XNALabel(Constants.FontSize08pt5) - { - DrawArea = GetNameLabelLocation(), - ForeColor = ColorConstants.BeigeText, - Text = CapitalizeName(character.Name), - TextAlign = LabelAlignment.MiddleCenter, - AutoSize = false - }; - _nameLabel.SetParentControl(this); - - _levelLabel = new XNALabel(Constants.FontSize09) - { - DrawArea = GetLevelLabelLocation(), - ForeColor = ColorConstants.BeigeText, - Text = character.Stats.Stats[CharacterStat.Level].ToString() - }; - _levelLabel.SetParentControl(this); - - _adminGraphic = CreateAdminGraphic(character.AdminLevel); - } + public CharacterInfoPanel(int characterIndex, + Character character, + INativeGraphicsManager gfxManager, + IEODialogButtonService dialogButtonService, + ILoginController loginController, + ICharacterManagementController characterManagementController, + ICharacterRendererFactory rendererFactory, + IRendererRepositoryResetter rendererRepositoryResetter, + IUserInputProvider userInputProvider, + IXnaControlSoundMapper xnaControlSoundMapper) + : this(characterIndex, gfxManager, dialogButtonService) + { + _character = character; + _loginController = loginController; + _characterManagementController = characterManagementController; + _rendererRepositoryResetter = rendererRepositoryResetter; + _userInputProvider = userInputProvider; + _xnaControlSoundMapper = xnaControlSoundMapper; + + _characterControl = new CharacterControl(character, rendererFactory) + { + DrawPosition = new Vector2(68, 28) + }; + _characterControl.SetParentControl(this); + + _nameLabel = new XNALabel(Constants.FontSize08pt5) + { + DrawArea = GetNameLabelLocation(), + ForeColor = ColorConstants.BeigeText, + Text = CapitalizeName(character.Name), + TextAlign = LabelAlignment.MiddleCenter, + AutoSize = false + }; + _nameLabel.SetParentControl(this); + + _levelLabel = new XNALabel(Constants.FontSize09) + { + DrawArea = GetLevelLabelLocation(), + ForeColor = ColorConstants.BeigeText, + Text = character.Stats.Stats[CharacterStat.Level].ToString() + }; + _levelLabel.SetParentControl(this); + + _adminGraphic = CreateAdminGraphic(character.AdminLevel); + } - public override void Initialize() - { - _characterControl.Initialize(); + public override void Initialize() + { + _characterControl.Initialize(); - _loginButton.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_loginButton); + _loginButton.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_loginButton); - _deleteButton.Initialize(); - _xnaControlSoundMapper.BindSoundToControl(_deleteButton); + _deleteButton.Initialize(); + _xnaControlSoundMapper.BindSoundToControl(_deleteButton); - _nameLabel.Initialize(); - _levelLabel.Initialize(); + _nameLabel.Initialize(); + _levelLabel.Initialize(); - base.Initialize(); - } + base.Initialize(); + } - protected override bool ShouldUpdate() - { - return Visible; - } + protected override bool ShouldUpdate() + { + return Visible; + } - protected override void OnUpdateControl(GameTime gameTime) - { - DoUpdateLogic(gameTime); - base.OnUpdateControl(gameTime); - } + protected override void OnUpdateControl(GameTime gameTime) + { + DoUpdateLogic(gameTime); + base.OnUpdateControl(gameTime); + } - protected override void OnDrawControl(GameTime gameTime) - { - _spriteBatch.Begin(); - _spriteBatch.Draw(_backgroundImage, DrawPositionWithParentOffset, Color.White); - _spriteBatch.End(); + protected override void OnDrawControl(GameTime gameTime) + { + _spriteBatch.Begin(); + _spriteBatch.Draw(_backgroundImage, DrawPositionWithParentOffset, Color.White); + _spriteBatch.End(); - DoDrawLogic(gameTime); + DoDrawLogic(gameTime); - base.OnDrawControl(gameTime); - } + base.OnDrawControl(gameTime); + } - protected virtual void AsyncButtonClick(Func clickHandler) - { - if (_activeTask == null) + protected virtual void AsyncButtonClick(Func clickHandler) { - _activeTask = clickHandler(); - _activeTask.ContinueWith(_ => _activeTask = null); + if (_activeTask == null) + { + _activeTask = clickHandler(); + _activeTask.ContinueWith(_ => _activeTask = null); + } } - } - - protected virtual void DoUpdateLogic(GameTime gameTime) - { - _characterControl.Update(gameTime); - var previousKeyState = _userInputProvider.PreviousKeyState; - var currentKeyState = _userInputProvider.CurrentKeyState; - if (currentKeyState.IsKeyPressedOnce(previousKeyState, Keys.D1 + _characterIndex)) + protected virtual void DoUpdateLogic(GameTime gameTime) { - AsyncButtonClick(() => _loginController.LoginToCharacter(_character)); + _characterControl.Update(gameTime); + + var previousKeyState = _userInputProvider.PreviousKeyState; + var currentKeyState = _userInputProvider.CurrentKeyState; + if (currentKeyState.IsKeyPressedOnce(previousKeyState, Keys.D1 + _characterIndex)) + { + AsyncButtonClick(() => _loginController.LoginToCharacter(_character)); + } } - } - protected virtual void DoDrawLogic(GameTime gameTime) - { - _characterControl.Draw(gameTime); - - if (_adminGraphic.HasTexture && !_spriteBatch.IsDisposed) + protected virtual void DoDrawLogic(GameTime gameTime) { - _spriteBatch.Begin(); - _spriteBatch.Draw(_adminGraphic.SheetTexture, GetAdminGraphicLocation(), _adminGraphic.SourceRectangle, Color.White); - _spriteBatch.End(); + _characterControl.Draw(gameTime); + + if (_adminGraphic.HasTexture && !_spriteBatch.IsDisposed) + { + _spriteBatch.Begin(); + _spriteBatch.Draw(_adminGraphic.SheetTexture, GetAdminGraphicLocation(), _adminGraphic.SourceRectangle, Color.White); + _spriteBatch.End(); + } } - } - private static Rectangle GetNameLabelLocation() - { - return new Rectangle(165, 26, 89, 22); - } + private static Rectangle GetNameLabelLocation() + { + return new Rectangle(165, 26, 89, 22); + } - private static Rectangle GetLevelLabelLocation() - { - return new Rectangle(29, 99, 1, 1); - } + private static Rectangle GetLevelLabelLocation() + { + return new Rectangle(29, 99, 1, 1); + } - private Vector2 GetAdminGraphicLocation() - { - return new Vector2(DrawAreaWithParentOffset.X + 109, DrawAreaWithParentOffset.Y + 97); - } + private Vector2 GetAdminGraphicLocation() + { + return new Vector2(DrawAreaWithParentOffset.X + 109, DrawAreaWithParentOffset.Y + 97); + } - private static string CapitalizeName(string name) - { - return string.IsNullOrEmpty(name) ? string.Empty : (char)(name[0] - 32) + name.Substring(1); - } + private static string CapitalizeName(string name) + { + return string.IsNullOrEmpty(name) ? string.Empty : (char)(name[0] - 32) + name.Substring(1); + } - private ISpriteSheet CreateAdminGraphic(AdminLevel adminLevel) - { - var adminGraphic = _gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 22); - - switch (adminLevel) - { - case AdminLevel.Player: - return new EmptySpriteSheet(); - case AdminLevel.Spy: - return new SpriteSheet(adminGraphic, new Rectangle(252, 39, 17, 17)); - case AdminLevel.LightGuide: - case AdminLevel.Guardian: - case AdminLevel.GameMaster: - case AdminLevel.HighGameMaster: - return new SpriteSheet(adminGraphic, new Rectangle(233, 39, 17, 17)); - default: - throw new ArgumentOutOfRangeException(nameof(adminLevel), adminLevel, null); + private ISpriteSheet CreateAdminGraphic(AdminLevel adminLevel) + { + var adminGraphic = _gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 22); + + switch (adminLevel) + { + case AdminLevel.Player: + return new EmptySpriteSheet(); + case AdminLevel.Spy: + return new SpriteSheet(adminGraphic, new Rectangle(252, 39, 17, 17)); + case AdminLevel.LightGuide: + case AdminLevel.Guardian: + case AdminLevel.GameMaster: + case AdminLevel.HighGameMaster: + return new SpriteSheet(adminGraphic, new Rectangle(233, 39, 17, 17)); + default: + throw new ArgumentOutOfRangeException(nameof(adminLevel), adminLevel, null); + } } } -} -/// -/// This is a no-op class that represents an empty character slot. The buttons don't do anything, and nothing is drawn / updated -/// -public class EmptyCharacterInfoPanel : CharacterInfoPanel -{ - public EmptyCharacterInfoPanel(int characterIndex, - INativeGraphicsManager gfxManager, - IEODialogButtonService dialogButtonService) - : base(characterIndex, gfxManager, dialogButtonService) + /// + /// This is a no-op class that represents an empty character slot. The buttons don't do anything, and nothing is drawn / updated + /// + public class EmptyCharacterInfoPanel : CharacterInfoPanel { - } + public EmptyCharacterInfoPanel(int characterIndex, + INativeGraphicsManager gfxManager, + IEODialogButtonService dialogButtonService) + : base(characterIndex, gfxManager, dialogButtonService) + { + } - public override void Initialize() - { - } + public override void Initialize() + { + } - protected override void DoUpdateLogic(GameTime gameTime) - { - } + protected override void DoUpdateLogic(GameTime gameTime) + { + } - protected override void DoDrawLogic(GameTime gameTime) - { - } + protected override void DoDrawLogic(GameTime gameTime) + { + } - protected override void AsyncButtonClick(Func clickHandler) - { + protected override void AsyncButtonClick(Func clickHandler) + { + } } } \ No newline at end of file diff --git a/EndlessClient/UIControls/CharacterInfoPanelFactory.cs b/EndlessClient/UIControls/CharacterInfoPanelFactory.cs index 268b19a75..5cd92c24b 100644 --- a/EndlessClient/UIControls/CharacterInfoPanelFactory.cs +++ b/EndlessClient/UIControls/CharacterInfoPanelFactory.cs @@ -9,66 +9,67 @@ using System; using System.Collections.Generic; -namespace EndlessClient.UIControls; - -[AutoMappedType(IsSingleton = true)] -public class CharacterInfoPanelFactory : ICharacterInfoPanelFactory +namespace EndlessClient.UIControls { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly ICharacterRendererFactory _characterRendererFactory; - private readonly IRendererRepositoryResetter _rendererRepositoryResetter; - private readonly IEODialogButtonService _eoDialogButtonService; - private readonly IUserInputProvider _userInputProvider; - private readonly IXnaControlSoundMapper _xnaControlSoundMapper; - private ILoginController _loginController; - private ICharacterManagementController _characterManagementController; - - public CharacterInfoPanelFactory(INativeGraphicsManager nativeGraphicsManager, - ICharacterRendererFactory characterRendererFactory, - IRendererRepositoryResetter rendererRepositoryResetter, - IEODialogButtonService eoDialogButtonService, - IUserInputProvider userInputProvider, - IXnaControlSoundMapper xnaControlSoundMapper) + [AutoMappedType(IsSingleton = true)] + public class CharacterInfoPanelFactory : ICharacterInfoPanelFactory { - _nativeGraphicsManager = nativeGraphicsManager; - _characterRendererFactory = characterRendererFactory; - _rendererRepositoryResetter = rendererRepositoryResetter; - _eoDialogButtonService = eoDialogButtonService; - _userInputProvider = userInputProvider; - _xnaControlSoundMapper = xnaControlSoundMapper; - } + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly ICharacterRendererFactory _characterRendererFactory; + private readonly IRendererRepositoryResetter _rendererRepositoryResetter; + private readonly IEODialogButtonService _eoDialogButtonService; + private readonly IUserInputProvider _userInputProvider; + private readonly IXnaControlSoundMapper _xnaControlSoundMapper; + private ILoginController _loginController; + private ICharacterManagementController _characterManagementController; - public void InjectLoginController(ILoginController loginController) - { - _loginController = loginController; - } - - public void InjectCharacterManagementController(ICharacterManagementController characterManagementController) - { - _characterManagementController = characterManagementController; - } + public CharacterInfoPanelFactory(INativeGraphicsManager nativeGraphicsManager, + ICharacterRendererFactory characterRendererFactory, + IRendererRepositoryResetter rendererRepositoryResetter, + IEODialogButtonService eoDialogButtonService, + IUserInputProvider userInputProvider, + IXnaControlSoundMapper xnaControlSoundMapper) + { + _nativeGraphicsManager = nativeGraphicsManager; + _characterRendererFactory = characterRendererFactory; + _rendererRepositoryResetter = rendererRepositoryResetter; + _eoDialogButtonService = eoDialogButtonService; + _userInputProvider = userInputProvider; + _xnaControlSoundMapper = xnaControlSoundMapper; + } - public IEnumerable CreatePanels(IEnumerable characters) - { - if (_loginController == null || _characterManagementController == null) - throw new InvalidOperationException("Missing controllers - the Unity container was initialized incorrectly"); + public void InjectLoginController(ILoginController loginController) + { + _loginController = loginController; + } - int i = 0; - foreach (var character in characters) + public void InjectCharacterManagementController(ICharacterManagementController characterManagementController) { - yield return new CharacterInfoPanel(i++, - character, - _nativeGraphicsManager, - _eoDialogButtonService, - _loginController, - _characterManagementController, - _characterRendererFactory, - _rendererRepositoryResetter, - _userInputProvider, - _xnaControlSoundMapper); + _characterManagementController = characterManagementController; } - for (; i < 3; ++i) - yield return new EmptyCharacterInfoPanel(i, _nativeGraphicsManager, _eoDialogButtonService); + public IEnumerable CreatePanels(IEnumerable characters) + { + if (_loginController == null || _characterManagementController == null) + throw new InvalidOperationException("Missing controllers - the Unity container was initialized incorrectly"); + + int i = 0; + foreach (var character in characters) + { + yield return new CharacterInfoPanel(i++, + character, + _nativeGraphicsManager, + _eoDialogButtonService, + _loginController, + _characterManagementController, + _characterRendererFactory, + _rendererRepositoryResetter, + _userInputProvider, + _xnaControlSoundMapper); + } + + for (; i < 3; ++i) + yield return new EmptyCharacterInfoPanel(i, _nativeGraphicsManager, _eoDialogButtonService); + } } } \ No newline at end of file diff --git a/EndlessClient/UIControls/ChatModePictureBox.cs b/EndlessClient/UIControls/ChatModePictureBox.cs index 22c03ead4..4a88e318c 100644 --- a/EndlessClient/UIControls/ChatModePictureBox.cs +++ b/EndlessClient/UIControls/ChatModePictureBox.cs @@ -8,95 +8,96 @@ using System; using XNAControls; -namespace EndlessClient.UIControls; - -public class ChatModePictureBox : XNAPictureBox +namespace EndlessClient.UIControls { - private readonly IChatModeCalculator _chatModeCalculator; - private readonly IHudControlProvider _hudControlProvider; - - public enum ChatMode + public class ChatModePictureBox : XNAPictureBox { - NoText, - Public, - Private, - Global, - Group, - Admin, - Muted, - Guild - } + private readonly IChatModeCalculator _chatModeCalculator; + private readonly IHudControlProvider _hudControlProvider; - private string _lastChat; - private Option _endMuteTime; + public enum ChatMode + { + NoText, + Public, + Private, + Global, + Group, + Admin, + Muted, + Guild + } - public ChatModePictureBox(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - IChatModeCalculator chatModeCalculator, - IHudControlProvider hudControlProvider) - { - _chatModeCalculator = chatModeCalculator; - _hudControlProvider = hudControlProvider; + private string _lastChat; + private Option _endMuteTime; - _lastChat = ""; - _endMuteTime = Option.None(); + public ChatModePictureBox(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + IChatModeCalculator chatModeCalculator, + IHudControlProvider hudControlProvider) + { + _chatModeCalculator = chatModeCalculator; + _hudControlProvider = hudControlProvider; - Texture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 31); + _lastChat = ""; + _endMuteTime = Option.None(); - DrawArea = new Rectangle(16, 309, Texture.Width, Texture.Height / 8 - 2); - SourceRectangle = new Rectangle(0, 0, Texture.Width, Texture.Height / 8 - 2); + Texture = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 31); - if (clientWindowSizeProvider.Resizable) - { - DrawPosition = new Vector2(122, clientWindowSizeProvider.Height - 39); - clientWindowSizeProvider.GameWindowSizeChanged += (_, _) => DrawPosition = new Vector2(122, clientWindowSizeProvider.Height - 39); + DrawArea = new Rectangle(16, 309, Texture.Width, Texture.Height / 8 - 2); + SourceRectangle = new Rectangle(0, 0, Texture.Width, Texture.Height / 8 - 2); + + if (clientWindowSizeProvider.Resizable) + { + DrawPosition = new Vector2(122, clientWindowSizeProvider.Height - 39); + clientWindowSizeProvider.GameWindowSizeChanged += (_, _) => DrawPosition = new Vector2(122, clientWindowSizeProvider.Height - 39); + } } - } - public void SetMuted(DateTime endMuteTime) - { - _lastChat = ""; - _endMuteTime = Option.Some(endMuteTime); - UpdateSourceRectangleForMode(ChatMode.Muted); - } + public void SetMuted(DateTime endMuteTime) + { + _lastChat = ""; + _endMuteTime = Option.Some(endMuteTime); + UpdateSourceRectangleForMode(ChatMode.Muted); + } - protected override void OnUpdateControl(GameTime gameTime) - { - _endMuteTime.Match( - some: endTime => - { - if (DateTime.Now >= endTime) + protected override void OnUpdateControl(GameTime gameTime) + { + _endMuteTime.Match( + some: endTime => { - _endMuteTime = Option.None(); - UpdateSourceRectangleForMode(ChatMode.NoText); - } - }, - none: () => - { - if (AtLeastOneCharTypedOrDeleted()) + if (DateTime.Now >= endTime) + { + _endMuteTime = Option.None(); + UpdateSourceRectangleForMode(ChatMode.NoText); + } + }, + none: () => { - UpdateSourceRectangleForMode(_chatModeCalculator.CalculateMode(ChatTextBox.Text)); - _lastChat = ChatTextBox.Text; - } - }); + if (AtLeastOneCharTypedOrDeleted()) + { + UpdateSourceRectangleForMode(_chatModeCalculator.CalculateMode(ChatTextBox.Text)); + _lastChat = ChatTextBox.Text; + } + }); + + base.OnUpdateControl(gameTime); + } - base.OnUpdateControl(gameTime); - } + private bool AtLeastOneCharTypedOrDeleted() + { + return _hudControlProvider.IsInGame && + ((_lastChat.Length == 0 && ChatTextBox.Text.Length > 0) || + (_lastChat.Length > 0 && ChatTextBox.Text.Length == 0)); + } - private bool AtLeastOneCharTypedOrDeleted() - { - return _hudControlProvider.IsInGame && - ((_lastChat.Length == 0 && ChatTextBox.Text.Length > 0) || - (_lastChat.Length > 0 && ChatTextBox.Text.Length == 0)); - } + private void UpdateSourceRectangleForMode(ChatMode mode) + { + if (!SourceRectangle.HasValue) + throw new InvalidOperationException("SourceRectangle is expected to have a value."); - private void UpdateSourceRectangleForMode(ChatMode mode) - { - if (!SourceRectangle.HasValue) - throw new InvalidOperationException("SourceRectangle is expected to have a value."); + SourceRectangle = new Rectangle(0, (int)((int)mode * (Texture.Height / 8f)), Texture.Width, Texture.Height / 8 - 2); + } - SourceRectangle = new Rectangle(0, (int)((int)mode * (Texture.Height / 8f)), Texture.Width, Texture.Height / 8 - 2); + private ChatTextBox ChatTextBox => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); } - - private ChatTextBox ChatTextBox => _hudControlProvider.GetComponent(HudControlIdentifier.ChatTextBox); } \ No newline at end of file diff --git a/EndlessClient/UIControls/ChatTextBox.cs b/EndlessClient/UIControls/ChatTextBox.cs index b1c23847b..5bb41dc62 100644 --- a/EndlessClient/UIControls/ChatTextBox.cs +++ b/EndlessClient/UIControls/ChatTextBox.cs @@ -10,128 +10,129 @@ using System; using XNAControls; -namespace EndlessClient.UIControls; - -/// -/// Special instance of an XNATextBox that should ignore input from the number pad (which is used for Emotes) -/// -public class ChatTextBox : XNATextBox +namespace EndlessClient.UIControls { - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - - private bool _ignoreAllInput; - private Option _endMuteTime; + /// + /// Special instance of an XNATextBox that should ignore input from the number pad (which is used for Emotes) + /// + public class ChatTextBox : XNATextBox + { + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly Rectangle? _leftSide, _background, _rightSide; + private bool _ignoreAllInput; + private Option _endMuteTime; - public ChatTextBox(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - IContentProvider contentManagerProvider) - : base(Rectangle.Empty, // (124, 308, 440, 19) - Constants.FontSize08, - caretTexture: contentManagerProvider.Textures[ContentProvider.Cursor]) - { - _nativeGraphicsManager = nativeGraphicsManager; - _clientWindowSizeProvider = clientWindowSizeProvider; + private readonly Rectangle? _leftSide, _background, _rightSide; - if (_clientWindowSizeProvider.Resizable) + public ChatTextBox(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + IContentProvider contentManagerProvider) + : base(Rectangle.Empty, // (124, 308, 440, 19) + Constants.FontSize08, + caretTexture: contentManagerProvider.Textures[ContentProvider.Cursor]) { - _leftSide = new Rectangle(10, 308, 12, 20); - _background = new Rectangle(22, 308, 560, 20); - _rightSide = new Rectangle(578, 308, 11, 20); + _nativeGraphicsManager = nativeGraphicsManager; + _clientWindowSizeProvider = clientWindowSizeProvider; - DrawArea = new Rectangle(124, _clientWindowSizeProvider.Height - 40, _clientWindowSizeProvider.Width - 116, 20); + if (_clientWindowSizeProvider.Resizable) + { + _leftSide = new Rectangle(10, 308, 12, 20); + _background = new Rectangle(22, 308, 560, 20); + _rightSide = new Rectangle(578, 308, 11, 20); - // original X coordinate accounting for the width of chat mode picture - LeftPadding = 124; + DrawArea = new Rectangle(124, _clientWindowSizeProvider.Height - 40, _clientWindowSizeProvider.Width - 116, 20); - _clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => + // original X coordinate accounting for the width of chat mode picture + LeftPadding = 124; + + _clientWindowSizeProvider.GameWindowSizeChanged += (o, e) => + { + // status icons: 124 width + // friend/ignore: 40 width + DrawArea = new Rectangle(124, _clientWindowSizeProvider.Height - 40, _clientWindowSizeProvider.Width - 116, 20); + MaxWidth = DrawArea.Width - 184; + }; + } + else { - // status icons: 124 width - // friend/ignore: 40 width - DrawArea = new Rectangle(124, _clientWindowSizeProvider.Height - 40, _clientWindowSizeProvider.Width - 116, 20); - MaxWidth = DrawArea.Width - 184; - }; - } - else - { - DrawArea = new Rectangle(124, 308, 440, 20); + DrawArea = new Rectangle(124, 308, 440, 20); + } + + MaxChars = 140; + _endMuteTime = Option.None(); } - MaxChars = 140; - _endMuteTime = Option.None(); - } + public override void Initialize() + { + base.Initialize(); - public override void Initialize() - { - base.Initialize(); + // This must be done after Initialize because MaxWidth uses the sprite font. + // SpriteFont is loaded in LoadContent which is called by Initialize. + MaxWidth = _clientWindowSizeProvider.Resizable ? DrawArea.Width - 184 : 440; + } - // This must be done after Initialize because MaxWidth uses the sprite font. - // SpriteFont is loaded in LoadContent which is called by Initialize. - MaxWidth = _clientWindowSizeProvider.Resizable ? DrawArea.Width - 184 : 440; - } + public void SetMuted(DateTime endMuteTime) + { + _ignoreAllInput = true; + _endMuteTime = Option.Some(endMuteTime); + } - public void SetMuted(DateTime endMuteTime) - { - _ignoreAllInput = true; - _endMuteTime = Option.Some(endMuteTime); - } + protected override void OnUpdateControl(GameTime gameTime) + { + _endMuteTime.MatchSome(endTime => + { + if (DateTime.Now > endTime) + { + _endMuteTime = Option.None(); + _ignoreAllInput = false; + } + }); + + base.OnUpdateControl(gameTime); + } - protected override void OnUpdateControl(GameTime gameTime) - { - _endMuteTime.MatchSome(endTime => + protected override void OnDrawControl(GameTime gameTime) { - if (DateTime.Now > endTime) + if (_clientWindowSizeProvider.Resizable && _background != null) { - _endMuteTime = Option.None(); - _ignoreAllInput = false; + _spriteBatch.Begin(samplerState: SamplerState.LinearWrap); + _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, true), DrawArea, _background, Color.White); + _spriteBatch.End(); + + _spriteBatch.Begin(); + _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false), DrawPosition, _leftSide, Color.White); + _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false), new Vector2(DrawArea.X + DrawArea.Width - _rightSide.Value.Width, DrawPosition.Y), _rightSide, Color.White); + _spriteBatch.End(); } - }); - - base.OnUpdateControl(gameTime); - } - protected override void OnDrawControl(GameTime gameTime) - { - if (_clientWindowSizeProvider.Resizable && _background != null) - { - _spriteBatch.Begin(samplerState: SamplerState.LinearWrap); - _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, true), DrawArea, _background, Color.White); - _spriteBatch.End(); - - _spriteBatch.Begin(); - _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false), DrawPosition, _leftSide, Color.White); - _spriteBatch.Draw(_nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false), new Vector2(DrawArea.X + DrawArea.Width - _rightSide.Value.Width, DrawPosition.Y), _rightSide, Color.White); - _spriteBatch.End(); + base.OnDrawControl(gameTime); } - base.OnDrawControl(gameTime); - } - - protected override bool HandleTextInput(KeyboardEventArgs eventArgs) - { - if (_ignoreAllInput) - return false; + protected override bool HandleTextInput(KeyboardEventArgs eventArgs) + { + if (_ignoreAllInput) + return false; - if (IsSpecialInput(eventArgs.Key, eventArgs.Modifiers)) - HandleSpecialInput(eventArgs.Key); - else - base.HandleTextInput(eventArgs); + if (IsSpecialInput(eventArgs.Key, eventArgs.Modifiers)) + HandleSpecialInput(eventArgs.Key); + else + base.HandleTextInput(eventArgs); - return true; - } + return true; + } - private void HandleSpecialInput(Keys key) - { - if (key == Keys.Escape) - Text = ""; - } + private void HandleSpecialInput(Keys key) + { + if (key == Keys.Escape) + Text = ""; + } - private bool IsSpecialInput(Keys k, KeyboardModifiers modifiers) - { - return k == Keys.Escape || k == Keys.Decimal || - (k >= Keys.NumPad0 && k <= Keys.NumPad9) || - modifiers == KeyboardModifiers.Alt; + private bool IsSpecialInput(Keys k, KeyboardModifiers modifiers) + { + return k == Keys.Escape || k == Keys.Decimal || + (k >= Keys.NumPad0 && k <= Keys.NumPad9) || + modifiers == KeyboardModifiers.Alt; + } } } \ No newline at end of file diff --git a/EndlessClient/UIControls/ClickableArea.cs b/EndlessClient/UIControls/ClickableArea.cs index 5b1f59d78..12103f835 100644 --- a/EndlessClient/UIControls/ClickableArea.cs +++ b/EndlessClient/UIControls/ClickableArea.cs @@ -3,38 +3,39 @@ using System; using XNAControls; -namespace EndlessClient.UIControls; - -public class ClickableArea : XNAControl, IXNAButton +namespace EndlessClient.UIControls { - public Rectangle ClickArea + public class ClickableArea : XNAControl, IXNAButton { - get => DrawArea; - set => DrawArea = value; - } + public Rectangle ClickArea + { + get => DrawArea; + set => DrawArea = value; + } - public int? FlashSpeed - { - get => throw new InvalidOperationException("Unable to get flash speed on clickable area"); - set => throw new InvalidOperationException("Unable to get flash speed on clickable area"); - } + public int? FlashSpeed + { + get => throw new InvalidOperationException("Unable to get flash speed on clickable area"); + set => throw new InvalidOperationException("Unable to get flash speed on clickable area"); + } - public event EventHandler OnClick; + public event EventHandler OnClick; - public event EventHandler OnClickDrag - { - add => throw new InvalidOperationException("Unable to set ClickDrag event on clickable area"); - remove => throw new InvalidOperationException("Unable to set ClickDrag event on clickable area"); - } + public event EventHandler OnClickDrag + { + add => throw new InvalidOperationException("Unable to set ClickDrag event on clickable area"); + remove => throw new InvalidOperationException("Unable to set ClickDrag event on clickable area"); + } - public ClickableArea(Rectangle area) - { - ClickArea = area; - } + public ClickableArea(Rectangle area) + { + ClickArea = area; + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - OnClick?.Invoke(control, eventArgs); - return true; + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + OnClick?.Invoke(control, eventArgs); + return true; + } } } \ No newline at end of file diff --git a/EndlessClient/UIControls/CreateCharacterControl.cs b/EndlessClient/UIControls/CreateCharacterControl.cs index 60e79184e..a945d61a0 100644 --- a/EndlessClient/UIControls/CreateCharacterControl.cs +++ b/EndlessClient/UIControls/CreateCharacterControl.cs @@ -6,76 +6,77 @@ using System; using XNAControls; -namespace EndlessClient.UIControls; - -public class CreateCharacterControl : CharacterControl +namespace EndlessClient.UIControls { - private Vector2 _lastPosition; + public class CreateCharacterControl : CharacterControl + { + private Vector2 _lastPosition; - public event EventHandler Clicked; + public event EventHandler Clicked; - // default properties - public CreateCharacterControl(ICharacterRendererFactory characterRendererFactory) - : this(GetDefaultProperties(), characterRendererFactory) { } + // default properties + public CreateCharacterControl(ICharacterRendererFactory characterRendererFactory) + : this(GetDefaultProperties(), characterRendererFactory) { } - // custom render properties - public CreateCharacterControl(CharacterRenderProperties renderProperties, ICharacterRendererFactory characterRendererFactory) - : base(Character.Default.WithRenderProperties(renderProperties.WithDirection(EODirection.Down)), characterRendererFactory) - { - SetSize(99, 123); - _lastPosition = Vector2.Zero; - } + // custom render properties + public CreateCharacterControl(CharacterRenderProperties renderProperties, ICharacterRendererFactory characterRendererFactory) + : base(Character.Default.WithRenderProperties(renderProperties.WithDirection(EODirection.Down)), characterRendererFactory) + { + SetSize(99, 123); + _lastPosition = Vector2.Zero; + } - protected override void OnUpdateControl(GameTime gameTime) - { - if (!ShouldUpdate()) - return; + protected override void OnUpdateControl(GameTime gameTime) + { + if (!ShouldUpdate()) + return; - var actualDrawPosition = new Vector2(DrawPositionWithParentOffset.X + 40, - DrawPositionWithParentOffset.Y + 36); + var actualDrawPosition = new Vector2(DrawPositionWithParentOffset.X + 40, + DrawPositionWithParentOffset.Y + 36); - if (_lastPosition != actualDrawPosition) - _characterRenderer.SetAbsoluteScreenPosition((int)actualDrawPosition.X, (int)actualDrawPosition.Y); + if (_lastPosition != actualDrawPosition) + _characterRenderer.SetAbsoluteScreenPosition((int)actualDrawPosition.X, (int)actualDrawPosition.Y); - base.OnUpdateControl(gameTime); + base.OnUpdateControl(gameTime); - _lastPosition = actualDrawPosition; - } + _lastPosition = actualDrawPosition; + } - protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) - { - var nextDirectionInt = (int)RenderProperties.Direction + 1; - var nextDirection = (EODirection)(nextDirectionInt % 4); - RenderProperties = RenderProperties.WithDirection(nextDirection); + protected override bool HandleClick(IXNAControl control, MouseEventArgs eventArgs) + { + var nextDirectionInt = (int)RenderProperties.Direction + 1; + var nextDirection = (EODirection)(nextDirectionInt % 4); + RenderProperties = RenderProperties.WithDirection(nextDirection); - Clicked?.Invoke(this, EventArgs.Empty); + Clicked?.Invoke(this, EventArgs.Empty); - return true; - } + return true; + } - public void NextGender() - { - RenderProperties = RenderProperties.WithGender((RenderProperties.Gender + 1) % 2); - } + public void NextGender() + { + RenderProperties = RenderProperties.WithGender((RenderProperties.Gender + 1) % 2); + } - public void NextRace() - { - RenderProperties = RenderProperties.WithRace((RenderProperties.Race + 1) % 6); - } + public void NextRace() + { + RenderProperties = RenderProperties.WithRace((RenderProperties.Race + 1) % 6); + } - public void NextHairStyle() - { - RenderProperties = RenderProperties.WithHairStyle((RenderProperties.HairStyle + 1) % 21); - } + public void NextHairStyle() + { + RenderProperties = RenderProperties.WithHairStyle((RenderProperties.HairStyle + 1) % 21); + } - public void NextHairColor() - { - RenderProperties = RenderProperties.WithHairColor((RenderProperties.HairColor + 1) % 10); - } + public void NextHairColor() + { + RenderProperties = RenderProperties.WithHairColor((RenderProperties.HairColor + 1) % 10); + } - private static CharacterRenderProperties GetDefaultProperties() - { - return new CharacterRenderProperties.Builder { HairStyle = 1 }.ToImmutable(); + private static CharacterRenderProperties GetDefaultProperties() + { + return new CharacterRenderProperties.Builder { HairStyle = 1 }.ToImmutable(); + } } } \ No newline at end of file diff --git a/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs b/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs index 11789a3e1..a96eebfae 100644 --- a/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs +++ b/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs @@ -2,11 +2,12 @@ using EOLib.Domain.Character; using System.Collections.Generic; -namespace EndlessClient.UIControls; - -public interface ICharacterInfoPanelFactory +namespace EndlessClient.UIControls { - IEnumerable CreatePanels(IEnumerable characters); - void InjectLoginController(ILoginController loginController); - void InjectCharacterManagementController(ICharacterManagementController characterManagementController); + public interface ICharacterInfoPanelFactory + { + IEnumerable CreatePanels(IEnumerable characters); + void InjectLoginController(ILoginController loginController); + void InjectCharacterManagementController(ICharacterManagementController characterManagementController); + } } \ No newline at end of file diff --git a/EndlessClient/UIControls/ScrollBar.cs b/EndlessClient/UIControls/ScrollBar.cs index aba6e0455..82bc11581 100644 --- a/EndlessClient/UIControls/ScrollBar.cs +++ b/EndlessClient/UIControls/ScrollBar.cs @@ -5,230 +5,231 @@ using System; using XNAControls; -namespace EndlessClient.UIControls; - -public enum ScrollBarColors +namespace EndlessClient.UIControls { - LightOnDark, //bottom set of light - LightOnLight, //top set of light - LightOnMed, //middle set of light - DarkOnDark //very bottom set -} + public enum ScrollBarColors + { + LightOnDark, //bottom set of light + LightOnLight, //top set of light + LightOnMed, //middle set of light + DarkOnDark //very bottom set + } -public class ScrollBar : XNAControl, IScrollHandler -{ - private Rectangle scrollArea; //area valid for scrolling: always 16 from top and 16 from bottom - public int ScrollOffset { get; private set; } - public int LinesToRender { get; set; } + public class ScrollBar : XNAControl, IScrollHandler + { + private Rectangle scrollArea; //area valid for scrolling: always 16 from top and 16 from bottom + public int ScrollOffset { get; private set; } + public int LinesToRender { get; set; } - private readonly XNAButton _upButton, _downButton, _scrollButton; - private readonly Texture2D _backgroundTexture; - private readonly Rectangle? _backgroundTextureSource; + private readonly XNAButton _upButton, _downButton, _scrollButton; + private readonly Texture2D _backgroundTexture; + private readonly Rectangle? _backgroundTextureSource; - private int _totalHeight; + private int _totalHeight; - public override Rectangle DrawArea - { - get => base.DrawArea; - set + public override Rectangle DrawArea { - base.DrawArea = value; + get => base.DrawArea; + set + { + base.DrawArea = value; - scrollArea = new Rectangle(0, 15, 0, value.Height - 15); + scrollArea = new Rectangle(0, 15, 0, value.Height - 15); - if (_downButton != null) - _downButton.DrawPosition = new Vector2(0, value.Height - 15); + if (_downButton != null) + _downButton.DrawPosition = new Vector2(0, value.Height - 15); + } } - } - public ScrollBar(Vector2 locationRelativeToParent, - Vector2 size, - ScrollBarColors palette, - INativeGraphicsManager nativeGraphicsManager) - { - DrawPosition = locationRelativeToParent; - SetSize((int)size.X, (int)size.Y); - ScrollOffset = 0; - - var scrollSpriteSheet = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 29); - var upArrows = new Rectangle[2]; - var downArrows = new Rectangle[2]; - int vertOff; - switch (palette) + public ScrollBar(Vector2 locationRelativeToParent, + Vector2 size, + ScrollBarColors palette, + INativeGraphicsManager nativeGraphicsManager) { - case ScrollBarColors.LightOnLight: vertOff = 0; break; - case ScrollBarColors.LightOnMed: vertOff = 105; break; - case ScrollBarColors.LightOnDark: vertOff = 180; break; - case ScrollBarColors.DarkOnDark: vertOff = 255; break; - default: throw new ArgumentOutOfRangeException(nameof(palette)); + DrawPosition = locationRelativeToParent; + SetSize((int)size.X, (int)size.Y); + ScrollOffset = 0; + + var scrollSpriteSheet = nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 29); + var upArrows = new Rectangle[2]; + var downArrows = new Rectangle[2]; + int vertOff; + switch (palette) + { + case ScrollBarColors.LightOnLight: vertOff = 0; break; + case ScrollBarColors.LightOnMed: vertOff = 105; break; + case ScrollBarColors.LightOnDark: vertOff = 180; break; + case ScrollBarColors.DarkOnDark: vertOff = 255; break; + default: throw new ArgumentOutOfRangeException(nameof(palette)); + } + + //regions based on verticle offset (which is based on the chosen palette) + upArrows[0] = new Rectangle(0, vertOff + 15 * 3, 16, 15); + upArrows[1] = new Rectangle(0, vertOff + 15 * 4, 16, 15); + downArrows[0] = new Rectangle(0, vertOff + 15, 16, 15); + downArrows[1] = new Rectangle(0, vertOff + 15 * 2, 16, 15); + var scrollBox = new Rectangle(0, vertOff, 16, 15); + + _upButton = new XNAButton(scrollSpriteSheet, Vector2.Zero, upArrows[0], upArrows[1]); + _upButton.OnClick += arrowClicked; + _upButton.SetParentControl(this); + + _downButton = new XNAButton(scrollSpriteSheet, new Vector2(0, size.Y - 15), downArrows[0], downArrows[1]); + _downButton.OnClick += arrowClicked; + _downButton.SetParentControl(this); + + _scrollButton = new XNAButton(scrollSpriteSheet, new Vector2(0, 15), scrollBox, scrollBox); + _scrollButton.OnClickDrag += OnScrollButtonDragged; + _scrollButton.SetParentControl(this); + + _totalHeight = DrawAreaWithParentOffset.Height; } - //regions based on verticle offset (which is based on the chosen palette) - upArrows[0] = new Rectangle(0, vertOff + 15 * 3, 16, 15); - upArrows[1] = new Rectangle(0, vertOff + 15 * 4, 16, 15); - downArrows[0] = new Rectangle(0, vertOff + 15, 16, 15); - downArrows[1] = new Rectangle(0, vertOff + 15 * 2, 16, 15); - var scrollBox = new Rectangle(0, vertOff, 16, 15); - - _upButton = new XNAButton(scrollSpriteSheet, Vector2.Zero, upArrows[0], upArrows[1]); - _upButton.OnClick += arrowClicked; - _upButton.SetParentControl(this); - - _downButton = new XNAButton(scrollSpriteSheet, new Vector2(0, size.Y - 15), downArrows[0], downArrows[1]); - _downButton.OnClick += arrowClicked; - _downButton.SetParentControl(this); - - _scrollButton = new XNAButton(scrollSpriteSheet, new Vector2(0, 15), scrollBox, scrollBox); - _scrollButton.OnClickDrag += OnScrollButtonDragged; - _scrollButton.SetParentControl(this); - - _totalHeight = DrawAreaWithParentOffset.Height; - } - - public ScrollBar(Vector2 locationRelativeToParent, Texture2D backgroundTexture, Rectangle? backgroundTextureSource, ScrollBarColors palette, INativeGraphicsManager nativeGraphicsManager) - : this(locationRelativeToParent, - (backgroundTextureSource.HasValue ? backgroundTextureSource.Value.Size : backgroundTexture.Bounds.Size).ToVector2(), - palette, - nativeGraphicsManager) - { - _backgroundTexture = backgroundTexture; - _backgroundTextureSource = backgroundTextureSource; - - // assume vertical scrollbar : center on background image - _upButton.DrawPosition = new Vector2((DrawArea.Width - _upButton.DrawArea.Width) / 2, _upButton.DrawPosition.Y + 1); - _downButton.DrawPosition = new Vector2((DrawArea.Width - _downButton.DrawArea.Width) / 2, _downButton.DrawPosition.Y); - _scrollButton.DrawPosition = new Vector2((DrawArea.Width - _scrollButton.DrawArea.Width) / 2, _scrollButton.DrawPosition.Y); - } - - public override void Initialize() - { - _upButton.Initialize(); - _downButton.Initialize(); - _scrollButton.Initialize(); - - base.Initialize(); - } + public ScrollBar(Vector2 locationRelativeToParent, Texture2D backgroundTexture, Rectangle? backgroundTextureSource, ScrollBarColors palette, INativeGraphicsManager nativeGraphicsManager) + : this(locationRelativeToParent, + (backgroundTextureSource.HasValue ? backgroundTextureSource.Value.Size : backgroundTexture.Bounds.Size).ToVector2(), + palette, + nativeGraphicsManager) + { + _backgroundTexture = backgroundTexture; + _backgroundTextureSource = backgroundTextureSource; - public void UpdateDimensions(int numberOfLines) - { - _totalHeight = numberOfLines; - } + // assume vertical scrollbar : center on background image + _upButton.DrawPosition = new Vector2((DrawArea.Width - _upButton.DrawArea.Width) / 2, _upButton.DrawPosition.Y + 1); + _downButton.DrawPosition = new Vector2((DrawArea.Width - _downButton.DrawArea.Width) / 2, _downButton.DrawPosition.Y); + _scrollButton.DrawPosition = new Vector2((DrawArea.Width - _scrollButton.DrawArea.Width) / 2, _scrollButton.DrawPosition.Y); + } - public void ScrollToTop() - { - ScrollOffset = 0; - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawArea.X, _upButton.DrawArea.Height); - } + public override void Initialize() + { + _upButton.Initialize(); + _downButton.Initialize(); + _scrollButton.Initialize(); - public void ScrollToEnd() - { - while (ScrollOffset < _totalHeight - LinesToRender) - arrowClicked(_downButton, new EventArgs()); - } + base.Initialize(); + } - public void SetScrollOffset(int offset) - { - ScrollOffset = offset; - } + public void UpdateDimensions(int numberOfLines) + { + _totalHeight = numberOfLines; + } - public void SetDownArrowFlashSpeed(int milliseconds) - { - _downButton.FlashSpeed = milliseconds; - } + public void ScrollToTop() + { + ScrollOffset = 0; + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawArea.X, _upButton.DrawArea.Height); + } - protected override void OnDrawControl(GameTime gameTime) - { - if (_backgroundTexture != null) + public void ScrollToEnd() { - _spriteBatch.Begin(); - _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _backgroundTextureSource, Color.White); - _spriteBatch.End(); + while (ScrollOffset < _totalHeight - LinesToRender) + arrowClicked(_downButton, new EventArgs()); } - base.OnDrawControl(gameTime); - } + public void SetScrollOffset(int offset) + { + ScrollOffset = offset; + } - //the point of arrowClicked and scrollDragged is to respond to input on the three buttons in such - // a way that ScrollOffset is updated and the Y coordinate for the scroll box is updated. - // ScrollOffset provides a value that is used within the EOScrollDialog.Draw method. - // The Y coordinate for the scroll box determines where it is drawn. - private void arrowClicked(object btn, EventArgs e) - { - //_totalHeight contains the number of lines to render - //any less than LinesToRender shouldn't scroll - if (_totalHeight <= LinesToRender) - return; + public void SetDownArrowFlashSpeed(int milliseconds) + { + _downButton.FlashSpeed = milliseconds; + } - if (btn == _upButton) + protected override void OnDrawControl(GameTime gameTime) { - if (ScrollOffset > 0) - ScrollOffset--; - else - return; + if (_backgroundTexture != null) + { + _spriteBatch.Begin(); + _spriteBatch.Draw(_backgroundTexture, DrawAreaWithParentOffset, _backgroundTextureSource, Color.White); + _spriteBatch.End(); + } + + base.OnDrawControl(gameTime); } - else if (btn == _downButton) + + //the point of arrowClicked and scrollDragged is to respond to input on the three buttons in such + // a way that ScrollOffset is updated and the Y coordinate for the scroll box is updated. + // ScrollOffset provides a value that is used within the EOScrollDialog.Draw method. + // The Y coordinate for the scroll box determines where it is drawn. + private void arrowClicked(object btn, EventArgs e) { - if (_downButton.FlashSpeed.HasValue) - _downButton.FlashSpeed = null; //as soon as it is clicked, stop flashing + //_totalHeight contains the number of lines to render + //any less than LinesToRender shouldn't scroll + if (_totalHeight <= LinesToRender) + return; - if (ScrollOffset < _totalHeight - LinesToRender) - ScrollOffset++; + if (btn == _upButton) + { + if (ScrollOffset > 0) + ScrollOffset--; + else + return; + } + else if (btn == _downButton) + { + if (_downButton.FlashSpeed.HasValue) + _downButton.FlashSpeed = null; //as soon as it is clicked, stop flashing + + if (ScrollOffset < _totalHeight - LinesToRender) + ScrollOffset++; + else + return; + } else + { return; - } - else - { - return; + } + + var pixelsPerLine = (float)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / (_totalHeight - LinesToRender); + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, _scrollButton.DrawArea.Height + pixelsPerLine * ScrollOffset); + if (_scrollButton.DrawPosition.Y > scrollArea.Height - _scrollButton.DrawArea.Height) + { + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, scrollArea.Height - _scrollButton.DrawArea.Height); + } } - var pixelsPerLine = (float)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / (_totalHeight - LinesToRender); - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, _scrollButton.DrawArea.Height + pixelsPerLine * ScrollOffset); - if (_scrollButton.DrawPosition.Y > scrollArea.Height - _scrollButton.DrawArea.Height) + private void OnScrollButtonDragged(object btn, MouseEventArgs e) { - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, scrollArea.Height - _scrollButton.DrawArea.Height); - } - } + if (_downButton.FlashSpeed.HasValue) + _downButton.FlashSpeed = null; //as soon as we are dragged, stop flashing - private void OnScrollButtonDragged(object btn, MouseEventArgs e) - { - if (_downButton.FlashSpeed.HasValue) - _downButton.FlashSpeed = null; //as soon as we are dragged, stop flashing + var y = e.Position.Y - (DrawAreaWithParentOffset.Y + _scrollButton.DrawArea.Height / 2); - var y = e.Position.Y - (DrawAreaWithParentOffset.Y + _scrollButton.DrawArea.Height / 2); + if (y < _upButton.DrawAreaWithParentOffset.Height) + y = _upButton.DrawAreaWithParentOffset.Height + 1; + else if (y > scrollArea.Height - _scrollButton.DrawArea.Height) + y = scrollArea.Height - _scrollButton.DrawArea.Height; - if (y < _upButton.DrawAreaWithParentOffset.Height) - y = _upButton.DrawAreaWithParentOffset.Height + 1; - else if (y > scrollArea.Height - _scrollButton.DrawArea.Height) - y = scrollArea.Height - _scrollButton.DrawArea.Height; + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, y); - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, y); + if (_totalHeight <= LinesToRender) + return; - if (_totalHeight <= LinesToRender) - return; + var pixelsPerLine = (double)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / (_totalHeight - LinesToRender); + ScrollOffset = (int)Math.Round((y - _scrollButton.DrawArea.Height) / pixelsPerLine); + } - var pixelsPerLine = (double)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / (_totalHeight - LinesToRender); - ScrollOffset = (int)Math.Round((y - _scrollButton.DrawArea.Height) / pixelsPerLine); - } + protected override bool HandleMouseWheelMoved(IXNAControl control, MouseEventArgs eventArgs) + { + if (_totalHeight <= LinesToRender) + return false; - protected override bool HandleMouseWheelMoved(IXNAControl control, MouseEventArgs eventArgs) - { - if (_totalHeight <= LinesToRender) - return false; + //value must be /-120, otherwise you get "Natural" (smooth) scroll. We'll have none of that. + var dif = eventArgs.ScrollWheelDelta / -120; + if ((dif < 0 && dif + ScrollOffset >= 0) || (dif > 0 && ScrollOffset + dif <= _totalHeight - LinesToRender)) + { + ScrollOffset += dif; - //value must be /-120, otherwise you get "Natural" (smooth) scroll. We'll have none of that. - var dif = eventArgs.ScrollWheelDelta / -120; - if ((dif < 0 && dif + ScrollOffset >= 0) || (dif > 0 && ScrollOffset + dif <= _totalHeight - LinesToRender)) - { - ScrollOffset += dif; + var pixelsPerLine = (float)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / + (_totalHeight - LinesToRender); + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, _scrollButton.DrawArea.Height + pixelsPerLine * ScrollOffset); - var pixelsPerLine = (float)(scrollArea.Height - _scrollButton.DrawArea.Height * 2) / - (_totalHeight - LinesToRender); - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, _scrollButton.DrawArea.Height + pixelsPerLine * ScrollOffset); + if (_scrollButton.DrawPosition.Y > scrollArea.Height - _scrollButton.DrawArea.Height) + _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, scrollArea.Height - _scrollButton.DrawArea.Height); + } - if (_scrollButton.DrawPosition.Y > scrollArea.Height - _scrollButton.DrawArea.Height) - _scrollButton.DrawPosition = new Vector2(_scrollButton.DrawPosition.X, scrollArea.Height - _scrollButton.DrawArea.Height); + return true; } - - return true; } } \ No newline at end of file diff --git a/EndlessClient/UIControls/StatusBarLabel.cs b/EndlessClient/UIControls/StatusBarLabel.cs index 84205c57a..4a4ef72ea 100644 --- a/EndlessClient/UIControls/StatusBarLabel.cs +++ b/EndlessClient/UIControls/StatusBarLabel.cs @@ -7,75 +7,76 @@ using System; using XNAControls; -namespace EndlessClient.UIControls; - -public class StatusBarLabel : XNALabel +namespace EndlessClient.UIControls { - private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000; + public class StatusBarLabel : XNALabel + { + private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000; - private readonly INativeGraphicsManager _nativeGraphicsManager; - private readonly IClientWindowSizeProvider _clientWindowSizeProvider; - private readonly IStatusLabelTextProvider _statusLabelTextProvider; + private readonly INativeGraphicsManager _nativeGraphicsManager; + private readonly IClientWindowSizeProvider _clientWindowSizeProvider; + private readonly IStatusLabelTextProvider _statusLabelTextProvider; - private readonly Rectangle _leftSide = new Rectangle(58, 451, 12, 20); - private readonly Rectangle _background = new Rectangle(70, 451, 548, 20); - private readonly Rectangle _rightSide = new Rectangle(618, 451, 12, 20); + private readonly Rectangle _leftSide = new Rectangle(58, 451, 12, 20); + private readonly Rectangle _background = new Rectangle(70, 451, 548, 20); + private readonly Rectangle _rightSide = new Rectangle(618, 451, 12, 20); - private readonly Texture2D _hudBackground; + private readonly Texture2D _hudBackground; - public StatusBarLabel(INativeGraphicsManager nativeGraphicsManager, - IClientWindowSizeProvider clientWindowSizeProvider, - IStatusLabelTextProvider statusLabelTextProvider) - : base(Constants.FontSize07) - { - _nativeGraphicsManager = nativeGraphicsManager; - _clientWindowSizeProvider = clientWindowSizeProvider; - _statusLabelTextProvider = statusLabelTextProvider; - - if (_clientWindowSizeProvider.Resizable) + public StatusBarLabel(INativeGraphicsManager nativeGraphicsManager, + IClientWindowSizeProvider clientWindowSizeProvider, + IStatusLabelTextProvider statusLabelTextProvider) + : base(Constants.FontSize07) { - DrawArea = new Rectangle(40, _clientWindowSizeProvider.Height - 15, 1, 1); - _clientWindowSizeProvider.GameWindowSizeChanged += (_, _) => DrawArea = new Rectangle(40, _clientWindowSizeProvider.Height - 15, 1, 1); + _nativeGraphicsManager = nativeGraphicsManager; + _clientWindowSizeProvider = clientWindowSizeProvider; + _statusLabelTextProvider = statusLabelTextProvider; - _hudBackground = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false, true); - } - else - { - DrawArea = new Rectangle(97, _clientWindowSizeProvider.Height - 26, 1, 1); - } - } + if (_clientWindowSizeProvider.Resizable) + { + DrawArea = new Rectangle(40, _clientWindowSizeProvider.Height - 15, 1, 1); + _clientWindowSizeProvider.GameWindowSizeChanged += (_, _) => DrawArea = new Rectangle(40, _clientWindowSizeProvider.Height - 15, 1, 1); - protected override void OnUnconditionalUpdateControl(GameTime gameTime) - { - if (Text != _statusLabelTextProvider.StatusText) - { - Text = _statusLabelTextProvider.StatusText; + _hudBackground = _nativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 1, false, true); + } + else + { + DrawArea = new Rectangle(97, _clientWindowSizeProvider.Height - 26, 1, 1); + } } - if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS) + protected override void OnUnconditionalUpdateControl(GameTime gameTime) { - Text = string.Empty; - } + if (Text != _statusLabelTextProvider.StatusText) + { + Text = _statusLabelTextProvider.StatusText; + } - base.OnUnconditionalUpdateControl(gameTime); - } + if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS) + { + Text = string.Empty; + } - protected override void OnDrawControl(GameTime gameTime) - { - if (_clientWindowSizeProvider.Resizable) + base.OnUnconditionalUpdateControl(gameTime); + } + + protected override void OnDrawControl(GameTime gameTime) { - var bgDrawArea = new Rectangle(0, _clientWindowSizeProvider.Height - 20, _clientWindowSizeProvider.Width, 20); + if (_clientWindowSizeProvider.Resizable) + { + var bgDrawArea = new Rectangle(0, _clientWindowSizeProvider.Height - 20, _clientWindowSizeProvider.Width, 20); - _spriteBatch.Begin(samplerState: SamplerState.LinearWrap); - _spriteBatch.Draw(_hudBackground, bgDrawArea, _background, Color.White); - _spriteBatch.End(); + _spriteBatch.Begin(samplerState: SamplerState.LinearWrap); + _spriteBatch.Draw(_hudBackground, bgDrawArea, _background, Color.White); + _spriteBatch.End(); - _spriteBatch.Begin(); - _spriteBatch.Draw(_hudBackground, bgDrawArea.Location.ToVector2(), _leftSide, Color.White); - _spriteBatch.Draw(_hudBackground, new Vector2(_clientWindowSizeProvider.Width - _rightSide.Width, bgDrawArea.Y), _rightSide, Color.White); - _spriteBatch.End(); - } + _spriteBatch.Begin(); + _spriteBatch.Draw(_hudBackground, bgDrawArea.Location.ToVector2(), _leftSide, Color.White); + _spriteBatch.Draw(_hudBackground, new Vector2(_clientWindowSizeProvider.Width - _rightSide.Width, bgDrawArea.Y), _rightSide, Color.White); + _spriteBatch.End(); + } - base.OnDrawControl(gameTime); + base.OnDrawControl(gameTime); + } } } \ No newline at end of file diff --git a/EndlessClient/UIControls/TimeLabel.cs b/EndlessClient/UIControls/TimeLabel.cs index 98bf3837c..38c0b9e3a 100644 --- a/EndlessClient/UIControls/TimeLabel.cs +++ b/EndlessClient/UIControls/TimeLabel.cs @@ -4,38 +4,39 @@ using System; using XNAControls; -namespace EndlessClient.UIControls; - -public class TimeLabel : XNALabel +namespace EndlessClient.UIControls { - private DateTime _lastUpdateTime; - - public TimeLabel(IClientWindowSizeProvider windowSizeProvider) - : base(Constants.FontSize07) + public class TimeLabel : XNALabel { - _lastUpdateTime = DateTime.Now; - DrawArea = GetPositionBasedOnWindowSize(windowSizeProvider); - windowSizeProvider.GameWindowSizeChanged += (_, _) => DrawArea = GetPositionBasedOnWindowSize(windowSizeProvider); - } + private DateTime _lastUpdateTime; - protected override void OnUpdateControl(GameTime gameTime) - { - if (DateTime.Now.Second != _lastUpdateTime.Second) + public TimeLabel(IClientWindowSizeProvider windowSizeProvider) + : base(Constants.FontSize07) { - Text = $"{DateTime.Now.Hour,2:D2}:{DateTime.Now.Minute,2:D2}:{DateTime.Now.Second,2:D2}"; - _lastUpdateTime = DateTime.Now; + DrawArea = GetPositionBasedOnWindowSize(windowSizeProvider); + windowSizeProvider.GameWindowSizeChanged += (_, _) => DrawArea = GetPositionBasedOnWindowSize(windowSizeProvider); } - base.OnUpdateControl(gameTime); - } + protected override void OnUpdateControl(GameTime gameTime) + { + if (DateTime.Now.Second != _lastUpdateTime.Second) + { + Text = $"{DateTime.Now.Hour,2:D2}:{DateTime.Now.Minute,2:D2}:{DateTime.Now.Second,2:D2}"; - private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider windowSizeProvider) - { - //original location: 558, 456 - var xLoc = windowSizeProvider.Width - 82; - var yLoc = windowSizeProvider.Height - (windowSizeProvider.Resizable ? 15 : 26); + _lastUpdateTime = DateTime.Now; + } + + base.OnUpdateControl(gameTime); + } - return new Rectangle(xLoc, yLoc, 1, 1); + private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider windowSizeProvider) + { + //original location: 558, 456 + var xLoc = windowSizeProvider.Width - 82; + var yLoc = windowSizeProvider.Height - (windowSizeProvider.Resizable ? 15 : 26); + + return new Rectangle(xLoc, yLoc, 1, 1); + } } } \ No newline at end of file diff --git a/EndlessClient/UIControls/XnaControlSoundMapper.cs b/EndlessClient/UIControls/XnaControlSoundMapper.cs index e33f70a96..880c32796 100644 --- a/EndlessClient/UIControls/XnaControlSoundMapper.cs +++ b/EndlessClient/UIControls/XnaControlSoundMapper.cs @@ -5,41 +5,42 @@ using Optional; using XNAControls; -namespace EndlessClient.UIControls; - -[AutoMappedType] -public class XnaControlSoundMapper : IXnaControlSoundMapper +namespace EndlessClient.UIControls { - private readonly IConfigurationProvider _configurationProvider; - private readonly ISfxPlayer _sfxPlayer; - - public XnaControlSoundMapper(IConfigurationProvider configurationProvider, - ISfxPlayer sfxPlayer) + [AutoMappedType] + public class XnaControlSoundMapper : IXnaControlSoundMapper { - _configurationProvider = configurationProvider; - _sfxPlayer = sfxPlayer; - } + private readonly IConfigurationProvider _configurationProvider; + private readonly ISfxPlayer _sfxPlayer; - public void BindSoundToControl(IGameComponent component, Option soundEffectOverride = default) - { - soundEffectOverride.MatchSome(x => SetupSpecificSound((dynamic)component, x)); - soundEffectOverride.MatchNone(() => SetupSound((dynamic)component)); - } + public XnaControlSoundMapper(IConfigurationProvider configurationProvider, + ISfxPlayer sfxPlayer) + { + _configurationProvider = configurationProvider; + _sfxPlayer = sfxPlayer; + } - private void SetupSound(IXNAButton button) => SetupSpecificSound(button, SoundEffectID.ButtonClick); - private void SetupSpecificSound(IXNAButton button, SoundEffectID sound) => button.OnClick += (_, _) => _sfxPlayer.PlaySfx(sound); + public void BindSoundToControl(IGameComponent component, Option soundEffectOverride = default) + { + soundEffectOverride.MatchSome(x => SetupSpecificSound((dynamic)component, x)); + soundEffectOverride.MatchNone(() => SetupSound((dynamic)component)); + } - private void SetupSound(IXNATextBox textBox) => SetupSpecificSound(textBox, SoundEffectID.TextBoxFocus); - private void SetupSpecificSound(IXNATextBox textBox, SoundEffectID sound) => textBox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(sound); + private void SetupSound(IXNAButton button) => SetupSpecificSound(button, SoundEffectID.ButtonClick); + private void SetupSpecificSound(IXNAButton button, SoundEffectID sound) => button.OnClick += (_, _) => _sfxPlayer.PlaySfx(sound); - private void SetupSound(CreateCharacterControl characterControl) => SetupSpecificSound(characterControl, SoundEffectID.TextBoxFocus); - private void SetupSpecificSound(CreateCharacterControl characterControl, SoundEffectID sound) => characterControl.Clicked += (_, _) => _sfxPlayer.PlaySfx(sound); + private void SetupSound(IXNATextBox textBox) => SetupSpecificSound(textBox, SoundEffectID.TextBoxFocus); + private void SetupSpecificSound(IXNATextBox textBox, SoundEffectID sound) => textBox.OnGotFocus += (_, _) => _sfxPlayer.PlaySfx(sound); - private void SetupSound(object unmatched) { } - private void SetupSpecificSound(object unmatched, SoundEffectID sound) { } -} + private void SetupSound(CreateCharacterControl characterControl) => SetupSpecificSound(characterControl, SoundEffectID.TextBoxFocus); + private void SetupSpecificSound(CreateCharacterControl characterControl, SoundEffectID sound) => characterControl.Clicked += (_, _) => _sfxPlayer.PlaySfx(sound); -public interface IXnaControlSoundMapper -{ - void BindSoundToControl(IGameComponent component, Option soundEffectOverride = default); + private void SetupSound(object unmatched) { } + private void SetupSpecificSound(object unmatched, SoundEffectID sound) { } + } + + public interface IXnaControlSoundMapper + { + void BindSoundToControl(IGameComponent component, Option soundEffectOverride = default); + } } \ No newline at end of file From c1f78480386fceb4c36c0ab3e3bb99f04a6af8f2 Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Wed, 31 Jul 2024 22:17:34 +0100 Subject: [PATCH 04/11] editor config updates --- .editorconfig | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.editorconfig b/.editorconfig index d2f90518b..cb0ec6014 100644 --- a/.editorconfig +++ b/.editorconfig @@ -78,8 +78,8 @@ dotnet_style_allow_statement_immediately_after_block_experimental = true # var preferences csharp_style_var_elsewhere = false:silent -csharp_style_var_for_built_in_types = false:silent -csharp_style_var_when_type_is_apparent = false:silent +csharp_style_var_for_built_in_types = true:silent +csharp_style_var_when_type_is_apparent = true:silent # Expression-bodied members csharp_style_expression_bodied_accessors = true:silent @@ -113,7 +113,7 @@ csharp_prefer_braces = true:silent csharp_prefer_simple_using_statement = true:suggestion csharp_style_namespace_declarations = block_scoped:warning csharp_style_prefer_method_group_conversion = true:silent -csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_prefer_primary_constructors = false:suggestion csharp_style_prefer_top_level_statements = true:silent # Expression-level preferences @@ -259,9 +259,9 @@ dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent dotnet_style_allow_multiple_blank_lines_experimental = true:silent dotnet_style_allow_statement_immediately_after_block_experimental = true:silent dotnet_code_quality_unused_parameters = all:suggestion -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:silent dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent dotnet_style_qualification_for_field = false:silent dotnet_style_qualification_for_property = false:silent From e605574eebd2a405312842178565259f0f8c46d4 Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Wed, 31 Jul 2024 22:45:46 +0100 Subject: [PATCH 05/11] feat: add build failure on dotnet format violation --- EndlessClient/EndlessClient.csproj | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/EndlessClient/EndlessClient.csproj b/EndlessClient/EndlessClient.csproj index 1ac9f1b06..1fa79d048 100644 --- a/EndlessClient/EndlessClient.csproj +++ b/EndlessClient/EndlessClient.csproj @@ -1,4 +1,7 @@  + + + net6.0-windows WinExe @@ -75,7 +78,6 @@ Icon.bmp - From 9682d1b6785b3152a5de95397027fbffe26cf7fd Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Wed, 31 Jul 2024 23:23:24 +0100 Subject: [PATCH 06/11] style: dotnet format in linux --- EndlessClient/GameExecution/GameRunnerBase.cs | 6 +++--- EndlessClient/GameExecution/ReleaseGameRunner.cs | 5 ++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/EndlessClient/GameExecution/GameRunnerBase.cs b/EndlessClient/GameExecution/GameRunnerBase.cs index 5d9eaf43f..b93e36726 100644 --- a/EndlessClient/GameExecution/GameRunnerBase.cs +++ b/EndlessClient/GameExecution/GameRunnerBase.cs @@ -1,11 +1,11 @@ -using System.Diagnostics; -using System.IO; -using AutomaticTypeMapper; +using AutomaticTypeMapper; using EndlessClient.Initialization; using EOLib.Config; using EOLib.Graphics; using EOLib.Localization; using System; +using System.Diagnostics; +using System.IO; using System.Net; #if !LINUX && !OSX diff --git a/EndlessClient/GameExecution/ReleaseGameRunner.cs b/EndlessClient/GameExecution/ReleaseGameRunner.cs index a03d47224..a816bda2c 100644 --- a/EndlessClient/GameExecution/ReleaseGameRunner.cs +++ b/EndlessClient/GameExecution/ReleaseGameRunner.cs @@ -1,6 +1,5 @@ -using System; -using AutomaticTypeMapper; - +using AutomaticTypeMapper; +using System; using System.Runtime.Versioning; #if !LINUX && !OSX From f8679fa8f683921f4efd58ffe9d7893c390d2091 Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Wed, 31 Jul 2024 23:35:56 +0100 Subject: [PATCH 07/11] fix: add .gitattribute that forces git to honour existing line ending patterns --- .gitattributes | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitattributes b/.gitattributes index 412eeda78..8287b8209 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,5 @@ # Auto detect text files and perform LF normalization -* text=auto +* text=auto eol=crlf # Custom for Visual Studio *.cs diff=csharp @@ -19,4 +19,4 @@ *.pdf diff=astextplain *.PDF diff=astextplain *.rtf diff=astextplain -*.RTF diff=astextplain +*.RTF diff=astextplain \ No newline at end of file From d500550d780ddf72452a2381c4bf5915b3a51fe6 Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Wed, 31 Jul 2024 23:36:38 +0100 Subject: [PATCH 08/11] fix: force eol=crlf for .cs files --- .gitattributes | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index 8287b8209..439b87186 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,7 +2,7 @@ * text=auto eol=crlf # Custom for Visual Studio -*.cs diff=csharp +*.cs diff=csharp eol=crlf *.sln merge=union *.csproj merge=union *.vbproj merge=union From f1c16bd411be1906ecd41804040c714b8334ae85 Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Wed, 31 Jul 2024 23:49:12 +0100 Subject: [PATCH 09/11] docs: update readme --- README.md | 6 ++++++ contributing.md | 8 +++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 78130ca47..f6be31923 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,12 @@ After installing, clone (or fork+clone) this repository locally and open the sol > - Windows: `rmdir -recurse -force $env:USERPROFILE\\.dotnet\\toolResolverCache` > - Linux: `rm -rf ~/.dotnet/toolResolverCache` +> ⚠️ If you get build errors due to formatting +> +> Run the following commands: +> - Windows: `dotnet format EndlessClient.sln` +> - Linux: `dotnet format EndlessClient.Linux.sln` + ### Building on Mac 1. Download and install the [.NET 6.0 SDK (x64)](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-6.0.403-macos-x64-installer). diff --git a/contributing.md b/contributing.md index f9b31db66..1a48cd663 100644 --- a/contributing.md +++ b/contributing.md @@ -1,4 +1,4 @@ -# Contributing +# Contributing This is a general guide for contributing to the EndlessClient project. Pull requests that do not meet the minimum of these requirements will not be accepted, and you will be referred to this document. This is an evolving document and is subject to change without notice. @@ -30,6 +30,12 @@ Here are the style requirements for this project. This is the bare minimum you m - Put empty lines around functions, properties, etc. - Avoid use of explicit `this` or `base` keywords +> ⚠️ If you do not adhere to the above code style, your build may fail locally +> +> To resolve build errors due to formatting, run the following commands: +> - Windows: `dotnet format EndlessClient.sln` +> - Linux: `dotnet format EndlessClient.Linux.sln` + ### Naming Try to follow standard C# namining conventions From e4b3f8907e0478c6271377285c96a1e35b694760 Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Fri, 2 Aug 2024 09:31:05 +0100 Subject: [PATCH 10/11] style: rerun dotnet format with system usings first docs: update readme about building on mac --- .editorconfig | 2 +- EndlessClient/Audio/MfxPlayer.cs | 8 ++++---- EndlessClient/Audio/SfxPlayer.cs | 4 ++-- EndlessClient/Content/ContentProvider.cs | 8 ++++---- EndlessClient/ControlSets/BackButtonControlSet.cs | 4 ++-- EndlessClient/ControlSets/BaseControlSet.cs | 8 ++++---- EndlessClient/ControlSets/ControlSetFactory.cs | 4 ++-- .../ControlSets/CreateAccountControlSet.cs | 8 ++++---- EndlessClient/ControlSets/EmptyControlSet.cs | 6 +++--- EndlessClient/ControlSets/IControlSet.cs | 6 +++--- EndlessClient/ControlSets/IHudControlProvider.cs | 6 +++--- EndlessClient/ControlSets/InGameControlSet.cs | 8 ++++---- EndlessClient/ControlSets/InitialControlSet.cs | 6 +++--- .../ControlSets/IntermediateControlSet.cs | 2 +- EndlessClient/ControlSets/LoggedInControlSet.cs | 8 ++++---- .../ControlSets/LoginPromptControlSet.cs | 8 ++++---- EndlessClient/Controllers/AccountController.cs | 4 ++-- .../Controllers/CharacterManagementController.cs | 4 ++-- EndlessClient/Controllers/ChatController.cs | 4 ++-- EndlessClient/Controllers/InventoryController.cs | 6 +++--- EndlessClient/Controllers/LoginController.cs | 8 ++++---- EndlessClient/Controllers/MainButtonController.cs | 8 ++++---- .../Controllers/MapInteractionController.cs | 6 +++--- .../Controllers/NPCInteractionController.cs | 4 ++-- .../Actions/AccountDialogDisplayActions.cs | 6 +++--- .../Dialogs/Actions/CharacterDialogActions.cs | 6 +++--- .../Dialogs/Actions/ErrorDialogDisplayAction.cs | 8 ++++---- EndlessClient/Dialogs/Actions/HelpActions.cs | 4 ++-- .../Actions/IAccountDialogDisplayActions.cs | 4 ++-- .../Dialogs/Actions/ICharacterDialogActions.cs | 4 ++-- .../Dialogs/Actions/InGameDialogActions.cs | 8 ++++---- .../Dialogs/Actions/NpcInteractionActions.cs | 4 ++-- EndlessClient/Dialogs/ActiveDialogRepository.cs | 6 +++--- EndlessClient/Dialogs/BankAccountDialog.cs | 4 ++-- EndlessClient/Dialogs/BarberDialog.cs | 2 +- EndlessClient/Dialogs/BardDialog.cs | 4 ++-- EndlessClient/Dialogs/BaseEODialog.cs | 4 ++-- EndlessClient/Dialogs/BoardDialog.cs | 8 ++++---- EndlessClient/Dialogs/BookDialog.cs | 6 +++--- EndlessClient/Dialogs/ChangePasswordDialog.cs | 6 +++--- EndlessClient/Dialogs/ChestDialog.cs | 6 +++--- EndlessClient/Dialogs/CreateCharacterDialog.cs | 4 ++-- EndlessClient/Dialogs/EOMessageBox.cs | 4 ++-- .../Dialogs/Extensions/EquipLocationExtensions.cs | 4 ++-- .../Dialogs/Factories/BarberDialogFactory.cs | 2 +- .../Factories/FriendIgnoreListDialogFactory.cs | 6 +++--- .../Dialogs/Factories/HelpDialogFactory.cs | 6 +++--- EndlessClient/Dialogs/FriendIgnoreListDialog.cs | 6 +++--- EndlessClient/Dialogs/GameLoadingDialog.cs | 4 ++-- EndlessClient/Dialogs/InnkeeperDialog.cs | 6 +++--- EndlessClient/Dialogs/ItemTransferDialog.cs | 4 ++-- EndlessClient/Dialogs/JukeboxDialog.cs | 6 +++--- EndlessClient/Dialogs/LawDialog.cs | 8 ++++---- EndlessClient/Dialogs/ListDialogItem.cs | 4 ++-- EndlessClient/Dialogs/LockerDialog.cs | 6 +++--- EndlessClient/Dialogs/PaperdollDialog.cs | 8 ++++---- EndlessClient/Dialogs/PaperdollDialogItem.cs | 4 ++-- EndlessClient/Dialogs/ProgressDialog.cs | 6 +++--- EndlessClient/Dialogs/QuestDialog.cs | 8 ++++---- EndlessClient/Dialogs/QuestStatusDialog.cs | 4 ++-- EndlessClient/Dialogs/ScrollingListDialog.cs | 8 ++++---- EndlessClient/Dialogs/ScrollingMessageDialog.cs | 6 +++--- EndlessClient/Dialogs/SessionExpDialog.cs | 4 ++-- EndlessClient/Dialogs/ShopDialog.cs | 8 ++++---- EndlessClient/Dialogs/SkillmasterDialog.cs | 10 +++++----- EndlessClient/Dialogs/TextMultiInputDialog.cs | 8 ++++---- EndlessClient/Dialogs/TradeDialog.cs | 10 +++++----- EndlessClient/GameExecution/EndlessGame.cs | 12 ++++++------ EndlessClient/GameExecution/GameRunnerBase.cs | 10 +++++----- EndlessClient/GameExecution/GameStateActions.cs | 8 ++++---- EndlessClient/GameExecution/IEndlessGame.cs | 4 ++-- EndlessClient/GameExecution/ReleaseGameRunner.cs | 4 ++-- EndlessClient/HUD/AStarPathFinder.cs | 8 ++++---- EndlessClient/HUD/Chat/ChatBubbleActions.cs | 2 +- EndlessClient/HUD/Chat/ChatNotificationActions.cs | 8 ++++---- EndlessClient/HUD/Chat/ChatPanelTab.cs | 8 ++++---- EndlessClient/HUD/Chat/PrivateMessageActions.cs | 4 ++-- EndlessClient/HUD/Controls/DraggablePanelItem.cs | 4 ++-- EndlessClient/HUD/Controls/HudControlsFactory.cs | 8 ++++---- EndlessClient/HUD/Controls/IHudControlsFactory.cs | 4 ++-- .../HUD/Controls/PeriodicStatUpdaterComponent.cs | 6 +++--- EndlessClient/HUD/HudStateActions.cs | 6 +++--- EndlessClient/HUD/IStatusLabelTextRepository.cs | 4 ++-- EndlessClient/HUD/Inventory/InventoryPanelItem.cs | 4 ++-- EndlessClient/HUD/Inventory/InventoryService.cs | 4 ++-- .../HUD/Inventory/InventorySlotRepository.cs | 4 ++-- .../HUD/Inventory/InventorySpaceValidator.cs | 6 +++--- EndlessClient/HUD/Panels/ActiveSpellsPanel.cs | 15 +++++++-------- EndlessClient/HUD/Panels/ChatPanel.cs | 8 ++++---- EndlessClient/HUD/Panels/DraggableHudPanel.cs | 4 ++-- EndlessClient/HUD/Panels/IHudPanel.cs | 4 ++-- EndlessClient/HUD/Panels/InventoryPanel.cs | 14 +++++++------- EndlessClient/HUD/Panels/NewsPanel.cs | 6 +++--- EndlessClient/HUD/Panels/OnlineListPanel.cs | 8 ++++---- EndlessClient/HUD/Panels/PartyPanel.cs | 6 +++--- EndlessClient/HUD/Panels/SettingsPanel.cs | 8 ++++---- EndlessClient/HUD/Panels/StatsPanel.cs | 6 +++--- EndlessClient/HUD/Party/PartyPanelMember.cs | 4 ++-- EndlessClient/HUD/Spells/SpellPanelItem.cs | 4 ++-- EndlessClient/HUD/Spells/SpellSelectActions.cs | 4 ++-- .../HUD/Spells/SpellSlotDataRepository.cs | 4 ++-- EndlessClient/HUD/StatusBars/HPStatusBar.cs | 4 ++-- EndlessClient/HUD/StatusBars/SPStatusBar.cs | 4 ++-- EndlessClient/HUD/StatusBars/StatusBarBase.cs | 4 ++-- EndlessClient/HUD/StatusBars/TNLStatusBar.cs | 6 +++--- EndlessClient/HUD/StatusBars/TPStatusBar.cs | 4 ++-- EndlessClient/HUD/StatusLabelSetter.cs | 2 +- EndlessClient/HUD/UserInterfaceActions.cs | 8 ++++---- .../Initialization/EndlessClientInitializer.cs | 4 ++-- .../Initialization/GraphicsInitializer.cs | 4 ++-- EndlessClient/Input/IUserInputTimeRepository.cs | 4 ++-- EndlessClient/Input/InputHandlerBase.cs | 6 +++--- EndlessClient/Input/PanelShortcutHandler.cs | 4 ++-- EndlessClient/Input/UnwalkableTileActions.cs | 4 ++-- .../Input/UnwalkableTileActionsHandler.cs | 4 ++-- EndlessClient/Input/UserInputHandler.cs | 8 ++++---- EndlessClient/Network/UnknownEntitiesRequester.cs | 10 +++++----- EndlessClient/Program.cs | 6 +++--- .../Character/CharacterAnimationActions.cs | 8 ++++---- .../Rendering/Character/CharacterAnimator.cs | 10 +++++----- .../Rendering/Character/CharacterRenderer.cs | 6 +++--- .../Character/CharacterRendererUpdater.cs | 8 ++++---- .../Rendering/Character/CharacterStateCache.cs | 9 ++++----- .../Rendering/Character/ICharacterRenderer.cs | 4 ++-- .../Character/ICharacterRendererRepository.cs | 6 +++--- .../Rendering/Character/ICharacterStateCache.cs | 5 ++--- .../Rendering/Character/PeriodicEmoteHandler.cs | 6 +++--- .../CharacterProperties/ArmorRenderer.cs | 4 ++-- .../CharacterProperties/BootsRenderer.cs | 4 ++-- .../CharacterPropertyRendererBuilder.cs | 6 +++--- .../HairRenderLocationCalculator.cs | 4 ++-- .../ICharacterPropertyRendererBuilder.cs | 2 +- .../CharacterProperties/ShieldRenderer.cs | 4 ++-- .../SkinRenderLocationCalculator.cs | 2 +- .../CharacterProperties/WeaponRenderer.cs | 4 ++-- EndlessClient/Rendering/Chat/ChatBubble.cs | 6 +++--- .../Rendering/Chat/ChatBubbleTextureProvider.cs | 4 ++-- .../Rendering/Chat/ChatColorExtensions.cs | 4 ++-- .../Rendering/Chat/ChatRenderableGenerator.cs | 8 ++++---- .../Rendering/Chat/IChatRenderableGenerator.cs | 4 ++-- .../Rendering/ClientWindowSizeRepository.cs | 6 +++--- EndlessClient/Rendering/ContextMenuRenderer.cs | 8 ++++---- .../Rendering/DispatcherGameComponent.cs | 8 ++++---- EndlessClient/Rendering/Effects/EffectRenderer.cs | 9 ++++----- .../Rendering/Effects/EffectSpriteInfo.cs | 6 +++--- .../Rendering/Effects/EffectSpriteManager.cs | 4 ++-- .../Effects/PositionOffsetEffectMetadata.cs | 4 ++-- .../Rendering/GridDrawCoordinateCalculator.cs | 5 ++--- EndlessClient/Rendering/HealthBarRenderer.cs | 8 ++++---- EndlessClient/Rendering/Map/ClickDispatcher.cs | 8 ++++---- .../Rendering/Map/DynamicMapObjectUpdater.cs | 8 ++++---- EndlessClient/Rendering/Map/MapChangedActions.cs | 4 ++-- .../Rendering/Map/MapEntityRendererProvider.cs | 2 +- .../Rendering/Map/MapObjectBoundsCalculator.cs | 4 ++-- .../Rendering/Map/MapRenderDistanceCalculator.cs | 4 ++-- EndlessClient/Rendering/Map/MapRenderer.cs | 8 ++++---- EndlessClient/Rendering/Map/MiniMapRenderer.cs | 6 +++--- .../MapEntityRenderers/BaseMapEntityRenderer.cs | 6 +++--- .../MapEntityRenderers/IMapEntityRenderer.cs | 4 ++-- .../MapEntityRenderers/MapItemLayerRenderer.cs | 6 +++--- .../MapEntityRenderers/MapObjectLayerRenderer.cs | 8 ++++---- .../MapEntityRenderers/NPCEntityRenderer.cs | 4 ++-- .../OtherCharacterEntityRenderer.cs | 4 ++-- .../MapEntityRenderers/WallLayerRenderer.cs | 4 ++-- .../Rendering/Metadata/EffectMetadataProvider.cs | 4 ++-- .../Rendering/Metadata/GFXMetadataLoader.cs | 8 ++++---- .../Rendering/Metadata/HatMetadataProvider.cs | 4 ++-- .../Rendering/Metadata/IMetadataProvider.cs | 4 ++-- .../Rendering/Metadata/NPCMetadataProvider.cs | 4 ++-- .../Rendering/Metadata/ShieldMetadataProvider.cs | 4 ++-- .../Rendering/Metadata/WeaponMetadataProvider.cs | 4 ++-- EndlessClient/Rendering/MouseCursorRenderer.cs | 8 ++++---- EndlessClient/Rendering/NPC/INPCRenderer.cs | 2 +- EndlessClient/Rendering/NPC/NPCAnimator.cs | 6 +++--- EndlessClient/Rendering/NPC/NPCCache.cs | 4 ++-- EndlessClient/Rendering/NPC/NPCRenderer.cs | 8 ++++---- .../Rendering/NPC/NPCRendererRepository.cs | 6 +++--- EndlessClient/Rendering/NPC/NPCRendererUpdater.cs | 6 +++--- .../Rendering/PlayerStatusIconRenderer.cs | 4 ++-- EndlessClient/Rendering/PointComparer.cs | 4 ++-- .../Sprites/CharacterSpriteCalculator.cs | 6 +++--- .../Rendering/Sprites/EmptySpriteSheet.cs | 4 ++-- .../Rendering/Sprites/NPCSpriteDataCache.cs | 8 ++++---- EndlessClient/Services/FriendIgnoreListService.cs | 4 ++-- EndlessClient/Subscribers/ArenaEventSubscriber.cs | 4 ++-- .../Subscribers/OtherCharacterEventSubscriber.cs | 6 +++--- EndlessClient/Test/CharacterStateTest.cs | 8 ++++---- EndlessClient/UIControls/BlinkingLabel.cs | 4 ++-- EndlessClient/UIControls/CharacterInfoPanel.cs | 6 +++--- .../UIControls/CharacterInfoPanelFactory.cs | 6 +++--- EndlessClient/UIControls/ChatModePictureBox.cs | 4 ++-- EndlessClient/UIControls/ChatTextBox.cs | 4 ++-- EndlessClient/UIControls/ClickableArea.cs | 4 ++-- .../UIControls/CreateCharacterControl.cs | 4 ++-- .../UIControls/ICharacterInfoPanelFactory.cs | 4 ++-- EndlessClient/UIControls/ScrollBar.cs | 4 ++-- EndlessClient/UIControls/StatusBarLabel.cs | 4 ++-- EndlessClient/UIControls/TimeLabel.cs | 4 ++-- README.md | 5 +++++ global.json | 6 ++++++ 200 files changed, 562 insertions(+), 556 deletions(-) create mode 100644 global.json diff --git a/.editorconfig b/.editorconfig index cb0ec6014..596bca640 100644 --- a/.editorconfig +++ b/.editorconfig @@ -19,7 +19,7 @@ insert_final_newline = false # Organize usings dotnet_separate_import_directive_groups = false -dotnet_sort_system_directives_first = false +dotnet_sort_system_directives_first = true file_header_template = unset # this. and Me. preferences diff --git a/EndlessClient/Audio/MfxPlayer.cs b/EndlessClient/Audio/MfxPlayer.cs index fd3cd231f..8cfe0c4d4 100644 --- a/EndlessClient/Audio/MfxPlayer.cs +++ b/EndlessClient/Audio/MfxPlayer.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System; +using System.IO; +using System.Linq; +using AutomaticTypeMapper; using Commons.Music.Midi; using EOLib; using EOLib.Config; using EOLib.IO.Map; -using System; -using System.IO; -using System.Linq; namespace EndlessClient.Audio { diff --git a/EndlessClient/Audio/SfxPlayer.cs b/EndlessClient/Audio/SfxPlayer.cs index 4ae6db01d..1b22031a9 100644 --- a/EndlessClient/Audio/SfxPlayer.cs +++ b/EndlessClient/Audio/SfxPlayer.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EndlessClient.Content; using EOLib.Config; using Microsoft.Xna.Framework.Audio; -using System; namespace EndlessClient.Audio { diff --git a/EndlessClient/Content/ContentProvider.cs b/EndlessClient/Content/ContentProvider.cs index a7aacd0e4..98999483c 100644 --- a/EndlessClient/Content/ContentProvider.cs +++ b/EndlessClient/Content/ContentProvider.cs @@ -1,13 +1,13 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Audio; using EOLib; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.BitmapFonts; -using System.Collections.Generic; -using System.IO; -using System.Linq; namespace EndlessClient.Content { diff --git a/EndlessClient/ControlSets/BackButtonControlSet.cs b/EndlessClient/ControlSets/BackButtonControlSet.cs index c4ad0cd9f..4c369ead1 100644 --- a/EndlessClient/ControlSets/BackButtonControlSet.cs +++ b/EndlessClient/ControlSets/BackButtonControlSet.cs @@ -1,10 +1,10 @@ -using EndlessClient.Content; +using System; +using EndlessClient.Content; using EndlessClient.Controllers; using EndlessClient.Rendering; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; using XNAControls; namespace EndlessClient.ControlSets diff --git a/EndlessClient/ControlSets/BaseControlSet.cs b/EndlessClient/ControlSets/BaseControlSet.cs index c0e9e109e..a623779cd 100644 --- a/EndlessClient/ControlSets/BaseControlSet.cs +++ b/EndlessClient/ControlSets/BaseControlSet.cs @@ -1,11 +1,11 @@ -using EndlessClient.Content; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Content; using EndlessClient.GameExecution; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.ControlSets diff --git a/EndlessClient/ControlSets/ControlSetFactory.cs b/EndlessClient/ControlSets/ControlSetFactory.cs index ea25b2924..53b831449 100644 --- a/EndlessClient/ControlSets/ControlSetFactory.cs +++ b/EndlessClient/ControlSets/ControlSetFactory.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EndlessClient.Content; using EndlessClient.Controllers; using EndlessClient.Dialogs; @@ -11,7 +12,6 @@ using EOLib.Config; using EOLib.Domain.Login; using EOLib.Graphics; -using System; namespace EndlessClient.ControlSets { diff --git a/EndlessClient/ControlSets/CreateAccountControlSet.cs b/EndlessClient/ControlSets/CreateAccountControlSet.cs index 51bda50cc..e463c6abc 100644 --- a/EndlessClient/ControlSets/CreateAccountControlSet.cs +++ b/EndlessClient/ControlSets/CreateAccountControlSet.cs @@ -1,4 +1,7 @@ -using EndlessClient.Content; +using System; +using System.Linq; +using System.Threading.Tasks; +using EndlessClient.Content; using EndlessClient.Controllers; using EndlessClient.GameExecution; using EndlessClient.Input; @@ -8,9 +11,6 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.Linq; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.ControlSets diff --git a/EndlessClient/ControlSets/EmptyControlSet.cs b/EndlessClient/ControlSets/EmptyControlSet.cs index 1fe96ebbe..36ae45450 100644 --- a/EndlessClient/ControlSets/EmptyControlSet.cs +++ b/EndlessClient/ControlSets/EmptyControlSet.cs @@ -1,9 +1,9 @@ -using EndlessClient.Content; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Content; using EndlessClient.GameExecution; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.ControlSets diff --git a/EndlessClient/ControlSets/IControlSet.cs b/EndlessClient/ControlSets/IControlSet.cs index c77c536a4..ea2c6c298 100644 --- a/EndlessClient/ControlSets/IControlSet.cs +++ b/EndlessClient/ControlSets/IControlSet.cs @@ -1,9 +1,9 @@ -using EndlessClient.Content; +using System; +using System.Collections.Generic; +using EndlessClient.Content; using EndlessClient.GameExecution; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; using XNAControls; namespace EndlessClient.ControlSets diff --git a/EndlessClient/ControlSets/IHudControlProvider.cs b/EndlessClient/ControlSets/IHudControlProvider.cs index c6693c135..5afacd65c 100644 --- a/EndlessClient/ControlSets/IHudControlProvider.cs +++ b/EndlessClient/ControlSets/IHudControlProvider.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.GameExecution; using EndlessClient.HUD.Controls; using EndlessClient.HUD.Panels; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; namespace EndlessClient.ControlSets { diff --git a/EndlessClient/ControlSets/InGameControlSet.cs b/EndlessClient/ControlSets/InGameControlSet.cs index 12bb0dfd6..a31fd2fc8 100644 --- a/EndlessClient/ControlSets/InGameControlSet.cs +++ b/EndlessClient/ControlSets/InGameControlSet.cs @@ -1,4 +1,7 @@ -using EndlessClient.Controllers; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Controllers; using EndlessClient.Dialogs; using EndlessClient.Dialogs.Factories; using EndlessClient.GameExecution; @@ -6,9 +9,6 @@ using EndlessClient.Rendering; using EOLib.Localization; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.ControlSets diff --git a/EndlessClient/ControlSets/InitialControlSet.cs b/EndlessClient/ControlSets/InitialControlSet.cs index 11c4d8a31..ef1290530 100644 --- a/EndlessClient/ControlSets/InitialControlSet.cs +++ b/EndlessClient/ControlSets/InitialControlSet.cs @@ -1,4 +1,6 @@ -using EndlessClient.Content; +using System; +using System.Threading.Tasks; +using EndlessClient.Content; using EndlessClient.Controllers; using EndlessClient.GameExecution; using EOLib; @@ -6,8 +8,6 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.ControlSets diff --git a/EndlessClient/ControlSets/IntermediateControlSet.cs b/EndlessClient/ControlSets/IntermediateControlSet.cs index 63ebe9f95..40cdd9fd2 100644 --- a/EndlessClient/ControlSets/IntermediateControlSet.cs +++ b/EndlessClient/ControlSets/IntermediateControlSet.cs @@ -1,3 +1,4 @@ +using System; using EndlessClient.Content; using EndlessClient.Controllers; using EndlessClient.GameExecution; @@ -5,7 +6,6 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; using XNAControls; namespace EndlessClient.ControlSets diff --git a/EndlessClient/ControlSets/LoggedInControlSet.cs b/EndlessClient/ControlSets/LoggedInControlSet.cs index 325b4895b..86bfad51e 100644 --- a/EndlessClient/ControlSets/LoggedInControlSet.cs +++ b/EndlessClient/ControlSets/LoggedInControlSet.cs @@ -1,13 +1,13 @@ -using EndlessClient.Controllers; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using EndlessClient.Controllers; using EndlessClient.GameExecution; using EndlessClient.Input; using EndlessClient.Rendering; using EndlessClient.UIControls; using EOLib.Domain.Login; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.ControlSets diff --git a/EndlessClient/ControlSets/LoginPromptControlSet.cs b/EndlessClient/ControlSets/LoginPromptControlSet.cs index 2da2d5452..6721730c2 100644 --- a/EndlessClient/ControlSets/LoginPromptControlSet.cs +++ b/EndlessClient/ControlSets/LoginPromptControlSet.cs @@ -1,4 +1,7 @@ -using EndlessClient.Content; +using System; +using System.Linq; +using System.Threading.Tasks; +using EndlessClient.Content; using EndlessClient.Controllers; using EndlessClient.GameExecution; using EndlessClient.Input; @@ -8,9 +11,6 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.Linq; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.ControlSets diff --git a/EndlessClient/Controllers/AccountController.cs b/EndlessClient/Controllers/AccountController.cs index 79394a599..6db21f0a3 100644 --- a/EndlessClient/Controllers/AccountController.cs +++ b/EndlessClient/Controllers/AccountController.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EndlessClient.Dialogs.Actions; using EndlessClient.GameExecution; using EOLib.Domain.Account; using EOLib.Net; using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.Controllers diff --git a/EndlessClient/Controllers/CharacterManagementController.cs b/EndlessClient/Controllers/CharacterManagementController.cs index 90eb67e2a..cce7bdc6a 100644 --- a/EndlessClient/Controllers/CharacterManagementController.cs +++ b/EndlessClient/Controllers/CharacterManagementController.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Dialogs.Actions; using EndlessClient.GameExecution; @@ -9,7 +10,6 @@ using EOLib.Net.Connection; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.Controllers diff --git a/EndlessClient/Controllers/ChatController.cs b/EndlessClient/Controllers/ChatController.cs index 4e84953b2..10b6a0204 100644 --- a/EndlessClient/Controllers/ChatController.cs +++ b/EndlessClient/Controllers/ChatController.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.ControlSets; using EndlessClient.HUD; @@ -9,7 +10,6 @@ using EOLib.Domain.Chat.Commands; using EOLib.Domain.Map; using EOLib.Localization; -using System; namespace EndlessClient.Controllers { diff --git a/EndlessClient/Controllers/InventoryController.cs b/EndlessClient/Controllers/InventoryController.cs index 34ccb0ba6..fab2f4fe8 100644 --- a/EndlessClient/Controllers/InventoryController.cs +++ b/EndlessClient/Controllers/InventoryController.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.ControlSets; using EndlessClient.Dialogs; @@ -20,8 +22,6 @@ using EOLib.IO.Pub; using EOLib.IO.Repositories; using EOLib.Localization; -using System; -using System.Linq; using XNAControls; namespace EndlessClient.Controllers diff --git a/EndlessClient/Controllers/LoginController.cs b/EndlessClient/Controllers/LoginController.cs index b8fc7b40f..00a9f75e3 100644 --- a/EndlessClient/Controllers/LoginController.cs +++ b/EndlessClient/Controllers/LoginController.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.IO; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EndlessClient.Dialogs; using EndlessClient.Dialogs.Actions; using EndlessClient.Dialogs.Factories; @@ -21,9 +24,6 @@ using EOLib.Net.FileTransfer; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.IO; -using System.Threading.Tasks; namespace EndlessClient.Controllers { diff --git a/EndlessClient/Controllers/MainButtonController.cs b/EndlessClient/Controllers/MainButtonController.cs index 4f68aa7ff..30b4edf6d 100644 --- a/EndlessClient/Controllers/MainButtonController.cs +++ b/EndlessClient/Controllers/MainButtonController.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Threading; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EndlessClient.Dialogs.Actions; using EndlessClient.GameExecution; using EndlessClient.Rendering; @@ -9,9 +12,6 @@ using EOLib.Net.PacketProcessing; using Moffat.EndlessOnline.SDK.Packet; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Threading; -using System.Threading.Tasks; namespace EndlessClient.Controllers { diff --git a/EndlessClient/Controllers/MapInteractionController.cs b/EndlessClient/Controllers/MapInteractionController.cs index b64509482..c36a9898a 100644 --- a/EndlessClient/Controllers/MapInteractionController.cs +++ b/EndlessClient/Controllers/MapInteractionController.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.ControlSets; using EndlessClient.Dialogs; @@ -25,8 +27,6 @@ using EOLib.Localization; using Optional; using Optional.Collections; -using System; -using System.Linq; namespace EndlessClient.Controllers { diff --git a/EndlessClient/Controllers/NPCInteractionController.cs b/EndlessClient/Controllers/NPCInteractionController.cs index f031b3596..8f4a7e405 100644 --- a/EndlessClient/Controllers/NPCInteractionController.cs +++ b/EndlessClient/Controllers/NPCInteractionController.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Dialogs; using EndlessClient.Dialogs.Actions; using EndlessClient.HUD; @@ -7,7 +8,6 @@ using EOLib.Domain.NPC; using EOLib.IO.Repositories; using EOLib.Localization; -using System.Linq; namespace EndlessClient.Controllers { diff --git a/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs b/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs index 6a7fa651b..30652d864 100644 --- a/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs +++ b/EndlessClient/Dialogs/Actions/AccountDialogDisplayActions.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EndlessClient.Dialogs.Factories; using EOLib.Domain.Account; using EOLib.Localization; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.Dialogs.Actions diff --git a/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs b/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs index ee99390e4..d25fc5859 100644 --- a/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/CharacterDialogActions.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EndlessClient.Dialogs.Factories; using EOLib.Domain.Character; using EOLib.Localization; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.Dialogs.Actions diff --git a/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs b/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs index 430d84281..514c789ee 100644 --- a/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs +++ b/EndlessClient/Dialogs/Actions/ErrorDialogDisplayAction.cs @@ -1,13 +1,13 @@ -using AutomaticTypeMapper; +using System; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Dialogs.Factories; using EOLib.Localization; using EOLib.Net; using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Net.Sockets; -using System.Runtime.InteropServices; namespace EndlessClient.Dialogs.Actions { diff --git a/EndlessClient/Dialogs/Actions/HelpActions.cs b/EndlessClient/Dialogs/Actions/HelpActions.cs index ee018a1d0..c325ea77d 100644 --- a/EndlessClient/Dialogs/Actions/HelpActions.cs +++ b/EndlessClient/Dialogs/Actions/HelpActions.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Dialogs.Factories; using EOLib.Domain.Report; using EOLib.Localization; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs.Actions diff --git a/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs b/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs index b394df971..93b2d41f0 100644 --- a/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs +++ b/EndlessClient/Dialogs/Actions/IAccountDialogDisplayActions.cs @@ -1,7 +1,7 @@ -using EOLib.Domain.Account; +using System.Threading.Tasks; +using EOLib.Domain.Account; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.Dialogs.Actions diff --git a/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs b/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs index c681896cc..97ee3d0da 100644 --- a/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/ICharacterDialogActions.cs @@ -1,7 +1,7 @@ -using EOLib.Domain.Character; +using System.Threading.Tasks; +using EOLib.Domain.Character; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.Dialogs.Actions diff --git a/EndlessClient/Dialogs/Actions/InGameDialogActions.cs b/EndlessClient/Dialogs/Actions/InGameDialogActions.cs index 58562eea9..7551da3ad 100644 --- a/EndlessClient/Dialogs/Actions/InGameDialogActions.cs +++ b/EndlessClient/Dialogs/Actions/InGameDialogActions.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Dialogs.Factories; using EndlessClient.HUD; @@ -8,9 +11,6 @@ using EOLib.Domain.Interact.Skill; using EOLib.Localization; using Optional; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs.Actions diff --git a/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs b/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs index d6ebec130..c65b7d52c 100644 --- a/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs +++ b/EndlessClient/Dialogs/Actions/NpcInteractionActions.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Dialogs.Factories; using EOLib.Domain.Interact; @@ -9,7 +10,6 @@ using EOLib.IO.Repositories; using EOLib.Localization; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; using XNAControls; diff --git a/EndlessClient/Dialogs/ActiveDialogRepository.cs b/EndlessClient/Dialogs/ActiveDialogRepository.cs index b8932eee4..b41c41ffd 100644 --- a/EndlessClient/Dialogs/ActiveDialogRepository.cs +++ b/EndlessClient/Dialogs/ActiveDialogRepository.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; -using Optional; -using System; +using System; using System.Collections.Generic; using System.Linq; +using AutomaticTypeMapper; +using Optional; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/BankAccountDialog.cs b/EndlessClient/Dialogs/BankAccountDialog.cs index f6d9f22bc..740a86eae 100644 --- a/EndlessClient/Dialogs/BankAccountDialog.cs +++ b/EndlessClient/Dialogs/BankAccountDialog.cs @@ -1,4 +1,5 @@ -using EndlessClient.ControlSets; +using System; +using EndlessClient.ControlSets; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.HUD; @@ -13,7 +14,6 @@ using Microsoft.Xna.Framework; using Optional; using Optional.Collections; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/BarberDialog.cs b/EndlessClient/Dialogs/BarberDialog.cs index f730de83f..f6a2d7371 100644 --- a/EndlessClient/Dialogs/BarberDialog.cs +++ b/EndlessClient/Dialogs/BarberDialog.cs @@ -1,3 +1,4 @@ +using System; using EndlessClient.Audio; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; @@ -10,7 +11,6 @@ using EOLib.Localization; using Microsoft.Xna.Framework; using Optional.Collections; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/BardDialog.cs b/EndlessClient/Dialogs/BardDialog.cs index b2ba3498d..8dad95c06 100644 --- a/EndlessClient/Dialogs/BardDialog.cs +++ b/EndlessClient/Dialogs/BardDialog.cs @@ -1,4 +1,5 @@ -using EndlessClient.Controllers; +using System; +using EndlessClient.Controllers; using EndlessClient.Dialogs.Services; using EOLib.Graphics; using Microsoft.Xna.Framework; @@ -6,7 +7,6 @@ using MonoGame.Extended.Input; using MonoGame.Extended.Input.InputListeners; using Optional; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/BaseEODialog.cs b/EndlessClient/Dialogs/BaseEODialog.cs index 52d39c3d8..5952768eb 100644 --- a/EndlessClient/Dialogs/BaseEODialog.cs +++ b/EndlessClient/Dialogs/BaseEODialog.cs @@ -1,7 +1,7 @@ -using EndlessClient.GameExecution; +using System; +using EndlessClient.GameExecution; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/BoardDialog.cs b/EndlessClient/Dialogs/BoardDialog.cs index e648db10b..fa0808bf8 100644 --- a/EndlessClient/Dialogs/BoardDialog.cs +++ b/EndlessClient/Dialogs/BoardDialog.cs @@ -1,4 +1,7 @@ -using EndlessClient.Content; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Content; using EndlessClient.ControlSets; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; @@ -14,9 +17,6 @@ using MonoGame.Extended.Input.InputListeners; using Optional; using Optional.Collections; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/BookDialog.cs b/EndlessClient/Dialogs/BookDialog.cs index fef42d67f..b10252646 100644 --- a/EndlessClient/Dialogs/BookDialog.cs +++ b/EndlessClient/Dialogs/BookDialog.cs @@ -1,12 +1,12 @@ -using EndlessClient.Dialogs.Services; +using System; +using System.Collections.Generic; +using EndlessClient.Dialogs.Services; using EndlessClient.UIControls; using EOLib; using EOLib.Domain.Character; using EOLib.Graphics; using EOLib.IO.Repositories; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; using XNAControls; using static EndlessClient.Dialogs.QuestStatusListDialogItem; diff --git a/EndlessClient/Dialogs/ChangePasswordDialog.cs b/EndlessClient/Dialogs/ChangePasswordDialog.cs index 37089edbe..b88c7a04b 100644 --- a/EndlessClient/Dialogs/ChangePasswordDialog.cs +++ b/EndlessClient/Dialogs/ChangePasswordDialog.cs @@ -1,4 +1,6 @@ -using EndlessClient.Content; +using System; +using System.Linq; +using EndlessClient.Content; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.GameExecution; @@ -10,8 +12,6 @@ using EOLib.Localization; using Microsoft.Xna.Framework; using Optional; -using System; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/ChestDialog.cs b/EndlessClient/Dialogs/ChestDialog.cs index 7cd10cab2..0aff00ded 100644 --- a/EndlessClient/Dialogs/ChestDialog.cs +++ b/EndlessClient/Dialogs/ChestDialog.cs @@ -1,4 +1,6 @@ -using EndlessClient.ControlSets; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.ControlSets; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.HUD; @@ -14,8 +16,6 @@ using EOLib.IO.Repositories; using EOLib.Localization; using Microsoft.Xna.Framework; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Dialogs { diff --git a/EndlessClient/Dialogs/CreateCharacterDialog.cs b/EndlessClient/Dialogs/CreateCharacterDialog.cs index 3a46497ff..912852749 100644 --- a/EndlessClient/Dialogs/CreateCharacterDialog.cs +++ b/EndlessClient/Dialogs/CreateCharacterDialog.cs @@ -1,4 +1,5 @@ -using EndlessClient.Content; +using System; +using EndlessClient.Content; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.GameExecution; @@ -11,7 +12,6 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Optional; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/EOMessageBox.cs b/EndlessClient/Dialogs/EOMessageBox.cs index a5889e812..aadc7ad52 100644 --- a/EndlessClient/Dialogs/EOMessageBox.cs +++ b/EndlessClient/Dialogs/EOMessageBox.cs @@ -1,9 +1,9 @@ -using EndlessClient.Dialogs.Services; +using System; +using EndlessClient.Dialogs.Services; using EndlessClient.GameExecution; using EOLib; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs b/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs index fe2f63539..f2c74d39f 100644 --- a/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs +++ b/EndlessClient/Dialogs/Extensions/EquipLocationExtensions.cs @@ -1,6 +1,6 @@ -using EOLib.IO; +using System; +using EOLib.IO; using Microsoft.Xna.Framework; -using System; namespace EndlessClient.Dialogs.Extensions { diff --git a/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs b/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs index ec9055cb3..7c4dabe1e 100644 --- a/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/BarberDialogFactory.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Content; @@ -11,7 +12,6 @@ using EOLib.Graphics; using EOLib.IO.Repositories; using EOLib.Localization; -using System.Collections.Generic; namespace EndlessClient.Dialogs.Factories { diff --git a/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs b/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs index d46c7c18a..09bd62474 100644 --- a/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/FriendIgnoreListDialogFactory.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.ControlSets; using EndlessClient.Dialogs.Services; using EndlessClient.GameExecution; @@ -10,8 +12,6 @@ using EOLib.Domain.Online; using EOLib.Graphics; using EOLib.Localization; -using System; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs.Factories diff --git a/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs b/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs index 5560d1b46..80d4d1d61 100644 --- a/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs +++ b/EndlessClient/Dialogs/Factories/HelpDialogFactory.cs @@ -1,12 +1,12 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Content; using EndlessClient.Dialogs.Actions; using EndlessClient.Dialogs.Services; using EOLib; using EOLib.Graphics; using EOLib.Localization; -using System; -using System.Collections.Generic; namespace EndlessClient.Dialogs.Factories { diff --git a/EndlessClient/Dialogs/FriendIgnoreListDialog.cs b/EndlessClient/Dialogs/FriendIgnoreListDialog.cs index ba481f3c8..7a6d0459e 100644 --- a/EndlessClient/Dialogs/FriendIgnoreListDialog.cs +++ b/EndlessClient/Dialogs/FriendIgnoreListDialog.cs @@ -1,9 +1,9 @@ -using EndlessClient.Dialogs.Services; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Dialogs.Services; using EOLib.Domain.Online; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Dialogs { diff --git a/EndlessClient/Dialogs/GameLoadingDialog.cs b/EndlessClient/Dialogs/GameLoadingDialog.cs index 67fde1c75..678893cfd 100644 --- a/EndlessClient/Dialogs/GameLoadingDialog.cs +++ b/EndlessClient/Dialogs/GameLoadingDialog.cs @@ -1,11 +1,11 @@ -using EndlessClient.GameExecution; +using System; +using EndlessClient.GameExecution; using EndlessClient.Rendering; using EOLib; using EOLib.Graphics; using EOLib.Localization; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/InnkeeperDialog.cs b/EndlessClient/Dialogs/InnkeeperDialog.cs index 22bd4d0cb..f98503f6e 100644 --- a/EndlessClient/Dialogs/InnkeeperDialog.cs +++ b/EndlessClient/Dialogs/InnkeeperDialog.cs @@ -1,4 +1,6 @@ -using EndlessClient.Content; +using System; +using System.Collections.Generic; +using EndlessClient.Content; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EOLib; @@ -9,8 +11,6 @@ using EOLib.Localization; using Microsoft.Xna.Framework; using Optional.Collections; -using System; -using System.Collections.Generic; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/ItemTransferDialog.cs b/EndlessClient/Dialogs/ItemTransferDialog.cs index 1ba819737..a8c79f3c1 100644 --- a/EndlessClient/Dialogs/ItemTransferDialog.cs +++ b/EndlessClient/Dialogs/ItemTransferDialog.cs @@ -1,4 +1,5 @@ -using EndlessClient.Content; +using System; +using EndlessClient.Content; using EndlessClient.Dialogs.Services; using EndlessClient.HUD.Chat; using EOLib; @@ -7,7 +8,6 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.Input.InputListeners; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/JukeboxDialog.cs b/EndlessClient/Dialogs/JukeboxDialog.cs index f6df54d5a..4541d237c 100644 --- a/EndlessClient/Dialogs/JukeboxDialog.cs +++ b/EndlessClient/Dialogs/JukeboxDialog.cs @@ -1,4 +1,6 @@ -using EndlessClient.Audio; +using System; +using System.Collections.Generic; +using EndlessClient.Audio; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EOLib.Domain.Character; @@ -9,8 +11,6 @@ using MonoGame.Extended.Input.InputListeners; using Optional; using Optional.Collections; -using System; -using System.Collections.Generic; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/LawDialog.cs b/EndlessClient/Dialogs/LawDialog.cs index 1a8a8f950..070e47f29 100644 --- a/EndlessClient/Dialogs/LawDialog.cs +++ b/EndlessClient/Dialogs/LawDialog.cs @@ -1,4 +1,7 @@ -using EndlessClient.Content; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Content; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EOLib; @@ -9,9 +12,6 @@ using EOLib.IO.Repositories; using EOLib.Localization; using Optional.Collections; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/ListDialogItem.cs b/EndlessClient/Dialogs/ListDialogItem.cs index ffa4f2e5d..37684cc84 100644 --- a/EndlessClient/Dialogs/ListDialogItem.cs +++ b/EndlessClient/Dialogs/ListDialogItem.cs @@ -1,10 +1,10 @@ -using EOLib; +using System; +using EOLib; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.Input; using MonoGame.Extended.Input.InputListeners; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/LockerDialog.cs b/EndlessClient/Dialogs/LockerDialog.cs index accc1eb83..eaeebbd4f 100644 --- a/EndlessClient/Dialogs/LockerDialog.cs +++ b/EndlessClient/Dialogs/LockerDialog.cs @@ -1,4 +1,6 @@ -using EndlessClient.ControlSets; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.ControlSets; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.HUD; @@ -13,8 +15,6 @@ using EOLib.IO.Repositories; using EOLib.Localization; using Microsoft.Xna.Framework; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Dialogs { diff --git a/EndlessClient/Dialogs/PaperdollDialog.cs b/EndlessClient/Dialogs/PaperdollDialog.cs index 5d102b03d..c2811a636 100644 --- a/EndlessClient/Dialogs/PaperdollDialog.cs +++ b/EndlessClient/Dialogs/PaperdollDialog.cs @@ -1,4 +1,7 @@ -using EndlessClient.Audio; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Audio; using EndlessClient.Controllers; using EndlessClient.ControlSets; using EndlessClient.Dialogs.Extensions; @@ -15,9 +18,6 @@ using EOLib.Localization; using Microsoft.Xna.Framework; using Optional; -using System; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Dialogs { diff --git a/EndlessClient/Dialogs/PaperdollDialogItem.cs b/EndlessClient/Dialogs/PaperdollDialogItem.cs index 5209495bf..14e30679b 100644 --- a/EndlessClient/Dialogs/PaperdollDialogItem.cs +++ b/EndlessClient/Dialogs/PaperdollDialogItem.cs @@ -1,4 +1,5 @@ -using EndlessClient.Audio; +using System; +using EndlessClient.Audio; using EndlessClient.Dialogs.Extensions; using EndlessClient.HUD.Panels; using EOLib.Graphics; @@ -8,7 +9,6 @@ using MonoGame.Extended.Input; using MonoGame.Extended.Input.InputListeners; using Optional; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/ProgressDialog.cs b/EndlessClient/Dialogs/ProgressDialog.cs index 1bcf03e12..93d73d9ce 100644 --- a/EndlessClient/Dialogs/ProgressDialog.cs +++ b/EndlessClient/Dialogs/ProgressDialog.cs @@ -1,12 +1,12 @@ -using EndlessClient.Dialogs.Services; +using System; +using System.Threading; +using EndlessClient.Dialogs.Services; using EndlessClient.GameExecution; using EOLib; using EOLib.Config; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.Threading; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/QuestDialog.cs b/EndlessClient/Dialogs/QuestDialog.cs index de1328595..578b223ea 100644 --- a/EndlessClient/Dialogs/QuestDialog.cs +++ b/EndlessClient/Dialogs/QuestDialog.cs @@ -1,4 +1,7 @@ -using EndlessClient.Content; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Content; using EndlessClient.Dialogs.Services; using EOLib; using EOLib.Domain.Interact.Quest; @@ -7,9 +10,6 @@ using Microsoft.Xna.Framework; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Optional; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/QuestStatusDialog.cs b/EndlessClient/Dialogs/QuestStatusDialog.cs index 2d3b4e65f..0a535f840 100644 --- a/EndlessClient/Dialogs/QuestStatusDialog.cs +++ b/EndlessClient/Dialogs/QuestStatusDialog.cs @@ -1,11 +1,11 @@ -using EndlessClient.Dialogs.Services; +using System.Collections.Generic; +using EndlessClient.Dialogs.Services; using EOLib.Domain.Character; using EOLib.Domain.Interact.Quest; using EOLib.Graphics; using EOLib.Localization; using Microsoft.Xna.Framework; using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Collections.Generic; namespace EndlessClient.Dialogs { diff --git a/EndlessClient/Dialogs/ScrollingListDialog.cs b/EndlessClient/Dialogs/ScrollingListDialog.cs index d4eb5596c..8092aaf32 100644 --- a/EndlessClient/Dialogs/ScrollingListDialog.cs +++ b/EndlessClient/Dialogs/ScrollingListDialog.cs @@ -1,4 +1,7 @@ -using EndlessClient.Dialogs.Factories; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.UIControls; using EOLib; @@ -8,9 +11,6 @@ using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.BitmapFonts; using MonoGame.Extended.Input.InputListeners; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/ScrollingMessageDialog.cs b/EndlessClient/Dialogs/ScrollingMessageDialog.cs index 26d4762e5..47e490a00 100644 --- a/EndlessClient/Dialogs/ScrollingMessageDialog.cs +++ b/EndlessClient/Dialogs/ScrollingMessageDialog.cs @@ -1,4 +1,6 @@ -using EndlessClient.Content; +using System; +using System.Collections.Generic; +using EndlessClient.Content; using EndlessClient.Dialogs.Services; using EndlessClient.GameExecution; using EndlessClient.UIControls; @@ -6,8 +8,6 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using MonoGame.Extended.BitmapFonts; -using System; -using System.Collections.Generic; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/SessionExpDialog.cs b/EndlessClient/Dialogs/SessionExpDialog.cs index f24dfda7b..7f806db41 100644 --- a/EndlessClient/Dialogs/SessionExpDialog.cs +++ b/EndlessClient/Dialogs/SessionExpDialog.cs @@ -1,11 +1,11 @@ -using EndlessClient.Dialogs.Services; +using System; +using EndlessClient.Dialogs.Services; using EOLib; using EOLib.Domain.Character; using EOLib.Graphics; using EOLib.Localization; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/ShopDialog.cs b/EndlessClient/Dialogs/ShopDialog.cs index 29e5c7efc..a18a4deef 100644 --- a/EndlessClient/Dialogs/ShopDialog.cs +++ b/EndlessClient/Dialogs/ShopDialog.cs @@ -1,4 +1,7 @@ -using EndlessClient.Dialogs.Factories; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.HUD.Inventory; using EOLib.Domain.Character; @@ -9,9 +12,6 @@ using Microsoft.Xna.Framework; using Optional; using Optional.Collections; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/SkillmasterDialog.cs b/EndlessClient/Dialogs/SkillmasterDialog.cs index 3f58ec8f2..d4229b964 100644 --- a/EndlessClient/Dialogs/SkillmasterDialog.cs +++ b/EndlessClient/Dialogs/SkillmasterDialog.cs @@ -1,4 +1,8 @@ -using EndlessClient.Content; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using EndlessClient.Content; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.HUD; @@ -10,10 +14,6 @@ using EOLib.Localization; using Microsoft.Xna.Framework; using Optional.Collections; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/TextMultiInputDialog.cs b/EndlessClient/Dialogs/TextMultiInputDialog.cs index 73af29c43..b41fee9c2 100644 --- a/EndlessClient/Dialogs/TextMultiInputDialog.cs +++ b/EndlessClient/Dialogs/TextMultiInputDialog.cs @@ -1,13 +1,13 @@ -using EndlessClient.Content; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Content; using EndlessClient.Dialogs.Services; using EndlessClient.HUD.Chat; using EOLib; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/Dialogs/TradeDialog.cs b/EndlessClient/Dialogs/TradeDialog.cs index 3a4f56235..00084eb9b 100644 --- a/EndlessClient/Dialogs/TradeDialog.cs +++ b/EndlessClient/Dialogs/TradeDialog.cs @@ -1,4 +1,8 @@ -using EndlessClient.Audio; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using EndlessClient.Audio; using EndlessClient.Dialogs.Factories; using EndlessClient.Dialogs.Services; using EndlessClient.HUD; @@ -14,10 +18,6 @@ using EOLib.Localization; using Microsoft.Xna.Framework; using Optional.Collections; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; using XNAControls; namespace EndlessClient.Dialogs diff --git a/EndlessClient/GameExecution/EndlessGame.cs b/EndlessClient/GameExecution/EndlessGame.cs index 2cb41e3e2..58e4c6f47 100644 --- a/EndlessClient/GameExecution/EndlessGame.cs +++ b/EndlessClient/GameExecution/EndlessGame.cs @@ -1,4 +1,9 @@ -using AutomaticTypeMapper; +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Content; using EndlessClient.Controllers; @@ -18,11 +23,6 @@ using Microsoft.Xna.Framework.Input; using MonoGame.Extended.BitmapFonts; using MonoGame.Extended.Input; -using System; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; namespace EndlessClient.GameExecution { diff --git a/EndlessClient/GameExecution/GameRunnerBase.cs b/EndlessClient/GameExecution/GameRunnerBase.cs index b93e36726..1f74f8535 100644 --- a/EndlessClient/GameExecution/GameRunnerBase.cs +++ b/EndlessClient/GameExecution/GameRunnerBase.cs @@ -1,12 +1,12 @@ -using AutomaticTypeMapper; +using System; +using System.Diagnostics; +using System.IO; +using System.Net; +using AutomaticTypeMapper; using EndlessClient.Initialization; using EOLib.Config; using EOLib.Graphics; using EOLib.Localization; -using System; -using System.Diagnostics; -using System.IO; -using System.Net; #if !LINUX && !OSX using System.Windows.Forms; diff --git a/EndlessClient/GameExecution/GameStateActions.cs b/EndlessClient/GameExecution/GameStateActions.cs index 2673b7105..7536b81e8 100644 --- a/EndlessClient/GameExecution/GameStateActions.cs +++ b/EndlessClient/GameExecution/GameStateActions.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.ControlSets; using EndlessClient.HUD.Panels; @@ -9,9 +12,6 @@ using EOLib.Domain.Character; using EOLib.Domain.Login; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls.Input; namespace EndlessClient.GameExecution diff --git a/EndlessClient/GameExecution/IEndlessGame.cs b/EndlessClient/GameExecution/IEndlessGame.cs index d9066581d..06e3eb969 100644 --- a/EndlessClient/GameExecution/IEndlessGame.cs +++ b/EndlessClient/GameExecution/IEndlessGame.cs @@ -1,6 +1,6 @@ -using Microsoft.Xna.Framework; +using System; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; -using System; namespace EndlessClient.GameExecution { diff --git a/EndlessClient/GameExecution/ReleaseGameRunner.cs b/EndlessClient/GameExecution/ReleaseGameRunner.cs index a816bda2c..abe6e97ac 100644 --- a/EndlessClient/GameExecution/ReleaseGameRunner.cs +++ b/EndlessClient/GameExecution/ReleaseGameRunner.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; -using System; +using System; using System.Runtime.Versioning; +using AutomaticTypeMapper; #if !LINUX && !OSX using System.Windows.Forms; diff --git a/EndlessClient/HUD/AStarPathFinder.cs b/EndlessClient/HUD/AStarPathFinder.cs index c3902916c..001ec85bc 100644 --- a/EndlessClient/HUD/AStarPathFinder.cs +++ b/EndlessClient/HUD/AStarPathFinder.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; -using EOLib.Domain.Character; -using EOLib.Domain.Map; -using System; +using System; using System.Collections.Generic; using System.Linq; +using AutomaticTypeMapper; +using EOLib.Domain.Character; +using EOLib.Domain.Map; namespace EndlessClient.HUD { diff --git a/EndlessClient/HUD/Chat/ChatBubbleActions.cs b/EndlessClient/HUD/Chat/ChatBubbleActions.cs index 2bfa991a7..633828104 100644 --- a/EndlessClient/HUD/Chat/ChatBubbleActions.cs +++ b/EndlessClient/HUD/Chat/ChatBubbleActions.cs @@ -1,3 +1,4 @@ +using System.Linq; using AutomaticTypeMapper; using EndlessClient.Rendering.Character; using EndlessClient.Rendering.Chat; @@ -5,7 +6,6 @@ using EOLib.Domain.Chat; using EOLib.Domain.Party; using Optional; -using System.Linq; namespace EndlessClient.HUD.Chat { diff --git a/EndlessClient/HUD/Chat/ChatNotificationActions.cs b/EndlessClient/HUD/Chat/ChatNotificationActions.cs index ab8d4d06b..525e0cfc2 100644 --- a/EndlessClient/HUD/Chat/ChatNotificationActions.cs +++ b/EndlessClient/HUD/Chat/ChatNotificationActions.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Globalization; +using System.Windows; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.ControlSets; using EndlessClient.HUD.Controls; @@ -9,9 +12,6 @@ using EOLib.Domain.Notifiers; using EOLib.Localization; using Optional; -using System; -using System.Globalization; -using System.Windows; namespace EndlessClient.HUD.Chat { diff --git a/EndlessClient/HUD/Chat/ChatPanelTab.cs b/EndlessClient/HUD/Chat/ChatPanelTab.cs index 382c57040..88bbda614 100644 --- a/EndlessClient/HUD/Chat/ChatPanelTab.cs +++ b/EndlessClient/HUD/Chat/ChatPanelTab.cs @@ -1,4 +1,7 @@ -using EndlessClient.ControlSets; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.ControlSets; using EndlessClient.HUD.Controls; using EndlessClient.HUD.Panels; using EndlessClient.Rendering.Chat; @@ -11,9 +14,6 @@ using MonoGame.Extended.BitmapFonts; using MonoGame.Extended.Input; using MonoGame.Extended.Input.InputListeners; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.HUD.Chat diff --git a/EndlessClient/HUD/Chat/PrivateMessageActions.cs b/EndlessClient/HUD/Chat/PrivateMessageActions.cs index 6b57fe969..47c8e20bc 100644 --- a/EndlessClient/HUD/Chat/PrivateMessageActions.cs +++ b/EndlessClient/HUD/Chat/PrivateMessageActions.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EndlessClient.ControlSets; using EndlessClient.HUD.Controls; using EndlessClient.HUD.Panels; using EOLib.Domain.Character; using EOLib.Domain.Chat; using EOLib.Localization; -using System; namespace EndlessClient.HUD.Chat { diff --git a/EndlessClient/HUD/Controls/DraggablePanelItem.cs b/EndlessClient/HUD/Controls/DraggablePanelItem.cs index 7632e5fce..d9c9427e5 100644 --- a/EndlessClient/HUD/Controls/DraggablePanelItem.cs +++ b/EndlessClient/HUD/Controls/DraggablePanelItem.cs @@ -1,7 +1,7 @@ -using Microsoft.Xna.Framework; +using System; +using Microsoft.Xna.Framework; using MonoGame.Extended.Input; using MonoGame.Extended.Input.InputListeners; -using System; using XNAControls; namespace EndlessClient.HUD.Controls diff --git a/EndlessClient/HUD/Controls/HudControlsFactory.cs b/EndlessClient/HUD/Controls/HudControlsFactory.cs index 793f450de..556b96917 100644 --- a/EndlessClient/HUD/Controls/HudControlsFactory.cs +++ b/EndlessClient/HUD/Controls/HudControlsFactory.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Content; using EndlessClient.Controllers; @@ -26,9 +29,6 @@ using EOLib.Graphics; using EOLib.Localization; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.HUD.Controls diff --git a/EndlessClient/HUD/Controls/IHudControlsFactory.cs b/EndlessClient/HUD/Controls/IHudControlsFactory.cs index dc788bcdb..c35fb7fd7 100644 --- a/EndlessClient/HUD/Controls/IHudControlsFactory.cs +++ b/EndlessClient/HUD/Controls/IHudControlsFactory.cs @@ -1,6 +1,6 @@ -using EndlessClient.Controllers; +using System.Collections.Generic; +using EndlessClient.Controllers; using Microsoft.Xna.Framework; -using System.Collections.Generic; namespace EndlessClient.HUD.Controls { diff --git a/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs b/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs index 02baaf161..ba50ec3ca 100644 --- a/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs +++ b/EndlessClient/HUD/Controls/PeriodicStatUpdaterComponent.cs @@ -1,9 +1,9 @@ -using EndlessClient.GameExecution; +using System; +using System.Diagnostics; +using EndlessClient.GameExecution; using EOLib.Domain.Character; using Microsoft.Xna.Framework; using Optional; -using System; -using System.Diagnostics; namespace EndlessClient.HUD.Controls { diff --git a/EndlessClient/HUD/HudStateActions.cs b/EndlessClient/HUD/HudStateActions.cs index 1b2d78473..cb77610f0 100644 --- a/EndlessClient/HUD/HudStateActions.cs +++ b/EndlessClient/HUD/HudStateActions.cs @@ -1,12 +1,12 @@ -using AutomaticTypeMapper; +using System; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.ControlSets; using EndlessClient.HUD.Panels; using EndlessClient.Rendering; using EOLib.Domain.Map; using EOLib.IO.Repositories; using EOLib.Localization; -using System; -using System.Linq; namespace EndlessClient.HUD { diff --git a/EndlessClient/HUD/IStatusLabelTextRepository.cs b/EndlessClient/HUD/IStatusLabelTextRepository.cs index 59eb2d9ca..12f17f9c3 100644 --- a/EndlessClient/HUD/IStatusLabelTextRepository.cs +++ b/EndlessClient/HUD/IStatusLabelTextRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System; +using System; +using AutomaticTypeMapper; namespace EndlessClient.HUD { diff --git a/EndlessClient/HUD/Inventory/InventoryPanelItem.cs b/EndlessClient/HUD/Inventory/InventoryPanelItem.cs index 10400ca73..50e38a9e8 100644 --- a/EndlessClient/HUD/Inventory/InventoryPanelItem.cs +++ b/EndlessClient/HUD/Inventory/InventoryPanelItem.cs @@ -1,4 +1,5 @@ -using EndlessClient.Audio; +using System; +using EndlessClient.Audio; using EndlessClient.Dialogs; using EndlessClient.HUD.Controls; using EndlessClient.HUD.Panels; @@ -12,7 +13,6 @@ using MonoGame.Extended.Input; using MonoGame.Extended.Input.InputListeners; using Optional; -using System; using XNAControls; namespace EndlessClient.HUD.Inventory diff --git a/EndlessClient/HUD/Inventory/InventoryService.cs b/EndlessClient/HUD/Inventory/InventoryService.cs index c1b43937a..5ca5fdb59 100644 --- a/EndlessClient/HUD/Inventory/InventoryService.cs +++ b/EndlessClient/HUD/Inventory/InventoryService.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.HUD.Panels; using EOLib.IO; using EOLib.IO.Extensions; using Optional; -using System.Collections.Generic; namespace EndlessClient.HUD.Inventory { diff --git a/EndlessClient/HUD/Inventory/InventorySlotRepository.cs b/EndlessClient/HUD/Inventory/InventorySlotRepository.cs index aa4be9371..88a8d798b 100644 --- a/EndlessClient/HUD/Inventory/InventorySlotRepository.cs +++ b/EndlessClient/HUD/Inventory/InventorySlotRepository.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.HUD.Panels; using EOLib; using EOLib.IO.Map; -using System.Collections.Generic; namespace EndlessClient.HUD.Inventory { diff --git a/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs b/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs index 4cbeac495..d30e8a184 100644 --- a/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs +++ b/EndlessClient/HUD/Inventory/InventorySpaceValidator.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.IO; @@ -6,8 +8,6 @@ using EOLib.IO.Repositories; using Optional; using Optional.Collections; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.HUD.Inventory { diff --git a/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs b/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs index 0178d79ef..feddf2936 100644 --- a/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs +++ b/EndlessClient/HUD/Panels/ActiveSpellsPanel.cs @@ -1,4 +1,10 @@ -using EndlessClient.Audio; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using EndlessClient.Audio; using EndlessClient.Controllers; using EndlessClient.ControlSets; using EndlessClient.Dialogs; @@ -22,14 +28,7 @@ using MonoGame.Extended.Input; using Optional; using Optional.Collections; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; using XNAControls; - using static EndlessClient.HUD.Spells.SpellPanelItem; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Panels/ChatPanel.cs b/EndlessClient/HUD/Panels/ChatPanel.cs index 856db4f09..63e39c657 100644 --- a/EndlessClient/HUD/Panels/ChatPanel.cs +++ b/EndlessClient/HUD/Panels/ChatPanel.cs @@ -1,4 +1,7 @@ -using EndlessClient.ControlSets; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.ControlSets; using EndlessClient.HUD.Chat; using EndlessClient.Rendering; using EndlessClient.Rendering.Chat; @@ -8,9 +11,6 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using MonoGame.Extended.BitmapFonts; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Panels/DraggableHudPanel.cs b/EndlessClient/HUD/Panels/DraggableHudPanel.cs index 3a3316c3e..c689fb513 100644 --- a/EndlessClient/HUD/Panels/DraggableHudPanel.cs +++ b/EndlessClient/HUD/Panels/DraggableHudPanel.cs @@ -1,7 +1,7 @@ -using EndlessClient.Rendering; +using System; +using EndlessClient.Rendering; using MonoGame.Extended.Input.InputListeners; using Optional; -using System; using XNAControls; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Panels/IHudPanel.cs b/EndlessClient/HUD/Panels/IHudPanel.cs index e380c4618..afd13c118 100644 --- a/EndlessClient/HUD/Panels/IHudPanel.cs +++ b/EndlessClient/HUD/Panels/IHudPanel.cs @@ -1,5 +1,5 @@ -using Microsoft.Xna.Framework; -using System; +using System; +using Microsoft.Xna.Framework; using XNAControls; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Panels/InventoryPanel.cs b/EndlessClient/HUD/Panels/InventoryPanel.cs index aa3abf31d..f3c9d9e8c 100644 --- a/EndlessClient/HUD/Panels/InventoryPanel.cs +++ b/EndlessClient/HUD/Panels/InventoryPanel.cs @@ -1,4 +1,10 @@ -using EndlessClient.Audio; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using EndlessClient.Audio; using EndlessClient.Controllers; using EndlessClient.ControlSets; using EndlessClient.Dialogs; @@ -24,12 +30,6 @@ using MonoGame.Extended.Input; using Optional; using Optional.Collections; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; using XNAControls; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Panels/NewsPanel.cs b/EndlessClient/HUD/Panels/NewsPanel.cs index ad983b417..474c7f163 100644 --- a/EndlessClient/HUD/Panels/NewsPanel.cs +++ b/EndlessClient/HUD/Panels/NewsPanel.cs @@ -1,4 +1,6 @@ -using EndlessClient.Rendering; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Rendering; using EndlessClient.Rendering.Chat; using EndlessClient.UIControls; using EOLib.Domain.Login; @@ -6,8 +8,6 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.BitmapFonts; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Panels/OnlineListPanel.cs b/EndlessClient/HUD/Panels/OnlineListPanel.cs index 6f892ebb2..d49f9b6d1 100644 --- a/EndlessClient/HUD/Panels/OnlineListPanel.cs +++ b/EndlessClient/HUD/Panels/OnlineListPanel.cs @@ -1,4 +1,7 @@ -using EndlessClient.Audio; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Audio; using EndlessClient.ControlSets; using EndlessClient.HUD.Controls; using EndlessClient.Rendering; @@ -16,9 +19,6 @@ using MonoGame.Extended.Input; using MonoGame.Extended.Input.InputListeners; using Optional.Unsafe; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Panels/PartyPanel.cs b/EndlessClient/HUD/Panels/PartyPanel.cs index 40bc1a4ea..06d0d9de7 100644 --- a/EndlessClient/HUD/Panels/PartyPanel.cs +++ b/EndlessClient/HUD/Panels/PartyPanel.cs @@ -1,4 +1,6 @@ -using EndlessClient.Content; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Content; using EndlessClient.HUD.Party; using EndlessClient.Rendering; using EndlessClient.UIControls; @@ -8,8 +10,6 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using Optional.Collections; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Panels/SettingsPanel.cs b/EndlessClient/HUD/Panels/SettingsPanel.cs index c459144dc..0dc86b5d7 100644 --- a/EndlessClient/HUD/Panels/SettingsPanel.cs +++ b/EndlessClient/HUD/Panels/SettingsPanel.cs @@ -1,4 +1,7 @@ -using EndlessClient.Audio; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Audio; using EndlessClient.Dialogs; using EndlessClient.Dialogs.Factories; using EndlessClient.Rendering; @@ -8,9 +11,6 @@ using EOLib.Graphics; using EOLib.Localization; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Panels/StatsPanel.cs b/EndlessClient/HUD/Panels/StatsPanel.cs index 9106f5563..828038b6d 100644 --- a/EndlessClient/HUD/Panels/StatsPanel.cs +++ b/EndlessClient/HUD/Panels/StatsPanel.cs @@ -1,4 +1,6 @@ -using EndlessClient.Controllers; +using System; +using System.Linq; +using EndlessClient.Controllers; using EndlessClient.Dialogs; using EndlessClient.Dialogs.Factories; using EndlessClient.Rendering; @@ -7,8 +9,6 @@ using EOLib.Domain.Extensions; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System; -using System.Linq; using XNAControls; namespace EndlessClient.HUD.Panels diff --git a/EndlessClient/HUD/Party/PartyPanelMember.cs b/EndlessClient/HUD/Party/PartyPanelMember.cs index f37254f22..c6d5ac8dc 100644 --- a/EndlessClient/HUD/Party/PartyPanelMember.cs +++ b/EndlessClient/HUD/Party/PartyPanelMember.cs @@ -1,4 +1,5 @@ -using EndlessClient.Content; +using System; +using EndlessClient.Content; using EOLib; using EOLib.Domain.Chat; using EOLib.Domain.Party; @@ -6,7 +7,6 @@ using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; using XNAControls; namespace EndlessClient.HUD.Party diff --git a/EndlessClient/HUD/Spells/SpellPanelItem.cs b/EndlessClient/HUD/Spells/SpellPanelItem.cs index ad936f914..88ddf3dd4 100644 --- a/EndlessClient/HUD/Spells/SpellPanelItem.cs +++ b/EndlessClient/HUD/Spells/SpellPanelItem.cs @@ -1,4 +1,5 @@ -using EndlessClient.Audio; +using System; +using EndlessClient.Audio; using EndlessClient.HUD.Controls; using EndlessClient.HUD.Panels; using EOLib.Domain.Character; @@ -8,7 +9,6 @@ using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using MonoGame.Extended.Input.InputListeners; -using System; using XNAControls; namespace EndlessClient.HUD.Spells diff --git a/EndlessClient/HUD/Spells/SpellSelectActions.cs b/EndlessClient/HUD/Spells/SpellSelectActions.cs index 58a3035bf..0e70a4dd6 100644 --- a/EndlessClient/HUD/Spells/SpellSelectActions.cs +++ b/EndlessClient/HUD/Spells/SpellSelectActions.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Party; using EOLib.IO.Repositories; using EOLib.Localization; using Optional; -using System.Linq; namespace EndlessClient.HUD.Spells { diff --git a/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs b/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs index e6bae1c2e..46aa93c3d 100644 --- a/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs +++ b/EndlessClient/HUD/Spells/SpellSlotDataRepository.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.HUD.Panels; using EOLib.Domain.Character; using Optional; -using System.Collections.Generic; namespace EndlessClient.HUD.Spells { diff --git a/EndlessClient/HUD/StatusBars/HPStatusBar.cs b/EndlessClient/HUD/StatusBars/HPStatusBar.cs index 03150e25c..fb573b92a 100644 --- a/EndlessClient/HUD/StatusBars/HPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/HPStatusBar.cs @@ -1,8 +1,8 @@ -using EndlessClient.Rendering; +using System; +using EndlessClient.Rendering; using EOLib.Domain.Character; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System; namespace EndlessClient.HUD.StatusBars { diff --git a/EndlessClient/HUD/StatusBars/SPStatusBar.cs b/EndlessClient/HUD/StatusBars/SPStatusBar.cs index cf2e2916a..aeaa364f7 100644 --- a/EndlessClient/HUD/StatusBars/SPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/SPStatusBar.cs @@ -1,8 +1,8 @@ -using EndlessClient.Rendering; +using System; +using EndlessClient.Rendering; using EOLib.Domain.Character; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System; namespace EndlessClient.HUD.StatusBars { diff --git a/EndlessClient/HUD/StatusBars/StatusBarBase.cs b/EndlessClient/HUD/StatusBars/StatusBarBase.cs index aec449222..7035fe01d 100644 --- a/EndlessClient/HUD/StatusBars/StatusBarBase.cs +++ b/EndlessClient/HUD/StatusBars/StatusBarBase.cs @@ -1,4 +1,5 @@ -using EndlessClient.Rendering; +using System; +using EndlessClient.Rendering; using EOLib; using EOLib.Domain.Character; using EOLib.Graphics; @@ -6,7 +7,6 @@ using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.Input.InputListeners; using Optional; -using System; using XNAControls; namespace EndlessClient.HUD.StatusBars diff --git a/EndlessClient/HUD/StatusBars/TNLStatusBar.cs b/EndlessClient/HUD/StatusBars/TNLStatusBar.cs index 9919e57a8..26e9c0ba7 100644 --- a/EndlessClient/HUD/StatusBars/TNLStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/TNLStatusBar.cs @@ -1,10 +1,10 @@ -using EndlessClient.Input; +using System; +using System.Collections.Generic; +using EndlessClient.Input; using EndlessClient.Rendering; using EOLib.Domain.Character; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; namespace EndlessClient.HUD.StatusBars { diff --git a/EndlessClient/HUD/StatusBars/TPStatusBar.cs b/EndlessClient/HUD/StatusBars/TPStatusBar.cs index 0d9c2705b..2fe98f293 100644 --- a/EndlessClient/HUD/StatusBars/TPStatusBar.cs +++ b/EndlessClient/HUD/StatusBars/TPStatusBar.cs @@ -1,9 +1,9 @@ -using EndlessClient.Input; +using System; +using EndlessClient.Input; using EndlessClient.Rendering; using EOLib.Domain.Character; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System; namespace EndlessClient.HUD.StatusBars { diff --git a/EndlessClient/HUD/StatusLabelSetter.cs b/EndlessClient/HUD/StatusLabelSetter.cs index 547124824..46501d04f 100644 --- a/EndlessClient/HUD/StatusLabelSetter.cs +++ b/EndlessClient/HUD/StatusLabelSetter.cs @@ -1,7 +1,7 @@ +using System; using AutomaticTypeMapper; using EOLib.Domain.Chat; using EOLib.Localization; -using System; namespace EndlessClient.HUD { diff --git a/EndlessClient/HUD/UserInterfaceActions.cs b/EndlessClient/HUD/UserInterfaceActions.cs index 46a0c2a3d..7eb59f115 100644 --- a/EndlessClient/HUD/UserInterfaceActions.cs +++ b/EndlessClient/HUD/UserInterfaceActions.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Dialogs.Actions; using EOLib.Domain.Character; using EOLib.Domain.Map; @@ -6,9 +9,6 @@ using EOLib.IO.Repositories; using EOLib.Localization; using Moffat.EndlessOnline.SDK.Protocol.Net; -using System; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.HUD { diff --git a/EndlessClient/Initialization/EndlessClientInitializer.cs b/EndlessClient/Initialization/EndlessClientInitializer.cs index f4d90833d..feda3c023 100644 --- a/EndlessClient/Initialization/EndlessClientInitializer.cs +++ b/EndlessClient/Initialization/EndlessClientInitializer.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Content; using EndlessClient.Controllers; using EndlessClient.ControlSets; @@ -8,7 +9,6 @@ using EndlessClient.UIControls; using Microsoft.Xna.Framework; using MonoGame.Extended.Input.InputListeners; -using System.Collections.Generic; using XNAControls; using XNAControls.Input; diff --git a/EndlessClient/Initialization/GraphicsInitializer.cs b/EndlessClient/Initialization/GraphicsInitializer.cs index d39032ce5..5d297de3c 100644 --- a/EndlessClient/Initialization/GraphicsInitializer.cs +++ b/EndlessClient/Initialization/GraphicsInitializer.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; +using System.IO; +using AutomaticTypeMapper; using EOLib.Graphics; using PELoaderLib; -using System.IO; namespace EndlessClient.Initialization { diff --git a/EndlessClient/Input/IUserInputTimeRepository.cs b/EndlessClient/Input/IUserInputTimeRepository.cs index e4d074b4b..a6b950047 100644 --- a/EndlessClient/Input/IUserInputTimeRepository.cs +++ b/EndlessClient/Input/IUserInputTimeRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System; +using System; +using AutomaticTypeMapper; namespace EndlessClient.Input { diff --git a/EndlessClient/Input/InputHandlerBase.cs b/EndlessClient/Input/InputHandlerBase.cs index e93648ddd..f86cf5eef 100644 --- a/EndlessClient/Input/InputHandlerBase.cs +++ b/EndlessClient/Input/InputHandlerBase.cs @@ -1,9 +1,9 @@ -using EndlessClient.GameExecution; +using System; +using System.Linq; +using EndlessClient.GameExecution; using EOLib.Domain.Map; using Microsoft.Xna.Framework.Input; using Optional; -using System; -using System.Linq; namespace EndlessClient.Input { diff --git a/EndlessClient/Input/PanelShortcutHandler.cs b/EndlessClient/Input/PanelShortcutHandler.cs index 6287056b9..316b9f598 100644 --- a/EndlessClient/Input/PanelShortcutHandler.cs +++ b/EndlessClient/Input/PanelShortcutHandler.cs @@ -1,9 +1,9 @@ -using EndlessClient.GameExecution; +using System.Linq; +using EndlessClient.GameExecution; using EndlessClient.HUD; using EOLib.Domain.Map; using Microsoft.Xna.Framework.Input; using Optional; -using System.Linq; namespace EndlessClient.Input { diff --git a/EndlessClient/Input/UnwalkableTileActions.cs b/EndlessClient/Input/UnwalkableTileActions.cs index 5eeed3648..b1dc20da0 100644 --- a/EndlessClient/Input/UnwalkableTileActions.cs +++ b/EndlessClient/Input/UnwalkableTileActions.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Dialogs.Factories; using EndlessClient.HUD; @@ -7,7 +8,6 @@ using EOLib.Domain.Map; using EOLib.IO.Map; using EOLib.Localization; -using System.Collections.Generic; namespace EndlessClient.Input { diff --git a/EndlessClient/Input/UnwalkableTileActionsHandler.cs b/EndlessClient/Input/UnwalkableTileActionsHandler.cs index c09c702eb..9669a2642 100644 --- a/EndlessClient/Input/UnwalkableTileActionsHandler.cs +++ b/EndlessClient/Input/UnwalkableTileActionsHandler.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Dialogs.Actions; using EOLib.Domain.Character; using EOLib.Domain.Map; -using System.Collections.Generic; namespace EndlessClient.Input { diff --git a/EndlessClient/Input/UserInputHandler.cs b/EndlessClient/Input/UserInputHandler.cs index 376889d2f..03bd64adb 100644 --- a/EndlessClient/Input/UserInputHandler.cs +++ b/EndlessClient/Input/UserInputHandler.cs @@ -1,13 +1,13 @@ -using EndlessClient.Controllers; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Controllers; using EndlessClient.Dialogs; using EndlessClient.GameExecution; using EndlessClient.HUD; using EndlessClient.Rendering; using EOLib.Domain.Map; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Input diff --git a/EndlessClient/Network/UnknownEntitiesRequester.cs b/EndlessClient/Network/UnknownEntitiesRequester.cs index 53446e24f..0378835d8 100644 --- a/EndlessClient/Network/UnknownEntitiesRequester.cs +++ b/EndlessClient/Network/UnknownEntitiesRequester.cs @@ -1,4 +1,8 @@ -using EndlessClient.GameExecution; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using EndlessClient.GameExecution; using EndlessClient.Rendering; using EndlessClient.Rendering.Character; using EndlessClient.Rendering.NPC; @@ -7,10 +11,6 @@ using EOLib.Domain.NPC; using EOLib.IO.Map; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; namespace EndlessClient.Network { diff --git a/EndlessClient/Program.cs b/EndlessClient/Program.cs index 3b86ced2b..d02ab6db2 100644 --- a/EndlessClient/Program.cs +++ b/EndlessClient/Program.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using EndlessClient.GameExecution; -using System; +using System; using System.Reflection; +using AutomaticTypeMapper; +using EndlessClient.GameExecution; namespace EndlessClient { diff --git a/EndlessClient/Rendering/Character/CharacterAnimationActions.cs b/EndlessClient/Rendering/Character/CharacterAnimationActions.cs index ae352a600..b4a0d2f58 100644 --- a/EndlessClient/Rendering/Character/CharacterAnimationActions.cs +++ b/EndlessClient/Rendering/Character/CharacterAnimationActions.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.ControlSets; using EndlessClient.HUD; @@ -21,9 +24,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; using Optional.Collections; -using System; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Rendering.Character { diff --git a/EndlessClient/Rendering/Character/CharacterAnimator.cs b/EndlessClient/Rendering/Character/CharacterAnimator.cs index 496a02f01..1494c5108 100644 --- a/EndlessClient/Rendering/Character/CharacterAnimator.cs +++ b/EndlessClient/Rendering/Character/CharacterAnimator.cs @@ -1,4 +1,8 @@ -using EndlessClient.GameExecution; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using EndlessClient.GameExecution; using EndlessClient.HUD; using EndlessClient.HUD.Spells; using EndlessClient.Rendering.Metadata; @@ -12,10 +16,6 @@ using EOLib.IO.Pub; using Microsoft.Xna.Framework; using Optional; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; namespace EndlessClient.Rendering.Character { diff --git a/EndlessClient/Rendering/Character/CharacterRenderer.cs b/EndlessClient/Rendering/Character/CharacterRenderer.cs index be14bc636..916e143d5 100644 --- a/EndlessClient/Rendering/Character/CharacterRenderer.cs +++ b/EndlessClient/Rendering/Character/CharacterRenderer.cs @@ -1,4 +1,6 @@ -using EndlessClient.Audio; +using System; +using System.Linq; +using EndlessClient.Audio; using EndlessClient.GameExecution; using EndlessClient.Input; using EndlessClient.Rendering.CharacterProperties; @@ -18,8 +20,6 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Optional; -using System; -using System.Linq; using XNAControls; namespace EndlessClient.Rendering.Character diff --git a/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs b/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs index 219739c6f..3f8713272 100644 --- a/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs +++ b/EndlessClient/Rendering/Character/CharacterRendererUpdater.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Rendering.Effects; using EndlessClient.Rendering.Factories; using EOLib; @@ -7,9 +10,6 @@ using Microsoft.Xna.Framework; using Optional; using Optional.Collections; -using System; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Rendering.Character { diff --git a/EndlessClient/Rendering/Character/CharacterStateCache.cs b/EndlessClient/Rendering/Character/CharacterStateCache.cs index bbd518cf3..bdc75771e 100644 --- a/EndlessClient/Rendering/Character/CharacterStateCache.cs +++ b/EndlessClient/Rendering/Character/CharacterStateCache.cs @@ -1,10 +1,9 @@ -using AutomaticTypeMapper; -using EOLib; -using Optional; -using System; +using System; using System.Collections.Generic; using System.Linq; - +using AutomaticTypeMapper; +using EOLib; +using Optional; using DomainCharacter = EOLib.Domain.Character.Character; namespace EndlessClient.Rendering.Character diff --git a/EndlessClient/Rendering/Character/ICharacterRenderer.cs b/EndlessClient/Rendering/Character/ICharacterRenderer.cs index 02a7d51a4..13457876a 100644 --- a/EndlessClient/Rendering/Character/ICharacterRenderer.cs +++ b/EndlessClient/Rendering/Character/ICharacterRenderer.cs @@ -1,6 +1,6 @@ -using Microsoft.Xna.Framework; +using System; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; namespace EndlessClient.Rendering.Character { diff --git a/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs b/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs index 3249f039e..d1f8c118e 100644 --- a/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs +++ b/EndlessClient/Rendering/Character/ICharacterRendererRepository.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using Optional; -using System; +using System; using System.Collections.Generic; +using AutomaticTypeMapper; +using Optional; namespace EndlessClient.Rendering.Character { diff --git a/EndlessClient/Rendering/Character/ICharacterStateCache.cs b/EndlessClient/Rendering/Character/ICharacterStateCache.cs index 4dba53934..cba0412a1 100644 --- a/EndlessClient/Rendering/Character/ICharacterStateCache.cs +++ b/EndlessClient/Rendering/Character/ICharacterStateCache.cs @@ -1,6 +1,5 @@ -using Optional; -using System.Collections.Generic; - +using System.Collections.Generic; +using Optional; using DomainCharacter = EOLib.Domain.Character.Character; namespace EndlessClient.Rendering.Character diff --git a/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs b/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs index fda41ba48..dfe02d497 100644 --- a/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs +++ b/EndlessClient/Rendering/Character/PeriodicEmoteHandler.cs @@ -1,4 +1,6 @@ -using EndlessClient.Audio; +using System; +using System.Diagnostics; +using EndlessClient.Audio; using EndlessClient.Controllers; using EndlessClient.GameExecution; using EndlessClient.HUD; @@ -8,8 +10,6 @@ using EOLib.Localization; using Microsoft.Xna.Framework; using Optional; -using System; -using System.Diagnostics; namespace EndlessClient.Rendering.Character { diff --git a/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs index 768f8320c..9f84c348f 100644 --- a/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ArmorRenderer.cs @@ -1,11 +1,11 @@ -using EndlessClient.Rendering.Metadata.Models; +using System; +using EndlessClient.Rendering.Metadata.Models; using EndlessClient.Rendering.Sprites; using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; namespace EndlessClient.Rendering.CharacterProperties { diff --git a/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs b/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs index f2ca4ee5e..4dc635b5c 100644 --- a/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/BootsRenderer.cs @@ -1,11 +1,11 @@ -using EndlessClient.Rendering.Metadata.Models; +using System; +using EndlessClient.Rendering.Metadata.Models; using EndlessClient.Rendering.Sprites; using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; namespace EndlessClient.Rendering.CharacterProperties { diff --git a/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs b/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs index 016df3bc5..244147b40 100644 --- a/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs +++ b/EndlessClient/Rendering/CharacterProperties/CharacterPropertyRendererBuilder.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Rendering.Character; using EndlessClient.Rendering.Metadata; using EndlessClient.Rendering.Metadata.Models; @@ -8,8 +10,6 @@ using EOLib.IO; using EOLib.IO.Pub; using EOLib.IO.Repositories; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Rendering.CharacterProperties { diff --git a/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs b/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs index 53e904a0d..db4516a8b 100644 --- a/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs +++ b/EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs @@ -1,8 +1,8 @@ -using EOLib; +using System; +using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; -using System; namespace EndlessClient.Rendering.CharacterProperties { diff --git a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs index be977a4be..2b03ff394 100644 --- a/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs +++ b/EndlessClient/Rendering/CharacterProperties/ICharacterPropertyRendererBuilder.cs @@ -1,6 +1,6 @@ +using System.Collections.Generic; using EndlessClient.Rendering.Character; using EOLib.Domain.Character; -using System.Collections.Generic; namespace EndlessClient.Rendering.CharacterProperties { diff --git a/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs b/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs index c8c7f54dd..f1d1371d1 100644 --- a/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/ShieldRenderer.cs @@ -1,11 +1,11 @@ -using EndlessClient.Rendering.Metadata.Models; +using System; +using EndlessClient.Rendering.Metadata.Models; using EndlessClient.Rendering.Sprites; using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; namespace EndlessClient.Rendering.CharacterProperties { diff --git a/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs b/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs index c346df073..87e2445aa 100644 --- a/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs +++ b/EndlessClient/Rendering/CharacterProperties/SkinRenderLocationCalculator.cs @@ -1,8 +1,8 @@ +using System; using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; -using System; namespace EndlessClient.Rendering.CharacterProperties { diff --git a/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs b/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs index 7709d977d..ad480bdf7 100644 --- a/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs +++ b/EndlessClient/Rendering/CharacterProperties/WeaponRenderer.cs @@ -1,11 +1,11 @@ -using EndlessClient.Rendering.Metadata.Models; +using System; +using EndlessClient.Rendering.Metadata.Models; using EndlessClient.Rendering.Sprites; using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; namespace EndlessClient.Rendering.CharacterProperties { diff --git a/EndlessClient/Rendering/Chat/ChatBubble.cs b/EndlessClient/Rendering/Chat/ChatBubble.cs index 58add07d0..35e3fef73 100644 --- a/EndlessClient/Rendering/Chat/ChatBubble.cs +++ b/EndlessClient/Rendering/Chat/ChatBubble.cs @@ -1,11 +1,11 @@ -using EndlessClient.GameExecution; +using System; +using System.Diagnostics; +using EndlessClient.GameExecution; using EOLib; using EOLib.Config; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Optional; -using System; -using System.Diagnostics; using XNAControls; namespace EndlessClient.Rendering.Chat diff --git a/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs b/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs index e9a3cdbf9..e4311e494 100644 --- a/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs +++ b/EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Content; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; -using System.Collections.Generic; namespace EndlessClient.Rendering.Chat { diff --git a/EndlessClient/Rendering/Chat/ChatColorExtensions.cs b/EndlessClient/Rendering/Chat/ChatColorExtensions.cs index cf46f5dff..7d558b298 100644 --- a/EndlessClient/Rendering/Chat/ChatColorExtensions.cs +++ b/EndlessClient/Rendering/Chat/ChatColorExtensions.cs @@ -1,7 +1,7 @@ -using EOLib.Domain.Chat; +using System; +using EOLib.Domain.Chat; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System; namespace EndlessClient.Rendering.Chat { diff --git a/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs b/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs index 6e0ac4955..1855dbbba 100644 --- a/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs +++ b/EndlessClient/Rendering/Chat/ChatRenderableGenerator.cs @@ -1,12 +1,12 @@ -using EndlessClient.Services; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Services; using EOLib; using EOLib.Domain.Chat; using EOLib.Graphics; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.BitmapFonts; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Rendering.Chat diff --git a/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs b/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs index 27a6ad5f3..54ec4c815 100644 --- a/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs +++ b/EndlessClient/Rendering/Chat/IChatRenderableGenerator.cs @@ -1,5 +1,5 @@ -using EOLib.Domain.Chat; -using System.Collections.Generic; +using System.Collections.Generic; +using EOLib.Domain.Chat; namespace EndlessClient.Rendering.Chat { diff --git a/EndlessClient/Rendering/ClientWindowSizeRepository.cs b/EndlessClient/Rendering/ClientWindowSizeRepository.cs index 17cbd99fe..045f2c2c4 100644 --- a/EndlessClient/Rendering/ClientWindowSizeRepository.cs +++ b/EndlessClient/Rendering/ClientWindowSizeRepository.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib; using EOLib.Graphics; -using System; -using System.Collections.Generic; namespace EndlessClient.Rendering { diff --git a/EndlessClient/Rendering/ContextMenuRenderer.cs b/EndlessClient/Rendering/ContextMenuRenderer.cs index c58f8d02e..54cab99f0 100644 --- a/EndlessClient/Rendering/ContextMenuRenderer.cs +++ b/EndlessClient/Rendering/ContextMenuRenderer.cs @@ -1,4 +1,7 @@ -using EndlessClient.Audio; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Audio; using EndlessClient.ControlSets; using EndlessClient.Dialogs.Actions; using EndlessClient.Dialogs.Factories; @@ -20,9 +23,6 @@ using MonoGame.Extended.Input; using MonoGame.Extended.Input.InputListeners; using Optional; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Rendering diff --git a/EndlessClient/Rendering/DispatcherGameComponent.cs b/EndlessClient/Rendering/DispatcherGameComponent.cs index 66eeded55..82c0e7f51 100644 --- a/EndlessClient/Rendering/DispatcherGameComponent.cs +++ b/EndlessClient/Rendering/DispatcherGameComponent.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; -using EndlessClient.GameExecution; -using Microsoft.Xna.Framework; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using AutomaticTypeMapper; +using EndlessClient.GameExecution; +using Microsoft.Xna.Framework; namespace EndlessClient.Rendering { diff --git a/EndlessClient/Rendering/Effects/EffectRenderer.cs b/EndlessClient/Rendering/Effects/EffectRenderer.cs index d23ae9644..87993a12d 100644 --- a/EndlessClient/Rendering/Effects/EffectRenderer.cs +++ b/EndlessClient/Rendering/Effects/EffectRenderer.cs @@ -1,4 +1,7 @@ -using EndlessClient.Audio; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using EndlessClient.Audio; using EndlessClient.Rendering.Metadata.Models; using EOLib.Domain.Character; using EOLib.Domain.Extensions; @@ -6,10 +9,6 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Optional; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; - using DomainCharacter = EOLib.Domain.Character.Character; using DomainNPC = EOLib.Domain.NPC.NPC; diff --git a/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs b/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs index 5e19c8081..b807af9a5 100644 --- a/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs +++ b/EndlessClient/Rendering/Effects/EffectSpriteInfo.cs @@ -1,9 +1,9 @@ -using EndlessClient.Rendering.Metadata.Models; +using System; +using System.Collections.Generic; +using EndlessClient.Rendering.Metadata.Models; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Optional; -using System; -using System.Collections.Generic; namespace EndlessClient.Rendering.Effects { diff --git a/EndlessClient/Rendering/Effects/EffectSpriteManager.cs b/EndlessClient/Rendering/Effects/EffectSpriteManager.cs index e04c60a53..234a7d56b 100644 --- a/EndlessClient/Rendering/Effects/EffectSpriteManager.cs +++ b/EndlessClient/Rendering/Effects/EffectSpriteManager.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Rendering.Metadata; using EndlessClient.Rendering.Metadata.Models; using EOLib.Graphics; using Microsoft.Xna.Framework.Graphics; -using System.Collections.Generic; namespace EndlessClient.Rendering.Effects { diff --git a/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs b/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs index d2d1b81a5..e86b7d7d1 100644 --- a/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs +++ b/EndlessClient/Rendering/Effects/PositionOffsetEffectMetadata.cs @@ -1,6 +1,6 @@ -using Amadevus.RecordGenerator; +using System.Collections.Generic; +using Amadevus.RecordGenerator; using Newtonsoft.Json; -using System.Collections.Generic; namespace EndlessClient.Rendering.Effects { diff --git a/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs b/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs index 373262174..ce25ee258 100644 --- a/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs +++ b/EndlessClient/Rendering/GridDrawCoordinateCalculator.cs @@ -1,10 +1,9 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using EOLib.Domain.Map; using Microsoft.Xna.Framework; -using System; - using DomainNPC = EOLib.Domain.NPC.NPC; namespace EndlessClient.Rendering diff --git a/EndlessClient/Rendering/HealthBarRenderer.cs b/EndlessClient/Rendering/HealthBarRenderer.cs index 11cb8b9be..83c1b214e 100644 --- a/EndlessClient/Rendering/HealthBarRenderer.cs +++ b/EndlessClient/Rendering/HealthBarRenderer.cs @@ -1,10 +1,10 @@ -using EOLib.Graphics; +using System; +using System.Collections.Generic; +using System.Linq; +using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Optional; -using System; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Rendering { diff --git a/EndlessClient/Rendering/Map/ClickDispatcher.cs b/EndlessClient/Rendering/Map/ClickDispatcher.cs index 9d7025423..10bb6ab09 100644 --- a/EndlessClient/Rendering/Map/ClickDispatcher.cs +++ b/EndlessClient/Rendering/Map/ClickDispatcher.cs @@ -1,4 +1,7 @@ -using EndlessClient.Controllers; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Controllers; using EndlessClient.ControlSets; using EndlessClient.HUD.Controls; using EndlessClient.HUD.Spells; @@ -13,9 +16,6 @@ using MonoGame.Extended.Input; using MonoGame.Extended.Input.InputListeners; using Optional; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; using DomainCharacter = EOLib.Domain.Character.Character; using DomainNPC = EOLib.Domain.NPC.NPC; diff --git a/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs b/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs index 52fc59fd5..8a796c696 100644 --- a/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs +++ b/EndlessClient/Rendering/Map/DynamicMapObjectUpdater.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Input; using EndlessClient.Rendering.Character; @@ -8,9 +11,6 @@ using EOLib.Domain.Map; using EOLib.IO.Map; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Rendering.Map { diff --git a/EndlessClient/Rendering/Map/MapChangedActions.cs b/EndlessClient/Rendering/Map/MapChangedActions.cs index 984c225f8..51601f251 100644 --- a/EndlessClient/Rendering/Map/MapChangedActions.cs +++ b/EndlessClient/Rendering/Map/MapChangedActions.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Controllers; using EndlessClient.ControlSets; @@ -16,7 +17,6 @@ using EOLib.IO.Repositories; using EOLib.Localization; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Linq; namespace EndlessClient.Rendering.Map { diff --git a/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs b/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs index a5049694a..8f53bdd11 100644 --- a/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs +++ b/EndlessClient/Rendering/Map/MapEntityRendererProvider.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using AutomaticTypeMapper; using EndlessClient.Rendering.Character; using EndlessClient.Rendering.MapEntityRenderers; @@ -6,7 +7,6 @@ using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.Graphics; -using System.Collections.Generic; namespace EndlessClient.Rendering.Map { diff --git a/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs b/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs index 1a6625b4a..ebc188d1b 100644 --- a/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs +++ b/EndlessClient/Rendering/Map/MapObjectBoundsCalculator.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Rendering.MapEntityRenderers; using EOLib.Domain.Character; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System.Linq; namespace EndlessClient.Rendering.Map { diff --git a/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs b/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs index 85a850863..37c067290 100644 --- a/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs +++ b/EndlessClient/Rendering/Map/MapRenderDistanceCalculator.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.IO.Map; -using System; namespace EndlessClient.Rendering.Map { diff --git a/EndlessClient/Rendering/Map/MapRenderer.cs b/EndlessClient/Rendering/Map/MapRenderer.cs index 60c66eaaa..5a0254d96 100644 --- a/EndlessClient/Rendering/Map/MapRenderer.cs +++ b/EndlessClient/Rendering/Map/MapRenderer.cs @@ -1,4 +1,7 @@ -using EndlessClient.Content; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Content; using EndlessClient.GameExecution; using EndlessClient.Rendering.Character; using EndlessClient.Rendering.Effects; @@ -14,9 +17,6 @@ using Microsoft.Xna.Framework.Input; using MonoGame.Extended.BitmapFonts; using Optional; -using System; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Rendering.Map { diff --git a/EndlessClient/Rendering/Map/MiniMapRenderer.cs b/EndlessClient/Rendering/Map/MiniMapRenderer.cs index 56cdbc24b..07733c1f7 100644 --- a/EndlessClient/Rendering/Map/MiniMapRenderer.cs +++ b/EndlessClient/Rendering/Map/MiniMapRenderer.cs @@ -1,4 +1,6 @@ -using EndlessClient.Rendering.Factories; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.Rendering.Factories; using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.Graphics; @@ -7,8 +9,6 @@ using EOLib.IO.Repositories; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Rendering.Map diff --git a/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs index f431effcb..88ccdd080 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/BaseMapEntityRenderer.cs @@ -1,9 +1,9 @@ -using EndlessClient.Rendering.Map; +using System; +using System.Collections.Generic; +using EndlessClient.Rendering.Map; using EOLib.Domain.Character; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.Collections.Generic; namespace EndlessClient.Rendering.MapEntityRenderers { diff --git a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs index 9315a11a5..1be23a1c2 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/IMapEntityRenderer.cs @@ -1,7 +1,7 @@ -using EndlessClient.Rendering.Map; +using System; +using EndlessClient.Rendering.Map; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; namespace EndlessClient.Rendering.MapEntityRenderers { diff --git a/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs index 8b7819708..935181814 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MapItemLayerRenderer.cs @@ -1,10 +1,10 @@ -using EndlessClient.Rendering.Map; +using System; +using System.Linq; +using EndlessClient.Rendering.Map; using EOLib.Domain.Character; using EOLib.Domain.Map; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.Linq; namespace EndlessClient.Rendering.MapEntityRenderers { diff --git a/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs index 3677dffa8..ffdf3aff0 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/MapObjectLayerRenderer.cs @@ -1,4 +1,7 @@ -using EndlessClient.Rendering.Map; +using System; +using System.DirectoryServices.ActiveDirectory; +using System.Linq; +using EndlessClient.Rendering.Map; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using EOLib.Domain.Map; @@ -6,9 +9,6 @@ using EOLib.IO.Map; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.DirectoryServices.ActiveDirectory; -using System.Linq; using DomainCharacter = EOLib.Domain.Character.Character; namespace EndlessClient.Rendering.MapEntityRenderers diff --git a/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs index ac63c5438..b49fb8532 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/NPCEntityRenderer.cs @@ -1,10 +1,10 @@ -using EndlessClient.Rendering.Map; +using System.Linq; +using EndlessClient.Rendering.Map; using EndlessClient.Rendering.NPC; using EOLib.Domain.Character; using EOLib.Domain.Map; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System.Linq; namespace EndlessClient.Rendering.MapEntityRenderers { diff --git a/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs index 25dd1a64e..d31cde25c 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/OtherCharacterEntityRenderer.cs @@ -1,10 +1,10 @@ -using EndlessClient.Rendering.Character; +using System.Linq; +using EndlessClient.Rendering.Character; using EndlessClient.Rendering.Map; using EOLib.Domain.Character; using EOLib.Domain.Map; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System.Linq; namespace EndlessClient.Rendering.MapEntityRenderers { diff --git a/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs b/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs index eb8687289..4fd37c518 100644 --- a/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs +++ b/EndlessClient/Rendering/MapEntityRenderers/WallLayerRenderer.cs @@ -1,11 +1,11 @@ -using EndlessClient.Rendering.Map; +using System.Linq; +using EndlessClient.Rendering.Map; using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.Graphics; using EOLib.IO.Map; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System.Linq; namespace EndlessClient.Rendering.MapEntityRenderers { diff --git a/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs b/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs index c6dfe7e0d..51011b376 100644 --- a/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/EffectMetadataProvider.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Rendering.Effects; using EndlessClient.Rendering.Metadata.Models; -using System.Collections.Generic; namespace EndlessClient.Rendering.Metadata { diff --git a/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs b/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs index 0456b8f54..aae52c7c8 100644 --- a/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs +++ b/EndlessClient/Rendering/Metadata/GFXMetadataLoader.cs @@ -1,12 +1,12 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Text; +using AutomaticTypeMapper; using EndlessClient.Rendering.Metadata.Models; using EOLib.Graphics; using Newtonsoft.Json; using Optional; using PELoaderLib; -using System; -using System.Collections.Generic; -using System.Text; namespace EndlessClient.Rendering.Metadata { diff --git a/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs b/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs index d1c783103..f8fc6f5b8 100644 --- a/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/HatMetadataProvider.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Rendering.Metadata.Models; -using System.Collections.Generic; namespace EndlessClient.Rendering.Metadata { diff --git a/EndlessClient/Rendering/Metadata/IMetadataProvider.cs b/EndlessClient/Rendering/Metadata/IMetadataProvider.cs index f7075edab..e7a5d35d1 100644 --- a/EndlessClient/Rendering/Metadata/IMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/IMetadataProvider.cs @@ -1,5 +1,5 @@ -using EndlessClient.Rendering.Metadata.Models; -using System.Collections.Generic; +using System.Collections.Generic; +using EndlessClient.Rendering.Metadata.Models; namespace EndlessClient.Rendering.Metadata { diff --git a/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs b/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs index b6009357f..8742d5c05 100644 --- a/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/NPCMetadataProvider.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Rendering.Metadata.Models; -using System.Collections.Generic; namespace EndlessClient.Rendering.Metadata { diff --git a/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs b/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs index b5fbab4ac..a4eec431d 100644 --- a/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/ShieldMetadataProvider.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Rendering.Metadata.Models; -using System.Collections.Generic; namespace EndlessClient.Rendering.Metadata { diff --git a/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs b/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs index 5aa1bf734..42320c127 100644 --- a/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs +++ b/EndlessClient/Rendering/Metadata/WeaponMetadataProvider.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.Rendering.Metadata.Models; -using System.Collections.Generic; namespace EndlessClient.Rendering.Metadata { diff --git a/EndlessClient/Rendering/MouseCursorRenderer.cs b/EndlessClient/Rendering/MouseCursorRenderer.cs index f311a3a5b..25582eac3 100644 --- a/EndlessClient/Rendering/MouseCursorRenderer.cs +++ b/EndlessClient/Rendering/MouseCursorRenderer.cs @@ -1,4 +1,7 @@ -using EndlessClient.Controllers; +using System; +using System.Diagnostics; +using System.Linq; +using EndlessClient.Controllers; using EndlessClient.Dialogs; using EndlessClient.HUD; using EndlessClient.Input; @@ -12,9 +15,6 @@ using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Optional; -using System; -using System.Diagnostics; -using System.Linq; using XNAControls; namespace EndlessClient.Rendering diff --git a/EndlessClient/Rendering/NPC/INPCRenderer.cs b/EndlessClient/Rendering/NPC/INPCRenderer.cs index 654c13446..deeb8e6c7 100644 --- a/EndlessClient/Rendering/NPC/INPCRenderer.cs +++ b/EndlessClient/Rendering/NPC/INPCRenderer.cs @@ -1,6 +1,6 @@ +using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; namespace EndlessClient.Rendering.NPC { diff --git a/EndlessClient/Rendering/NPC/NPCAnimator.cs b/EndlessClient/Rendering/NPC/NPCAnimator.cs index 77124741a..6ba1be037 100644 --- a/EndlessClient/Rendering/NPC/NPCAnimator.cs +++ b/EndlessClient/Rendering/NPC/NPCAnimator.cs @@ -1,12 +1,12 @@ -using EndlessClient.GameExecution; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.GameExecution; using EOLib; using EOLib.Domain.Extensions; using EOLib.Domain.Map; using EOLib.Domain.NPC; using Microsoft.Xna.Framework; using Optional.Collections; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Rendering.NPC { diff --git a/EndlessClient/Rendering/NPC/NPCCache.cs b/EndlessClient/Rendering/NPC/NPCCache.cs index 65c527286..bf05224cc 100644 --- a/EndlessClient/Rendering/NPC/NPCCache.cs +++ b/EndlessClient/Rendering/NPC/NPCCache.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EndlessClient.Rendering.NPC { diff --git a/EndlessClient/Rendering/NPC/NPCRenderer.cs b/EndlessClient/Rendering/NPC/NPCRenderer.cs index 56befc44e..4fc11ccf3 100644 --- a/EndlessClient/Rendering/NPC/NPCRenderer.cs +++ b/EndlessClient/Rendering/NPC/NPCRenderer.cs @@ -1,4 +1,7 @@ -using EndlessClient.GameExecution; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.GameExecution; using EndlessClient.Input; using EndlessClient.Rendering.Chat; using EndlessClient.Rendering.Effects; @@ -13,9 +16,6 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Optional; -using System; -using System.Collections.Generic; -using System.Linq; using XNAControls; namespace EndlessClient.Rendering.NPC diff --git a/EndlessClient/Rendering/NPC/NPCRendererRepository.cs b/EndlessClient/Rendering/NPC/NPCRendererRepository.cs index d6f93a73c..15783949d 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererRepository.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererRepository.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using EOLib.Domain.Map; -using System; +using System; using System.Collections.Generic; +using AutomaticTypeMapper; +using EOLib.Domain.Map; namespace EndlessClient.Rendering.NPC { diff --git a/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs b/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs index be61aa056..f5c24b7f7 100644 --- a/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs +++ b/EndlessClient/Rendering/NPC/NPCRendererUpdater.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Map; using Microsoft.Xna.Framework; using Optional; -using System; -using System.Linq; namespace EndlessClient.Rendering.NPC { diff --git a/EndlessClient/Rendering/PlayerStatusIconRenderer.cs b/EndlessClient/Rendering/PlayerStatusIconRenderer.cs index 7b984422f..efebacffa 100644 --- a/EndlessClient/Rendering/PlayerStatusIconRenderer.cs +++ b/EndlessClient/Rendering/PlayerStatusIconRenderer.cs @@ -1,10 +1,10 @@ -using EndlessClient.HUD.Spells; +using System; +using EndlessClient.HUD.Spells; using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; using XNAControls; namespace EndlessClient.Rendering diff --git a/EndlessClient/Rendering/PointComparer.cs b/EndlessClient/Rendering/PointComparer.cs index eadbb3f36..14bb1e178 100644 --- a/EndlessClient/Rendering/PointComparer.cs +++ b/EndlessClient/Rendering/PointComparer.cs @@ -1,5 +1,5 @@ -using Microsoft.Xna.Framework; -using System.Collections.Generic; +using System.Collections.Generic; +using Microsoft.Xna.Framework; namespace EndlessClient.Rendering { diff --git a/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs b/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs index e4f920f79..a03f1a957 100644 --- a/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs +++ b/EndlessClient/Rendering/Sprites/CharacterSpriteCalculator.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.Rendering.Metadata; using EndlessClient.Rendering.Metadata.Models; using EOLib; @@ -6,8 +8,6 @@ using EOLib.Domain.Extensions; using EOLib.Graphics; using Microsoft.Xna.Framework; -using System; -using System.Linq; namespace EndlessClient.Rendering.Sprites { diff --git a/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs b/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs index 5d8308eaf..46028fe61 100644 --- a/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs +++ b/EndlessClient/Rendering/Sprites/EmptySpriteSheet.cs @@ -1,6 +1,6 @@ -using Microsoft.Xna.Framework; +using System.Linq; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System.Linq; namespace EndlessClient.Rendering.Sprites { diff --git a/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs b/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs index 5909e4f48..173930a33 100644 --- a/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs +++ b/EndlessClient/Rendering/Sprites/NPCSpriteDataCache.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib; using EOLib.Domain.NPC; using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Rendering.Sprites { diff --git a/EndlessClient/Services/FriendIgnoreListService.cs b/EndlessClient/Services/FriendIgnoreListService.cs index 6aa0ced90..17e3561d0 100644 --- a/EndlessClient/Services/FriendIgnoreListService.cs +++ b/EndlessClient/Services/FriendIgnoreListService.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; +using AutomaticTypeMapper; namespace EndlessClient.Services { diff --git a/EndlessClient/Subscribers/ArenaEventSubscriber.cs b/EndlessClient/Subscribers/ArenaEventSubscriber.cs index d8cd83401..64e75a756 100644 --- a/EndlessClient/Subscribers/ArenaEventSubscriber.cs +++ b/EndlessClient/Subscribers/ArenaEventSubscriber.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Audio; using EndlessClient.ControlSets; using EndlessClient.HUD.Chat; @@ -11,7 +12,6 @@ using EOLib.Domain.Notifiers; using EOLib.IO.Map; using EOLib.Localization; -using System.Collections.Generic; namespace EndlessClient.Subscribers { diff --git a/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs b/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs index de1ebbe6f..5f3bbacaf 100644 --- a/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs +++ b/EndlessClient/Subscribers/OtherCharacterEventSubscriber.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Linq; +using AutomaticTypeMapper; using EndlessClient.HUD.Chat; using EndlessClient.Rendering.Character; using EndlessClient.Services; @@ -6,8 +8,6 @@ using EOLib.Config; using EOLib.Domain.Chat; using EOLib.Domain.Notifiers; -using System; -using System.Linq; namespace EndlessClient.Subscribers { diff --git a/EndlessClient/Test/CharacterStateTest.cs b/EndlessClient/Test/CharacterStateTest.cs index 8770a745e..baef41d94 100644 --- a/EndlessClient/Test/CharacterStateTest.cs +++ b/EndlessClient/Test/CharacterStateTest.cs @@ -1,4 +1,7 @@ -using EndlessClient.GameExecution; +using System; +using System.Collections.Generic; +using System.Linq; +using EndlessClient.GameExecution; using EndlessClient.Rendering.Character; using EndlessClient.Rendering.Factories; using EndlessClient.Rendering.Metadata; @@ -11,9 +14,6 @@ using EOLib.IO.Repositories; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; -using System; -using System.Collections.Generic; -using System.Linq; namespace EndlessClient.Test { diff --git a/EndlessClient/UIControls/BlinkingLabel.cs b/EndlessClient/UIControls/BlinkingLabel.cs index 1b845f448..1ed9d3bc7 100644 --- a/EndlessClient/UIControls/BlinkingLabel.cs +++ b/EndlessClient/UIControls/BlinkingLabel.cs @@ -1,5 +1,5 @@ -using Microsoft.Xna.Framework; -using System; +using System; +using Microsoft.Xna.Framework; using XNAControls; namespace EndlessClient.UIControls diff --git a/EndlessClient/UIControls/CharacterInfoPanel.cs b/EndlessClient/UIControls/CharacterInfoPanel.cs index df74d5481..3a3730f16 100644 --- a/EndlessClient/UIControls/CharacterInfoPanel.cs +++ b/EndlessClient/UIControls/CharacterInfoPanel.cs @@ -1,4 +1,6 @@ -using EndlessClient.Controllers; +using System; +using System.Threading.Tasks; +using EndlessClient.Controllers; using EndlessClient.Dialogs.Services; using EndlessClient.Input; using EndlessClient.Rendering; @@ -11,8 +13,6 @@ using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Moffat.EndlessOnline.SDK.Protocol; -using System; -using System.Threading.Tasks; using XNAControls; namespace EndlessClient.UIControls diff --git a/EndlessClient/UIControls/CharacterInfoPanelFactory.cs b/EndlessClient/UIControls/CharacterInfoPanelFactory.cs index 5cd92c24b..c8ebdca1d 100644 --- a/EndlessClient/UIControls/CharacterInfoPanelFactory.cs +++ b/EndlessClient/UIControls/CharacterInfoPanelFactory.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EndlessClient.Controllers; using EndlessClient.Dialogs.Services; using EndlessClient.Input; @@ -6,8 +8,6 @@ using EndlessClient.Rendering.Factories; using EOLib.Domain.Character; using EOLib.Graphics; -using System; -using System.Collections.Generic; namespace EndlessClient.UIControls { diff --git a/EndlessClient/UIControls/ChatModePictureBox.cs b/EndlessClient/UIControls/ChatModePictureBox.cs index 4a88e318c..369f16218 100644 --- a/EndlessClient/UIControls/ChatModePictureBox.cs +++ b/EndlessClient/UIControls/ChatModePictureBox.cs @@ -1,11 +1,11 @@ -using EndlessClient.ControlSets; +using System; +using EndlessClient.ControlSets; using EndlessClient.HUD.Chat; using EndlessClient.HUD.Controls; using EndlessClient.Rendering; using EOLib.Graphics; using Microsoft.Xna.Framework; using Optional; -using System; using XNAControls; namespace EndlessClient.UIControls diff --git a/EndlessClient/UIControls/ChatTextBox.cs b/EndlessClient/UIControls/ChatTextBox.cs index 5bb41dc62..c62ac8e3d 100644 --- a/EndlessClient/UIControls/ChatTextBox.cs +++ b/EndlessClient/UIControls/ChatTextBox.cs @@ -1,4 +1,5 @@ -using EndlessClient.Content; +using System; +using EndlessClient.Content; using EndlessClient.Rendering; using EOLib; using EOLib.Graphics; @@ -7,7 +8,6 @@ using Microsoft.Xna.Framework.Input; using MonoGame.Extended.Input.InputListeners; using Optional; -using System; using XNAControls; namespace EndlessClient.UIControls diff --git a/EndlessClient/UIControls/ClickableArea.cs b/EndlessClient/UIControls/ClickableArea.cs index 12103f835..52b3bb664 100644 --- a/EndlessClient/UIControls/ClickableArea.cs +++ b/EndlessClient/UIControls/ClickableArea.cs @@ -1,6 +1,6 @@ -using Microsoft.Xna.Framework; +using System; +using Microsoft.Xna.Framework; using MonoGame.Extended.Input.InputListeners; -using System; using XNAControls; namespace EndlessClient.UIControls diff --git a/EndlessClient/UIControls/CreateCharacterControl.cs b/EndlessClient/UIControls/CreateCharacterControl.cs index a945d61a0..056492216 100644 --- a/EndlessClient/UIControls/CreateCharacterControl.cs +++ b/EndlessClient/UIControls/CreateCharacterControl.cs @@ -1,9 +1,9 @@ -using EndlessClient.Rendering.Factories; +using System; +using EndlessClient.Rendering.Factories; using EOLib; using EOLib.Domain.Character; using Microsoft.Xna.Framework; using MonoGame.Extended.Input.InputListeners; -using System; using XNAControls; namespace EndlessClient.UIControls diff --git a/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs b/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs index a96eebfae..1fa155882 100644 --- a/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs +++ b/EndlessClient/UIControls/ICharacterInfoPanelFactory.cs @@ -1,6 +1,6 @@ -using EndlessClient.Controllers; +using System.Collections.Generic; +using EndlessClient.Controllers; using EOLib.Domain.Character; -using System.Collections.Generic; namespace EndlessClient.UIControls { diff --git a/EndlessClient/UIControls/ScrollBar.cs b/EndlessClient/UIControls/ScrollBar.cs index 82bc11581..879f8cd5f 100644 --- a/EndlessClient/UIControls/ScrollBar.cs +++ b/EndlessClient/UIControls/ScrollBar.cs @@ -1,8 +1,8 @@ -using EOLib.Graphics; +using System; +using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.Input.InputListeners; -using System; using XNAControls; namespace EndlessClient.UIControls diff --git a/EndlessClient/UIControls/StatusBarLabel.cs b/EndlessClient/UIControls/StatusBarLabel.cs index 4a4ef72ea..691789940 100644 --- a/EndlessClient/UIControls/StatusBarLabel.cs +++ b/EndlessClient/UIControls/StatusBarLabel.cs @@ -1,10 +1,10 @@ -using EndlessClient.HUD; +using System; +using EndlessClient.HUD; using EndlessClient.Rendering; using EOLib; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; using XNAControls; namespace EndlessClient.UIControls diff --git a/EndlessClient/UIControls/TimeLabel.cs b/EndlessClient/UIControls/TimeLabel.cs index 38c0b9e3a..a4a99e2f6 100644 --- a/EndlessClient/UIControls/TimeLabel.cs +++ b/EndlessClient/UIControls/TimeLabel.cs @@ -1,7 +1,7 @@ -using EndlessClient.Rendering; +using System; +using EndlessClient.Rendering; using EOLib; using Microsoft.Xna.Framework; -using System; using XNAControls; namespace EndlessClient.UIControls diff --git a/README.md b/README.md index f6be31923..13253faf3 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,11 @@ After installing, clone (or fork+clone) this repository locally and open the sol 6. Run `echo '' > EndlessClient/obj/Debug/net6.0-macos/osx-x64/EndlessClient.GlobalUsings.g.*.generated.cs` 7. Run the build again `dotnet build /p:PublishReadyToRun=false /p:TieredCompilation=false --self-contained EndlessClient` +#### Mac errors + +Problem: `error NETSDK1139: The target platform identifier macos was not recognized.` +Solution: run the command `sudo dotnet workload restore EndlessClient/EndlessClient.csproj` which will install the macos workload for you. + Todo list --------------------- diff --git a/global.json b/global.json new file mode 100644 index 000000000..b9357befe --- /dev/null +++ b/global.json @@ -0,0 +1,6 @@ +{ + "sdk" : { + "version": "6.0.0", + "rollForward": "latestFeature" + } +} \ No newline at end of file From 86b993489cb45c28086c8c4a4c34913d1e8cff94 Mon Sep 17 00:00:00 2001 From: Dan Oak Date: Fri, 2 Aug 2024 10:35:38 +0100 Subject: [PATCH 11/11] insert final newline set to true --- .editorconfig | 2 +- BatchMap/Program.cs | 8 ++++---- EOBot/ArgumentsParser.cs | 4 ++-- EOBot/BotBase.cs | 8 ++++---- EOBot/BotFramework.cs | 4 ++-- EOBot/BotHelper.cs | 10 +++++----- EOBot/Interpreter/BotInterpreter.cs | 4 ++-- EOBot/Interpreter/BuiltInIdentifierConfigurator.cs | 12 ++++++------ .../Interpreter/Extensions/SymbolTableExtensions.cs | 4 ++-- EOBot/Interpreter/States/AssignmentEvaluator.cs | 6 +++--- EOBot/Interpreter/States/BlockEvaluator.cs | 4 ++-- EOBot/Interpreter/States/ExpressionEvaluator.cs | 6 +++--- EOBot/Interpreter/States/ExpressionTailEvaluator.cs | 4 ++-- EOBot/Interpreter/States/FunctionEvaluator.cs | 6 +++--- EOBot/Interpreter/States/GotoEvaluator.cs | 4 ++-- EOBot/Interpreter/States/IfEvaluator.cs | 4 ++-- EOBot/Interpreter/States/LabelEvaluator.cs | 4 ++-- EOBot/Interpreter/States/OperandEvaluator.cs | 4 ++-- EOBot/Interpreter/States/ProgramState.cs | 4 ++-- EOBot/Interpreter/States/ScriptEvaluator.cs | 4 ++-- EOBot/Interpreter/States/StatementEvaluator.cs | 4 ++-- EOBot/Interpreter/States/VariableEvaluator.cs | 6 +++--- EOBot/Interpreter/States/WhileEvaluator.cs | 4 ++-- EOBot/Program.cs | 10 +++++----- EOBot/ScriptedBot.cs | 8 ++++---- EOBot/TrainerBot.cs | 12 ++++++------ EOLib.Config.Test/AssemblyInitializer.cs | 4 ++-- EOLib.Config.Test/ConfigFileLoadActionsTest.cs | 4 ++-- EOLib.Config.Test/IniReaderTest.cs | 4 ++-- EOLib.Config/ConfigFileLoadActions.cs | 4 ++-- EOLib.Config/IConfigurationRepository.cs | 4 ++-- EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs | 6 +++--- EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs | 8 ++++---- EOLib.Graphics.Test/NativeGraphicsManagerTest.cs | 8 ++++---- EOLib.Graphics.Test/PEFileCollectionTest.cs | 8 ++++---- EOLib.Graphics.Test/RectangleExtensionTest.cs | 4 ++-- EOLib.Graphics/ColorConstants.cs | 2 +- EOLib.Graphics/INativeGraphicsManager.cs | 4 ++-- EOLib.Graphics/NativeGraphicsLoader.cs | 4 ++-- EOLib.Graphics/NativeGraphicsManager.cs | 10 +++++----- EOLib.Graphics/PEFileCollection.cs | 6 +++--- EOLib.IO.Test/EIFRecordExtensionsTest.cs | 4 ++-- EOLib.IO.Test/Map/MapFilePropertiesTest.cs | 10 +++++----- EOLib.IO.Test/Map/MapFileTest.cs | 10 +++++----- EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs | 6 +++--- EOLib.IO.Test/Pub/BasePubFileTest.cs | 6 +++--- EOLib.IO.Test/Pub/ECFFileTest.cs | 4 ++-- EOLib.IO.Test/Pub/ECFRecordTest.cs | 6 +++--- EOLib.IO.Test/Pub/EIFFileTest.cs | 4 ++-- EOLib.IO.Test/Pub/EIFRecordTest.cs | 6 +++--- EOLib.IO.Test/Pub/ENFFileTest.cs | 4 ++-- EOLib.IO.Test/Pub/ENFRecordTest.cs | 6 +++--- EOLib.IO.Test/Pub/ESFFileTest.cs | 4 ++-- EOLib.IO.Test/Pub/ESFRecordTest.cs | 6 +++--- .../Services/Serializers/PubFileSerializerTest.cs | 10 +++++----- .../Services/Serializers/PubRecordSerializerTest.cs | 4 ++-- EOLib.IO/Actions/PubFileLoadActions.cs | 6 +++--- EOLib.IO/Extensions/PubFileExtensions.cs | 4 ++-- EOLib.IO/Pub/ECFRecord.cs | 4 ++-- EOLib.IO/Repositories/IMapFileRepository.cs | 4 ++-- EOLib.IO/Repositories/IPubFileRepository.cs | 4 ++-- EOLib.IO/Repositories/PubFileRepository.cs | 4 ++-- EOLib.IO/Services/BasePubLoadService.cs | 6 +++--- EOLib.IO/Services/IPubLoadService.cs | 4 ++-- EOLib.IO/Services/MapFileLoadService.cs | 4 ++-- EOLib.IO/Services/MapFileSaveService.cs | 6 +++--- EOLib.IO/Services/MapStringEncoderService.cs | 4 ++-- EOLib.IO/Services/NumberEncoderService.cs | 4 ++-- EOLib.IO/Services/PubFileSaveService.cs | 4 ++-- .../Serializers/ChestSpawnMapEntitySerializer.cs | 6 +++--- .../Services/Serializers/IPubFileDeserializer.cs | 4 ++-- .../Services/Serializers/IPubRecordSerializer.cs | 4 ++-- EOLib.IO/Services/Serializers/MapFileSerializer.cs | 6 +++--- .../Services/Serializers/MapPropertiesSerializer.cs | 8 ++++---- .../Serializers/NPCSpawnMapEntitySerializer.cs | 6 +++--- EOLib.IO/Services/Serializers/PubFileSerializer.cs | 6 +++--- EOLib.IO/Services/Serializers/PubRecordSerializer.cs | 6 +++--- .../Services/Serializers/SignMapEntitySerializer.cs | 6 +++--- .../Serializers/UnknownMapEntitySerializer.cs | 4 ++-- .../Services/Serializers/WarpMapEntitySerializer.cs | 6 +++--- EOLib.Localization.Test/DataFileLoadActionsTest.cs | 4 ++-- EOLib.Localization.Test/EDFLoaderServiceTest.cs | 4 ++-- .../LocalizedStringServiceTest.cs | 8 ++++---- EOLib.Localization/DataFileLoadActions.cs | 4 ++-- EOLib.Localization/DataFileRepository.cs | 4 ++-- EOLib.Localization/LocalizedStringFinder.cs | 4 ++-- EOLib.Localization/Services/EDFLoaderService.cs | 6 +++--- EOLib.Logger/DebugOnlyLogger.cs | 4 ++-- EOLib.Logger/LoggerFactory.cs | 6 +++--- EOLib.Logger/LoggerProvider.cs | 4 ++-- .../Net/FileTransfer/FileRequestServiceTest.cs | 12 ++++++------ EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs | 8 ++++---- EOLib/Domain/Account/AccountActions.cs | 8 ++++---- EOLib/Domain/Account/CreateAccountParameterResult.cs | 4 ++-- .../Account/CreateAccountParameterValidator.cs | 4 ++-- EOLib/Domain/Character/AttackValidationActions.cs | 4 ++-- EOLib/Domain/Character/CharacterActions.cs | 6 +++--- .../Domain/Character/CharacterInventoryRepository.cs | 4 ++-- EOLib/Domain/Character/CharacterManagementActions.cs | 6 +++--- EOLib/Domain/Character/CharacterSessionRepository.cs | 4 ++-- EOLib/Domain/Character/CharacterStats.cs | 6 +++--- EOLib/Domain/Character/EquippedItem.cs | 4 ++-- EOLib/Domain/Character/ExperienceTableProvider.cs | 4 ++-- EOLib/Domain/Character/GhostingRepository.cs | 4 ++-- EOLib/Domain/Character/InventoryItem.cs | 3 +-- EOLib/Domain/Character/PaperdollData.cs | 4 ++-- EOLib/Domain/Character/PaperdollRepository.cs | 4 ++-- EOLib/Domain/Character/TrainingActions.cs | 4 ++-- EOLib/Domain/Character/WalkValidationActions.cs | 6 +++--- EOLib/Domain/Chat/Builders/ChatPacketBuilder.cs | 4 ++-- EOLib/Domain/Chat/ChatActions.cs | 6 +++--- EOLib/Domain/Chat/ChatData.cs | 2 +- EOLib/Domain/Chat/ChatLoggerProvider.cs | 4 ++-- EOLib/Domain/Chat/ChatProcessor.cs | 8 ++++---- EOLib/Domain/Chat/ChatRepository.cs | 6 +++--- EOLib/Domain/Chat/LocalCommandHandler.cs | 6 +++--- EOLib/Domain/Chat/LoggingList.cs | 6 +++--- EOLib/Domain/Extensions/CharacterExtensions.cs | 4 ++-- .../CharacterRenderPropertiesExtensions.cs | 4 ++-- EOLib/Domain/Extensions/MapExtensions.cs | 6 +++--- EOLib/Domain/Extensions/NPCExtensions.cs | 4 ++-- EOLib/Domain/Extensions/PaperdollExtensions.cs | 4 ++-- EOLib/Domain/Interact/Board/BoardDataRepository.cs | 4 ++-- EOLib/Domain/Interact/Citizen/CitizenActions.cs | 6 +++--- .../Domain/Interact/Citizen/CitizenDataRepository.cs | 4 ++-- EOLib/Domain/Interact/Jukebox/JukeboxActions.cs | 4 ++-- EOLib/Domain/Interact/Quest/QuestDataRepository.cs | 4 ++-- EOLib/Domain/Interact/Quest/QuestDialogData.cs | 4 ++-- EOLib/Domain/Interact/Quest/QuestProgressData.cs | 4 ++-- EOLib/Domain/Interact/Shop/ShopDataRepository.cs | 4 ++-- EOLib/Domain/Interact/Skill/Skill.cs | 4 ++-- EOLib/Domain/Interact/Skill/SkillDataRepository.cs | 4 ++-- EOLib/Domain/Item/ItemActions.cs | 4 ++-- EOLib/Domain/Item/ItemDropValidator.cs | 4 ++-- EOLib/Domain/Item/ItemEquipValidator.cs | 4 ++-- EOLib/Domain/Item/ItemPickupValidator.cs | 4 ++-- EOLib/Domain/Item/ItemStringService.cs | 4 ++-- EOLib/Domain/Login/CharacterSelectorRepository.cs | 4 ++-- EOLib/Domain/Login/LoginActions.cs | 10 +++++----- EOLib/Domain/Login/NewsRepository.cs | 4 ++-- EOLib/Domain/Map/ChestDataRepository.cs | 4 ++-- EOLib/Domain/Map/CurrentMapStateRepository.cs | 4 ++-- EOLib/Domain/Map/IMapCellState.cs | 4 ++-- EOLib/Domain/Map/LockerDataRepository.cs | 4 ++-- EOLib/Domain/Map/MapCellState.cs | 4 ++-- EOLib/Domain/Map/MapCellStateProvider.cs | 6 +++--- EOLib/Domain/Map/MapCoordinate.cs | 4 ++-- EOLib/Domain/Map/MapItem.cs | 4 ++-- EOLib/Domain/Map/Sign.cs | 4 ++-- EOLib/Domain/Map/UnknownEntitiesRequestActions.cs | 4 ++-- EOLib/Domain/Map/UnlockChestValidator.cs | 4 ++-- EOLib/Domain/Map/UnlockDoorValidator.cs | 4 ++-- .../Notifiers/IOtherCharacterAnimationNotifier.cs | 4 ++-- EOLib/Domain/Notifiers/IUserInterfaceNotifier.cs | 4 ++-- EOLib/Domain/Online/OnlinePlayerRepository.cs | 4 ++-- EOLib/Domain/Party/PartyRepository.cs | 4 ++-- EOLib/Domain/Protocol/PingTimeRepository.cs | 4 ++-- EOLib/Domain/ResetStateAction.cs | 2 +- EOLib/Domain/Spells/SpellCastValidationActions.cs | 4 ++-- EOLib/Domain/Trade/TradeOffer.cs | 4 ++-- EOLib/Domain/Trade/TradeRepository.cs | 4 ++-- EOLib/HDSerialNumberService.cs | 4 ++-- EOLib/Net/Communication/INetworkClient.cs | 4 ++-- EOLib/Net/Communication/IPacketQueue.cs | 4 ++-- EOLib/Net/Communication/IPacketSendService.cs | 4 ++-- EOLib/Net/Communication/IWaitablePacketQueue.cs | 4 ++-- EOLib/Net/Communication/NetworkClient.cs | 10 +++++----- EOLib/Net/Communication/NetworkClientFactory.cs | 4 ++-- EOLib/Net/Communication/PacketQueue.cs | 4 ++-- EOLib/Net/Communication/PacketSendService.cs | 4 ++-- EOLib/Net/Communication/SafeAsyncNetworkOperation.cs | 4 ++-- .../Communication/SafeBlockingNetworkOperation.cs | 4 ++-- EOLib/Net/Communication/SafeNetworkOperationBase.cs | 4 ++-- .../Net/Communication/SafeNetworkOperationFactory.cs | 6 +++--- EOLib/Net/Connection/BackgroundReceiveActions.cs | 4 ++-- .../Connection/IBackgroundReceiveTaskRepository.cs | 4 ++-- EOLib/Net/Connection/INetworkConnectionActions.cs | 4 ++-- EOLib/Net/Connection/NetworkConnectionActions.cs | 6 +++--- EOLib/Net/FileTransfer/FileRequestActions.cs | 10 +++++----- EOLib/Net/FileTransfer/FileRequestService.cs | 8 ++++---- .../Net/FileTransfer/LoginFileChecksumRepository.cs | 4 ++-- EOLib/Net/Handlers/DefaultAsyncPacketHandler.cs | 4 ++-- EOLib/Net/Handlers/FamilyActionPair.cs | 4 ++-- EOLib/Net/Handlers/IPacketHandler.cs | 4 ++-- EOLib/Net/Handlers/PacketHandlerFinder.cs | 6 +++--- EOLib/Net/Handlers/PacketHandlerProvider.cs | 4 ++-- EOLib/Net/Handlers/PacketHandlingTypeFinder.cs | 6 +++--- EOLib/Net/PacketProcessing/PacketFactory.cs | 10 +++++----- EOLib/Net/PacketProcessing/PacketProcessActions.cs | 6 +++--- .../AdminInteract/AdminInteractAgree.cs | 4 ++-- .../AdminInteract/AdminInteractList.cs | 6 +++--- .../AdminInteract/AdminInteractRemove.cs | 4 ++-- .../AdminInteract/AdminInteractTell.cs | 4 ++-- EOLib/PacketHandlers/Arena/ArenaAcceptHandler.cs | 4 ++-- EOLib/PacketHandlers/Arena/ArenaDropHandler.cs | 4 ++-- EOLib/PacketHandlers/Arena/ArenaSpecHandler.cs | 4 ++-- EOLib/PacketHandlers/Arena/ArenaUseHandler.cs | 4 ++-- EOLib/PacketHandlers/Attack/AttackPlayerHandler.cs | 4 ++-- EOLib/PacketHandlers/Avatar/AvatarAdminHandler.cs | 4 ++-- EOLib/PacketHandlers/Avatar/AvatarRemoveHandler.cs | 4 ++-- EOLib/PacketHandlers/Avatar/AvatarReplyHandler.cs | 2 +- EOLib/PacketHandlers/Bank/BankReplyHandler.cs | 4 ++-- EOLib/PacketHandlers/Barber/BarberOpenHandler.cs | 2 +- EOLib/PacketHandlers/Board/BoardOpenHandler.cs | 4 ++-- EOLib/PacketHandlers/Cast/CastAcceptHandler.cs | 4 ++-- EOLib/PacketHandlers/Cast/CastReplyHandler.cs | 4 ++-- EOLib/PacketHandlers/Cast/CastSpecHandler.cs | 4 ++-- EOLib/PacketHandlers/Chat/AdminMessageHandler.cs | 4 ++-- EOLib/PacketHandlers/Chat/AnnounceMessageHandler.cs | 4 ++-- EOLib/PacketHandlers/Chat/GroupChatHandler.cs | 4 ++-- EOLib/PacketHandlers/Chat/MuteHandler.cs | 4 ++-- EOLib/PacketHandlers/Chat/PrivateMessageHandler.cs | 6 +++--- .../Chat/PrivateMessageTargetNotFound.cs | 4 ++-- EOLib/PacketHandlers/Chat/PublicChatHandler.cs | 4 ++-- EOLib/PacketHandlers/Chat/TalkServerHandler.cs | 4 ++-- EOLib/PacketHandlers/Chest/ChestAgreeHandler.cs | 6 +++--- EOLib/PacketHandlers/Chest/ChestCloseHandler.cs | 4 ++-- EOLib/PacketHandlers/Chest/ChestItemUpdateHandler.cs | 6 +++--- EOLib/PacketHandlers/Chest/ChestOpenHandler.cs | 6 +++--- EOLib/PacketHandlers/Citizen/CitizenOpenHandler.cs | 4 ++-- EOLib/PacketHandlers/Citizen/CitizenRemoveHandler.cs | 4 ++-- EOLib/PacketHandlers/Citizen/CitizenReplyHandler.cs | 4 ++-- .../PacketHandlers/Citizen/CitizenRequestHandler.cs | 4 ++-- EOLib/PacketHandlers/Commands/PingResponseHandler.cs | 4 ++-- EOLib/PacketHandlers/Door/DoorOpenHandler.cs | 4 ++-- EOLib/PacketHandlers/Effects/EffectAgreeHandler.cs | 4 ++-- EOLib/PacketHandlers/Effects/EffectPotionHandler.cs | 4 ++-- EOLib/PacketHandlers/Effects/MapDebuffHandler.cs | 6 +++--- EOLib/PacketHandlers/Effects/MapHpDrainHandler.cs | 4 ++-- EOLib/PacketHandlers/Effects/MapQuakeHandler.cs | 4 ++-- .../Effects/PlayerSpikeDamageHandler.cs | 4 ++-- .../Effects/TimedSpikeEffectHandler.cs | 6 +++--- EOLib/PacketHandlers/Emote/EmotePlayerHandler.cs | 4 ++-- EOLib/PacketHandlers/Init/FriendIgnoreListHandler.cs | 8 ++++---- EOLib/PacketHandlers/Init/InGameInitPacketHandler.cs | 4 ++-- EOLib/PacketHandlers/Init/MapMutationHandler.cs | 4 ++-- EOLib/PacketHandlers/Init/OnlinePlayerListHandler.cs | 6 +++--- EOLib/PacketHandlers/Items/ItemAcceptHandler.cs | 4 ++-- EOLib/PacketHandlers/Items/ItemAddHandler.cs | 4 ++-- EOLib/PacketHandlers/Items/ItemDropHandler.cs | 6 +++--- EOLib/PacketHandlers/Items/ItemGetHandler.cs | 4 ++-- EOLib/PacketHandlers/Items/ItemJunkHandler.cs | 4 ++-- EOLib/PacketHandlers/Items/ItemReplyHandler.cs | 8 ++++---- EOLib/PacketHandlers/Items/QuestItemChangeHandler.cs | 4 ++-- .../PacketHandlers/Jukebox/JukeboxMessageHandler.cs | 4 ++-- EOLib/PacketHandlers/Jukebox/JukeboxOpenHandler.cs | 4 ++-- EOLib/PacketHandlers/Jukebox/JukeboxPlayerHandler.cs | 4 ++-- EOLib/PacketHandlers/Jukebox/JukeboxReplyHandler.cs | 4 ++-- EOLib/PacketHandlers/Jukebox/JukeboxUseHandler.cs | 4 ++-- EOLib/PacketHandlers/Locker/LockerBuyHandler.cs | 4 ++-- EOLib/PacketHandlers/Locker/LockerModifyHandler.cs | 4 ++-- EOLib/PacketHandlers/Locker/LockerOpenHandler.cs | 4 ++-- EOLib/PacketHandlers/Locker/LockerSpecHandler.cs | 4 ++-- EOLib/PacketHandlers/MapInfo/MapInfoReplyHandler.cs | 4 ++-- EOLib/PacketHandlers/Marriage/MarriageOpenHandler.cs | 4 ++-- .../PacketHandlers/Marriage/MarriageReplyHandler.cs | 4 ++-- EOLib/PacketHandlers/Message/MessageAcceptHandler.cs | 6 +++--- EOLib/PacketHandlers/Message/MessageCloseHandler.cs | 4 ++-- EOLib/PacketHandlers/Music/MusicPlayerHandler.cs | 4 ++-- EOLib/PacketHandlers/NPC/NPCAcceptHandler.cs | 4 ++-- EOLib/PacketHandlers/NPC/NPCAgreeHandler.cs | 4 ++-- EOLib/PacketHandlers/NPC/NPCDeathHandler.cs | 6 +++--- EOLib/PacketHandlers/NPC/NPCDialogHandler.cs | 4 ++-- EOLib/PacketHandlers/NPC/NPCJunkHandler.cs | 6 +++--- EOLib/PacketHandlers/NPC/NPCPlayerHandler.cs | 7 +++---- EOLib/PacketHandlers/NPC/NPCReplyHandler.cs | 4 ++-- EOLib/PacketHandlers/NPC/NPCSpecHandler.cs | 6 +++--- EOLib/PacketHandlers/NPC/NPCTakeDamageHandler.cs | 4 ++-- EOLib/PacketHandlers/Paperdoll/ItemEquipHandler.cs | 4 ++-- EOLib/PacketHandlers/Party/PartyAddHandler.cs | 4 ++-- EOLib/PacketHandlers/Party/PartyCreateHandler.cs | 4 ++-- EOLib/PacketHandlers/Party/PartyRemoveHandler.cs | 4 ++-- EOLib/PacketHandlers/Party/PartyRequestHandler.cs | 4 ++-- EOLib/PacketHandlers/Players/PlayersAgreeHandler.cs | 6 +++--- EOLib/PacketHandlers/Priest/PriestOpenHandler.cs | 4 ++-- EOLib/PacketHandlers/Priest/PriestReplyHandler.cs | 4 ++-- EOLib/PacketHandlers/Priest/PriestRequestHandler.cs | 4 ++-- EOLib/PacketHandlers/Quest/QuestDialogHandler.cs | 6 +++--- EOLib/PacketHandlers/Quest/QuestListHandler.cs | 4 ++-- .../Quest/QuestStatusMessageHandler.cs | 4 ++-- EOLib/PacketHandlers/Recover/RecoverAgreeHandler.cs | 6 +++--- EOLib/PacketHandlers/Recover/RecoverReplyHandler.cs | 4 ++-- EOLib/PacketHandlers/Refresh/RefreshReplyHandler.cs | 7 +++---- EOLib/PacketHandlers/Shop/ShopCraftHandler.cs | 4 ++-- EOLib/PacketHandlers/Shop/ShopOpenHandler.cs | 6 +++--- EOLib/PacketHandlers/Shop/ShopTradeHandler.cs | 4 ++-- EOLib/PacketHandlers/Spell/SpellRequestHandler.cs | 4 ++-- .../PacketHandlers/Spell/SpellTargetGroupHandler.cs | 6 +++--- .../PacketHandlers/Spell/SpellTargetOtherHandler.cs | 4 ++-- EOLib/PacketHandlers/Spell/SpellTargetSelfHandler.cs | 4 ++-- .../PacketHandlers/StatSkill/StatskillJunkHandler.cs | 4 ++-- .../PacketHandlers/StatSkill/StatskillOpenHandler.cs | 6 +++--- .../StatSkill/StatskillRemoveHandler.cs | 4 ++-- .../StatSkill/StatskillReplyHandler.cs | 4 ++-- .../PacketHandlers/StatSkill/StatskillTakeHandler.cs | 6 +++--- EOLib/PacketHandlers/Trade/TradeCloseHandler.cs | 4 ++-- .../PacketHandlers/Trade/TradeOfferUpdateHandler.cs | 4 ++-- EOLib/PacketHandlers/Trade/TradeOpenHandler.cs | 4 ++-- EOLib/PacketHandlers/Trade/TradeRequestHandler.cs | 4 ++-- EOLib/PacketHandlers/Trade/TradeUseHandler.cs | 4 ++-- EOLib/PacketHandlers/Walk/WalkPlayerHandler.cs | 4 ++-- EOLib/PacketHandlers/Walk/WalkReplyHandler.cs | 4 ++-- EOLib/PacketHandlers/Warp/WarpAgreeHandler.cs | 9 ++++----- EOLib/PacketHandlers/Warp/WarpRequestHandler.cs | 6 +++--- 304 files changed, 736 insertions(+), 740 deletions(-) diff --git a/.editorconfig b/.editorconfig index 596bca640..a90241775 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,7 +13,7 @@ tab_width = 4 # New line preferences end_of_line = crlf -insert_final_newline = false +insert_final_newline = true #### .NET Coding Conventions #### diff --git a/BatchMap/Program.cs b/BatchMap/Program.cs index c88ed8e56..42606e4cc 100644 --- a/BatchMap/Program.cs +++ b/BatchMap/Program.cs @@ -1,12 +1,12 @@ -using AutomaticTypeMapper; +using System; +using System.IO; +using System.Linq; +using AutomaticTypeMapper; using EOLib; using EOLib.IO.Actions; using EOLib.IO.Map; using EOLib.IO.Repositories; using EOLib.IO.Services; -using System; -using System.IO; -using System.Linq; namespace BatchMap { diff --git a/EOBot/ArgumentsParser.cs b/EOBot/ArgumentsParser.cs index a0a0c7a6a..0face5c1c 100644 --- a/EOBot/ArgumentsParser.cs +++ b/EOBot/ArgumentsParser.cs @@ -1,7 +1,7 @@ -using EOBot.Interpreter.Variables; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; +using EOBot.Interpreter.Variables; namespace EOBot { diff --git a/EOBot/BotBase.cs b/EOBot/BotBase.cs index 731bcded0..aae6ea06c 100644 --- a/EOBot/BotBase.cs +++ b/EOBot/BotBase.cs @@ -1,4 +1,7 @@ -using EOLib; +using System; +using System.Threading; +using System.Threading.Tasks; +using EOLib; using EOLib.Config; using EOLib.Domain.Protocol; using EOLib.Net.Communication; @@ -6,9 +9,6 @@ using EOLib.Net.PacketProcessing; using Moffat.EndlessOnline.SDK.Packet; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Threading; -using System.Threading.Tasks; namespace EOBot { diff --git a/EOBot/BotFramework.cs b/EOBot/BotFramework.cs index 732455115..1a61d4e4c 100644 --- a/EOBot/BotFramework.cs +++ b/EOBot/BotFramework.cs @@ -1,9 +1,9 @@ -using EOLib.Net.Handlers; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using EOLib.Net.Handlers; namespace EOBot { diff --git a/EOBot/BotHelper.cs b/EOBot/BotHelper.cs index 373f4addd..e4d1a3a71 100644 --- a/EOBot/BotHelper.cs +++ b/EOBot/BotHelper.cs @@ -1,4 +1,8 @@ -using EOLib.Domain.Account; +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using EOLib.Domain.Account; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -7,10 +11,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional.Collections; -using System; -using System.IO; -using System.Linq; -using System.Threading.Tasks; namespace EOBot { diff --git a/EOBot/Interpreter/BotInterpreter.cs b/EOBot/Interpreter/BotInterpreter.cs index 4be01ea55..0f1c62830 100644 --- a/EOBot/Interpreter/BotInterpreter.cs +++ b/EOBot/Interpreter/BotInterpreter.cs @@ -1,8 +1,8 @@ -using EOBot.Interpreter.States; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; +using EOBot.Interpreter.States; namespace EOBot.Interpreter { diff --git a/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs b/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs index 7069b8c51..139c58898 100644 --- a/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs +++ b/EOBot/Interpreter/BuiltInIdentifierConfigurator.cs @@ -1,4 +1,9 @@ -using EOBot.Interpreter.States; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using EOBot.Interpreter.States; using EOBot.Interpreter.Variables; using EOLib; using EOLib.Config; @@ -15,11 +20,6 @@ using Moffat.EndlessOnline.SDK.Packet; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; namespace EOBot.Interpreter { diff --git a/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs b/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs index 974525d41..04b9010eb 100644 --- a/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs +++ b/EOBot/Interpreter/Extensions/SymbolTableExtensions.cs @@ -1,6 +1,6 @@ -using EOBot.Interpreter.States; +using System.Collections.Generic; +using EOBot.Interpreter.States; using EOBot.Interpreter.Variables; -using System.Collections.Generic; namespace EOBot.Interpreter.Extensions { diff --git a/EOBot/Interpreter/States/AssignmentEvaluator.cs b/EOBot/Interpreter/States/AssignmentEvaluator.cs index 4cd58275e..72e60a991 100644 --- a/EOBot/Interpreter/States/AssignmentEvaluator.cs +++ b/EOBot/Interpreter/States/AssignmentEvaluator.cs @@ -1,8 +1,8 @@ -using EOBot.Interpreter.Extensions; -using EOBot.Interpreter.Variables; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; +using EOBot.Interpreter.Variables; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/BlockEvaluator.cs b/EOBot/Interpreter/States/BlockEvaluator.cs index eca9cec26..ad9880e07 100644 --- a/EOBot/Interpreter/States/BlockEvaluator.cs +++ b/EOBot/Interpreter/States/BlockEvaluator.cs @@ -1,6 +1,6 @@ -using EOBot.Interpreter.Extensions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/ExpressionEvaluator.cs b/EOBot/Interpreter/States/ExpressionEvaluator.cs index 1df7948e7..8b70a3916 100644 --- a/EOBot/Interpreter/States/ExpressionEvaluator.cs +++ b/EOBot/Interpreter/States/ExpressionEvaluator.cs @@ -1,8 +1,8 @@ -using EOBot.Interpreter.Extensions; -using EOBot.Interpreter.Variables; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; +using EOBot.Interpreter.Variables; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/ExpressionTailEvaluator.cs b/EOBot/Interpreter/States/ExpressionTailEvaluator.cs index c24d311dd..87b30b8e0 100644 --- a/EOBot/Interpreter/States/ExpressionTailEvaluator.cs +++ b/EOBot/Interpreter/States/ExpressionTailEvaluator.cs @@ -1,6 +1,6 @@ -using EOBot.Interpreter.Extensions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/FunctionEvaluator.cs b/EOBot/Interpreter/States/FunctionEvaluator.cs index 8888e0837..a1c0d5586 100644 --- a/EOBot/Interpreter/States/FunctionEvaluator.cs +++ b/EOBot/Interpreter/States/FunctionEvaluator.cs @@ -1,9 +1,9 @@ -using EOBot.Interpreter.Extensions; -using EOBot.Interpreter.Variables; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; +using EOBot.Interpreter.Variables; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/GotoEvaluator.cs b/EOBot/Interpreter/States/GotoEvaluator.cs index 71c2d5292..1b8bd400a 100644 --- a/EOBot/Interpreter/States/GotoEvaluator.cs +++ b/EOBot/Interpreter/States/GotoEvaluator.cs @@ -1,5 +1,5 @@ -using EOBot.Interpreter.Extensions; -using System.Threading.Tasks; +using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/IfEvaluator.cs b/EOBot/Interpreter/States/IfEvaluator.cs index 1285e7df0..9e4b72f46 100644 --- a/EOBot/Interpreter/States/IfEvaluator.cs +++ b/EOBot/Interpreter/States/IfEvaluator.cs @@ -1,6 +1,6 @@ -using EOBot.Interpreter.Extensions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/LabelEvaluator.cs b/EOBot/Interpreter/States/LabelEvaluator.cs index def562c1c..77bd9fc13 100644 --- a/EOBot/Interpreter/States/LabelEvaluator.cs +++ b/EOBot/Interpreter/States/LabelEvaluator.cs @@ -1,5 +1,5 @@ -using EOBot.Interpreter.Extensions; -using System.Threading.Tasks; +using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/OperandEvaluator.cs b/EOBot/Interpreter/States/OperandEvaluator.cs index 058dbb9a3..7d81db58e 100644 --- a/EOBot/Interpreter/States/OperandEvaluator.cs +++ b/EOBot/Interpreter/States/OperandEvaluator.cs @@ -1,6 +1,6 @@ -using EOBot.Interpreter.Extensions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/ProgramState.cs b/EOBot/Interpreter/States/ProgramState.cs index 5ce7906d7..819273129 100644 --- a/EOBot/Interpreter/States/ProgramState.cs +++ b/EOBot/Interpreter/States/ProgramState.cs @@ -1,7 +1,7 @@ -using EOBot.Interpreter.Variables; -using System; +using System; using System.Collections.Generic; using System.Linq; +using EOBot.Interpreter.Variables; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/ScriptEvaluator.cs b/EOBot/Interpreter/States/ScriptEvaluator.cs index 93cf583c1..40426a6c3 100644 --- a/EOBot/Interpreter/States/ScriptEvaluator.cs +++ b/EOBot/Interpreter/States/ScriptEvaluator.cs @@ -1,6 +1,6 @@ -using EOBot.Interpreter.Extensions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/StatementEvaluator.cs b/EOBot/Interpreter/States/StatementEvaluator.cs index cda9f1fb4..8aa2e90c8 100644 --- a/EOBot/Interpreter/States/StatementEvaluator.cs +++ b/EOBot/Interpreter/States/StatementEvaluator.cs @@ -1,6 +1,6 @@ -using EOBot.Interpreter.Extensions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/VariableEvaluator.cs b/EOBot/Interpreter/States/VariableEvaluator.cs index 44f2ff5d7..babb260a2 100644 --- a/EOBot/Interpreter/States/VariableEvaluator.cs +++ b/EOBot/Interpreter/States/VariableEvaluator.cs @@ -1,7 +1,7 @@ -using EOBot.Interpreter.Extensions; -using EOBot.Interpreter.Variables; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; +using EOBot.Interpreter.Variables; namespace EOBot.Interpreter.States { diff --git a/EOBot/Interpreter/States/WhileEvaluator.cs b/EOBot/Interpreter/States/WhileEvaluator.cs index b8b576296..4c29ec5a3 100644 --- a/EOBot/Interpreter/States/WhileEvaluator.cs +++ b/EOBot/Interpreter/States/WhileEvaluator.cs @@ -1,6 +1,6 @@ -using EOBot.Interpreter.Extensions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using EOBot.Interpreter.Extensions; namespace EOBot.Interpreter.States { diff --git a/EOBot/Program.cs b/EOBot/Program.cs index 48acacfc4..2cbc6e2fa 100644 --- a/EOBot/Program.cs +++ b/EOBot/Program.cs @@ -1,4 +1,8 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EOBot.Interpreter; using EOLib; using EOLib.Domain.Character; @@ -9,10 +13,6 @@ using EOLib.Domain.Spells; using EOLib.IO.Repositories; using Optional; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace EOBot { diff --git a/EOBot/ScriptedBot.cs b/EOBot/ScriptedBot.cs index bd5c2a5d5..e9f3dd08f 100644 --- a/EOBot/ScriptedBot.cs +++ b/EOBot/ScriptedBot.cs @@ -1,9 +1,9 @@ -using EOBot.Interpreter; -using EOBot.Interpreter.States; -using EOBot.Interpreter.Variables; -using System; +using System; using System.Threading; using System.Threading.Tasks; +using EOBot.Interpreter; +using EOBot.Interpreter.States; +using EOBot.Interpreter.Variables; namespace EOBot { diff --git a/EOBot/TrainerBot.cs b/EOBot/TrainerBot.cs index ad1245c55..011ff9575 100644 --- a/EOBot/TrainerBot.cs +++ b/EOBot/TrainerBot.cs @@ -1,4 +1,9 @@ -using EOLib; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using EOLib; using EOLib.Domain.Account; using EOLib.Domain.Character; using EOLib.Domain.Chat; @@ -12,11 +17,6 @@ using EOLib.Net; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; namespace EOBot { diff --git a/EOLib.Config.Test/AssemblyInitializer.cs b/EOLib.Config.Test/AssemblyInitializer.cs index fc78224d8..181f39823 100644 --- a/EOLib.Config.Test/AssemblyInitializer.cs +++ b/EOLib.Config.Test/AssemblyInitializer.cs @@ -1,5 +1,5 @@ -using NUnit.Framework; -using System.IO; +using System.IO; +using NUnit.Framework; [SetUpFixture] public class AssemblyInitializer diff --git a/EOLib.Config.Test/ConfigFileLoadActionsTest.cs b/EOLib.Config.Test/ConfigFileLoadActionsTest.cs index 3b7fa6496..7c3d5f461 100644 --- a/EOLib.Config.Test/ConfigFileLoadActionsTest.cs +++ b/EOLib.Config.Test/ConfigFileLoadActionsTest.cs @@ -1,6 +1,6 @@ -using NUnit.Framework; -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.IO; +using NUnit.Framework; namespace EOLib.Config.Test { diff --git a/EOLib.Config.Test/IniReaderTest.cs b/EOLib.Config.Test/IniReaderTest.cs index 3b45a75d1..324a61ed2 100644 --- a/EOLib.Config.Test/IniReaderTest.cs +++ b/EOLib.Config.Test/IniReaderTest.cs @@ -1,6 +1,6 @@ -using NUnit.Framework; -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.IO; +using NUnit.Framework; namespace EOLib.Config.Test { diff --git a/EOLib.Config/ConfigFileLoadActions.cs b/EOLib.Config/ConfigFileLoadActions.cs index 5bedaca3e..05b7f03ae 100644 --- a/EOLib.Config/ConfigFileLoadActions.cs +++ b/EOLib.Config/ConfigFileLoadActions.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System; +using System; +using AutomaticTypeMapper; namespace EOLib.Config { diff --git a/EOLib.Config/IConfigurationRepository.cs b/EOLib.Config/IConfigurationRepository.cs index 46b4e110d..6c756757b 100644 --- a/EOLib.Config/IConfigurationRepository.cs +++ b/EOLib.Config/IConfigurationRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System; +using System; +using AutomaticTypeMapper; namespace EOLib.Config { diff --git a/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs b/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs index b0d45a271..e2befc452 100644 --- a/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs +++ b/EOLib.Graphics.Test/GraphicsDeviceTestHelper.cs @@ -1,8 +1,8 @@ -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System; +using System; using System.ComponentModel.Design; using System.Diagnostics.CodeAnalysis; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; namespace EOLib.Graphics.Test { diff --git a/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs b/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs index e0442036c..a8705a5af 100644 --- a/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs +++ b/EOLib.Graphics.Test/NativeGraphicsLoaderTest.cs @@ -1,10 +1,10 @@ -using Moq; -using NUnit.Framework; -using PELoaderLib; -using System; +using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; +using Moq; +using NUnit.Framework; +using PELoaderLib; namespace EOLib.Graphics.Test { diff --git a/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs b/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs index 2373ed3d6..b5e3eea43 100644 --- a/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs +++ b/EOLib.Graphics.Test/NativeGraphicsManagerTest.cs @@ -1,10 +1,10 @@ -using Microsoft.Xna.Framework; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Moq; using NUnit.Framework; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; namespace EOLib.Graphics.Test { diff --git a/EOLib.Graphics.Test/PEFileCollectionTest.cs b/EOLib.Graphics.Test/PEFileCollectionTest.cs index 229246829..7c8458f41 100644 --- a/EOLib.Graphics.Test/PEFileCollectionTest.cs +++ b/EOLib.Graphics.Test/PEFileCollectionTest.cs @@ -1,10 +1,10 @@ -using Moq; -using NUnit.Framework; -using PELoaderLib; -using System; +using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; +using Moq; +using NUnit.Framework; +using PELoaderLib; namespace EOLib.Graphics.Test { diff --git a/EOLib.Graphics.Test/RectangleExtensionTest.cs b/EOLib.Graphics.Test/RectangleExtensionTest.cs index 173fed9df..4c12f982d 100644 --- a/EOLib.Graphics.Test/RectangleExtensionTest.cs +++ b/EOLib.Graphics.Test/RectangleExtensionTest.cs @@ -1,6 +1,6 @@ -using Microsoft.Xna.Framework; +using System.Diagnostics.CodeAnalysis; +using Microsoft.Xna.Framework; using NUnit.Framework; -using System.Diagnostics.CodeAnalysis; namespace EOLib.Graphics.Test { diff --git a/EOLib.Graphics/ColorConstants.cs b/EOLib.Graphics/ColorConstants.cs index 263e332c4..e16585bdb 100644 --- a/EOLib.Graphics/ColorConstants.cs +++ b/EOLib.Graphics/ColorConstants.cs @@ -1,5 +1,5 @@ -using Microsoft.Xna.Framework; using System.Diagnostics.CodeAnalysis; +using Microsoft.Xna.Framework; namespace EOLib.Graphics { diff --git a/EOLib.Graphics/INativeGraphicsManager.cs b/EOLib.Graphics/INativeGraphicsManager.cs index 369272294..db5f6c351 100644 --- a/EOLib.Graphics/INativeGraphicsManager.cs +++ b/EOLib.Graphics/INativeGraphicsManager.cs @@ -1,5 +1,5 @@ -using Microsoft.Xna.Framework.Graphics; -using System; +using System; +using Microsoft.Xna.Framework.Graphics; namespace EOLib.Graphics { diff --git a/EOLib.Graphics/NativeGraphicsLoader.cs b/EOLib.Graphics/NativeGraphicsLoader.cs index 208c961b4..6066e2080 100644 --- a/EOLib.Graphics/NativeGraphicsLoader.cs +++ b/EOLib.Graphics/NativeGraphicsLoader.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System; +using System; +using AutomaticTypeMapper; namespace EOLib.Graphics { diff --git a/EOLib.Graphics/NativeGraphicsManager.cs b/EOLib.Graphics/NativeGraphicsManager.cs index 9e68c5513..d387d5474 100644 --- a/EOLib.Graphics/NativeGraphicsManager.cs +++ b/EOLib.Graphics/NativeGraphicsManager.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; -using CommunityToolkit.HighPerformance; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; +using AutomaticTypeMapper; +using CommunityToolkit.HighPerformance; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; namespace EOLib.Graphics { diff --git a/EOLib.Graphics/PEFileCollection.cs b/EOLib.Graphics/PEFileCollection.cs index 01671d0d4..6902aeec2 100644 --- a/EOLib.Graphics/PEFileCollection.cs +++ b/EOLib.Graphics/PEFileCollection.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; -using PELoaderLib; -using System; +using System; using System.Collections.Generic; using System.IO; +using AutomaticTypeMapper; +using PELoaderLib; namespace EOLib.Graphics { diff --git a/EOLib.IO.Test/EIFRecordExtensionsTest.cs b/EOLib.IO.Test/EIFRecordExtensionsTest.cs index d0dc6f4d2..1a7aef846 100644 --- a/EOLib.IO.Test/EIFRecordExtensionsTest.cs +++ b/EOLib.IO.Test/EIFRecordExtensionsTest.cs @@ -1,7 +1,7 @@ -using EOLib.IO.Extensions; +using System.Diagnostics.CodeAnalysis; +using EOLib.IO.Extensions; using EOLib.IO.Pub; using NUnit.Framework; -using System.Diagnostics.CodeAnalysis; namespace EOLib.IO.Test { diff --git a/EOLib.IO.Test/Map/MapFilePropertiesTest.cs b/EOLib.IO.Test/Map/MapFilePropertiesTest.cs index 08a70bc5f..0850ca6ea 100644 --- a/EOLib.IO.Test/Map/MapFilePropertiesTest.cs +++ b/EOLib.IO.Test/Map/MapFilePropertiesTest.cs @@ -1,14 +1,14 @@ -using EOLib.IO.Map; -using EOLib.IO.Services; -using EOLib.IO.Services.Serializers; -using NUnit.Framework; -using System; +using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Text; +using EOLib.IO.Map; +using EOLib.IO.Services; +using EOLib.IO.Services.Serializers; +using NUnit.Framework; namespace EOLib.IO.Test.Map { diff --git a/EOLib.IO.Test/Map/MapFileTest.cs b/EOLib.IO.Test/Map/MapFileTest.cs index 7b4d7e272..89d86977d 100644 --- a/EOLib.IO.Test/Map/MapFileTest.cs +++ b/EOLib.IO.Test/Map/MapFileTest.cs @@ -1,11 +1,11 @@ -using EOLib.IO.Map; -using EOLib.IO.Services; -using EOLib.IO.Services.Serializers; -using NUnit.Framework; -using System; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; +using EOLib.IO.Map; +using EOLib.IO.Services; +using EOLib.IO.Services.Serializers; +using NUnit.Framework; namespace EOLib.IO.Test.Map { diff --git a/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs b/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs index c335b98c5..e87cb9c57 100644 --- a/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs +++ b/EOLib.IO.Test/Map/MapStringEncoderServiceTest.cs @@ -1,9 +1,9 @@ -using EOLib.IO.Services; -using NUnit.Framework; -using System; +using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; +using EOLib.IO.Services; +using NUnit.Framework; namespace EOLib.IO.Test.Map { diff --git a/EOLib.IO.Test/Pub/BasePubFileTest.cs b/EOLib.IO.Test/Pub/BasePubFileTest.cs index e134471e7..94b1dfea9 100644 --- a/EOLib.IO.Test/Pub/BasePubFileTest.cs +++ b/EOLib.IO.Test/Pub/BasePubFileTest.cs @@ -1,7 +1,7 @@ -using EOLib.IO.Pub; -using NUnit.Framework; -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using EOLib.IO.Pub; +using NUnit.Framework; namespace EOLib.IO.Test.Pub { diff --git a/EOLib.IO.Test/Pub/ECFFileTest.cs b/EOLib.IO.Test/Pub/ECFFileTest.cs index 62f571cb2..8c9e1a990 100644 --- a/EOLib.IO.Test/Pub/ECFFileTest.cs +++ b/EOLib.IO.Test/Pub/ECFFileTest.cs @@ -1,6 +1,6 @@ -using EOLib.IO.Pub; +using System.Diagnostics.CodeAnalysis; +using EOLib.IO.Pub; using NUnit.Framework; -using System.Diagnostics.CodeAnalysis; namespace EOLib.IO.Test.Pub { diff --git a/EOLib.IO.Test/Pub/ECFRecordTest.cs b/EOLib.IO.Test/Pub/ECFRecordTest.cs index 76566a938..0f7d7002a 100644 --- a/EOLib.IO.Test/Pub/ECFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ECFRecordTest.cs @@ -1,8 +1,8 @@ -using EOLib.IO.Pub; -using NUnit.Framework; -using System; +using System; using System.Diagnostics.CodeAnalysis; using System.Linq; +using EOLib.IO.Pub; +using NUnit.Framework; namespace EOLib.IO.Test.Pub { diff --git a/EOLib.IO.Test/Pub/EIFFileTest.cs b/EOLib.IO.Test/Pub/EIFFileTest.cs index bb2f90cac..d5ebad4a9 100644 --- a/EOLib.IO.Test/Pub/EIFFileTest.cs +++ b/EOLib.IO.Test/Pub/EIFFileTest.cs @@ -1,6 +1,6 @@ -using EOLib.IO.Pub; +using System.Diagnostics.CodeAnalysis; +using EOLib.IO.Pub; using NUnit.Framework; -using System.Diagnostics.CodeAnalysis; namespace EOLib.IO.Test.Pub { diff --git a/EOLib.IO.Test/Pub/EIFRecordTest.cs b/EOLib.IO.Test/Pub/EIFRecordTest.cs index e3840beea..77f9b0e18 100644 --- a/EOLib.IO.Test/Pub/EIFRecordTest.cs +++ b/EOLib.IO.Test/Pub/EIFRecordTest.cs @@ -1,8 +1,8 @@ -using EOLib.IO.Pub; -using NUnit.Framework; -using System; +using System; using System.Diagnostics.CodeAnalysis; using System.Linq; +using EOLib.IO.Pub; +using NUnit.Framework; namespace EOLib.IO.Test.Pub { diff --git a/EOLib.IO.Test/Pub/ENFFileTest.cs b/EOLib.IO.Test/Pub/ENFFileTest.cs index 89d74be44..506ed4bca 100644 --- a/EOLib.IO.Test/Pub/ENFFileTest.cs +++ b/EOLib.IO.Test/Pub/ENFFileTest.cs @@ -1,6 +1,6 @@ -using EOLib.IO.Pub; +using System.Diagnostics.CodeAnalysis; +using EOLib.IO.Pub; using NUnit.Framework; -using System.Diagnostics.CodeAnalysis; namespace EOLib.IO.Test.Pub { diff --git a/EOLib.IO.Test/Pub/ENFRecordTest.cs b/EOLib.IO.Test/Pub/ENFRecordTest.cs index 175effd1c..9458f3451 100644 --- a/EOLib.IO.Test/Pub/ENFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ENFRecordTest.cs @@ -1,8 +1,8 @@ -using EOLib.IO.Pub; -using NUnit.Framework; -using System; +using System; using System.Diagnostics.CodeAnalysis; using System.Linq; +using EOLib.IO.Pub; +using NUnit.Framework; namespace EOLib.IO.Test.Pub { diff --git a/EOLib.IO.Test/Pub/ESFFileTest.cs b/EOLib.IO.Test/Pub/ESFFileTest.cs index ec0bfca2d..73f4fd41f 100644 --- a/EOLib.IO.Test/Pub/ESFFileTest.cs +++ b/EOLib.IO.Test/Pub/ESFFileTest.cs @@ -1,6 +1,6 @@ -using EOLib.IO.Pub; +using System.Diagnostics.CodeAnalysis; +using EOLib.IO.Pub; using NUnit.Framework; -using System.Diagnostics.CodeAnalysis; namespace EOLib.IO.Test.Pub { diff --git a/EOLib.IO.Test/Pub/ESFRecordTest.cs b/EOLib.IO.Test/Pub/ESFRecordTest.cs index 361c8c8b5..ee267fd0f 100644 --- a/EOLib.IO.Test/Pub/ESFRecordTest.cs +++ b/EOLib.IO.Test/Pub/ESFRecordTest.cs @@ -1,8 +1,8 @@ -using EOLib.IO.Pub; -using NUnit.Framework; -using System; +using System; using System.Diagnostics.CodeAnalysis; using System.Linq; +using EOLib.IO.Pub; +using NUnit.Framework; namespace EOLib.IO.Test.Pub { diff --git a/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs b/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs index d27c0a779..d03902e10 100644 --- a/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs +++ b/EOLib.IO.Test/Services/Serializers/PubFileSerializerTest.cs @@ -1,12 +1,12 @@ -using EOLib.IO.Pub; -using EOLib.IO.Services; -using EOLib.IO.Services.Serializers; -using NUnit.Framework; -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; +using EOLib.IO.Pub; +using EOLib.IO.Services; +using EOLib.IO.Services.Serializers; +using NUnit.Framework; namespace EOLib.IO.Test.Services.Serializers { diff --git a/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs b/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs index cc0efb3b0..336fc79cf 100644 --- a/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs +++ b/EOLib.IO.Test/Services/Serializers/PubRecordSerializerTest.cs @@ -1,8 +1,8 @@ -using EOLib.IO.Pub; +using System.Collections.Generic; +using EOLib.IO.Pub; using EOLib.IO.Services; using EOLib.IO.Services.Serializers; using NUnit.Framework; -using System.Collections.Generic; namespace EOLib.IO.Test.Services.Serializers { diff --git a/EOLib.IO/Actions/PubFileLoadActions.cs b/EOLib.IO/Actions/PubFileLoadActions.cs index ccecea1e2..6f666ca4b 100644 --- a/EOLib.IO/Actions/PubFileLoadActions.cs +++ b/EOLib.IO/Actions/PubFileLoadActions.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.IO; +using System.Linq; +using AutomaticTypeMapper; using EOLib.IO.Extensions; using EOLib.IO.Pub; using EOLib.IO.Repositories; using EOLib.IO.Services; -using System.IO; -using System.Linq; namespace EOLib.IO.Actions { diff --git a/EOLib.IO/Extensions/PubFileExtensions.cs b/EOLib.IO/Extensions/PubFileExtensions.cs index 7ab752562..577339825 100644 --- a/EOLib.IO/Extensions/PubFileExtensions.cs +++ b/EOLib.IO/Extensions/PubFileExtensions.cs @@ -1,7 +1,7 @@ -using EOLib.IO.Pub; -using System; +using System; using System.Collections.Generic; using System.Linq; +using EOLib.IO.Pub; namespace EOLib.IO.Extensions { diff --git a/EOLib.IO/Pub/ECFRecord.cs b/EOLib.IO/Pub/ECFRecord.cs index 685156c8c..b122685d5 100644 --- a/EOLib.IO/Pub/ECFRecord.cs +++ b/EOLib.IO/Pub/ECFRecord.cs @@ -1,10 +1,10 @@ -using EOLib.IO.Services; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; +using EOLib.IO.Services; namespace EOLib.IO.Pub { diff --git a/EOLib.IO/Repositories/IMapFileRepository.cs b/EOLib.IO/Repositories/IMapFileRepository.cs index b28d9d189..1fb62752d 100644 --- a/EOLib.IO/Repositories/IMapFileRepository.cs +++ b/EOLib.IO/Repositories/IMapFileRepository.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.IO.Map; -using System.Collections.Generic; namespace EOLib.IO.Repositories { diff --git a/EOLib.IO/Repositories/IPubFileRepository.cs b/EOLib.IO/Repositories/IPubFileRepository.cs index be3485cf9..3462a3fa7 100644 --- a/EOLib.IO/Repositories/IPubFileRepository.cs +++ b/EOLib.IO/Repositories/IPubFileRepository.cs @@ -1,5 +1,5 @@ -using EOLib.IO.Pub; -using System.Collections.Generic; +using System.Collections.Generic; +using EOLib.IO.Pub; namespace EOLib.IO.Repositories { diff --git a/EOLib.IO/Repositories/PubFileRepository.cs b/EOLib.IO/Repositories/PubFileRepository.cs index 2b705e8d2..157ab4c68 100644 --- a/EOLib.IO/Repositories/PubFileRepository.cs +++ b/EOLib.IO/Repositories/PubFileRepository.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.IO.Pub; -using System.Collections.Generic; namespace EOLib.IO.Repositories { diff --git a/EOLib.IO/Services/BasePubLoadService.cs b/EOLib.IO/Services/BasePubLoadService.cs index 0e0667ddf..b7a706fe7 100644 --- a/EOLib.IO/Services/BasePubLoadService.cs +++ b/EOLib.IO/Services/BasePubLoadService.cs @@ -1,8 +1,8 @@ -using EOLib.IO.Pub; -using EOLib.IO.Services.Serializers; -using System; +using System; using System.Collections.Generic; using System.IO; +using EOLib.IO.Pub; +using EOLib.IO.Services.Serializers; namespace EOLib.IO.Services { diff --git a/EOLib.IO/Services/IPubLoadService.cs b/EOLib.IO/Services/IPubLoadService.cs index 9cdc07737..e9febbd6f 100644 --- a/EOLib.IO/Services/IPubLoadService.cs +++ b/EOLib.IO/Services/IPubLoadService.cs @@ -1,5 +1,5 @@ -using EOLib.IO.Pub; -using System.Collections.Generic; +using System.Collections.Generic; +using EOLib.IO.Pub; namespace EOLib.IO.Services { diff --git a/EOLib.IO/Services/MapFileLoadService.cs b/EOLib.IO/Services/MapFileLoadService.cs index 7632e56b0..3bd23bda9 100644 --- a/EOLib.IO/Services/MapFileLoadService.cs +++ b/EOLib.IO/Services/MapFileLoadService.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; +using System.IO; +using AutomaticTypeMapper; using EOLib.IO.Map; using EOLib.IO.Services.Serializers; -using System.IO; namespace EOLib.IO.Services { diff --git a/EOLib.IO/Services/MapFileSaveService.cs b/EOLib.IO/Services/MapFileSaveService.cs index fbb2790a4..77aa5011a 100644 --- a/EOLib.IO/Services/MapFileSaveService.cs +++ b/EOLib.IO/Services/MapFileSaveService.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; +using System; +using System.IO; +using AutomaticTypeMapper; using EOLib.IO.Map; using EOLib.IO.Services.Serializers; -using System; -using System.IO; namespace EOLib.IO.Services { diff --git a/EOLib.IO/Services/MapStringEncoderService.cs b/EOLib.IO/Services/MapStringEncoderService.cs index db9c82a77..c3152dced 100644 --- a/EOLib.IO/Services/MapStringEncoderService.cs +++ b/EOLib.IO/Services/MapStringEncoderService.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using System; +using System; using System.Linq; using System.Text; +using AutomaticTypeMapper; namespace EOLib.IO.Services { diff --git a/EOLib.IO/Services/NumberEncoderService.cs b/EOLib.IO/Services/NumberEncoderService.cs index e86a863de..898f5d21b 100644 --- a/EOLib.IO/Services/NumberEncoderService.cs +++ b/EOLib.IO/Services/NumberEncoderService.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using Moffat.EndlessOnline.SDK.Data; -using System; namespace EOLib.IO.Services { diff --git a/EOLib.IO/Services/PubFileSaveService.cs b/EOLib.IO/Services/PubFileSaveService.cs index 024dfc9ec..8c5094c37 100644 --- a/EOLib.IO/Services/PubFileSaveService.cs +++ b/EOLib.IO/Services/PubFileSaveService.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; +using System.IO; +using AutomaticTypeMapper; using EOLib.IO.Pub; using EOLib.IO.Services.Serializers; -using System.IO; namespace EOLib.IO.Services { diff --git a/EOLib.IO/Services/Serializers/ChestSpawnMapEntitySerializer.cs b/EOLib.IO/Services/Serializers/ChestSpawnMapEntitySerializer.cs index dad2f552a..e9706c8e2 100644 --- a/EOLib.IO/Services/Serializers/ChestSpawnMapEntitySerializer.cs +++ b/EOLib.IO/Services/Serializers/ChestSpawnMapEntitySerializer.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using EOLib.IO.Map; -using System; +using System; using System.Collections.Generic; +using AutomaticTypeMapper; +using EOLib.IO.Map; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.IO/Services/Serializers/IPubFileDeserializer.cs b/EOLib.IO/Services/Serializers/IPubFileDeserializer.cs index 064e50308..2c8b61349 100644 --- a/EOLib.IO/Services/Serializers/IPubFileDeserializer.cs +++ b/EOLib.IO/Services/Serializers/IPubFileDeserializer.cs @@ -1,5 +1,5 @@ -using EOLib.IO.Pub; -using System; +using System; +using EOLib.IO.Pub; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.IO/Services/Serializers/IPubRecordSerializer.cs b/EOLib.IO/Services/Serializers/IPubRecordSerializer.cs index 2663bf14d..ffb46aed7 100644 --- a/EOLib.IO/Services/Serializers/IPubRecordSerializer.cs +++ b/EOLib.IO/Services/Serializers/IPubRecordSerializer.cs @@ -1,5 +1,5 @@ -using EOLib.IO.Pub; -using System; +using System; +using EOLib.IO.Pub; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.IO/Services/Serializers/MapFileSerializer.cs b/EOLib.IO/Services/Serializers/MapFileSerializer.cs index 3ed94b47c..2e5c36814 100644 --- a/EOLib.IO/Services/Serializers/MapFileSerializer.cs +++ b/EOLib.IO/Services/Serializers/MapFileSerializer.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; -using EOLib.IO.Map; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; +using AutomaticTypeMapper; +using EOLib.IO.Map; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.IO/Services/Serializers/MapPropertiesSerializer.cs b/EOLib.IO/Services/Serializers/MapPropertiesSerializer.cs index bc98c8e80..276a582e5 100644 --- a/EOLib.IO/Services/Serializers/MapPropertiesSerializer.cs +++ b/EOLib.IO/Services/Serializers/MapPropertiesSerializer.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; -using EOLib.IO.Map; -using Moffat.EndlessOnline.SDK.Data; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using AutomaticTypeMapper; +using EOLib.IO.Map; +using Moffat.EndlessOnline.SDK.Data; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.IO/Services/Serializers/NPCSpawnMapEntitySerializer.cs b/EOLib.IO/Services/Serializers/NPCSpawnMapEntitySerializer.cs index a404f8ecb..c1efc5286 100644 --- a/EOLib.IO/Services/Serializers/NPCSpawnMapEntitySerializer.cs +++ b/EOLib.IO/Services/Serializers/NPCSpawnMapEntitySerializer.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using EOLib.IO.Map; -using System; +using System; using System.Collections.Generic; +using AutomaticTypeMapper; +using EOLib.IO.Map; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.IO/Services/Serializers/PubFileSerializer.cs b/EOLib.IO/Services/Serializers/PubFileSerializer.cs index bd1977398..b3a8b9248 100644 --- a/EOLib.IO/Services/Serializers/PubFileSerializer.cs +++ b/EOLib.IO/Services/Serializers/PubFileSerializer.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; -using EOLib.IO.Pub; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Text; +using AutomaticTypeMapper; +using EOLib.IO.Pub; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.IO/Services/Serializers/PubRecordSerializer.cs b/EOLib.IO/Services/Serializers/PubRecordSerializer.cs index 94fc7d1ab..02a152350 100644 --- a/EOLib.IO/Services/Serializers/PubRecordSerializer.cs +++ b/EOLib.IO/Services/Serializers/PubRecordSerializer.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; -using EOLib.IO.Pub; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using AutomaticTypeMapper; +using EOLib.IO.Pub; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.IO/Services/Serializers/SignMapEntitySerializer.cs b/EOLib.IO/Services/Serializers/SignMapEntitySerializer.cs index c837fc340..ab90f7af8 100644 --- a/EOLib.IO/Services/Serializers/SignMapEntitySerializer.cs +++ b/EOLib.IO/Services/Serializers/SignMapEntitySerializer.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; -using EOLib.IO.Map; -using System; +using System; using System.Collections.Generic; using System.Linq; +using AutomaticTypeMapper; +using EOLib.IO.Map; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.IO/Services/Serializers/UnknownMapEntitySerializer.cs b/EOLib.IO/Services/Serializers/UnknownMapEntitySerializer.cs index 9ddc299a2..d9dac4a4f 100644 --- a/EOLib.IO/Services/Serializers/UnknownMapEntitySerializer.cs +++ b/EOLib.IO/Services/Serializers/UnknownMapEntitySerializer.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.IO.Map; -using System; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.IO/Services/Serializers/WarpMapEntitySerializer.cs b/EOLib.IO/Services/Serializers/WarpMapEntitySerializer.cs index 3afe54795..9ea93e7ee 100644 --- a/EOLib.IO/Services/Serializers/WarpMapEntitySerializer.cs +++ b/EOLib.IO/Services/Serializers/WarpMapEntitySerializer.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using EOLib.IO.Map; -using System; +using System; using System.Collections.Generic; +using AutomaticTypeMapper; +using EOLib.IO.Map; namespace EOLib.IO.Services.Serializers { diff --git a/EOLib.Localization.Test/DataFileLoadActionsTest.cs b/EOLib.Localization.Test/DataFileLoadActionsTest.cs index ae1b6cb45..2de931a38 100644 --- a/EOLib.Localization.Test/DataFileLoadActionsTest.cs +++ b/EOLib.Localization.Test/DataFileLoadActionsTest.cs @@ -1,6 +1,6 @@ -using NUnit.Framework; -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.IO; +using NUnit.Framework; namespace EOLib.Localization.Test { diff --git a/EOLib.Localization.Test/EDFLoaderServiceTest.cs b/EOLib.Localization.Test/EDFLoaderServiceTest.cs index 763494618..dde150849 100644 --- a/EOLib.Localization.Test/EDFLoaderServiceTest.cs +++ b/EOLib.Localization.Test/EDFLoaderServiceTest.cs @@ -1,9 +1,9 @@ -using NUnit.Framework; -using System; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; +using NUnit.Framework; namespace EOLib.Localization.Test { diff --git a/EOLib.Localization.Test/LocalizedStringServiceTest.cs b/EOLib.Localization.Test/LocalizedStringServiceTest.cs index 389b1ef31..7a54ee717 100644 --- a/EOLib.Localization.Test/LocalizedStringServiceTest.cs +++ b/EOLib.Localization.Test/LocalizedStringServiceTest.cs @@ -1,9 +1,9 @@ -using EOLib.Config; -using Moq; -using NUnit.Framework; -using System; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using EOLib.Config; +using Moq; +using NUnit.Framework; namespace EOLib.Localization.Test { diff --git a/EOLib.Localization/DataFileLoadActions.cs b/EOLib.Localization/DataFileLoadActions.cs index 787d34aba..0b9b9e26f 100644 --- a/EOLib.Localization/DataFileLoadActions.cs +++ b/EOLib.Localization/DataFileLoadActions.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; -using System.IO; +using System.IO; using System.Linq; +using AutomaticTypeMapper; namespace EOLib.Localization { diff --git a/EOLib.Localization/DataFileRepository.cs b/EOLib.Localization/DataFileRepository.cs index c0ac4ebb8..28eeda4be 100644 --- a/EOLib.Localization/DataFileRepository.cs +++ b/EOLib.Localization/DataFileRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Localization { diff --git a/EOLib.Localization/LocalizedStringFinder.cs b/EOLib.Localization/LocalizedStringFinder.cs index 57dab15ae..8dce6da72 100644 --- a/EOLib.Localization/LocalizedStringFinder.cs +++ b/EOLib.Localization/LocalizedStringFinder.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.Config; -using System; namespace EOLib.Localization { diff --git a/EOLib.Localization/Services/EDFLoaderService.cs b/EOLib.Localization/Services/EDFLoaderService.cs index b22d9b010..2eafd9550 100644 --- a/EOLib.Localization/Services/EDFLoaderService.cs +++ b/EOLib.Localization/Services/EDFLoaderService.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; -using Moffat.EndlessOnline.SDK.Data; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; +using AutomaticTypeMapper; +using Moffat.EndlessOnline.SDK.Data; namespace EOLib.Localization { diff --git a/EOLib.Logger/DebugOnlyLogger.cs b/EOLib.Logger/DebugOnlyLogger.cs index 1f40f26ba..aaf3f6158 100644 --- a/EOLib.Logger/DebugOnlyLogger.cs +++ b/EOLib.Logger/DebugOnlyLogger.cs @@ -1,8 +1,8 @@ -using EOLib.Config; -using System; +using System; using System.Diagnostics; using System.IO; using System.Threading; +using EOLib.Config; namespace EOLib.Logger { diff --git a/EOLib.Logger/LoggerFactory.cs b/EOLib.Logger/LoggerFactory.cs index 7055a9339..2d34d6d29 100644 --- a/EOLib.Logger/LoggerFactory.cs +++ b/EOLib.Logger/LoggerFactory.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using EOLib.Config; -using System; +using System; using System.Linq; +using AutomaticTypeMapper; +using EOLib.Config; namespace EOLib.Logger { diff --git a/EOLib.Logger/LoggerProvider.cs b/EOLib.Logger/LoggerProvider.cs index f0e490d43..5f0d504e5 100644 --- a/EOLib.Logger/LoggerProvider.cs +++ b/EOLib.Logger/LoggerProvider.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System; +using System; +using AutomaticTypeMapper; namespace EOLib.Logger { diff --git a/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs b/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs index 390f36ff0..00c7d386c 100644 --- a/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs +++ b/EOLib.Test/Net/FileTransfer/FileRequestServiceTest.cs @@ -1,4 +1,9 @@ -using EOLib.Domain.Protocol; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using EOLib.Domain.Protocol; using EOLib.IO.Map; using EOLib.IO.Pub; using EOLib.IO.Services; @@ -13,11 +18,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Moq; using NUnit.Framework; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Text; namespace EOLib.Test.Net.FileTransfer { diff --git a/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs b/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs index ad022e3dd..71890d2b1 100644 --- a/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs +++ b/EOLib.Test/TestHelpers/PacketSendServiceHelpers.cs @@ -1,10 +1,10 @@ -using EOLib.Net.Communication; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; +using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Data; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moq; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading.Tasks; namespace EOLib.Test.TestHelpers { diff --git a/EOLib/Domain/Account/AccountActions.cs b/EOLib/Domain/Account/AccountActions.cs index 0a34a1c5a..d59bbbdf5 100644 --- a/EOLib/Domain/Account/AccountActions.cs +++ b/EOLib/Domain/Account/AccountActions.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Localization; using EOLib.Net; @@ -8,9 +11,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Linq; -using System.Net; -using System.Threading.Tasks; namespace EOLib.Domain.Account { diff --git a/EOLib/Domain/Account/CreateAccountParameterResult.cs b/EOLib/Domain/Account/CreateAccountParameterResult.cs index 522080566..cce3b522e 100644 --- a/EOLib/Domain/Account/CreateAccountParameterResult.cs +++ b/EOLib/Domain/Account/CreateAccountParameterResult.cs @@ -1,5 +1,5 @@ -using EOLib.Localization; -using System; +using System; +using EOLib.Localization; namespace EOLib.Domain.Account { diff --git a/EOLib/Domain/Account/CreateAccountParameterValidator.cs b/EOLib/Domain/Account/CreateAccountParameterValidator.cs index 0db59a87e..0e695f0c0 100644 --- a/EOLib/Domain/Account/CreateAccountParameterValidator.cs +++ b/EOLib/Domain/Account/CreateAccountParameterValidator.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Linq; +using System.Linq; +using AutomaticTypeMapper; namespace EOLib.Domain.Account { diff --git a/EOLib/Domain/Character/AttackValidationActions.cs b/EOLib/Domain/Character/AttackValidationActions.cs index 11d19839d..78d3ba300 100644 --- a/EOLib/Domain/Character/AttackValidationActions.cs +++ b/EOLib/Domain/Character/AttackValidationActions.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Extensions; using EOLib.Domain.Map; using EOLib.IO.Repositories; -using System.Linq; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/CharacterActions.cs b/EOLib/Domain/Character/CharacterActions.cs index a4b050885..ef6d60490 100644 --- a/EOLib/Domain/Character/CharacterActions.cs +++ b/EOLib/Domain/Character/CharacterActions.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Extensions; using EOLib.Domain.Map; using EOLib.Domain.Spells; @@ -8,8 +10,6 @@ using Moffat.EndlessOnline.SDK.Protocol; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; -using System; -using System.Linq; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/CharacterInventoryRepository.cs b/EOLib/Domain/Character/CharacterInventoryRepository.cs index 4f5404d9a..3e735f238 100644 --- a/EOLib/Domain/Character/CharacterInventoryRepository.cs +++ b/EOLib/Domain/Character/CharacterInventoryRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/CharacterManagementActions.cs b/EOLib/Domain/Character/CharacterManagementActions.cs index 5bba07018..21f4ac61c 100644 --- a/EOLib/Domain/Character/CharacterManagementActions.cs +++ b/EOLib/Domain/Character/CharacterManagementActions.cs @@ -1,12 +1,12 @@ -using AutomaticTypeMapper; +using System.Linq; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Net; using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Linq; -using System.Threading.Tasks; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/CharacterSessionRepository.cs b/EOLib/Domain/Character/CharacterSessionRepository.cs index 688862021..ee48aa7b0 100644 --- a/EOLib/Domain/Character/CharacterSessionRepository.cs +++ b/EOLib/Domain/Character/CharacterSessionRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System; +using System; +using AutomaticTypeMapper; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/CharacterStats.cs b/EOLib/Domain/Character/CharacterStats.cs index ee067d0dc..473a17be3 100644 --- a/EOLib/Domain/Character/CharacterStats.cs +++ b/EOLib/Domain/Character/CharacterStats.cs @@ -1,8 +1,8 @@ -using Amadevus.RecordGenerator; -using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; +using System; using System.Collections.Generic; using System.Linq; +using Amadevus.RecordGenerator; +using Moffat.EndlessOnline.SDK.Protocol.Net.Server; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/EquippedItem.cs b/EOLib/Domain/Character/EquippedItem.cs index 7d4ecf209..d0c199d0c 100644 --- a/EOLib/Domain/Character/EquippedItem.cs +++ b/EOLib/Domain/Character/EquippedItem.cs @@ -1,7 +1,7 @@ -using EOLib.IO; +using System; +using EOLib.IO; using EOLib.IO.Extensions; using EOLib.IO.Pub; -using System; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/ExperienceTableProvider.cs b/EOLib/Domain/Character/ExperienceTableProvider.cs index 3dc73df4a..2fff39545 100644 --- a/EOLib/Domain/Character/ExperienceTableProvider.cs +++ b/EOLib/Domain/Character/ExperienceTableProvider.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; -using System; +using System; using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/GhostingRepository.cs b/EOLib/Domain/Character/GhostingRepository.cs index 83b0d27d7..fd88ae427 100644 --- a/EOLib/Domain/Character/GhostingRepository.cs +++ b/EOLib/Domain/Character/GhostingRepository.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Diagnostics; +using AutomaticTypeMapper; using Optional; -using System.Diagnostics; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/InventoryItem.cs b/EOLib/Domain/Character/InventoryItem.cs index 8a24d11d2..adc0534d7 100644 --- a/EOLib/Domain/Character/InventoryItem.cs +++ b/EOLib/Domain/Character/InventoryItem.cs @@ -1,6 +1,5 @@ -using Amadevus.RecordGenerator; using System; - +using Amadevus.RecordGenerator; using NetItem = Moffat.EndlessOnline.SDK.Protocol.Net.Item; namespace EOLib.Domain.Character diff --git a/EOLib/Domain/Character/PaperdollData.cs b/EOLib/Domain/Character/PaperdollData.cs index d827ff52a..5413bbc2e 100644 --- a/EOLib/Domain/Character/PaperdollData.cs +++ b/EOLib/Domain/Character/PaperdollData.cs @@ -1,8 +1,8 @@ -using Amadevus.RecordGenerator; +using System.Collections.Generic; +using Amadevus.RecordGenerator; using EOLib.IO; using Moffat.EndlessOnline.SDK.Protocol; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/PaperdollRepository.cs b/EOLib/Domain/Character/PaperdollRepository.cs index 8d0f48cda..bacc09d9e 100644 --- a/EOLib/Domain/Character/PaperdollRepository.cs +++ b/EOLib/Domain/Character/PaperdollRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/TrainingActions.cs b/EOLib/Domain/Character/TrainingActions.cs index 1f66d9c01..30555490d 100644 --- a/EOLib/Domain/Character/TrainingActions.cs +++ b/EOLib/Domain/Character/TrainingActions.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; -using System; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Character/WalkValidationActions.cs b/EOLib/Domain/Character/WalkValidationActions.cs index 7a42c7fa6..bcd7f1c53 100644 --- a/EOLib/Domain/Character/WalkValidationActions.cs +++ b/EOLib/Domain/Character/WalkValidationActions.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Extensions; using EOLib.Domain.Map; using EOLib.IO.Map; using Optional; -using System; -using System.Linq; namespace EOLib.Domain.Character { diff --git a/EOLib/Domain/Chat/Builders/ChatPacketBuilder.cs b/EOLib/Domain/Chat/Builders/ChatPacketBuilder.cs index 1cac74e42..9c22a20f0 100644 --- a/EOLib/Domain/Chat/Builders/ChatPacketBuilder.cs +++ b/EOLib/Domain/Chat/Builders/ChatPacketBuilder.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; -using System; namespace EOLib.Domain.Chat.Builders { diff --git a/EOLib/Domain/Chat/ChatActions.cs b/EOLib/Domain/Chat/ChatActions.cs index 1221d89bd..be7a13953 100644 --- a/EOLib/Domain/Chat/ChatActions.cs +++ b/EOLib/Domain/Chat/ChatActions.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Chat.Builders; using EOLib.Domain.Map; @@ -6,8 +8,6 @@ using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; -using System; -using System.Linq; namespace EOLib.Domain.Chat { diff --git a/EOLib/Domain/Chat/ChatData.cs b/EOLib/Domain/Chat/ChatData.cs index b810ba7b3..3ea910917 100644 --- a/EOLib/Domain/Chat/ChatData.cs +++ b/EOLib/Domain/Chat/ChatData.cs @@ -1,5 +1,5 @@ -using Amadevus.RecordGenerator; using System; +using Amadevus.RecordGenerator; namespace EOLib.Domain.Chat { diff --git a/EOLib/Domain/Chat/ChatLoggerProvider.cs b/EOLib/Domain/Chat/ChatLoggerProvider.cs index eaf2e1734..af4b50a24 100644 --- a/EOLib/Domain/Chat/ChatLoggerProvider.cs +++ b/EOLib/Domain/Chat/ChatLoggerProvider.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.Config; using EOLib.Logger; -using System; namespace EOLib.Domain.Chat { diff --git a/EOLib/Domain/Chat/ChatProcessor.cs b/EOLib/Domain/Chat/ChatProcessor.cs index b2539eff6..81d2b34ca 100644 --- a/EOLib/Domain/Chat/ChatProcessor.cs +++ b/EOLib/Domain/Chat/ChatProcessor.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; -using EOLib.Config; -using EOLib.Localization; -using System; +using System; using System.Linq; using System.Text; +using AutomaticTypeMapper; +using EOLib.Config; +using EOLib.Localization; namespace EOLib.Domain.Chat { diff --git a/EOLib/Domain/Chat/ChatRepository.cs b/EOLib/Domain/Chat/ChatRepository.cs index 99b529390..daa8bad71 100644 --- a/EOLib/Domain/Chat/ChatRepository.cs +++ b/EOLib/Domain/Chat/ChatRepository.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; -using EOLib.Config; -using System; +using System; using System.Collections.Generic; using System.Linq; +using AutomaticTypeMapper; +using EOLib.Config; namespace EOLib.Domain.Chat { diff --git a/EOLib/Domain/Chat/LocalCommandHandler.cs b/EOLib/Domain/Chat/LocalCommandHandler.cs index 7cdbbe470..db2755b8b 100644 --- a/EOLib/Domain/Chat/LocalCommandHandler.cs +++ b/EOLib/Domain/Chat/LocalCommandHandler.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; -using EOLib.Domain.Chat.Commands; -using System; +using System; using System.Collections.Generic; using System.Linq; +using AutomaticTypeMapper; +using EOLib.Domain.Chat.Commands; namespace EOLib.Domain.Chat { diff --git a/EOLib/Domain/Chat/LoggingList.cs b/EOLib/Domain/Chat/LoggingList.cs index e8f5d0703..3779aef4f 100644 --- a/EOLib/Domain/Chat/LoggingList.cs +++ b/EOLib/Domain/Chat/LoggingList.cs @@ -1,8 +1,8 @@ -using EOLib.Config; -using EOLib.Localization; -using System; +using System; using System.Collections; using System.Collections.Generic; +using EOLib.Config; +using EOLib.Localization; namespace EOLib.Domain.Chat { diff --git a/EOLib/Domain/Extensions/CharacterExtensions.cs b/EOLib/Domain/Extensions/CharacterExtensions.cs index 91b46d4ba..bf8a4ae63 100644 --- a/EOLib/Domain/Extensions/CharacterExtensions.cs +++ b/EOLib/Domain/Extensions/CharacterExtensions.cs @@ -1,5 +1,5 @@ -using EOLib.Domain.Character; -using System; +using System; +using EOLib.Domain.Character; namespace EOLib.Domain.Extensions { diff --git a/EOLib/Domain/Extensions/CharacterRenderPropertiesExtensions.cs b/EOLib/Domain/Extensions/CharacterRenderPropertiesExtensions.cs index 67c68e555..ecf88409d 100644 --- a/EOLib/Domain/Extensions/CharacterRenderPropertiesExtensions.cs +++ b/EOLib/Domain/Extensions/CharacterRenderPropertiesExtensions.cs @@ -1,6 +1,6 @@ -using EOLib.Domain.Character; +using System.Linq; +using EOLib.Domain.Character; using EOLib.Domain.Map; -using System.Linq; namespace EOLib.Domain.Extensions { diff --git a/EOLib/Domain/Extensions/MapExtensions.cs b/EOLib/Domain/Extensions/MapExtensions.cs index 327fbc066..691d0350f 100644 --- a/EOLib/Domain/Extensions/MapExtensions.cs +++ b/EOLib/Domain/Extensions/MapExtensions.cs @@ -1,8 +1,8 @@ -using EOLib.Domain.Map; -using EOLib.IO.Map; -using System; +using System; using System.Collections.Generic; using System.Linq; +using EOLib.Domain.Map; +using EOLib.IO.Map; namespace EOLib.Domain.Extensions { diff --git a/EOLib/Domain/Extensions/NPCExtensions.cs b/EOLib/Domain/Extensions/NPCExtensions.cs index 3c006da89..9e79cecc9 100644 --- a/EOLib/Domain/Extensions/NPCExtensions.cs +++ b/EOLib/Domain/Extensions/NPCExtensions.cs @@ -1,6 +1,6 @@ -using EOLib.Domain.NPC; -using System; +using System; using System.Linq; +using EOLib.Domain.NPC; namespace EOLib.Domain.Extensions { diff --git a/EOLib/Domain/Extensions/PaperdollExtensions.cs b/EOLib/Domain/Extensions/PaperdollExtensions.cs index c83737373..7f59a7efe 100644 --- a/EOLib/Domain/Extensions/PaperdollExtensions.cs +++ b/EOLib/Domain/Extensions/PaperdollExtensions.cs @@ -1,6 +1,6 @@ -using EOLib.IO; +using System.Collections.Generic; +using EOLib.IO; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.Domain.Extensions { diff --git a/EOLib/Domain/Interact/Board/BoardDataRepository.cs b/EOLib/Domain/Interact/Board/BoardDataRepository.cs index 4e9d80921..b99db2e75 100644 --- a/EOLib/Domain/Interact/Board/BoardDataRepository.cs +++ b/EOLib/Domain/Interact/Board/BoardDataRepository.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using Optional; -using System.Collections.Generic; namespace EOLib.Domain.Interact.Board { diff --git a/EOLib/Domain/Interact/Citizen/CitizenActions.cs b/EOLib/Domain/Interact/Citizen/CitizenActions.cs index a4464f11b..c8348198b 100644 --- a/EOLib/Domain/Interact/Citizen/CitizenActions.cs +++ b/EOLib/Domain/Interact/Citizen/CitizenActions.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Map; using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; -using System.Collections.Generic; -using System.Linq; namespace EOLib.Domain.Interact.Citizen { diff --git a/EOLib/Domain/Interact/Citizen/CitizenDataRepository.cs b/EOLib/Domain/Interact/Citizen/CitizenDataRepository.cs index f771942bf..cdd45c8be 100644 --- a/EOLib/Domain/Interact/Citizen/CitizenDataRepository.cs +++ b/EOLib/Domain/Interact/Citizen/CitizenDataRepository.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using Optional; -using System.Collections.Generic; namespace EOLib.Domain.Interact.Citizen { diff --git a/EOLib/Domain/Interact/Jukebox/JukeboxActions.cs b/EOLib/Domain/Interact/Jukebox/JukeboxActions.cs index 5505bdf7b..f6435ff95 100644 --- a/EOLib/Domain/Interact/Jukebox/JukeboxActions.cs +++ b/EOLib/Domain/Interact/Jukebox/JukeboxActions.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.IO; using EOLib.IO.Repositories; using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Optional.Collections; -using System; namespace EOLib.Domain.Interact.Jukebox { diff --git a/EOLib/Domain/Interact/Quest/QuestDataRepository.cs b/EOLib/Domain/Interact/Quest/QuestDataRepository.cs index 57eefe423..47f80a731 100644 --- a/EOLib/Domain/Interact/Quest/QuestDataRepository.cs +++ b/EOLib/Domain/Interact/Quest/QuestDataRepository.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.NPC; using Optional; -using System.Collections.Generic; namespace EOLib.Domain.Interact.Quest { diff --git a/EOLib/Domain/Interact/Quest/QuestDialogData.cs b/EOLib/Domain/Interact/Quest/QuestDialogData.cs index 6126d5a7f..b83f4ae87 100644 --- a/EOLib/Domain/Interact/Quest/QuestDialogData.cs +++ b/EOLib/Domain/Interact/Quest/QuestDialogData.cs @@ -1,5 +1,5 @@ -using Amadevus.RecordGenerator; -using System.Collections.Generic; +using System.Collections.Generic; +using Amadevus.RecordGenerator; namespace EOLib.Domain.Interact.Quest { diff --git a/EOLib/Domain/Interact/Quest/QuestProgressData.cs b/EOLib/Domain/Interact/Quest/QuestProgressData.cs index 8d502b3b2..8870cedcb 100644 --- a/EOLib/Domain/Interact/Quest/QuestProgressData.cs +++ b/EOLib/Domain/Interact/Quest/QuestProgressData.cs @@ -1,6 +1,6 @@ -using Amadevus.RecordGenerator; +using System; +using Amadevus.RecordGenerator; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; namespace EOLib.Domain.Interact.Quest { diff --git a/EOLib/Domain/Interact/Shop/ShopDataRepository.cs b/EOLib/Domain/Interact/Shop/ShopDataRepository.cs index 906271510..e3f3e310c 100644 --- a/EOLib/Domain/Interact/Shop/ShopDataRepository.cs +++ b/EOLib/Domain/Interact/Shop/ShopDataRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Domain.Interact.Shop { diff --git a/EOLib/Domain/Interact/Skill/Skill.cs b/EOLib/Domain/Interact/Skill/Skill.cs index d607c49f4..8b5cacef8 100644 --- a/EOLib/Domain/Interact/Skill/Skill.cs +++ b/EOLib/Domain/Interact/Skill/Skill.cs @@ -1,5 +1,5 @@ -using Amadevus.RecordGenerator; -using System.Collections.Generic; +using System.Collections.Generic; +using Amadevus.RecordGenerator; namespace EOLib.Domain.Interact.Skill { diff --git a/EOLib/Domain/Interact/Skill/SkillDataRepository.cs b/EOLib/Domain/Interact/Skill/SkillDataRepository.cs index c5d523cd6..92ab5646b 100644 --- a/EOLib/Domain/Interact/Skill/SkillDataRepository.cs +++ b/EOLib/Domain/Interact/Skill/SkillDataRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Domain.Interact.Skill { diff --git a/EOLib/Domain/Item/ItemActions.cs b/EOLib/Domain/Item/ItemActions.cs index b70f57e85..73bab0548 100644 --- a/EOLib/Domain/Item/ItemActions.cs +++ b/EOLib/Domain/Item/ItemActions.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.IO; +using AutomaticTypeMapper; using EOLib.Domain.Map; using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Data; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; -using System.IO; namespace EOLib.Domain.Item { diff --git a/EOLib/Domain/Item/ItemDropValidator.cs b/EOLib/Domain/Item/ItemDropValidator.cs index dc2f50a65..f14a521e8 100644 --- a/EOLib/Domain/Item/ItemDropValidator.cs +++ b/EOLib/Domain/Item/ItemDropValidator.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.IO; using EOLib.IO.Repositories; -using System; namespace EOLib.Domain.Item { diff --git a/EOLib/Domain/Item/ItemEquipValidator.cs b/EOLib/Domain/Item/ItemEquipValidator.cs index ad2f104a5..7a0960513 100644 --- a/EOLib/Domain/Item/ItemEquipValidator.cs +++ b/EOLib/Domain/Item/ItemEquipValidator.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.IO; using EOLib.IO.Extensions; using EOLib.IO.Pub; using EOLib.IO.Repositories; -using System.Linq; namespace EOLib.Domain.Item { diff --git a/EOLib/Domain/Item/ItemPickupValidator.cs b/EOLib/Domain/Item/ItemPickupValidator.cs index 29fdc1797..947f950a4 100644 --- a/EOLib/Domain/Item/ItemPickupValidator.cs +++ b/EOLib/Domain/Item/ItemPickupValidator.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.Config; using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.IO.Repositories; using Optional; -using System; namespace EOLib.Domain.Item { diff --git a/EOLib/Domain/Item/ItemStringService.cs b/EOLib/Domain/Item/ItemStringService.cs index 0b31b0c69..6aa7b7dc6 100644 --- a/EOLib/Domain/Item/ItemStringService.cs +++ b/EOLib/Domain/Item/ItemStringService.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.IO.Pub; -using System; namespace EOLib.Domain.Item { diff --git a/EOLib/Domain/Login/CharacterSelectorRepository.cs b/EOLib/Domain/Login/CharacterSelectorRepository.cs index 4cd4714de..984567de0 100644 --- a/EOLib/Domain/Login/CharacterSelectorRepository.cs +++ b/EOLib/Domain/Login/CharacterSelectorRepository.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using Optional; -using System.Collections.Generic; namespace EOLib.Domain.Login { diff --git a/EOLib/Domain/Login/LoginActions.cs b/EOLib/Domain/Login/LoginActions.cs index 7a4593d91..6a07d7238 100644 --- a/EOLib/Domain/Login/LoginActions.cs +++ b/EOLib/Domain/Login/LoginActions.cs @@ -1,4 +1,8 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using EOLib.Domain.Map; @@ -9,10 +13,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace EOLib.Domain.Login { diff --git a/EOLib/Domain/Login/NewsRepository.cs b/EOLib/Domain/Login/NewsRepository.cs index ba4cc1d6b..ffb77947f 100644 --- a/EOLib/Domain/Login/NewsRepository.cs +++ b/EOLib/Domain/Login/NewsRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Domain.Login { diff --git a/EOLib/Domain/Map/ChestDataRepository.cs b/EOLib/Domain/Map/ChestDataRepository.cs index d498d0c38..b39906ec4 100644 --- a/EOLib/Domain/Map/ChestDataRepository.cs +++ b/EOLib/Domain/Map/ChestDataRepository.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; -using System.Collections.Generic; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/CurrentMapStateRepository.cs b/EOLib/Domain/Map/CurrentMapStateRepository.cs index aa12a166e..0128622a7 100644 --- a/EOLib/Domain/Map/CurrentMapStateRepository.cs +++ b/EOLib/Domain/Map/CurrentMapStateRepository.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using Optional; using System; using System.Collections.Generic; +using AutomaticTypeMapper; +using Optional; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/IMapCellState.cs b/EOLib/Domain/Map/IMapCellState.cs index c0e60a27d..2e97d6fa5 100644 --- a/EOLib/Domain/Map/IMapCellState.cs +++ b/EOLib/Domain/Map/IMapCellState.cs @@ -1,7 +1,7 @@ -using EOLib.Domain.Character; +using System.Collections.Generic; +using EOLib.Domain.Character; using EOLib.IO.Map; using Optional; -using System.Collections.Generic; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/LockerDataRepository.cs b/EOLib/Domain/Map/LockerDataRepository.cs index b2c98aad6..dde7124f1 100644 --- a/EOLib/Domain/Map/LockerDataRepository.cs +++ b/EOLib/Domain/Map/LockerDataRepository.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; -using System.Collections.Generic; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/MapCellState.cs b/EOLib/Domain/Map/MapCellState.cs index 4de0fa620..06cf20c00 100644 --- a/EOLib/Domain/Map/MapCellState.cs +++ b/EOLib/Domain/Map/MapCellState.cs @@ -1,6 +1,6 @@ -using EOLib.IO.Map; +using System.Collections.Generic; +using EOLib.IO.Map; using Optional; -using System.Collections.Generic; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/MapCellStateProvider.cs b/EOLib/Domain/Map/MapCellStateProvider.cs index 26604c047..206b5fcf9 100644 --- a/EOLib/Domain/Map/MapCellStateProvider.cs +++ b/EOLib/Domain/Map/MapCellStateProvider.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using EOLib.Domain.NPC; @@ -6,8 +8,6 @@ using EOLib.IO.Repositories; using Optional; using Optional.Collections; -using System.Collections.Generic; -using System.Linq; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/MapCoordinate.cs b/EOLib/Domain/Map/MapCoordinate.cs index 7e8d21464..9c7abc89f 100644 --- a/EOLib/Domain/Map/MapCoordinate.cs +++ b/EOLib/Domain/Map/MapCoordinate.cs @@ -1,5 +1,5 @@ -using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; +using System; +using Moffat.EndlessOnline.SDK.Protocol.Net.Server; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/MapItem.cs b/EOLib/Domain/Map/MapItem.cs index 31352bc00..77a32edb7 100644 --- a/EOLib/Domain/Map/MapItem.cs +++ b/EOLib/Domain/Map/MapItem.cs @@ -1,8 +1,8 @@ -using Amadevus.RecordGenerator; +using System; +using Amadevus.RecordGenerator; using EOLib.IO.Map; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/Sign.cs b/EOLib/Domain/Map/Sign.cs index 19823a3f8..bbcbc848a 100644 --- a/EOLib/Domain/Map/Sign.cs +++ b/EOLib/Domain/Map/Sign.cs @@ -1,5 +1,5 @@ -using EOLib.IO.Map; -using System.Linq; +using System.Linq; +using EOLib.IO.Map; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/UnknownEntitiesRequestActions.cs b/EOLib/Domain/Map/UnknownEntitiesRequestActions.cs index 322b625b6..b0a81d522 100644 --- a/EOLib/Domain/Map/UnknownEntitiesRequestActions.cs +++ b/EOLib/Domain/Map/UnknownEntitiesRequestActions.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; -using System.Linq; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/UnlockChestValidator.cs b/EOLib/Domain/Map/UnlockChestValidator.cs index 3baefd5bf..20572d831 100644 --- a/EOLib/Domain/Map/UnlockChestValidator.cs +++ b/EOLib/Domain/Map/UnlockChestValidator.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.IO.Map; using EOLib.IO.Repositories; using Optional; using Optional.Collections; -using System.Linq; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Map/UnlockDoorValidator.cs b/EOLib/Domain/Map/UnlockDoorValidator.cs index dd348c27e..5760ed2c3 100644 --- a/EOLib/Domain/Map/UnlockDoorValidator.cs +++ b/EOLib/Domain/Map/UnlockDoorValidator.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.IO.Repositories; using Optional; using Optional.Collections; -using System.Linq; namespace EOLib.Domain.Map { diff --git a/EOLib/Domain/Notifiers/IOtherCharacterAnimationNotifier.cs b/EOLib/Domain/Notifiers/IOtherCharacterAnimationNotifier.cs index 85fe5365a..45c7419a8 100644 --- a/EOLib/Domain/Notifiers/IOtherCharacterAnimationNotifier.cs +++ b/EOLib/Domain/Notifiers/IOtherCharacterAnimationNotifier.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Map; using EOLib.Domain.Spells; -using System.Collections.Generic; namespace EOLib.Domain.Notifiers { diff --git a/EOLib/Domain/Notifiers/IUserInterfaceNotifier.cs b/EOLib/Domain/Notifiers/IUserInterfaceNotifier.cs index df280ff03..0003e1771 100644 --- a/EOLib/Domain/Notifiers/IUserInterfaceNotifier.cs +++ b/EOLib/Domain/Notifiers/IUserInterfaceNotifier.cs @@ -1,8 +1,8 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Map; using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Collections.Generic; namespace EOLib.Domain.Notifiers { diff --git a/EOLib/Domain/Online/OnlinePlayerRepository.cs b/EOLib/Domain/Online/OnlinePlayerRepository.cs index 8bf27d4a5..ed8515447 100644 --- a/EOLib/Domain/Online/OnlinePlayerRepository.cs +++ b/EOLib/Domain/Online/OnlinePlayerRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Domain.Online { diff --git a/EOLib/Domain/Party/PartyRepository.cs b/EOLib/Domain/Party/PartyRepository.cs index 0406caad7..bbe93a745 100644 --- a/EOLib/Domain/Party/PartyRepository.cs +++ b/EOLib/Domain/Party/PartyRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Domain.Party { diff --git a/EOLib/Domain/Protocol/PingTimeRepository.cs b/EOLib/Domain/Protocol/PingTimeRepository.cs index d96e60976..cf2b7e6df 100644 --- a/EOLib/Domain/Protocol/PingTimeRepository.cs +++ b/EOLib/Domain/Protocol/PingTimeRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Diagnostics; +using System.Diagnostics; +using AutomaticTypeMapper; namespace EOLib.Domain.Protocol { diff --git a/EOLib/Domain/ResetStateAction.cs b/EOLib/Domain/ResetStateAction.cs index 00aafc9af..e66f6214c 100644 --- a/EOLib/Domain/ResetStateAction.cs +++ b/EOLib/Domain/ResetStateAction.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Domain { diff --git a/EOLib/Domain/Spells/SpellCastValidationActions.cs b/EOLib/Domain/Spells/SpellCastValidationActions.cs index 76829b55b..653a7ce83 100644 --- a/EOLib/Domain/Spells/SpellCastValidationActions.cs +++ b/EOLib/Domain/Spells/SpellCastValidationActions.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Map; using EOLib.IO; using EOLib.IO.Repositories; -using System.Linq; namespace EOLib.Domain.Spells { diff --git a/EOLib/Domain/Trade/TradeOffer.cs b/EOLib/Domain/Trade/TradeOffer.cs index fb967c410..ed5c46009 100644 --- a/EOLib/Domain/Trade/TradeOffer.cs +++ b/EOLib/Domain/Trade/TradeOffer.cs @@ -1,6 +1,6 @@ -using Amadevus.RecordGenerator; +using System.Collections.Generic; +using Amadevus.RecordGenerator; using EOLib.Domain.Character; -using System.Collections.Generic; namespace EOLib.Domain.Trade { diff --git a/EOLib/Domain/Trade/TradeRepository.cs b/EOLib/Domain/Trade/TradeRepository.cs index fb69fb78b..bb10d06c6 100644 --- a/EOLib/Domain/Trade/TradeRepository.cs +++ b/EOLib/Domain/Trade/TradeRepository.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; -using System.Collections.Generic; namespace EOLib.Domain.Trade { diff --git a/EOLib/HDSerialNumberService.cs b/EOLib/HDSerialNumberService.cs index d5d5d72b8..e0f93b26a 100644 --- a/EOLib/HDSerialNumberService.cs +++ b/EOLib/HDSerialNumberService.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; -using System; +using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; +using AutomaticTypeMapper; namespace EOLib { diff --git a/EOLib/Net/Communication/INetworkClient.cs b/EOLib/Net/Communication/INetworkClient.cs index 687534710..6be7a80ef 100644 --- a/EOLib/Net/Communication/INetworkClient.cs +++ b/EOLib/Net/Communication/INetworkClient.cs @@ -1,7 +1,7 @@ -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System; +using System; using System.Threading; using System.Threading.Tasks; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/IPacketQueue.cs b/EOLib/Net/Communication/IPacketQueue.cs index b333ee0ce..7887b2fc5 100644 --- a/EOLib/Net/Communication/IPacketQueue.cs +++ b/EOLib/Net/Communication/IPacketQueue.cs @@ -1,5 +1,5 @@ -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Collections.Generic; +using System.Collections.Generic; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/IPacketSendService.cs b/EOLib/Net/Communication/IPacketSendService.cs index 8070f377e..da0589e13 100644 --- a/EOLib/Net/Communication/IPacketSendService.cs +++ b/EOLib/Net/Communication/IPacketSendService.cs @@ -1,5 +1,5 @@ -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Threading.Tasks; +using System.Threading.Tasks; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/IWaitablePacketQueue.cs b/EOLib/Net/Communication/IWaitablePacketQueue.cs index 1977b3a78..887169193 100644 --- a/EOLib/Net/Communication/IWaitablePacketQueue.cs +++ b/EOLib/Net/Communication/IWaitablePacketQueue.cs @@ -1,5 +1,5 @@ -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Threading.Tasks; +using System.Threading.Tasks; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/NetworkClient.cs b/EOLib/Net/Communication/NetworkClient.cs index 514555f72..c3a7c88bb 100644 --- a/EOLib/Net/Communication/NetworkClient.cs +++ b/EOLib/Net/Communication/NetworkClient.cs @@ -1,12 +1,12 @@ -using EOLib.IO.Services; -using EOLib.Net.Handlers; -using EOLib.Net.PacketProcessing; -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System; +using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; +using EOLib.IO.Services; +using EOLib.Net.Handlers; +using EOLib.Net.PacketProcessing; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/NetworkClientFactory.cs b/EOLib/Net/Communication/NetworkClientFactory.cs index ac3de85df..d252a7485 100644 --- a/EOLib/Net/Communication/NetworkClientFactory.cs +++ b/EOLib/Net/Communication/NetworkClientFactory.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.IO.Services; using EOLib.Logger; using EOLib.Net.Handlers; using EOLib.Net.PacketProcessing; -using System; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/PacketQueue.cs b/EOLib/Net/Communication/PacketQueue.cs index 654a554da..48e2ed2c1 100644 --- a/EOLib/Net/Communication/PacketQueue.cs +++ b/EOLib/Net/Communication/PacketQueue.cs @@ -1,8 +1,8 @@ -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System; +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/PacketSendService.cs b/EOLib/Net/Communication/PacketSendService.cs index 7e53c29c0..ea225b6f2 100644 --- a/EOLib/Net/Communication/PacketSendService.cs +++ b/EOLib/Net/Communication/PacketSendService.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; +using System.Threading.Tasks; +using AutomaticTypeMapper; using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Threading.Tasks; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/SafeAsyncNetworkOperation.cs b/EOLib/Net/Communication/SafeAsyncNetworkOperation.cs index 82462da21..8e9cb4bf0 100644 --- a/EOLib/Net/Communication/SafeAsyncNetworkOperation.cs +++ b/EOLib/Net/Communication/SafeAsyncNetworkOperation.cs @@ -1,6 +1,6 @@ -using EOLib.Net.Connection; -using System; +using System; using System.Threading.Tasks; +using EOLib.Net.Connection; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/SafeBlockingNetworkOperation.cs b/EOLib/Net/Communication/SafeBlockingNetworkOperation.cs index f8362e57a..0d284e735 100644 --- a/EOLib/Net/Communication/SafeBlockingNetworkOperation.cs +++ b/EOLib/Net/Communication/SafeBlockingNetworkOperation.cs @@ -1,6 +1,6 @@ -using EOLib.Net.Connection; -using System; +using System; using System.Threading.Tasks; +using EOLib.Net.Connection; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/SafeNetworkOperationBase.cs b/EOLib/Net/Communication/SafeNetworkOperationBase.cs index 3f701550f..dafb5dd70 100644 --- a/EOLib/Net/Communication/SafeNetworkOperationBase.cs +++ b/EOLib/Net/Communication/SafeNetworkOperationBase.cs @@ -1,6 +1,6 @@ -using EOLib.Net.Connection; -using System; +using System; using System.Threading.Tasks; +using EOLib.Net.Connection; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Communication/SafeNetworkOperationFactory.cs b/EOLib/Net/Communication/SafeNetworkOperationFactory.cs index dfa78f277..0f2c0af82 100644 --- a/EOLib/Net/Communication/SafeNetworkOperationFactory.cs +++ b/EOLib/Net/Communication/SafeNetworkOperationFactory.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using EOLib.Net.Connection; -using System; +using System; using System.Threading.Tasks; +using AutomaticTypeMapper; +using EOLib.Net.Connection; namespace EOLib.Net.Communication { diff --git a/EOLib/Net/Connection/BackgroundReceiveActions.cs b/EOLib/Net/Connection/BackgroundReceiveActions.cs index 83483ef4f..4fbf89f19 100644 --- a/EOLib/Net/Connection/BackgroundReceiveActions.cs +++ b/EOLib/Net/Connection/BackgroundReceiveActions.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using EOLib.Net.Communication; using System.Threading; using System.Threading.Tasks; +using AutomaticTypeMapper; +using EOLib.Net.Communication; namespace EOLib.Net.Connection { diff --git a/EOLib/Net/Connection/IBackgroundReceiveTaskRepository.cs b/EOLib/Net/Connection/IBackgroundReceiveTaskRepository.cs index ec10cb704..cf25158f6 100644 --- a/EOLib/Net/Connection/IBackgroundReceiveTaskRepository.cs +++ b/EOLib/Net/Connection/IBackgroundReceiveTaskRepository.cs @@ -1,6 +1,6 @@ -using AutomaticTypeMapper; -using System.Threading; +using System.Threading; using System.Threading.Tasks; +using AutomaticTypeMapper; namespace EOLib.Net.Connection { diff --git a/EOLib/Net/Connection/INetworkConnectionActions.cs b/EOLib/Net/Connection/INetworkConnectionActions.cs index ab9335098..c8f5e839a 100644 --- a/EOLib/Net/Connection/INetworkConnectionActions.cs +++ b/EOLib/Net/Connection/INetworkConnectionActions.cs @@ -1,6 +1,6 @@ -using EOLib.Net.Communication; +using System.Threading.Tasks; +using EOLib.Net.Communication; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Threading.Tasks; namespace EOLib.Net.Connection { diff --git a/EOLib/Net/Connection/NetworkConnectionActions.cs b/EOLib/Net/Connection/NetworkConnectionActions.cs index 548248936..df193d58b 100644 --- a/EOLib/Net/Connection/NetworkConnectionActions.cs +++ b/EOLib/Net/Connection/NetworkConnectionActions.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EOLib.Config; using EOLib.Domain.Login; using EOLib.Net.Communication; @@ -6,8 +8,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Threading.Tasks; using Version = Moffat.EndlessOnline.SDK.Protocol.Net.Version; namespace EOLib.Net.Connection diff --git a/EOLib/Net/FileTransfer/FileRequestActions.cs b/EOLib/Net/FileTransfer/FileRequestActions.cs index 9b127ef51..af8b85beb 100644 --- a/EOLib/Net/FileTransfer/FileRequestActions.cs +++ b/EOLib/Net/FileTransfer/FileRequestActions.cs @@ -1,3 +1,8 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -9,11 +14,6 @@ using EOLib.IO.Services; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Optional; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; namespace EOLib.Net.FileTransfer { diff --git a/EOLib/Net/FileTransfer/FileRequestService.cs b/EOLib/Net/FileTransfer/FileRequestService.cs index a7d7aca84..f387d198f 100644 --- a/EOLib/Net/FileTransfer/FileRequestService.cs +++ b/EOLib/Net/FileTransfer/FileRequestService.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using AutomaticTypeMapper; using EOLib.IO.Map; using EOLib.IO.Pub; using EOLib.IO.Services.Serializers; @@ -6,9 +9,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; namespace EOLib.Net.FileTransfer { diff --git a/EOLib/Net/FileTransfer/LoginFileChecksumRepository.cs b/EOLib/Net/FileTransfer/LoginFileChecksumRepository.cs index a352471df..9a4962315 100644 --- a/EOLib/Net/FileTransfer/LoginFileChecksumRepository.cs +++ b/EOLib/Net/FileTransfer/LoginFileChecksumRepository.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Net.FileTransfer { diff --git a/EOLib/Net/Handlers/DefaultAsyncPacketHandler.cs b/EOLib/Net/Handlers/DefaultAsyncPacketHandler.cs index 45a406fef..b6dc54aaf 100644 --- a/EOLib/Net/Handlers/DefaultAsyncPacketHandler.cs +++ b/EOLib/Net/Handlers/DefaultAsyncPacketHandler.cs @@ -1,5 +1,5 @@ -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Threading.Tasks; +using System.Threading.Tasks; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Handlers { diff --git a/EOLib/Net/Handlers/FamilyActionPair.cs b/EOLib/Net/Handlers/FamilyActionPair.cs index 9eaca0888..1666a8fa2 100644 --- a/EOLib/Net/Handlers/FamilyActionPair.cs +++ b/EOLib/Net/Handlers/FamilyActionPair.cs @@ -1,6 +1,6 @@ -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System; +using System; using System.Collections; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Handlers { diff --git a/EOLib/Net/Handlers/IPacketHandler.cs b/EOLib/Net/Handlers/IPacketHandler.cs index f938f0a9e..eee19d9f7 100644 --- a/EOLib/Net/Handlers/IPacketHandler.cs +++ b/EOLib/Net/Handlers/IPacketHandler.cs @@ -1,5 +1,5 @@ -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Threading.Tasks; +using System.Threading.Tasks; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Handlers { diff --git a/EOLib/Net/Handlers/PacketHandlerFinder.cs b/EOLib/Net/Handlers/PacketHandlerFinder.cs index b1f79e609..ddd5660d2 100644 --- a/EOLib/Net/Handlers/PacketHandlerFinder.cs +++ b/EOLib/Net/Handlers/PacketHandlerFinder.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using AutomaticTypeMapper; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Handlers { diff --git a/EOLib/Net/Handlers/PacketHandlerProvider.cs b/EOLib/Net/Handlers/PacketHandlerProvider.cs index d6d4284e0..ff2962343 100644 --- a/EOLib/Net/Handlers/PacketHandlerProvider.cs +++ b/EOLib/Net/Handlers/PacketHandlerProvider.cs @@ -1,5 +1,5 @@ -using AutomaticTypeMapper; -using System.Collections.Generic; +using System.Collections.Generic; +using AutomaticTypeMapper; namespace EOLib.Net.Handlers { diff --git a/EOLib/Net/Handlers/PacketHandlingTypeFinder.cs b/EOLib/Net/Handlers/PacketHandlingTypeFinder.cs index e144850cc..e5d4ac478 100644 --- a/EOLib/Net/Handlers/PacketHandlingTypeFinder.cs +++ b/EOLib/Net/Handlers/PacketHandlingTypeFinder.cs @@ -1,7 +1,7 @@ -using AutomaticTypeMapper; -using Moffat.EndlessOnline.SDK.Protocol.Net; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using AutomaticTypeMapper; +using Moffat.EndlessOnline.SDK.Protocol.Net; namespace EOLib.Net.Handlers { diff --git a/EOLib/Net/PacketProcessing/PacketFactory.cs b/EOLib/Net/PacketProcessing/PacketFactory.cs index bef27f7bf..f5c3aee9e 100644 --- a/EOLib/Net/PacketProcessing/PacketFactory.cs +++ b/EOLib/Net/PacketProcessing/PacketFactory.cs @@ -1,12 +1,12 @@ -using EOLib.Net.Handlers; -using Moffat.EndlessOnline.SDK.Data; -using Moffat.EndlessOnline.SDK.Protocol.Net; -using Optional; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; +using EOLib.Net.Handlers; +using Moffat.EndlessOnline.SDK.Data; +using Moffat.EndlessOnline.SDK.Protocol.Net; +using Optional; namespace EOLib.Net.PacketProcessing { diff --git a/EOLib/Net/PacketProcessing/PacketProcessActions.cs b/EOLib/Net/PacketProcessing/PacketProcessActions.cs index aa7e887bb..125eb03ca 100644 --- a/EOLib/Net/PacketProcessing/PacketProcessActions.cs +++ b/EOLib/Net/PacketProcessing/PacketProcessActions.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System; +using System.Net.Sockets; +using AutomaticTypeMapper; using EOLib.Logger; using Moffat.EndlessOnline.SDK.Data; using Moffat.EndlessOnline.SDK.Packet; using Moffat.EndlessOnline.SDK.Protocol.Net; using Optional; -using System; -using System.Net.Sockets; namespace EOLib.Net.PacketProcessing { diff --git a/EOLib/PacketHandlers/AdminInteract/AdminInteractAgree.cs b/EOLib/PacketHandlers/AdminInteract/AdminInteractAgree.cs index 0ff814945..c342ed2fa 100644 --- a/EOLib/PacketHandlers/AdminInteract/AdminInteractAgree.cs +++ b/EOLib/PacketHandlers/AdminInteract/AdminInteractAgree.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.AdminInteract { diff --git a/EOLib/PacketHandlers/AdminInteract/AdminInteractList.cs b/EOLib/PacketHandlers/AdminInteract/AdminInteractList.cs index c3cf5253a..43cff598a 100644 --- a/EOLib/PacketHandlers/AdminInteract/AdminInteractList.cs +++ b/EOLib/PacketHandlers/AdminInteract/AdminInteractList.cs @@ -1,12 +1,12 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.AdminInteract { diff --git a/EOLib/PacketHandlers/AdminInteract/AdminInteractRemove.cs b/EOLib/PacketHandlers/AdminInteract/AdminInteractRemove.cs index 45c1cf94d..dcf8467e1 100644 --- a/EOLib/PacketHandlers/AdminInteract/AdminInteractRemove.cs +++ b/EOLib/PacketHandlers/AdminInteract/AdminInteractRemove.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.AdminInteract { diff --git a/EOLib/PacketHandlers/AdminInteract/AdminInteractTell.cs b/EOLib/PacketHandlers/AdminInteract/AdminInteractTell.cs index 9ea95f012..31e5b30f8 100644 --- a/EOLib/PacketHandlers/AdminInteract/AdminInteractTell.cs +++ b/EOLib/PacketHandlers/AdminInteract/AdminInteractTell.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.AdminInteract { diff --git a/EOLib/PacketHandlers/Arena/ArenaAcceptHandler.cs b/EOLib/PacketHandlers/Arena/ArenaAcceptHandler.cs index d25e359aa..12d46ce92 100644 --- a/EOLib/PacketHandlers/Arena/ArenaAcceptHandler.cs +++ b/EOLib/PacketHandlers/Arena/ArenaAcceptHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Arena { diff --git a/EOLib/PacketHandlers/Arena/ArenaDropHandler.cs b/EOLib/PacketHandlers/Arena/ArenaDropHandler.cs index 57b1b6c7b..034d4b1fe 100644 --- a/EOLib/PacketHandlers/Arena/ArenaDropHandler.cs +++ b/EOLib/PacketHandlers/Arena/ArenaDropHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Arena { diff --git a/EOLib/PacketHandlers/Arena/ArenaSpecHandler.cs b/EOLib/PacketHandlers/Arena/ArenaSpecHandler.cs index dbcadd350..469321f57 100644 --- a/EOLib/PacketHandlers/Arena/ArenaSpecHandler.cs +++ b/EOLib/PacketHandlers/Arena/ArenaSpecHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Arena { diff --git a/EOLib/PacketHandlers/Arena/ArenaUseHandler.cs b/EOLib/PacketHandlers/Arena/ArenaUseHandler.cs index 8170f87b2..e823df3f2 100644 --- a/EOLib/PacketHandlers/Arena/ArenaUseHandler.cs +++ b/EOLib/PacketHandlers/Arena/ArenaUseHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Arena { diff --git a/EOLib/PacketHandlers/Attack/AttackPlayerHandler.cs b/EOLib/PacketHandlers/Attack/AttackPlayerHandler.cs index fc7901488..711a94150 100644 --- a/EOLib/PacketHandlers/Attack/AttackPlayerHandler.cs +++ b/EOLib/PacketHandlers/Attack/AttackPlayerHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Attack { diff --git a/EOLib/PacketHandlers/Avatar/AvatarAdminHandler.cs b/EOLib/PacketHandlers/Avatar/AvatarAdminHandler.cs index 1a839f5c4..a618754ef 100644 --- a/EOLib/PacketHandlers/Avatar/AvatarAdminHandler.cs +++ b/EOLib/PacketHandlers/Avatar/AvatarAdminHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Avatar { diff --git a/EOLib/PacketHandlers/Avatar/AvatarRemoveHandler.cs b/EOLib/PacketHandlers/Avatar/AvatarRemoveHandler.cs index 6e5b86834..61bbb5672 100644 --- a/EOLib/PacketHandlers/Avatar/AvatarRemoveHandler.cs +++ b/EOLib/PacketHandlers/Avatar/AvatarRemoveHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Avatar { diff --git a/EOLib/PacketHandlers/Avatar/AvatarReplyHandler.cs b/EOLib/PacketHandlers/Avatar/AvatarReplyHandler.cs index 16eaaa0cf..8593ee315 100644 --- a/EOLib/PacketHandlers/Avatar/AvatarReplyHandler.cs +++ b/EOLib/PacketHandlers/Avatar/AvatarReplyHandler.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Extensions; @@ -7,7 +8,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Avatar { diff --git a/EOLib/PacketHandlers/Bank/BankReplyHandler.cs b/EOLib/PacketHandlers/Bank/BankReplyHandler.cs index a90c85f84..e003e266b 100644 --- a/EOLib/PacketHandlers/Bank/BankReplyHandler.cs +++ b/EOLib/PacketHandlers/Bank/BankReplyHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Interact.Bank; using EOLib.Domain.Login; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Bank { diff --git a/EOLib/PacketHandlers/Barber/BarberOpenHandler.cs b/EOLib/PacketHandlers/Barber/BarberOpenHandler.cs index 678c5e506..90b997e8f 100644 --- a/EOLib/PacketHandlers/Barber/BarberOpenHandler.cs +++ b/EOLib/PacketHandlers/Barber/BarberOpenHandler.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Interact.Barber; @@ -5,7 +6,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Barber { diff --git a/EOLib/PacketHandlers/Board/BoardOpenHandler.cs b/EOLib/PacketHandlers/Board/BoardOpenHandler.cs index f980932ae..0a1847ca7 100644 --- a/EOLib/PacketHandlers/Board/BoardOpenHandler.cs +++ b/EOLib/PacketHandlers/Board/BoardOpenHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact.Board; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -6,7 +7,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Board { diff --git a/EOLib/PacketHandlers/Cast/CastAcceptHandler.cs b/EOLib/PacketHandlers/Cast/CastAcceptHandler.cs index 41d6131ef..cb1a4c3f3 100644 --- a/EOLib/PacketHandlers/Cast/CastAcceptHandler.cs +++ b/EOLib/PacketHandlers/Cast/CastAcceptHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -7,7 +8,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Cast { diff --git a/EOLib/PacketHandlers/Cast/CastReplyHandler.cs b/EOLib/PacketHandlers/Cast/CastReplyHandler.cs index ba2588fc6..f906591fd 100644 --- a/EOLib/PacketHandlers/Cast/CastReplyHandler.cs +++ b/EOLib/PacketHandlers/Cast/CastReplyHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,7 +7,6 @@ using EOLib.PacketHandlers.NPC; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Cast { diff --git a/EOLib/PacketHandlers/Cast/CastSpecHandler.cs b/EOLib/PacketHandlers/Cast/CastSpecHandler.cs index e4b7c99fa..bb92ad9c5 100644 --- a/EOLib/PacketHandlers/Cast/CastSpecHandler.cs +++ b/EOLib/PacketHandlers/Cast/CastSpecHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -7,7 +8,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Cast { diff --git a/EOLib/PacketHandlers/Chat/AdminMessageHandler.cs b/EOLib/PacketHandlers/Chat/AdminMessageHandler.cs index 5984ddab7..7385b4b2d 100644 --- a/EOLib/PacketHandlers/Chat/AdminMessageHandler.cs +++ b/EOLib/PacketHandlers/Chat/AdminMessageHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Chat; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Chat { diff --git a/EOLib/PacketHandlers/Chat/AnnounceMessageHandler.cs b/EOLib/PacketHandlers/Chat/AnnounceMessageHandler.cs index d1da864f0..18fd2b84c 100644 --- a/EOLib/PacketHandlers/Chat/AnnounceMessageHandler.cs +++ b/EOLib/PacketHandlers/Chat/AnnounceMessageHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Chat; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Chat { diff --git a/EOLib/PacketHandlers/Chat/GroupChatHandler.cs b/EOLib/PacketHandlers/Chat/GroupChatHandler.cs index 6650f25ef..9e4b4b2cc 100644 --- a/EOLib/PacketHandlers/Chat/GroupChatHandler.cs +++ b/EOLib/PacketHandlers/Chat/GroupChatHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Chat; using EOLib.Domain.Login; @@ -6,7 +7,6 @@ using EOLib.Domain.Notifiers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Chat { diff --git a/EOLib/PacketHandlers/Chat/MuteHandler.cs b/EOLib/PacketHandlers/Chat/MuteHandler.cs index dc315aa5a..6c949c513 100644 --- a/EOLib/PacketHandlers/Chat/MuteHandler.cs +++ b/EOLib/PacketHandlers/Chat/MuteHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Chat { diff --git a/EOLib/PacketHandlers/Chat/PrivateMessageHandler.cs b/EOLib/PacketHandlers/Chat/PrivateMessageHandler.cs index 934bc338a..6d5bd2ea3 100644 --- a/EOLib/PacketHandlers/Chat/PrivateMessageHandler.cs +++ b/EOLib/PacketHandlers/Chat/PrivateMessageHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Chat; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Chat { diff --git a/EOLib/PacketHandlers/Chat/PrivateMessageTargetNotFound.cs b/EOLib/PacketHandlers/Chat/PrivateMessageTargetNotFound.cs index d428fbc52..2a8b3831b 100644 --- a/EOLib/PacketHandlers/Chat/PrivateMessageTargetNotFound.cs +++ b/EOLib/PacketHandlers/Chat/PrivateMessageTargetNotFound.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Chat; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Chat { diff --git a/EOLib/PacketHandlers/Chat/PublicChatHandler.cs b/EOLib/PacketHandlers/Chat/PublicChatHandler.cs index 4a22f8746..3792ad4d8 100644 --- a/EOLib/PacketHandlers/Chat/PublicChatHandler.cs +++ b/EOLib/PacketHandlers/Chat/PublicChatHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Chat; using EOLib.Domain.Login; @@ -6,7 +7,6 @@ using EOLib.Domain.Notifiers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Chat { diff --git a/EOLib/PacketHandlers/Chat/TalkServerHandler.cs b/EOLib/PacketHandlers/Chat/TalkServerHandler.cs index 7a32c987f..38ee4f830 100644 --- a/EOLib/PacketHandlers/Chat/TalkServerHandler.cs +++ b/EOLib/PacketHandlers/Chat/TalkServerHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Chat { diff --git a/EOLib/PacketHandlers/Chest/ChestAgreeHandler.cs b/EOLib/PacketHandlers/Chest/ChestAgreeHandler.cs index e68c90278..85aae2e7f 100644 --- a/EOLib/PacketHandlers/Chest/ChestAgreeHandler.cs +++ b/EOLib/PacketHandlers/Chest/ChestAgreeHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.Chest { diff --git a/EOLib/PacketHandlers/Chest/ChestCloseHandler.cs b/EOLib/PacketHandlers/Chest/ChestCloseHandler.cs index 311fb7eb0..e11ec3afb 100644 --- a/EOLib/PacketHandlers/Chest/ChestCloseHandler.cs +++ b/EOLib/PacketHandlers/Chest/ChestCloseHandler.cs @@ -1,10 +1,10 @@ -using EOLib.Domain.Login; +using System.Collections.Generic; +using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.IO.Map; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Chest { diff --git a/EOLib/PacketHandlers/Chest/ChestItemUpdateHandler.cs b/EOLib/PacketHandlers/Chest/ChestItemUpdateHandler.cs index adb0b9720..adb7b2b6e 100644 --- a/EOLib/PacketHandlers/Chest/ChestItemUpdateHandler.cs +++ b/EOLib/PacketHandlers/Chest/ChestItemUpdateHandler.cs @@ -1,11 +1,11 @@ -using EOLib.Domain.Character; +using System.Collections.Generic; +using System.Linq; +using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Optional.Collections; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.Chest { diff --git a/EOLib/PacketHandlers/Chest/ChestOpenHandler.cs b/EOLib/PacketHandlers/Chest/ChestOpenHandler.cs index 69e5aed3c..c87ee40dd 100644 --- a/EOLib/PacketHandlers/Chest/ChestOpenHandler.cs +++ b/EOLib/PacketHandlers/Chest/ChestOpenHandler.cs @@ -1,12 +1,12 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.Chest { diff --git a/EOLib/PacketHandlers/Citizen/CitizenOpenHandler.cs b/EOLib/PacketHandlers/Citizen/CitizenOpenHandler.cs index bcd7a2d60..fb9513e9d 100644 --- a/EOLib/PacketHandlers/Citizen/CitizenOpenHandler.cs +++ b/EOLib/PacketHandlers/Citizen/CitizenOpenHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Interact.Citizen; using EOLib.Domain.Login; @@ -7,7 +8,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Citizen { diff --git a/EOLib/PacketHandlers/Citizen/CitizenRemoveHandler.cs b/EOLib/PacketHandlers/Citizen/CitizenRemoveHandler.cs index 4fec1b1d9..c78c05431 100644 --- a/EOLib/PacketHandlers/Citizen/CitizenRemoveHandler.cs +++ b/EOLib/PacketHandlers/Citizen/CitizenRemoveHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Interact.Citizen; using EOLib.Domain.Login; @@ -6,7 +7,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Citizen { diff --git a/EOLib/PacketHandlers/Citizen/CitizenReplyHandler.cs b/EOLib/PacketHandlers/Citizen/CitizenReplyHandler.cs index 4516a3a5f..40e0484a3 100644 --- a/EOLib/PacketHandlers/Citizen/CitizenReplyHandler.cs +++ b/EOLib/PacketHandlers/Citizen/CitizenReplyHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Citizen { diff --git a/EOLib/PacketHandlers/Citizen/CitizenRequestHandler.cs b/EOLib/PacketHandlers/Citizen/CitizenRequestHandler.cs index ca0a44b10..b2025db35 100644 --- a/EOLib/PacketHandlers/Citizen/CitizenRequestHandler.cs +++ b/EOLib/PacketHandlers/Citizen/CitizenRequestHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Citizen { diff --git a/EOLib/PacketHandlers/Commands/PingResponseHandler.cs b/EOLib/PacketHandlers/Commands/PingResponseHandler.cs index 6ea95ede5..9983454f9 100644 --- a/EOLib/PacketHandlers/Commands/PingResponseHandler.cs +++ b/EOLib/PacketHandlers/Commands/PingResponseHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Domain.Protocol; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Commands { diff --git a/EOLib/PacketHandlers/Door/DoorOpenHandler.cs b/EOLib/PacketHandlers/Door/DoorOpenHandler.cs index debe7e5d3..4b9bf1fa9 100644 --- a/EOLib/PacketHandlers/Door/DoorOpenHandler.cs +++ b/EOLib/PacketHandlers/Door/DoorOpenHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Linq; using DomainWarp = EOLib.Domain.Map.Warp; namespace EOLib.PacketHandlers.Door diff --git a/EOLib/PacketHandlers/Effects/EffectAgreeHandler.cs b/EOLib/PacketHandlers/Effects/EffectAgreeHandler.cs index 5c7deb250..c01d520fb 100644 --- a/EOLib/PacketHandlers/Effects/EffectAgreeHandler.cs +++ b/EOLib/PacketHandlers/Effects/EffectAgreeHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Effects { diff --git a/EOLib/PacketHandlers/Effects/EffectPotionHandler.cs b/EOLib/PacketHandlers/Effects/EffectPotionHandler.cs index dfebc201b..45f043d91 100644 --- a/EOLib/PacketHandlers/Effects/EffectPotionHandler.cs +++ b/EOLib/PacketHandlers/Effects/EffectPotionHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Effects { diff --git a/EOLib/PacketHandlers/Effects/MapDebuffHandler.cs b/EOLib/PacketHandlers/Effects/MapDebuffHandler.cs index cb9634a43..f5c627770 100644 --- a/EOLib/PacketHandlers/Effects/MapDebuffHandler.cs +++ b/EOLib/PacketHandlers/Effects/MapDebuffHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -7,8 +9,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Effects { diff --git a/EOLib/PacketHandlers/Effects/MapHpDrainHandler.cs b/EOLib/PacketHandlers/Effects/MapHpDrainHandler.cs index 35b6c73f4..51954dc33 100644 --- a/EOLib/PacketHandlers/Effects/MapHpDrainHandler.cs +++ b/EOLib/PacketHandlers/Effects/MapHpDrainHandler.cs @@ -1,4 +1,6 @@  +using System; +using System.Collections.Generic; using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Extensions; @@ -7,8 +9,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Effects { diff --git a/EOLib/PacketHandlers/Effects/MapQuakeHandler.cs b/EOLib/PacketHandlers/Effects/MapQuakeHandler.cs index da85a63a8..2c4666229 100644 --- a/EOLib/PacketHandlers/Effects/MapQuakeHandler.cs +++ b/EOLib/PacketHandlers/Effects/MapQuakeHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Effects { diff --git a/EOLib/PacketHandlers/Effects/PlayerSpikeDamageHandler.cs b/EOLib/PacketHandlers/Effects/PlayerSpikeDamageHandler.cs index 7829f00a1..ba65b04f4 100644 --- a/EOLib/PacketHandlers/Effects/PlayerSpikeDamageHandler.cs +++ b/EOLib/PacketHandlers/Effects/PlayerSpikeDamageHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Extensions; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Effects { diff --git a/EOLib/PacketHandlers/Effects/TimedSpikeEffectHandler.cs b/EOLib/PacketHandlers/Effects/TimedSpikeEffectHandler.cs index c267894aa..7acf0bbcf 100644 --- a/EOLib/PacketHandlers/Effects/TimedSpikeEffectHandler.cs +++ b/EOLib/PacketHandlers/Effects/TimedSpikeEffectHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using EOLib.Domain.Login; @@ -9,8 +11,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Effects { diff --git a/EOLib/PacketHandlers/Emote/EmotePlayerHandler.cs b/EOLib/PacketHandlers/Emote/EmotePlayerHandler.cs index dccf7a6d5..050892d87 100644 --- a/EOLib/PacketHandlers/Emote/EmotePlayerHandler.cs +++ b/EOLib/PacketHandlers/Emote/EmotePlayerHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Emote { diff --git a/EOLib/PacketHandlers/Init/FriendIgnoreListHandler.cs b/EOLib/PacketHandlers/Init/FriendIgnoreListHandler.cs index abd0a303f..961a3c668 100644 --- a/EOLib/PacketHandlers/Init/FriendIgnoreListHandler.cs +++ b/EOLib/PacketHandlers/Init/FriendIgnoreListHandler.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; -using EOLib.Domain.Online; -using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; +using System; using System.Collections.Generic; using System.Linq; +using AutomaticTypeMapper; +using EOLib.Domain.Online; +using Moffat.EndlessOnline.SDK.Protocol.Net.Server; namespace EOLib.PacketHandlers.Init { diff --git a/EOLib/PacketHandlers/Init/InGameInitPacketHandler.cs b/EOLib/PacketHandlers/Init/InGameInitPacketHandler.cs index 0a9737d9e..0b0003b01 100644 --- a/EOLib/PacketHandlers/Init/InGameInitPacketHandler.cs +++ b/EOLib/PacketHandlers/Init/InGameInitPacketHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional.Collections; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Init { diff --git a/EOLib/PacketHandlers/Init/MapMutationHandler.cs b/EOLib/PacketHandlers/Init/MapMutationHandler.cs index 6a7d6e43b..24ccc7cd1 100644 --- a/EOLib/PacketHandlers/Init/MapMutationHandler.cs +++ b/EOLib/PacketHandlers/Init/MapMutationHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Notifiers; using EOLib.IO.Map; @@ -6,7 +7,6 @@ using EOLib.IO.Services; using EOLib.IO.Services.Serializers; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Init { diff --git a/EOLib/PacketHandlers/Init/OnlinePlayerListHandler.cs b/EOLib/PacketHandlers/Init/OnlinePlayerListHandler.cs index 4024bd429..af9f0c14f 100644 --- a/EOLib/PacketHandlers/Init/OnlinePlayerListHandler.cs +++ b/EOLib/PacketHandlers/Init/OnlinePlayerListHandler.cs @@ -1,9 +1,9 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Online; using EOLib.IO.Repositories; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.Init { diff --git a/EOLib/PacketHandlers/Items/ItemAcceptHandler.cs b/EOLib/PacketHandlers/Items/ItemAcceptHandler.cs index 4212475b8..cecb68779 100644 --- a/EOLib/PacketHandlers/Items/ItemAcceptHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemAcceptHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Items { diff --git a/EOLib/PacketHandlers/Items/ItemAddHandler.cs b/EOLib/PacketHandlers/Items/ItemAddHandler.cs index e2571b93f..11511c22d 100644 --- a/EOLib/PacketHandlers/Items/ItemAddHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemAddHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System; namespace EOLib.PacketHandlers.Items { diff --git a/EOLib/PacketHandlers/Items/ItemDropHandler.cs b/EOLib/PacketHandlers/Items/ItemDropHandler.cs index 2ed349ffa..56003a44b 100644 --- a/EOLib/PacketHandlers/Items/ItemDropHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemDropHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -7,8 +9,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Items { diff --git a/EOLib/PacketHandlers/Items/ItemGetHandler.cs b/EOLib/PacketHandlers/Items/ItemGetHandler.cs index b199602fb..dc681e69d 100644 --- a/EOLib/PacketHandlers/Items/ItemGetHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemGetHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -7,7 +8,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional.Collections; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Items { diff --git a/EOLib/PacketHandlers/Items/ItemJunkHandler.cs b/EOLib/PacketHandlers/Items/ItemJunkHandler.cs index b236ef9ef..2df222f90 100644 --- a/EOLib/PacketHandlers/Items/ItemJunkHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemJunkHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -6,7 +7,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional.Collections; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Items { diff --git a/EOLib/PacketHandlers/Items/ItemReplyHandler.cs b/EOLib/PacketHandlers/Items/ItemReplyHandler.cs index f9a6ce975..3407f1094 100644 --- a/EOLib/PacketHandlers/Items/ItemReplyHandler.cs +++ b/EOLib/PacketHandlers/Items/ItemReplyHandler.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -8,9 +11,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Moffat.EndlessOnline.SDK.Protocol.Pub; using Optional.Collections; -using System; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.Items { diff --git a/EOLib/PacketHandlers/Items/QuestItemChangeHandler.cs b/EOLib/PacketHandlers/Items/QuestItemChangeHandler.cs index 52ff637d9..d573db1db 100644 --- a/EOLib/PacketHandlers/Items/QuestItemChangeHandler.cs +++ b/EOLib/PacketHandlers/Items/QuestItemChangeHandler.cs @@ -1,9 +1,9 @@ -using EOLib.Domain.Character; +using System; +using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Optional.Collections; -using System; namespace EOLib.PacketHandlers.Items { diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxMessageHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxMessageHandler.cs index 6736f9868..bf3d0f7ec 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxMessageHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxMessageHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Jukebox { diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxOpenHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxOpenHandler.cs index cc3868b55..0a74fa467 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxOpenHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxOpenHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact.Jukebox; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -6,7 +7,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Jukebox { diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxPlayerHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxPlayerHandler.cs index dbe30102d..3d80ea9a7 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxPlayerHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxPlayerHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Jukebox { diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxReplyHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxReplyHandler.cs index 71bc1a6af..92f3efd76 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxReplyHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxReplyHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Jukebox { diff --git a/EOLib/PacketHandlers/Jukebox/JukeboxUseHandler.cs b/EOLib/PacketHandlers/Jukebox/JukeboxUseHandler.cs index 9a2dd932f..586f3a2cf 100644 --- a/EOLib/PacketHandlers/Jukebox/JukeboxUseHandler.cs +++ b/EOLib/PacketHandlers/Jukebox/JukeboxUseHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact.Jukebox; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -6,7 +7,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Jukebox { diff --git a/EOLib/PacketHandlers/Locker/LockerBuyHandler.cs b/EOLib/PacketHandlers/Locker/LockerBuyHandler.cs index 1ee22bcc9..9ec4f4acc 100644 --- a/EOLib/PacketHandlers/Locker/LockerBuyHandler.cs +++ b/EOLib/PacketHandlers/Locker/LockerBuyHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Interact.Bank; using EOLib.Domain.Login; @@ -7,7 +8,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Locker { diff --git a/EOLib/PacketHandlers/Locker/LockerModifyHandler.cs b/EOLib/PacketHandlers/Locker/LockerModifyHandler.cs index 77e59102c..f462d2582 100644 --- a/EOLib/PacketHandlers/Locker/LockerModifyHandler.cs +++ b/EOLib/PacketHandlers/Locker/LockerModifyHandler.cs @@ -1,10 +1,10 @@ -using EOLib.Domain.Character; +using System.Collections.Generic; +using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Optional.Collections; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Locker { diff --git a/EOLib/PacketHandlers/Locker/LockerOpenHandler.cs b/EOLib/PacketHandlers/Locker/LockerOpenHandler.cs index 3e87d749a..aa1c7278e 100644 --- a/EOLib/PacketHandlers/Locker/LockerOpenHandler.cs +++ b/EOLib/PacketHandlers/Locker/LockerOpenHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Locker { diff --git a/EOLib/PacketHandlers/Locker/LockerSpecHandler.cs b/EOLib/PacketHandlers/Locker/LockerSpecHandler.cs index 56a6b4abe..b0b4bbef0 100644 --- a/EOLib/PacketHandlers/Locker/LockerSpecHandler.cs +++ b/EOLib/PacketHandlers/Locker/LockerSpecHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Locker { diff --git a/EOLib/PacketHandlers/MapInfo/MapInfoReplyHandler.cs b/EOLib/PacketHandlers/MapInfo/MapInfoReplyHandler.cs index 74b9152ba..91755c811 100644 --- a/EOLib/PacketHandlers/MapInfo/MapInfoReplyHandler.cs +++ b/EOLib/PacketHandlers/MapInfo/MapInfoReplyHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using EOLib.Domain.Login; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Linq; namespace EOLib.PacketHandlers.MapInfo { diff --git a/EOLib/PacketHandlers/Marriage/MarriageOpenHandler.cs b/EOLib/PacketHandlers/Marriage/MarriageOpenHandler.cs index 138238a08..07ca8be81 100644 --- a/EOLib/PacketHandlers/Marriage/MarriageOpenHandler.cs +++ b/EOLib/PacketHandlers/Marriage/MarriageOpenHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Interact.Law; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Marriage { diff --git a/EOLib/PacketHandlers/Marriage/MarriageReplyHandler.cs b/EOLib/PacketHandlers/Marriage/MarriageReplyHandler.cs index e70f28171..31814f975 100644 --- a/EOLib/PacketHandlers/Marriage/MarriageReplyHandler.cs +++ b/EOLib/PacketHandlers/Marriage/MarriageReplyHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Interact; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Marriage { diff --git a/EOLib/PacketHandlers/Message/MessageAcceptHandler.cs b/EOLib/PacketHandlers/Message/MessageAcceptHandler.cs index 46fc4ca18..799b1b669 100644 --- a/EOLib/PacketHandlers/Message/MessageAcceptHandler.cs +++ b/EOLib/PacketHandlers/Message/MessageAcceptHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.Message { diff --git a/EOLib/PacketHandlers/Message/MessageCloseHandler.cs b/EOLib/PacketHandlers/Message/MessageCloseHandler.cs index c9cc78b70..a9acdbfee 100644 --- a/EOLib/PacketHandlers/Message/MessageCloseHandler.cs +++ b/EOLib/PacketHandlers/Message/MessageCloseHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Message { diff --git a/EOLib/PacketHandlers/Music/MusicPlayerHandler.cs b/EOLib/PacketHandlers/Music/MusicPlayerHandler.cs index 2b6451e96..186f2cd8c 100644 --- a/EOLib/PacketHandlers/Music/MusicPlayerHandler.cs +++ b/EOLib/PacketHandlers/Music/MusicPlayerHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Music { diff --git a/EOLib/PacketHandlers/NPC/NPCAcceptHandler.cs b/EOLib/PacketHandlers/NPC/NPCAcceptHandler.cs index ba8851bec..93e2070ef 100644 --- a/EOLib/PacketHandlers/NPC/NPCAcceptHandler.cs +++ b/EOLib/PacketHandlers/NPC/NPCAcceptHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Domain.Notifiers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.NPC { diff --git a/EOLib/PacketHandlers/NPC/NPCAgreeHandler.cs b/EOLib/PacketHandlers/NPC/NPCAgreeHandler.cs index 0d033d72d..495e09d3d 100644 --- a/EOLib/PacketHandlers/NPC/NPCAgreeHandler.cs +++ b/EOLib/PacketHandlers/NPC/NPCAgreeHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Linq; namespace EOLib.PacketHandlers.NPC { diff --git a/EOLib/PacketHandlers/NPC/NPCDeathHandler.cs b/EOLib/PacketHandlers/NPC/NPCDeathHandler.cs index facbfc33e..a859d52a9 100644 --- a/EOLib/PacketHandlers/NPC/NPCDeathHandler.cs +++ b/EOLib/PacketHandlers/NPC/NPCDeathHandler.cs @@ -1,4 +1,6 @@ -using EOLib.Domain.Character; +using System; +using System.Collections.Generic; +using EOLib.Domain.Character; using EOLib.Domain.Interact.Skill; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -7,8 +9,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System; -using System.Collections.Generic; namespace EOLib.PacketHandlers.NPC { diff --git a/EOLib/PacketHandlers/NPC/NPCDialogHandler.cs b/EOLib/PacketHandlers/NPC/NPCDialogHandler.cs index df0f92886..07f295467 100644 --- a/EOLib/PacketHandlers/NPC/NPCDialogHandler.cs +++ b/EOLib/PacketHandlers/NPC/NPCDialogHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Chat; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -8,7 +9,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional.Collections; -using System.Collections.Generic; namespace EOLib.PacketHandlers.NPC { diff --git a/EOLib/PacketHandlers/NPC/NPCJunkHandler.cs b/EOLib/PacketHandlers/NPC/NPCJunkHandler.cs index e6e2b4da2..209787dc5 100644 --- a/EOLib/PacketHandlers/NPC/NPCJunkHandler.cs +++ b/EOLib/PacketHandlers/NPC/NPCJunkHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -7,8 +9,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.NPC { diff --git a/EOLib/PacketHandlers/NPC/NPCPlayerHandler.cs b/EOLib/PacketHandlers/NPC/NPCPlayerHandler.cs index 6fd021638..aa2629d1c 100644 --- a/EOLib/PacketHandlers/NPC/NPCPlayerHandler.cs +++ b/EOLib/PacketHandlers/NPC/NPCPlayerHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Chat; using EOLib.Domain.Extensions; @@ -11,9 +13,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; using Optional.Collections; -using System; -using System.Collections.Generic; - using DomainNPC = EOLib.Domain.NPC.NPC; namespace EOLib.PacketHandlers.NPC diff --git a/EOLib/PacketHandlers/NPC/NPCReplyHandler.cs b/EOLib/PacketHandlers/NPC/NPCReplyHandler.cs index 41b343bdb..546429d39 100644 --- a/EOLib/PacketHandlers/NPC/NPCReplyHandler.cs +++ b/EOLib/PacketHandlers/NPC/NPCReplyHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Domain.Notifiers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.NPC { diff --git a/EOLib/PacketHandlers/NPC/NPCSpecHandler.cs b/EOLib/PacketHandlers/NPC/NPCSpecHandler.cs index 91758a4e3..69e52caa4 100644 --- a/EOLib/PacketHandlers/NPC/NPCSpecHandler.cs +++ b/EOLib/PacketHandlers/NPC/NPCSpecHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,8 +8,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System; -using System.Collections.Generic; namespace EOLib.PacketHandlers.NPC { diff --git a/EOLib/PacketHandlers/NPC/NPCTakeDamageHandler.cs b/EOLib/PacketHandlers/NPC/NPCTakeDamageHandler.cs index 35e2f92b8..82b781f33 100644 --- a/EOLib/PacketHandlers/NPC/NPCTakeDamageHandler.cs +++ b/EOLib/PacketHandlers/NPC/NPCTakeDamageHandler.cs @@ -1,4 +1,5 @@ -using EOLib.Domain.Character; +using System.Collections.Generic; +using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Domain.Notifiers; @@ -6,7 +7,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; namespace EOLib.PacketHandlers.NPC { diff --git a/EOLib/PacketHandlers/Paperdoll/ItemEquipHandler.cs b/EOLib/PacketHandlers/Paperdoll/ItemEquipHandler.cs index 5d2cbdc4a..13fbe0922 100644 --- a/EOLib/PacketHandlers/Paperdoll/ItemEquipHandler.cs +++ b/EOLib/PacketHandlers/Paperdoll/ItemEquipHandler.cs @@ -1,4 +1,5 @@ -using EOLib.Domain.Character; +using System.Linq; +using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.IO.Extensions; @@ -8,7 +9,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; using Optional.Collections; -using System.Linq; namespace EOLib.PacketHandlers.Paperdoll { diff --git a/EOLib/PacketHandlers/Party/PartyAddHandler.cs b/EOLib/PacketHandlers/Party/PartyAddHandler.cs index d6059216e..816192e6e 100644 --- a/EOLib/PacketHandlers/Party/PartyAddHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyAddHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Domain.Party; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Party { diff --git a/EOLib/PacketHandlers/Party/PartyCreateHandler.cs b/EOLib/PacketHandlers/Party/PartyCreateHandler.cs index 9b2737117..8f49b6d3e 100644 --- a/EOLib/PacketHandlers/Party/PartyCreateHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyCreateHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Domain.Party; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Party { diff --git a/EOLib/PacketHandlers/Party/PartyRemoveHandler.cs b/EOLib/PacketHandlers/Party/PartyRemoveHandler.cs index 8bb7fb5d2..38558d95c 100644 --- a/EOLib/PacketHandlers/Party/PartyRemoveHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyRemoveHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Domain.Party; @@ -6,7 +7,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional.Collections; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Party { diff --git a/EOLib/PacketHandlers/Party/PartyRequestHandler.cs b/EOLib/PacketHandlers/Party/PartyRequestHandler.cs index 6a6e4d80f..5600c380b 100644 --- a/EOLib/PacketHandlers/Party/PartyRequestHandler.cs +++ b/EOLib/PacketHandlers/Party/PartyRequestHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Party { diff --git a/EOLib/PacketHandlers/Players/PlayersAgreeHandler.cs b/EOLib/PacketHandlers/Players/PlayersAgreeHandler.cs index a08827987..8a773bd8d 100644 --- a/EOLib/PacketHandlers/Players/PlayersAgreeHandler.cs +++ b/EOLib/PacketHandlers/Players/PlayersAgreeHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using EOLib.Domain.Login; @@ -7,8 +9,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.Players { diff --git a/EOLib/PacketHandlers/Priest/PriestOpenHandler.cs b/EOLib/PacketHandlers/Priest/PriestOpenHandler.cs index 25fe5b7b0..563aed1b2 100644 --- a/EOLib/PacketHandlers/Priest/PriestOpenHandler.cs +++ b/EOLib/PacketHandlers/Priest/PriestOpenHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Interact.Priest; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Priest { diff --git a/EOLib/PacketHandlers/Priest/PriestReplyHandler.cs b/EOLib/PacketHandlers/Priest/PriestReplyHandler.cs index dd241fe3e..e7aa930a9 100644 --- a/EOLib/PacketHandlers/Priest/PriestReplyHandler.cs +++ b/EOLib/PacketHandlers/Priest/PriestReplyHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Priest { diff --git a/EOLib/PacketHandlers/Priest/PriestRequestHandler.cs b/EOLib/PacketHandlers/Priest/PriestRequestHandler.cs index e88647d95..599babdce 100644 --- a/EOLib/PacketHandlers/Priest/PriestRequestHandler.cs +++ b/EOLib/PacketHandlers/Priest/PriestRequestHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Interact.Priest; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Priest { diff --git a/EOLib/PacketHandlers/Quest/QuestDialogHandler.cs b/EOLib/PacketHandlers/Quest/QuestDialogHandler.cs index 25f64220c..4d47626f8 100644 --- a/EOLib/PacketHandlers/Quest/QuestDialogHandler.cs +++ b/EOLib/PacketHandlers/Quest/QuestDialogHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Interact.Quest; using EOLib.Domain.Login; @@ -6,8 +8,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.Quest { diff --git a/EOLib/PacketHandlers/Quest/QuestListHandler.cs b/EOLib/PacketHandlers/Quest/QuestListHandler.cs index d63bd1823..47e038c6b 100644 --- a/EOLib/PacketHandlers/Quest/QuestListHandler.cs +++ b/EOLib/PacketHandlers/Quest/QuestListHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Interact.Quest; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Linq; namespace EOLib.PacketHandlers.Quest { diff --git a/EOLib/PacketHandlers/Quest/QuestStatusMessageHandler.cs b/EOLib/PacketHandlers/Quest/QuestStatusMessageHandler.cs index 2fa34af49..fcacca2a2 100644 --- a/EOLib/PacketHandlers/Quest/QuestStatusMessageHandler.cs +++ b/EOLib/PacketHandlers/Quest/QuestStatusMessageHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Chat; using EOLib.Domain.Interact.Quest; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Quest { diff --git a/EOLib/PacketHandlers/Recover/RecoverAgreeHandler.cs b/EOLib/PacketHandlers/Recover/RecoverAgreeHandler.cs index df88300ea..bf2a91c70 100644 --- a/EOLib/PacketHandlers/Recover/RecoverAgreeHandler.cs +++ b/EOLib/PacketHandlers/Recover/RecoverAgreeHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,8 +8,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Recover { diff --git a/EOLib/PacketHandlers/Recover/RecoverReplyHandler.cs b/EOLib/PacketHandlers/Recover/RecoverReplyHandler.cs index ec35fe928..23a917d67 100644 --- a/EOLib/PacketHandlers/Recover/RecoverReplyHandler.cs +++ b/EOLib/PacketHandlers/Recover/RecoverReplyHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Recover { diff --git a/EOLib/PacketHandlers/Refresh/RefreshReplyHandler.cs b/EOLib/PacketHandlers/Refresh/RefreshReplyHandler.cs index 35c76421e..72bec5de9 100644 --- a/EOLib/PacketHandlers/Refresh/RefreshReplyHandler.cs +++ b/EOLib/PacketHandlers/Refresh/RefreshReplyHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,9 +8,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; -using System.Linq; - using DomainNPC = EOLib.Domain.NPC.NPC; namespace EOLib.PacketHandlers.Refresh diff --git a/EOLib/PacketHandlers/Shop/ShopCraftHandler.cs b/EOLib/PacketHandlers/Shop/ShopCraftHandler.cs index f4ee90a2b..e4cfc4d42 100644 --- a/EOLib/PacketHandlers/Shop/ShopCraftHandler.cs +++ b/EOLib/PacketHandlers/Shop/ShopCraftHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -6,7 +7,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional.Collections; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Shop { diff --git a/EOLib/PacketHandlers/Shop/ShopOpenHandler.cs b/EOLib/PacketHandlers/Shop/ShopOpenHandler.cs index 1b7496f9f..5d45ae575 100644 --- a/EOLib/PacketHandlers/Shop/ShopOpenHandler.cs +++ b/EOLib/PacketHandlers/Shop/ShopOpenHandler.cs @@ -1,12 +1,12 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Interact.Shop; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.Shop { diff --git a/EOLib/PacketHandlers/Shop/ShopTradeHandler.cs b/EOLib/PacketHandlers/Shop/ShopTradeHandler.cs index 253ed14a1..b99c431bf 100644 --- a/EOLib/PacketHandlers/Shop/ShopTradeHandler.cs +++ b/EOLib/PacketHandlers/Shop/ShopTradeHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -7,7 +8,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional.Collections; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Shop { diff --git a/EOLib/PacketHandlers/Spell/SpellRequestHandler.cs b/EOLib/PacketHandlers/Spell/SpellRequestHandler.cs index 585dc200a..ea410ba8b 100644 --- a/EOLib/PacketHandlers/Spell/SpellRequestHandler.cs +++ b/EOLib/PacketHandlers/Spell/SpellRequestHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Spell { diff --git a/EOLib/PacketHandlers/Spell/SpellTargetGroupHandler.cs b/EOLib/PacketHandlers/Spell/SpellTargetGroupHandler.cs index a4dc29e34..512657336 100644 --- a/EOLib/PacketHandlers/Spell/SpellTargetGroupHandler.cs +++ b/EOLib/PacketHandlers/Spell/SpellTargetGroupHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -8,8 +10,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional.Collections; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.Spell { diff --git a/EOLib/PacketHandlers/Spell/SpellTargetOtherHandler.cs b/EOLib/PacketHandlers/Spell/SpellTargetOtherHandler.cs index bd6a6b329..4042ef67f 100644 --- a/EOLib/PacketHandlers/Spell/SpellTargetOtherHandler.cs +++ b/EOLib/PacketHandlers/Spell/SpellTargetOtherHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Map; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Spell { diff --git a/EOLib/PacketHandlers/Spell/SpellTargetSelfHandler.cs b/EOLib/PacketHandlers/Spell/SpellTargetSelfHandler.cs index d798fad89..13934fb8d 100644 --- a/EOLib/PacketHandlers/Spell/SpellTargetSelfHandler.cs +++ b/EOLib/PacketHandlers/Spell/SpellTargetSelfHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Spell { diff --git a/EOLib/PacketHandlers/StatSkill/StatskillJunkHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillJunkHandler.cs index 11a1d0ce1..c4d4fb306 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillJunkHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillJunkHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Interact; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.StatSkill { diff --git a/EOLib/PacketHandlers/StatSkill/StatskillOpenHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillOpenHandler.cs index 5c238d6ae..9a2404d46 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillOpenHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillOpenHandler.cs @@ -1,12 +1,12 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Interact.Skill; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.StatSkill { diff --git a/EOLib/PacketHandlers/StatSkill/StatskillRemoveHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillRemoveHandler.cs index 59f69d042..ecbd3488d 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillRemoveHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillRemoveHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Interact; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.StatSkill { diff --git a/EOLib/PacketHandlers/StatSkill/StatskillReplyHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillReplyHandler.cs index df9267e84..85fb1d258 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillReplyHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillReplyHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Interact; using EOLib.Domain.Interact.Skill; using EOLib.Domain.Login; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.StatSkill { diff --git a/EOLib/PacketHandlers/StatSkill/StatskillTakeHandler.cs b/EOLib/PacketHandlers/StatSkill/StatskillTakeHandler.cs index 7f89ccb59..c84d28d02 100644 --- a/EOLib/PacketHandlers/StatSkill/StatskillTakeHandler.cs +++ b/EOLib/PacketHandlers/StatSkill/StatskillTakeHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Interact; using EOLib.Domain.Login; @@ -6,8 +8,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; -using System.Linq; namespace EOLib.PacketHandlers.StatSkill { diff --git a/EOLib/PacketHandlers/Trade/TradeCloseHandler.cs b/EOLib/PacketHandlers/Trade/TradeCloseHandler.cs index 41302db77..04e378f1a 100644 --- a/EOLib/PacketHandlers/Trade/TradeCloseHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeCloseHandler.cs @@ -1,11 +1,11 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Domain.Trade; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Trade { diff --git a/EOLib/PacketHandlers/Trade/TradeOfferUpdateHandler.cs b/EOLib/PacketHandlers/Trade/TradeOfferUpdateHandler.cs index 0e5929b38..75a31fef2 100644 --- a/EOLib/PacketHandlers/Trade/TradeOfferUpdateHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeOfferUpdateHandler.cs @@ -1,11 +1,11 @@ -using EOLib.Domain.Character; +using System.Linq; +using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Trade; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System.Linq; namespace EOLib.PacketHandlers.Trade { diff --git a/EOLib/PacketHandlers/Trade/TradeOpenHandler.cs b/EOLib/PacketHandlers/Trade/TradeOpenHandler.cs index 362019b71..3553725b9 100644 --- a/EOLib/PacketHandlers/Trade/TradeOpenHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeOpenHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -6,7 +7,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Trade { diff --git a/EOLib/PacketHandlers/Trade/TradeRequestHandler.cs b/EOLib/PacketHandlers/Trade/TradeRequestHandler.cs index c3e7d56fd..dab86e4e7 100644 --- a/EOLib/PacketHandlers/Trade/TradeRequestHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeRequestHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Trade { diff --git a/EOLib/PacketHandlers/Trade/TradeUseHandler.cs b/EOLib/PacketHandlers/Trade/TradeUseHandler.cs index 03cbc8f87..a20ea5180 100644 --- a/EOLib/PacketHandlers/Trade/TradeUseHandler.cs +++ b/EOLib/PacketHandlers/Trade/TradeUseHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Login; using EOLib.Domain.Notifiers; @@ -8,7 +9,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; using Optional.Collections; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Trade { diff --git a/EOLib/PacketHandlers/Walk/WalkPlayerHandler.cs b/EOLib/PacketHandlers/Walk/WalkPlayerHandler.cs index 60476a544..adfccc96c 100644 --- a/EOLib/PacketHandlers/Walk/WalkPlayerHandler.cs +++ b/EOLib/PacketHandlers/Walk/WalkPlayerHandler.cs @@ -1,4 +1,5 @@ -using AutomaticTypeMapper; +using System.Collections.Generic; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using EOLib.Domain.Login; @@ -7,7 +8,6 @@ using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Collections.Generic; namespace EOLib.PacketHandlers.Walk { diff --git a/EOLib/PacketHandlers/Walk/WalkReplyHandler.cs b/EOLib/PacketHandlers/Walk/WalkReplyHandler.cs index f6ad66578..e5254841d 100644 --- a/EOLib/PacketHandlers/Walk/WalkReplyHandler.cs +++ b/EOLib/PacketHandlers/Walk/WalkReplyHandler.cs @@ -1,10 +1,10 @@ -using AutomaticTypeMapper; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.Net.Handlers; using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System.Linq; namespace EOLib.PacketHandlers.Walk { diff --git a/EOLib/PacketHandlers/Warp/WarpAgreeHandler.cs b/EOLib/PacketHandlers/Warp/WarpAgreeHandler.cs index b47d6ec91..c756385ed 100644 --- a/EOLib/PacketHandlers/Warp/WarpAgreeHandler.cs +++ b/EOLib/PacketHandlers/Warp/WarpAgreeHandler.cs @@ -1,4 +1,7 @@ -using AutomaticTypeMapper; +using System; +using System.Collections.Generic; +using System.Linq; +using AutomaticTypeMapper; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using EOLib.Domain.Login; @@ -9,10 +12,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; using Optional; -using System; -using System.Collections.Generic; -using System.Linq; - using DomainNPC = EOLib.Domain.NPC.NPC; namespace EOLib.PacketHandlers.Warp diff --git a/EOLib/PacketHandlers/Warp/WarpRequestHandler.cs b/EOLib/PacketHandlers/Warp/WarpRequestHandler.cs index 5648d560a..318e162fb 100644 --- a/EOLib/PacketHandlers/Warp/WarpRequestHandler.cs +++ b/EOLib/PacketHandlers/Warp/WarpRequestHandler.cs @@ -1,4 +1,6 @@ -using AutomaticTypeMapper; +using System; +using System.IO; +using AutomaticTypeMapper; using EOLib.Domain.Login; using EOLib.Domain.Map; using EOLib.IO.Actions; @@ -9,8 +11,6 @@ using Moffat.EndlessOnline.SDK.Protocol.Net; using Moffat.EndlessOnline.SDK.Protocol.Net.Client; using Moffat.EndlessOnline.SDK.Protocol.Net.Server; -using System; -using System.IO; namespace EOLib.PacketHandlers.Warp {