diff --git a/docs-website/docs/server-features/inventory-charms.md b/docs-website/docs/server-features/inventory-charms.md new file mode 100644 index 0000000000..ce6ad4dd0c --- /dev/null +++ b/docs-website/docs/server-features/inventory-charms.md @@ -0,0 +1,71 @@ +--- +title: Figurines and charms +sidebar_label: Figurines and charms +description: Figurines and charms give a bonus while used in the inventory. +--- + +The figurines and charms are items of the in-game shop. They are not worn in +an equipment slot. Instead, the player right clicks them inside the inventory +to use them, and the bonus applies as long as they stay in use there. Another +right click stops the use. + +| Item | Number | Bonus | +| ------------------------ | ------ | ------------------------------ | +| Hawk Figurine | 13/128 | +10% critical damage chance | +| Goat Figurine | 13/129 | +10% excellent damage chance | +| Oak Charm | 13/130 | +50 maximum health | +| Maple Charm | 13/131 | +50 maximum mana | +| Golden Oak Charm | 13/132 | +100 health, +500 shield | +| Golden Maple Charm | 13/133 | +150 mana, +50 ability (AG) | + +The values are the ones which the game client shows in the item tooltip. For +the Golden Oak Charm, the Season 6 Episode 3 client shows +100 health and +500 +shield, which matches its `ItemAddOption.bmd`; older clients showed +150 and ++50. The values are stored as power-ups of the item definitions, so they can +be changed in the admin panel. + +## Rules + +* Only one item of the same kind can be in use at the same time. Using a + second one is refused with a message. The Hawk and Goat Figurines, the Oak + and Golden Oak Charms, and the Maple and Golden Maple Charms count as the + same kind: they form an exclusive group in the configuration. +* The item keeps its state when it is moved inside the inventory. +* When the item leaves the inventory, for example when it is dropped or moved + into the vault, it is no longer in use, and the bonus is removed. This also + happens when the item was removed from the configuration in the meantime. +* Using an item which is already in use keeps its bonus, so the current + health, mana and so on stay as they are. +* Like in the original game, the state is stored in the durability of the + item: 254 means in use, 255 means not in use. A new item starts with 255 + when it is added to the inventory. The item definitions have a durability + of 1, so the items are not stackable. + +## Configuration + +The *Items used inside the inventory* feature plugin defines which items can +be used inside the inventory. By default, these are the items 13/128 to +13/134. Each item can have an exclusive group: only one item of a group can +be in use at the same time. By default, the figurines are group 1, the oak +charms group 2 and the maple charms group 3. It also defines the +durability values of an item which is in use (254) and not in use (255). +They have to match the game client. When the plugin is deactivated, no item +can be used this way. + +## Update of existing databases + +The update *Add the figurines and charms* adds the items, and links the +products of the cash shop to them. Their packages were not for sale before, +because their products had no item. The update leaves them that way, so the +administrator can put them on sale in the admin panel. + +## Protocol + +The client sends the request `C1 BF 20` with the inventory slot and the +requested state. The server answers with the same packet and the new state of +the item. + +:::note +The Worn Horseshoe (13/134) is not added yet, because there is no attribute +for the item drop rate yet. +::: diff --git a/docs-website/sidebars.js b/docs-website/sidebars.js index 3bb71b4fdc..e6abd6eb83 100644 --- a/docs-website/sidebars.js +++ b/docs-website/sidebars.js @@ -65,6 +65,7 @@ const sidebars = { "server-features/anti-cheat", "server-features/test-actors", "server-features/gens", + "server-features/inventory-charms", "server-features/cash-shop", "server-features/discord", "server-features/player-shop-currencies", diff --git a/docs/Progress.md b/docs/Progress.md index f98a26e3c8..5a7f2a80e7 100644 --- a/docs/Progress.md +++ b/docs/Progress.md @@ -89,6 +89,7 @@ complexity and effort). Complexity 0 means we wont implement it. | *CrywolfGroup* | 0xBD | 100% | 10 | | | *LuckyCoin* | 0xBF0B-0xBF0D | 100% | 3 | Registration and exchange at Delgado | | *IllusionTempleGroup* | 0xBF | 100% | 10 | Team-based PvP mini game: relic pickup/delivery, scoring, skill points, special skills, rewards | +| *InventoryItemEquip* | 0xBF20 | 100% | 2 | Using figurines and charms inside the inventory | | FriendListRequest | 0xC0 | 0% | 0 | Not needed, friend list is sent automatically | | *FriendAdd* | 0xC1 | 100% | 2 | | | *WaitFriendAdd* | 0xC2 | 100% | 2 | | diff --git a/src/GameLogic/IItemPowerUpFactory.cs b/src/GameLogic/IItemPowerUpFactory.cs index f5ee5e07e9..6141a2736f 100644 --- a/src/GameLogic/IItemPowerUpFactory.cs +++ b/src/GameLogic/IItemPowerUpFactory.cs @@ -19,8 +19,12 @@ public interface IItemPowerUpFactory /// /// The item. /// The attribute system of the player who equipped the item. + /// + /// If set to true, the item isn't equipped, but in use inside the inventory, see . + /// Otherwise, an item which isn't equipped has no power ups. + /// /// The created power ups. - IEnumerable GetPowerUps(Item item, AttributeSystem attributeSystem); + IEnumerable GetPowerUps(Item item, AttributeSystem attributeSystem, bool isInUseInsideInventory = false); /// /// Gets the set power ups, which are created for existing s in the equipped items. diff --git a/src/GameLogic/InventoryItemUseConfiguration.cs b/src/GameLogic/InventoryItemUseConfiguration.cs new file mode 100644 index 0000000000..a4ae8741c0 --- /dev/null +++ b/src/GameLogic/InventoryItemUseConfiguration.cs @@ -0,0 +1,113 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.GameLogic; + +using MUnique.OpenMU.DataModel.Composition; +using MUnique.OpenMU.DataModel.Configuration.Items; + +/// +/// The configuration of the items which are used inside the inventory, like the figurines and charms. +/// +public class InventoryItemUseConfiguration +{ + /// + /// The default of , which is the value the game client expects. + /// + private const byte DefaultInUseDurability = 254; + + /// + /// The default of , which is the value the game client expects. + /// + private const byte DefaultNotInUseDurability = 255; + + /// + /// Gets or sets the items which are used inside the inventory instead of being equipped. + /// + /// + /// By default, these are the figurines (group 13, number 128 and 129), the charms (130 to 133) + /// and the worn horseshoe (134), which the game client requests to use with a right click in the inventory. + /// The figurines, the oak charms and the maple charms each form an exclusive group, + /// see . + /// + [MemberOfAggregate] + [ScaffoldColumn(true)] + [Display(ResourceType = typeof(PlugInResources), Name = nameof(PlugInResources.InventoryItemUseConfiguration_Items_Name), Description = nameof(PlugInResources.InventoryItemUseConfiguration_Items_Description))] + public ICollection Items { get; set; } = CreateDefaultItems(); + + /// + /// Gets or sets the durability of an item which is in use. + /// + /// + /// Like in the game client, the durability of such an item tells whether it's in use, + /// so this value has to match the client. + /// + [Display(ResourceType = typeof(PlugInResources), Name = nameof(PlugInResources.InventoryItemUseConfiguration_InUseDurability_Name), Description = nameof(PlugInResources.InventoryItemUseConfiguration_InUseDurability_Description))] + public byte InUseDurability { get; set; } = DefaultInUseDurability; + + /// + /// Gets or sets the durability of an item which isn't in use. + /// + /// + /// Like in the game client, the durability of such an item tells whether it's in use, + /// so this value has to match the client. A new item starts with it. + /// + [Display(ResourceType = typeof(PlugInResources), Name = nameof(PlugInResources.InventoryItemUseConfiguration_NotInUseDurability_Name), Description = nameof(PlugInResources.InventoryItemUseConfiguration_NotInUseDurability_Description))] + public byte NotInUseDurability { get; set; } = DefaultNotInUseDurability; + + /// + /// Determines whether the item definition belongs to an item which is used inside the inventory. + /// + /// The item definition. + /// true, if items of this definition are used inside the inventory; otherwise, false. + public bool Contains(ItemDefinition definition) + { + return this.Items.Any(id => id.Group == definition.Group && id.Number == definition.Number); + } + + /// + /// Determines whether items of the two definitions exclude each other, so that only one of them can be in use + /// at the same time. That's the case for the same definition, and for definitions of the same exclusive group. + /// + /// The item definition. + /// The other item definition. + /// true, if only one of the items can be in use at the same time; otherwise, false. + public bool AreExclusive(ItemDefinition definition, ItemDefinition otherDefinition) + { + if (definition == otherDefinition) + { + return true; + } + + var group = this.GetExclusiveGroup(definition); + return group != 0 && group == this.GetExclusiveGroup(otherDefinition); + } + + private static ICollection CreateDefaultItems() + { + const byte figurines = 1; + const byte oakCharms = 2; + const byte mapleCharms = 3; + return + [ + CreateItem(128, figurines), // Hawk Figurine + CreateItem(129, figurines), // Goat Figurine + CreateItem(130, oakCharms), // Oak Charm + CreateItem(131, mapleCharms), // Maple Charm + CreateItem(132, oakCharms), // Golden Oak Charm + CreateItem(133, mapleCharms), // Golden Maple Charm + CreateItem(134, 0), // Worn Horseshoe + ]; + + static InventoryUsedItemIdentifier CreateItem(short number, byte exclusiveGroup) + { + return new InventoryUsedItemIdentifier { Group = 13, Number = number, ExclusiveGroup = exclusiveGroup }; + } + } + + private byte GetExclusiveGroup(ItemDefinition definition) + { + return this.Items.FirstOrDefault(id => id.Group == definition.Group && id.Number == definition.Number)?.ExclusiveGroup ?? 0; + } +} diff --git a/src/GameLogic/InventoryItemUseFeaturePlugIn.cs b/src/GameLogic/InventoryItemUseFeaturePlugIn.cs new file mode 100644 index 0000000000..a4d5399f6d --- /dev/null +++ b/src/GameLogic/InventoryItemUseFeaturePlugIn.cs @@ -0,0 +1,40 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.GameLogic; + +using System.Runtime.InteropServices; +using MUnique.OpenMU.PlugIns; + +/// +/// The use of items inside the inventory, like the figurines and charms. +/// While such an item is in use, its power-ups apply, although it isn't equipped. +/// When it's deactivated, no item can be used inside the inventory. +/// +[PlugIn] +[Display(Name = nameof(PlugInResources.InventoryItemUseFeaturePlugIn_Name), Description = nameof(PlugInResources.InventoryItemUseFeaturePlugIn_Description), ResourceType = typeof(PlugInResources))] +[Guid("0C9C3D52-7B0E-4E55-9D1B-2E6A35C4F1A8")] +public class InventoryItemUseFeaturePlugIn : IFeaturePlugIn, ISupportCustomConfiguration, ISupportDefaultCustomConfiguration +{ + /// + public InventoryItemUseConfiguration? Configuration { get; set; } + + /// + /// Gets the configuration of the items which are used inside the inventory. + /// + /// The game context. + /// The configuration; null, if the feature is deactivated. + public static InventoryItemUseConfiguration? GetActiveConfiguration(IGameContext gameContext) + { + return gameContext.FeaturePlugIns.GetPlugIn() is { } plugIn + ? plugIn.Configuration ?? new InventoryItemUseConfiguration() + : null; + } + + /// + public object CreateDefaultConfig() + { + return new InventoryItemUseConfiguration(); + } +} diff --git a/src/GameLogic/InventoryStorage.cs b/src/GameLogic/InventoryStorage.cs index 6fdb514f05..c7b7f48fef 100644 --- a/src/GameLogic/InventoryStorage.cs +++ b/src/GameLogic/InventoryStorage.cs @@ -20,6 +20,8 @@ public class InventoryStorage : Storage, IInventoryStorage private readonly Player _player; + private Item? _itemMovedInsideInventory; + /// /// Initializes a new instance of the class. /// @@ -141,6 +143,28 @@ public override async ValueTask AddItemAsync(byte slot, Item item) { await this.RaiseEquippedItemsChangedAsync(convertedItem ?? item, true).ConfigureAwait(false); } + else + { + this.OnItemAddedToInventory(convertedItem ?? item); + if (convertedItem is not null) + { + // The hook may change the durability, e.g. of an item which is used inside the inventory. + // The temporary item is sent to the client when it's picked up, so it has to tell the same. + item.Durability = convertedItem.Durability; + } + } + } + + return success; + } + + /// + public override async ValueTask AddItemAsync(Item item) + { + var success = await base.AddItemAsync(item).ConfigureAwait(false); + if (success && !this.IsWearingSlot(item.ItemSlot)) + { + this.OnItemAddedToInventory(item); } return success; @@ -155,6 +179,23 @@ public override async ValueTask RemoveItemAsync(Item item) { await this.RaiseEquippedItemsChangedAsync(item, false).ConfigureAwait(false); } + else + { + this.OnItemRemovedFromInventory(item); + } + } + + /// + /// Keeps the use state and the power-ups of an item which is used inside the inventory, + /// while it's moved to another slot of the inventory, until the returned object is disposed. + /// Otherwise, removing the item would stop its use, like when it leaves the inventory. + /// + /// The item which is moved inside the inventory. + /// The object which ends keeping the use state when it's disposed. + public IDisposable KeepInventoryUseWhileMoving(Item item) + { + this._itemMovedInsideInventory = item; + return new MoveInsideInventoryScope(this); } /// @@ -194,6 +235,57 @@ private static Func KeepItemWithoutPlace(List itemsWithoutPlac }; } + /// + /// Handles an item which was added to an inventory slot which isn't equippable. + /// An item which is used inside the inventory gets its power-ups while it's in use. + /// + /// The item. + private void OnItemAddedToInventory(Item item) + { + if (this._player.Attributes is not { } attributes + || item.GetInventoryItemUseConfiguration(this._gameContext) is not { } configuration) + { + return; + } + + if (item.IsInUseInsideInventory(this._gameContext) && attributes.ItemPowerUps.ContainsKey(item)) + { + // It's still in use, e.g. after it was moved inside the inventory. + return; + } + + if ((int)item.Durability != configuration.InUseDurability + || this.Items.Any(other => other != item && other.Definition is { } otherDefinition && configuration.AreExclusive(item.Definition!, otherDefinition) && other.IsInUseInsideInventory(this._gameContext))) + { + // A new item starts without being used, and only one item of the same kind or exclusive group can be used at the same time. + item.Durability = configuration.NotInUseDurability; + } + + attributes.UpdateInventoryUsedItemPowerUps(item, this._gameContext); + } + + /// + /// Handles an item which was removed from an inventory slot which isn't equippable. + /// An item which is used inside the inventory stops being used when it leaves the inventory, e.g. when it's dropped. + /// Its power-ups are removed even when the item is no longer configured to be used inside the inventory, + /// so that the player doesn't keep them. + /// + /// The item. + private void OnItemRemovedFromInventory(Item item) + { + if (item == this._itemMovedInsideInventory) + { + return; + } + + if (item.GetInventoryItemUseConfiguration(this._gameContext) is { } configuration) + { + item.Durability = configuration.NotInUseDurability; + } + + this._player.Attributes?.RemoveInventoryUsedItemPowerUps(item); + } + private bool IsWearingSlot(int slot) { return slot >= FirstEquippableItemSlotIndex && slot <= LastEquippableItemSlotIndex; @@ -248,14 +340,18 @@ private void InitializePowerUps() powerUp.Dispose(); } - var factory = this._gameContext?.ItemPowerUpFactory; - if (factory != null) + if (this._gameContext?.ItemPowerUpFactory is { } factory) { foreach (var item in this.EquippedItems) { this._player.Attributes.ItemPowerUps.Add(item, factory.GetPowerUps(item, this._player.Attributes).ToList()); } + foreach (var item in this.Items.Where(item => item.IsInUseInsideInventory(this._gameContext))) + { + this._player.Attributes.ItemPowerUps.Add(item, factory.GetPowerUps(item, this._player.Attributes, true).ToList()); + } + this.UpdateSetPowerUps(); } else @@ -282,4 +378,27 @@ private void UpdateSetPowerUps() var factory = this._gameContext.ItemPowerUpFactory; this._player.Attributes.ItemSetPowerUps = factory.GetSetPowerUps(this.EquippedItems, this._player.Attributes, this._player.GameContext.Configuration).ToList(); } + + /// + /// The scope in which an item is moved inside the inventory, see . + /// + private sealed class MoveInsideInventoryScope : IDisposable + { + private readonly InventoryStorage _inventory; + + /// + /// Initializes a new instance of the class. + /// + /// The inventory. + public MoveInsideInventoryScope(InventoryStorage inventory) + { + this._inventory = inventory; + } + + /// + public void Dispose() + { + this._inventory._itemMovedInsideInventory = null; + } + } } diff --git a/src/GameLogic/InventoryUsedItemExtensions.cs b/src/GameLogic/InventoryUsedItemExtensions.cs new file mode 100644 index 0000000000..934fd41537 --- /dev/null +++ b/src/GameLogic/InventoryUsedItemExtensions.cs @@ -0,0 +1,106 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.GameLogic; + +using MUnique.OpenMU.DataModel.Entities; +using MUnique.OpenMU.GameLogic.Attributes; + +/// +/// Extensions for the items which are used inside the inventory, see . +/// Like in the game client, the durability of such an item tells whether it's in use, +/// see and . +/// While it's in use, its power-ups apply, although it isn't equipped. +/// +public static class InventoryUsedItemExtensions +{ + /// + /// Determines whether the item is one which is used inside the inventory. + /// + /// The item. + /// The game context. + /// true, if the item is used inside the inventory; otherwise, false. + public static bool IsUsedInsideInventory(this Item item, IGameContext gameContext) + { + return item.GetInventoryItemUseConfiguration(gameContext) is not null; + } + + /// + /// Determines whether the item is used inside the inventory, and currently in use. + /// + /// The item. + /// The game context. + /// true, if the item is in use inside the inventory; otherwise, false. + public static bool IsInUseInsideInventory(this Item item, IGameContext gameContext) + { + return item.GetInventoryItemUseConfiguration(gameContext) is { } configuration + && item.HasInUseState(configuration); + } + + /// + /// Gets the configuration of the items which are used inside the inventory, if the item is one of them. + /// + /// The item. + /// The game context. + /// The configuration, if the item is used inside the inventory; otherwise, null. + internal static InventoryItemUseConfiguration? GetInventoryItemUseConfiguration(this Item item, IGameContext gameContext) + { + return item.Definition is { } definition + && InventoryItemUseFeaturePlugIn.GetActiveConfiguration(gameContext) is { } configuration + && configuration.Contains(definition) + ? configuration + : null; + } + + /// + /// Updates the power-ups of an item which is used inside the inventory: + /// they're added when the item is in use and don't exist yet, and removed when it isn't in use. + /// Existing power-ups are kept, because removing them could lower the current health, mana etc. of the player. + /// + /// The attribute system of the player. + /// The item. + /// The game context. + internal static void UpdateInventoryUsedItemPowerUps(this ItemAwareAttributeSystem attributes, Item item, IGameContext gameContext) + { + if (!item.IsInUseInsideInventory(gameContext)) + { + attributes.RemoveInventoryUsedItemPowerUps(item); + return; + } + + if (!attributes.ItemPowerUps.ContainsKey(item) && gameContext.ItemPowerUpFactory is { } factory) + { + attributes.ItemPowerUps.Add(item, factory.GetPowerUps(item, attributes, true).ToList()); + } + } + + /// + /// Removes the power-ups of an item which is used inside the inventory, e.g. when it leaves the inventory. + /// + /// The attribute system of the player. + /// The item. + internal static void RemoveInventoryUsedItemPowerUps(this ItemAwareAttributeSystem attributes, Item item) + { + if (attributes.ItemPowerUps.Remove(item, out var powerUps)) + { + foreach (var powerUp in powerUps) + { + powerUp.Dispose(); + } + } + } + + /// + /// Determines whether the item has the state of an item which is in use inside the inventory: + /// it has the and it isn't equipped. + /// + /// The item. + /// The configuration. + /// true, if the item has the state of an item which is in use inside the inventory; otherwise, false. + private static bool HasInUseState(this Item item, InventoryItemUseConfiguration configuration) + { + return (int)item.Durability == configuration.InUseDurability + && (item.ItemSlot < InventoryConstants.FirstEquippableItemSlotIndex || item.ItemSlot > InventoryConstants.LastEquippableItemSlotIndex); + } +} diff --git a/src/GameLogic/InventoryUsedItemIdentifier.cs b/src/GameLogic/InventoryUsedItemIdentifier.cs new file mode 100644 index 0000000000..8534ff7f3a --- /dev/null +++ b/src/GameLogic/InventoryUsedItemIdentifier.cs @@ -0,0 +1,38 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.GameLogic; + +/// +/// Identifies an item definition which is used inside the inventory. +/// +public class InventoryUsedItemIdentifier +{ + /// + /// Gets or sets the group of the item definition. + /// + [Display(ResourceType = typeof(PlugInResources), Name = nameof(PlugInResources.InventoryUsedItemIdentifier_Group_Name), Description = nameof(PlugInResources.InventoryUsedItemIdentifier_Group_Description))] + public byte Group { get; set; } + + /// + /// Gets or sets the number of the item definition. + /// + [Display(ResourceType = typeof(PlugInResources), Name = nameof(PlugInResources.InventoryUsedItemIdentifier_Number_Name), Description = nameof(PlugInResources.InventoryUsedItemIdentifier_Number_Description))] + public short Number { get; set; } + + /// + /// Gets or sets the exclusive group of the item definition. + /// Only one item of the same exclusive group can be in use at the same time, + /// e.g. either the Hawk or the Goat Figurine. With 0, the item belongs to no group, + /// so only another item of the same definition is excluded. + /// + [Display(ResourceType = typeof(PlugInResources), Name = nameof(PlugInResources.InventoryUsedItemIdentifier_ExclusiveGroup_Name), Description = nameof(PlugInResources.InventoryUsedItemIdentifier_ExclusiveGroup_Description))] + public byte ExclusiveGroup { get; set; } + + /// + public override string ToString() + { + return $"{this.Group}/{this.Number}"; + } +} diff --git a/src/GameLogic/ItemPowerUpFactory.cs b/src/GameLogic/ItemPowerUpFactory.cs index 291184763c..28ee0fbc49 100644 --- a/src/GameLogic/ItemPowerUpFactory.cs +++ b/src/GameLogic/ItemPowerUpFactory.cs @@ -44,7 +44,7 @@ public ItemPowerUpFactory(ILogger logger, GameConfiguration } /// - public IEnumerable GetPowerUps(Item item, AttributeSystem attributeSystem) + public IEnumerable GetPowerUps(Item item, AttributeSystem attributeSystem, bool isInUseInsideInventory = false) { if (item.Definition is null) { @@ -57,7 +57,8 @@ public IEnumerable GetPowerUps(Item item, AttributeSystem attrib yield break; } - if (item.ItemSlot < InventoryConstants.FirstEquippableItemSlotIndex || item.ItemSlot > InventoryConstants.LastEquippableItemSlotIndex) + if ((item.ItemSlot < InventoryConstants.FirstEquippableItemSlotIndex || item.ItemSlot > InventoryConstants.LastEquippableItemSlotIndex) + && !isInUseInsideInventory) { yield break; } diff --git a/src/GameLogic/PlayerActions/Items/BuyNpcItemAction.cs b/src/GameLogic/PlayerActions/Items/BuyNpcItemAction.cs index ed9d017e91..5b21084d25 100644 --- a/src/GameLogic/PlayerActions/Items/BuyNpcItemAction.cs +++ b/src/GameLogic/PlayerActions/Items/BuyNpcItemAction.cs @@ -110,8 +110,11 @@ public async ValueTask BuyItemAsync(Player player, byte slot) var newItem = player.PersistenceContext.CreateNew(); newItem.AssignValues(itemTemplate); newItem.ItemSlot = (byte)toSlot; - await player.InvokeViewPlugInAsync(p => p.NpcItemBoughtAsync(newItem)).ConfigureAwait(false); + + // Added before it's sent to the client, because adding it may change its data, + // e.g. the state of an item which is used inside the inventory. await player.Inventory.AddItemAsync(newItem).ConfigureAwait(false); + await player.InvokeViewPlugInAsync(p => p.NpcItemBoughtAsync(newItem)).ConfigureAwait(false); player.GameContext.PlugInManager.GetPlugInPoint()?.ItemBought(player, newItem, storeItem, merchant); if (purchasePlugIns is not null) { diff --git a/src/GameLogic/PlayerActions/Items/MoveItemAction.cs b/src/GameLogic/PlayerActions/Items/MoveItemAction.cs index 49a1203675..a347c55c51 100644 --- a/src/GameLogic/PlayerActions/Items/MoveItemAction.cs +++ b/src/GameLogic/PlayerActions/Items/MoveItemAction.cs @@ -170,6 +170,11 @@ private async ValueTask PartiallyStackAsync(Player player, Item sourceItem, Item private async ValueTask MoveNormalAsync(Player player, Storages fromStorage, byte fromSlot, Storages toStorage, byte toSlot, IStorage fromItemStorage, Item item, IStorage toItemStorage) { var wasEquipped = fromItemStorage == player.Inventory && fromSlot <= LastEquippableItemSlotIndex; + + // An item which is used inside the inventory, like a charm, stays in use while it's moved inside the inventory. + using var keepInventoryUse = fromItemStorage == player.Inventory && toItemStorage == player.Inventory && toSlot > LastEquippableItemSlotIndex + ? player.Inventory.AsInventoryStorage?.KeepInventoryUseWhileMoving(item) + : null; await fromItemStorage.RemoveItemAsync(item).ConfigureAwait(false); var wasAdded = await toItemStorage.AddItemAsync(toSlot, item).ConfigureAwait(false); if (!wasAdded || (wasEquipped && !this.CompliesWithMapRequirements(player))) diff --git a/src/GameLogic/PlayerActions/Items/UseInventoryItemAction.cs b/src/GameLogic/PlayerActions/Items/UseInventoryItemAction.cs new file mode 100644 index 0000000000..3a61f0afb1 --- /dev/null +++ b/src/GameLogic/PlayerActions/Items/UseInventoryItemAction.cs @@ -0,0 +1,53 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.GameLogic.PlayerActions.Items; + +using MUnique.OpenMU.GameLogic.Views.Inventory; + +/// +/// The action to start or stop using an item inside the inventory, like a figurine or a charm, +/// see . +/// While such an item is in use, its power-ups apply. +/// +public class UseInventoryItemAction +{ + /// + /// Starts or stops using the item of the inventory slot. + /// + /// The player. + /// The inventory slot of the item. + /// The requested durability, which tells whether the item should be in use, + /// see and . + public async ValueTask SetItemInUseAsync(Player player, byte slot, byte requestedDurability) + { + if (player.PlayerState.CurrentState != PlayerState.EnteredWorld + || player.Inventory?.GetItem(slot) is not { } item + || slot <= InventoryConstants.LastEquippableItemSlotIndex + || item.GetInventoryItemUseConfiguration(player.GameContext) is not { } configuration + || player.Attributes is not { } attributes) + { + return; + } + + if (requestedDurability != configuration.InUseDurability && requestedDurability != configuration.NotInUseDurability) + { + player.Logger.LogWarning("Player {player} requested durability {requestedDurability} for {item}, which isn't possible.", player, requestedDurability, item); + await player.InvokeViewPlugInAsync(p => p.InventoryItemUseChangedAsync(item)).ConfigureAwait(false); + return; + } + + if (requestedDurability == configuration.InUseDurability + && player.Inventory.Items.Any(other => other != item && other.Definition is { } otherDefinition && configuration.AreExclusive(item.Definition!, otherDefinition) && other.IsInUseInsideInventory(player.GameContext))) + { + await player.ShowLocalizedBlueMessageAsync(nameof(PlayerMessage.SameItemAlreadyInUse)).ConfigureAwait(false); + await player.InvokeViewPlugInAsync(p => p.InventoryItemUseChangedAsync(item)).ConfigureAwait(false); + return; + } + + item.Durability = requestedDurability; + attributes.UpdateInventoryUsedItemPowerUps(item, player.GameContext); + await player.InvokeViewPlugInAsync(p => p.InventoryItemUseChangedAsync(item)).ConfigureAwait(false); + } +} diff --git a/src/GameLogic/Properties/PlayerMessage.Designer.cs b/src/GameLogic/Properties/PlayerMessage.Designer.cs index 34f67a89c0..ef91b2223f 100644 --- a/src/GameLogic/Properties/PlayerMessage.Designer.cs +++ b/src/GameLogic/Properties/PlayerMessage.Designer.cs @@ -3270,5 +3270,14 @@ public static string ItemCantBeUsedOnThisMap { return ResourceManager.GetString("ItemCantBeUsedOnThisMap", resourceCulture); } } + + /// + /// Looks up a localized string similar to An item of the same kind is already in use. Stop using it first, and then try again.. + /// + public static string SameItemAlreadyInUse { + get { + return ResourceManager.GetString("SameItemAlreadyInUse", resourceCulture); + } + } } } diff --git a/src/GameLogic/Properties/PlayerMessage.de.resx b/src/GameLogic/Properties/PlayerMessage.de.resx index f276922f78..33ba96f25e 100644 --- a/src/GameLogic/Properties/PlayerMessage.de.resx +++ b/src/GameLogic/Properties/PlayerMessage.de.resx @@ -1045,4 +1045,7 @@ Inventarerweiterungen: {18} Ein Charakter, für den Gegenstände warten, deren Gegenstandsart es nicht mehr gibt, kann nicht gelöscht werden. Bitte wenden Sie sich an einen Admin. + + Ein Gegenstand der gleichen Art wird bereits benutzt. Beende zuerst dessen Benutzung und versuche es dann erneut. + diff --git a/src/GameLogic/Properties/PlayerMessage.pt.resx b/src/GameLogic/Properties/PlayerMessage.pt.resx index 6cde074dae..e585bed3b3 100644 --- a/src/GameLogic/Properties/PlayerMessage.pt.resx +++ b/src/GameLogic/Properties/PlayerMessage.pt.resx @@ -1198,4 +1198,7 @@ Extensões de inventário: {18} Não é possível excluir um personagem enquanto aguardam itens cujo tipo de item não existe mais. Peça ajuda a um administrador. + + Um item do mesmo tipo já está em uso. Pare de usá-lo primeiro e tente novamente. + diff --git a/src/GameLogic/Properties/PlayerMessage.resx b/src/GameLogic/Properties/PlayerMessage.resx index afbbb560f4..b18724318c 100644 --- a/src/GameLogic/Properties/PlayerMessage.resx +++ b/src/GameLogic/Properties/PlayerMessage.resx @@ -1198,4 +1198,7 @@ Inventory Extensions: {18} Can't delete a character while items wait for it whose item type doesn't exist anymore. Please ask an admin. + + An item of the same kind is already in use. Stop using it first, and then try again. + diff --git a/src/GameLogic/Properties/PlugInResources.Designer.cs b/src/GameLogic/Properties/PlugInResources.Designer.cs index c78d4f2f67..8906602a78 100644 --- a/src/GameLogic/Properties/PlugInResources.Designer.cs +++ b/src/GameLogic/Properties/PlugInResources.Designer.cs @@ -4659,6 +4659,114 @@ public static string InventoryExtensionDeliveryPlugIn_Name { } } + /// + /// Looks up a localized string similar to The durability of an item which is in use. The game client tells by it whether the item is in use, so it has to match the client (default 254).. + /// + public static string InventoryItemUseConfiguration_InUseDurability_Description { + get { + return ResourceManager.GetString("InventoryItemUseConfiguration_InUseDurability_Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Durability in use. + /// + public static string InventoryItemUseConfiguration_InUseDurability_Name { + get { + return ResourceManager.GetString("InventoryItemUseConfiguration_InUseDurability_Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The items which are used inside the inventory instead of being equipped, e.g. the figurines and charms. Items of the same exclusive group can't be in use at the same time.. + /// + public static string InventoryItemUseConfiguration_Items_Description { + get { + return ResourceManager.GetString("InventoryItemUseConfiguration_Items_Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Items. + /// + public static string InventoryItemUseConfiguration_Items_Name { + get { + return ResourceManager.GetString("InventoryItemUseConfiguration_Items_Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The durability of an item which isn't in use, and of a new item. It has to match the game client (default 255).. + /// + public static string InventoryItemUseConfiguration_NotInUseDurability_Description { + get { + return ResourceManager.GetString("InventoryItemUseConfiguration_NotInUseDurability_Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Durability not in use. + /// + public static string InventoryItemUseConfiguration_NotInUseDurability_Name { + get { + return ResourceManager.GetString("InventoryItemUseConfiguration_NotInUseDurability_Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Only one item of the same exclusive group can be in use at the same time, e.g. either the Hawk or the Goat Figurine. With 0, only another item of the same definition is excluded.. + /// + public static string InventoryUsedItemIdentifier_ExclusiveGroup_Description { + get { + return ResourceManager.GetString("InventoryUsedItemIdentifier_ExclusiveGroup_Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Exclusive group. + /// + public static string InventoryUsedItemIdentifier_ExclusiveGroup_Name { + get { + return ResourceManager.GetString("InventoryUsedItemIdentifier_ExclusiveGroup_Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The group of the item definition.. + /// + public static string InventoryUsedItemIdentifier_Group_Description { + get { + return ResourceManager.GetString("InventoryUsedItemIdentifier_Group_Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Group. + /// + public static string InventoryUsedItemIdentifier_Group_Name { + get { + return ResourceManager.GetString("InventoryUsedItemIdentifier_Group_Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The number of the item definition.. + /// + public static string InventoryUsedItemIdentifier_Number_Description { + get { + return ResourceManager.GetString("InventoryUsedItemIdentifier_Number_Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Number. + /// + public static string InventoryUsedItemIdentifier_Number_Name { + get { + return ResourceManager.GetString("InventoryUsedItemIdentifier_Number_Name", resourceCulture); + } + } + /// /// Looks up a localized string similar to This plugin handles the drop of an item box, e.g. box of kundun.. /// @@ -8745,5 +8853,23 @@ public static string WorldChatChatCommandPlugIn_Name { return ResourceManager.GetString("WorldChatChatCommandPlugIn_Name", resourceCulture); } } + + /// + /// Looks up a localized string similar to Items used inside the inventory. + /// + public static string InventoryItemUseFeaturePlugIn_Name { + get { + return ResourceManager.GetString("InventoryItemUseFeaturePlugIn_Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Items like the figurines and charms are used inside the inventory. While such an item is in use, its power-ups apply.. + /// + public static string InventoryItemUseFeaturePlugIn_Description { + get { + return ResourceManager.GetString("InventoryItemUseFeaturePlugIn_Description", resourceCulture); + } + } } } diff --git a/src/GameLogic/Properties/PlugInResources.de.resx b/src/GameLogic/Properties/PlugInResources.de.resx index 8c2408195f..9f3dd7fbae 100644 --- a/src/GameLogic/Properties/PlugInResources.de.resx +++ b/src/GameLogic/Properties/PlugInResources.de.resx @@ -2079,4 +2079,46 @@ Die Anzahl der wartenden Gegenstände, die genannt werden, einer pro Nachricht. + + Im Inventar benutzte Gegenstände + + + Gegenstände wie die Figuren und Talismane werden im Inventar benutzt. Solange so ein Gegenstand benutzt wird, gelten seine Boni. + + + Gegenstände + + + Die Gegenstände, die im Inventar benutzt statt ausgerüstet werden, z.B. die Figuren und Talismane. Gegenstände derselben exklusiven Gruppe können nicht gleichzeitig benutzt werden. + + + Haltbarkeit in Benutzung + + + Die Haltbarkeit eines Gegenstands, der benutzt wird. Der Spiel-Client erkennt daran, ob er benutzt wird, daher muss sie zum Client passen (Standard 254). + + + Haltbarkeit ohne Benutzung + + + Die Haltbarkeit eines Gegenstands, der nicht benutzt wird, und eines neuen Gegenstands. Sie muss zum Spiel-Client passen (Standard 255). + + + Gruppe + + + Die Gruppe der Gegenstandsdefinition. + + + Nummer + + + Die Nummer der Gegenstandsdefinition. + + + Exklusive Gruppe + + + Nur ein Gegenstand derselben exklusiven Gruppe kann gleichzeitig benutzt werden, z.B. entweder die Falken- oder die Ziegenfigur. Mit 0 ist nur ein weiterer Gegenstand derselben Definition ausgeschlossen. + diff --git a/src/GameLogic/Properties/PlugInResources.resx b/src/GameLogic/Properties/PlugInResources.resx index ffa4ab6a00..2e9810a1b9 100644 --- a/src/GameLogic/Properties/PlugInResources.resx +++ b/src/GameLogic/Properties/PlugInResources.resx @@ -2122,6 +2122,12 @@ The number of waiting items which are named, one per message. + + Items used inside the inventory + + + Items like the figurines and charms are used inside the inventory. While such an item is in use, its power-ups apply. + Bot merchants Lets server-side bots sell the goods of their personal store on the market map (Loren Market) for a while, then go back hunting. Market map number @@ -2214,4 +2220,40 @@ The numbers of the city maps, separated by commas (0 = Lorencia, 2 = Devias, 3 = Noria, 51 = Elvenland). The bots open their store in the safezone near the spawn gate. New merchants per 30 seconds How many bots at most start a shift every 30 seconds. After a server start, the market fills up within minutes instead of all at once, and the parties of the bots don't fall apart together. + + Items + + + The items which are used inside the inventory instead of being equipped, e.g. the figurines and charms. Items of the same exclusive group can't be in use at the same time. + + + Durability in use + + + The durability of an item which is in use. The game client tells by it whether the item is in use, so it has to match the client (default 254). + + + Durability not in use + + + The durability of an item which isn't in use, and of a new item. It has to match the game client (default 255). + + + Group + + + The group of the item definition. + + + Number + + + The number of the item definition. + + + Exclusive group + + + Only one item of the same exclusive group can be in use at the same time, e.g. either the Hawk or the Goat Figurine. With 0, only another item of the same definition is excluded. + diff --git a/src/GameLogic/Properties/PlugInResources.zh-CN.resx b/src/GameLogic/Properties/PlugInResources.zh-CN.resx index 983992b0e7..ff77c2576c 100644 --- a/src/GameLogic/Properties/PlugInResources.zh-CN.resx +++ b/src/GameLogic/Properties/PlugInResources.zh-CN.resx @@ -1867,4 +1867,46 @@ 列出的等待物品数量,每条消息一件。 + + 在背包中使用的物品 + + + 雕像和护身符等物品在背包中使用。物品使用期间,其加成生效。 + + + 物品 + + + 在背包中使用而不是装备的物品,例如雕像和护符。同一互斥组的物品不能同时使用。 + + + 使用中的耐久度 + + + 正在使用的物品的耐久度。游戏客户端据此判断物品是否在使用,因此必须与客户端一致(默认 254)。 + + + 未使用时的耐久度 + + + 未使用的物品以及新物品的耐久度。必须与游戏客户端一致(默认 255)。 + + + 组 + + + 物品定义的组。 + + + 编号 + + + 物品定义的编号。 + + + 互斥组 + + + 同一互斥组中同时只能使用一个物品,例如鹰雕像或山羊雕像。为 0 时,只排除同一定义的其他物品。 + diff --git a/src/GameLogic/Storage.cs b/src/GameLogic/Storage.cs index c4871a8f63..aaa069c532 100644 --- a/src/GameLogic/Storage.cs +++ b/src/GameLogic/Storage.cs @@ -162,7 +162,7 @@ public virtual async ValueTask AddItemAsync(byte slot, Item item) } /// - public async ValueTask AddItemAsync(Item item) + public virtual async ValueTask AddItemAsync(Item item) { var freeSlot = this.CheckInvSpace(item); if (freeSlot is null) diff --git a/src/GameLogic/Views/Inventory/IInventoryItemUseChangedPlugIn.cs b/src/GameLogic/Views/Inventory/IInventoryItemUseChangedPlugIn.cs new file mode 100644 index 0000000000..26d15550fe --- /dev/null +++ b/src/GameLogic/Views/Inventory/IInventoryItemUseChangedPlugIn.cs @@ -0,0 +1,20 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.GameLogic.Views.Inventory; + +using MUnique.OpenMU.DataModel.Entities; + +/// +/// A view plugin which shows whether an item which is used inside the inventory is in use, +/// after the player requested to use it or to stop using it. +/// +public interface IInventoryItemUseChangedPlugIn : IViewPlugIn +{ + /// + /// Shows whether the item is in use. Its durability tells it, see . + /// + /// The item. + ValueTask InventoryItemUseChangedAsync(Item item); +} diff --git a/src/GameServer/MessageHandler/Items/InventoryItemEquipRequestHandlerPlugIn.cs b/src/GameServer/MessageHandler/Items/InventoryItemEquipRequestHandlerPlugIn.cs new file mode 100644 index 0000000000..5701e278b6 --- /dev/null +++ b/src/GameServer/MessageHandler/Items/InventoryItemEquipRequestHandlerPlugIn.cs @@ -0,0 +1,44 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.GameServer.MessageHandler.Items; + +using System.Runtime.InteropServices; +using MUnique.OpenMU.GameLogic; +using MUnique.OpenMU.GameLogic.PlayerActions.Items; +using MUnique.OpenMU.GameServer.MessageHandler.MuHelper; +using MUnique.OpenMU.Network.Packets.ClientToServer; +using MUnique.OpenMU.Network.PlugIns; +using MUnique.OpenMU.PlugIns; + +/// +/// Handler for the request to start or stop using an item inside the inventory, like a figurine or a charm. +/// +[PlugIn] +[Display(Name = nameof(PlugInResources.InventoryItemEquipRequestHandlerPlugIn_Name), Description = nameof(PlugInResources.InventoryItemEquipRequestHandlerPlugIn_Description), ResourceType = typeof(PlugInResources))] +[Guid("0CFF0E0C-E744-4F3C-A857-8106BBE76654")] +[MinimumClient(6, 0, ClientLanguage.Invariant)] +[BelongsToGroup(MuHelperGroupHandler.GroupKey)] +internal class InventoryItemEquipRequestHandlerPlugIn : ISubPacketHandlerPlugIn +{ + private readonly UseInventoryItemAction _action = new(); + + /// + public bool IsEncryptionExpected => false; + + /// + public byte Key => InventoryItemEquipRequest.SubCode; + + /// + public async ValueTask HandlePacketAsync(Player player, Memory packet) + { + if (packet.Length < InventoryItemEquipRequest.Length) + { + return; + } + + InventoryItemEquipRequest request = packet; + await this._action.SetItemInUseAsync(player, request.InventorySlot, request.Value).ConfigureAwait(false); + } +} diff --git a/src/GameServer/Properties/PlugInResources.Designer.cs b/src/GameServer/Properties/PlugInResources.Designer.cs index 38a657bc42..b78c7a703f 100644 --- a/src/GameServer/Properties/PlugInResources.Designer.cs +++ b/src/GameServer/Properties/PlugInResources.Designer.cs @@ -8064,5 +8064,17 @@ public static string CastleSiegeLifeStoneStatePlugIn_Name { /// Gets the localized InventoryRequestHandlerPlugIn_Description text. public static string InventoryRequestHandlerPlugIn_Description => ResourceManager.GetString("InventoryRequestHandlerPlugIn_Description", resourceCulture)!; + + /// Gets the localized InventoryItemEquipRequestHandlerPlugIn_Name text. + public static string InventoryItemEquipRequestHandlerPlugIn_Name => ResourceManager.GetString("InventoryItemEquipRequestHandlerPlugIn_Name", resourceCulture)!; + + /// Gets the localized InventoryItemEquipRequestHandlerPlugIn_Description text. + public static string InventoryItemEquipRequestHandlerPlugIn_Description => ResourceManager.GetString("InventoryItemEquipRequestHandlerPlugIn_Description", resourceCulture)!; + + /// Gets the localized InventoryItemUseChangedPlugIn_Name text. + public static string InventoryItemUseChangedPlugIn_Name => ResourceManager.GetString("InventoryItemUseChangedPlugIn_Name", resourceCulture)!; + + /// Gets the localized InventoryItemUseChangedPlugIn_Description text. + public static string InventoryItemUseChangedPlugIn_Description => ResourceManager.GetString("InventoryItemUseChangedPlugIn_Description", resourceCulture)!; } } diff --git a/src/GameServer/Properties/PlugInResources.de.resx b/src/GameServer/Properties/PlugInResources.de.resx index bc6cf9dc93..475182d876 100644 --- a/src/GameServer/Properties/PlugInResources.de.resx +++ b/src/GameServer/Properties/PlugInResources.de.resx @@ -2697,4 +2697,16 @@ Handler für die Anfrage, Glücksmünzen beim NPC Delgado gegen einen Gegenstand zu tauschen. + + Handler für die Benutzung von Gegenständen im Inventar + + + Handler für die Anfrage, einen Gegenstand im Inventar zu benutzen oder dessen Benutzung zu beenden, wie eine Figur oder einen Talisman. + + + Benutzung eines Inventargegenstands geändert + + + Die Standardimplementierung von IInventoryItemUseChangedPlugIn, die alles mit spezifischen Datenpaketen an den Spielclient weiterleitet. + diff --git a/src/GameServer/Properties/PlugInResources.resx b/src/GameServer/Properties/PlugInResources.resx index 854e9aaef6..a45328b6ee 100644 --- a/src/GameServer/Properties/PlugInResources.resx +++ b/src/GameServer/Properties/PlugInResources.resx @@ -2807,4 +2807,16 @@ Handles inventory refresh requests (0xF3, 0x10) by returning the current inventory, with configurable per-player throttling. + + Inventory item use request handler + + + Handler for the request to start or stop using an item inside the inventory, like a figurine or a charm. + + + Inventory item use changed + + + The default implementation of the IInventoryItemUseChangedPlugIn which is forwarding everything to the game client with specific data packets. + diff --git a/src/GameServer/Properties/PlugInResources.zh-CN.resx b/src/GameServer/Properties/PlugInResources.zh-CN.resx index 7d6f91aa02..742cea9312 100644 --- a/src/GameServer/Properties/PlugInResources.zh-CN.resx +++ b/src/GameServer/Properties/PlugInResources.zh-CN.resx @@ -2556,4 +2556,16 @@ 处理在NPC德尔加多处用幸运币兑换物品的请求。 + + 背包物品使用请求处理程序 + + + 处理在背包中开始或停止使用物品(如雕像或护符)的请求。 + + + 背包物品使用状态已更改 + + + IInventoryItemUseChangedPlugIn的默认实现,通过特定数据包将所有内容转发给游戏客户端。 + diff --git a/src/GameServer/RemoteView/Inventory/InventoryItemUseChangedPlugIn.cs b/src/GameServer/RemoteView/Inventory/InventoryItemUseChangedPlugIn.cs new file mode 100644 index 0000000000..bbdb503d54 --- /dev/null +++ b/src/GameServer/RemoteView/Inventory/InventoryItemUseChangedPlugIn.cs @@ -0,0 +1,36 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.GameServer.RemoteView.Inventory; + +using System.Runtime.InteropServices; +using MUnique.OpenMU.DataModel.Entities; +using MUnique.OpenMU.GameLogic.Views.Inventory; +using MUnique.OpenMU.Network.Packets.ServerToClient; +using MUnique.OpenMU.Network.PlugIns; +using MUnique.OpenMU.PlugIns; + +/// +/// The default implementation of the which is forwarding everything to the game client with specific data packets. +/// +[PlugIn] +[Display(Name = nameof(PlugInResources.InventoryItemUseChangedPlugIn_Name), Description = nameof(PlugInResources.InventoryItemUseChangedPlugIn_Description), ResourceType = typeof(PlugInResources))] +[Guid("77EB94A6-09DB-424F-B58A-F540D10DD7A6")] +[MinimumClient(6, 0, ClientLanguage.Invariant)] +public class InventoryItemUseChangedPlugIn : IInventoryItemUseChangedPlugIn +{ + private readonly RemotePlayer _player; + + /// + /// Initializes a new instance of the class. + /// + /// The player. + public InventoryItemUseChangedPlugIn(RemotePlayer player) => this._player = player; + + /// + public async ValueTask InventoryItemUseChangedAsync(Item item) + { + await this._player.Connection.SendInventoryItemEquipResultAsync(item.ItemSlot, (byte)item.Durability).ConfigureAwait(false); + } +} diff --git a/src/Persistence/Initialization/Properties/ItemNames.Designer.cs b/src/Persistence/Initialization/Properties/ItemNames.Designer.cs index 004560076a..a6e0821e12 100644 --- a/src/Persistence/Initialization/Properties/ItemNames.Designer.cs +++ b/src/Persistence/Initialization/Properties/ItemNames.Designer.cs @@ -5508,5 +5508,47 @@ public static string GladiatorsHonor { return ResourceManager.GetString("GladiatorsHonor", resourceCulture); } } + + /// Gets HawkFigurine from the configuration name resources. + public static string HawkFigurine { + get { + return ResourceManager.GetString("HawkFigurine", resourceCulture); + } + } + + /// Gets GoatFigurine from the configuration name resources. + public static string GoatFigurine { + get { + return ResourceManager.GetString("GoatFigurine", resourceCulture); + } + } + + /// Gets OakCharm from the configuration name resources. + public static string OakCharm { + get { + return ResourceManager.GetString("OakCharm", resourceCulture); + } + } + + /// Gets MapleCharm from the configuration name resources. + public static string MapleCharm { + get { + return ResourceManager.GetString("MapleCharm", resourceCulture); + } + } + + /// Gets GoldenOakCharm from the configuration name resources. + public static string GoldenOakCharm { + get { + return ResourceManager.GetString("GoldenOakCharm", resourceCulture); + } + } + + /// Gets GoldenMapleCharm from the configuration name resources. + public static string GoldenMapleCharm { + get { + return ResourceManager.GetString("GoldenMapleCharm", resourceCulture); + } + } } } diff --git a/src/Persistence/Initialization/Properties/ItemNames.de.resx b/src/Persistence/Initialization/Properties/ItemNames.de.resx index f4c4147756..f742bf6a12 100644 --- a/src/Persistence/Initialization/Properties/ItemNames.de.resx +++ b/src/Persistence/Initialization/Properties/ItemNames.de.resx @@ -2268,4 +2268,22 @@ Ehre des Gladiators + + Falkenfigur + + + Ziegenfigur + + + Eichentalisman + + + Ahorntalisman + + + Goldener Eichentalisman + + + Goldener Ahorntalisman + diff --git a/src/Persistence/Initialization/Properties/ItemNames.resx b/src/Persistence/Initialization/Properties/ItemNames.resx index 9eaee9c58f..f73b5c1aee 100644 --- a/src/Persistence/Initialization/Properties/ItemNames.resx +++ b/src/Persistence/Initialization/Properties/ItemNames.resx @@ -2352,4 +2352,22 @@ Gladiator's Honor + + Hawk Figurine + + + Goat Figurine + + + Oak Charm + + + Maple Charm + + + Golden Oak Charm + + + Golden Maple Charm + \ No newline at end of file diff --git a/src/Persistence/Initialization/Properties/ItemNames.zh-CN.resx b/src/Persistence/Initialization/Properties/ItemNames.zh-CN.resx index 5e05f54556..475a3cd6bc 100644 --- a/src/Persistence/Initialization/Properties/ItemNames.zh-CN.resx +++ b/src/Persistence/Initialization/Properties/ItemNames.zh-CN.resx @@ -2352,4 +2352,22 @@ 角斗士的荣耀 + + 鹰雕像 + + + 山羊雕像 + + + 橡树护符 + + + 枫树护符 + + + 黄金橡树护符 + + + 黄金枫树护符 + \ No newline at end of file diff --git a/src/Persistence/Initialization/Properties/PlugInResources.Designer.cs b/src/Persistence/Initialization/Properties/PlugInResources.Designer.cs index 50f343c520..bfa9188b10 100644 --- a/src/Persistence/Initialization/Properties/PlugInResources.Designer.cs +++ b/src/Persistence/Initialization/Properties/PlugInResources.Designer.cs @@ -1139,5 +1139,10 @@ public static string DataInitialization095d_Name { /// Gets the localized NpcSpawnsUpdatePlugInSeason6_Description text. public static string NpcSpawnsUpdatePlugInSeason6_Description => ResourceManager.GetString("NpcSpawnsUpdatePlugInSeason6_Description", resourceCulture)!; + /// Gets the localized AddFigurinesAndCharmsUpdatePlugIn_Name text. + public static string AddFigurinesAndCharmsUpdatePlugIn_Name => ResourceManager.GetString("AddFigurinesAndCharmsUpdatePlugIn_Name", resourceCulture)!; + + /// Gets the localized AddFigurinesAndCharmsUpdatePlugIn_Description text. + public static string AddFigurinesAndCharmsUpdatePlugIn_Description => ResourceManager.GetString("AddFigurinesAndCharmsUpdatePlugIn_Description", resourceCulture)!; } } diff --git a/src/Persistence/Initialization/Properties/PlugInResources.de.resx b/src/Persistence/Initialization/Properties/PlugInResources.de.resx index 099883e2a6..931692447d 100644 --- a/src/Persistence/Initialization/Properties/PlugInResources.de.resx +++ b/src/Persistence/Initialization/Properties/PlugInResources.de.resx @@ -1002,4 +1002,10 @@ Bringt die NPCs auf ihre Season-6-Positionen und Blickrichtungen (Lorencia, Devias, Noria, Arena, Atlans, Elfenland, Aida, Crywolf-Festung, Tal von Loren, Karutan, Kanturu und Illusionstempel), ergänzt den fehlenden Elfensoldaten von Devias, die zwei fehlenden Elfensoldaten von Noria sowie den Goldenen Bogenschützen von Devias und entfernt die NPCs, die es in Season 6 nicht gibt: aus den älteren Versionen die Trankverkäuferinnen von Noria und Verlorener Turm, die Sicherheitswächter von Verlorener Turm, Arena und Atlans, die Wache bei 114/125 und den Goldenen Bogenschützen von Lorencia; Lugard, Priester Devin und Mirage in Devias, die Season 6 nur in Elfenland und in der Crywolf-Festung hat; sowie die zweite Krone im Tal von Loren. Angepasste Positionen und Blickrichtungen dieser NPCs werden überschrieben. + + Figuren und Talismane hinzufügen + + + Dieses Update fügt die Falken- und Ziegenfigur sowie die (goldenen) Eichen- und Ahorntalismane hinzu, die ihre Boni geben, während sie im Inventar benutzt werden. + diff --git a/src/Persistence/Initialization/Properties/PlugInResources.resx b/src/Persistence/Initialization/Properties/PlugInResources.resx index 9f27cd325a..0929076b6b 100644 --- a/src/Persistence/Initialization/Properties/PlugInResources.resx +++ b/src/Persistence/Initialization/Properties/PlugInResources.resx @@ -470,4 +470,6 @@ Season 6 NPC spawns Brings the NPCs to their Season 6 positions and looking directions (Lorencia, Devias, Noria, Arena, Atlans, Elvenland, Aida, Crywolf Fortress, Valley of Loren, Karutan, Kanturu and Illusion Temple), adds the missing Elf Soldier of Devias, the two missing Elf Soldiers of Noria and the Golden Archer of Devias, and removes the NPCs which Season 6 doesn't have: of the older versions the Potion Girls of Noria and Lost Tower, the Safety Guardians of Lost Tower, Arena and Atlans, the guard at 114/125 and the Golden Archer of Lorencia; Lugard, Priest Devin and Mirage of Devias, which Season 6 has only in Elvenland and Crywolf Fortress; and the second Crown of Valley of Loren. Customized positions and directions of these NPCs are overwritten. + Add the figurines and charms + This update adds the Hawk and Goat Figurines and the (Golden) Oak and Maple Charms, which give their bonuses while they're used inside the inventory. diff --git a/src/Persistence/Initialization/Properties/PlugInResources.zh-CN.resx b/src/Persistence/Initialization/Properties/PlugInResources.zh-CN.resx index f51c6d1a68..fa010a72b2 100644 --- a/src/Persistence/Initialization/Properties/PlugInResources.zh-CN.resx +++ b/src/Persistence/Initialization/Properties/PlugInResources.zh-CN.resx @@ -511,4 +511,10 @@ 第六季NPC刷新点 将NPC调整为第六季的位置和朝向(勇者大陆、冰风谷、仙踪林、竞技场、亚特兰蒂斯、幻术园、幽暗森林、狼魂要塞、罗兰峡谷、卡伦特、坎特鲁和幻影寺院),补充冰风谷缺少的1名幻影导师、仙踪林缺少的2名幻影导师以及冰风谷的黄金弓箭手,并移除第六季没有的NPC:旧版本中仙踪林和失落之塔的药水少女(253)、失落之塔、竞技场和亚特兰蒂斯的安全守卫(240)、勇者大陆114/125处的守卫(247)以及勇者大陆的黄金弓箭手;冰风谷的陆迦德、弟子黛彬和弥拉邱(第六季中只在幻术园和狼魂要塞);以及罗兰峡谷的第二个王座(216)。会覆盖这些NPC自定义的位置和朝向。 + + 添加雕像和护符 + + + 此更新添加鹰雕像、山羊雕像以及(黄金)橡树和枫树护符,它们在背包中使用时提供加成。 + diff --git a/src/Persistence/Initialization/Updates/AddFigurinesAndCharmsUpdatePlugIn.cs b/src/Persistence/Initialization/Updates/AddFigurinesAndCharmsUpdatePlugIn.cs new file mode 100644 index 0000000000..0cd5cbc95a --- /dev/null +++ b/src/Persistence/Initialization/Updates/AddFigurinesAndCharmsUpdatePlugIn.cs @@ -0,0 +1,79 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.Persistence.Initialization.Updates; + +using System.Runtime.InteropServices; +using MUnique.OpenMU.DataModel.Configuration; +using MUnique.OpenMU.Persistence.Initialization.Properties; +using MUnique.OpenMU.Persistence.Initialization.VersionSeasonSix; +using MUnique.OpenMU.Persistence.Initialization.VersionSeasonSix.Items; +using MUnique.OpenMU.PlugIns; + +/// +/// This update adds the figurines and charms, which are used inside the inventory. +/// +[PlugIn] +[Display(Name = nameof(MUnique.OpenMU.Persistence.Initialization.Properties.PlugInResources.AddFigurinesAndCharmsUpdatePlugIn_Name), Description = nameof(MUnique.OpenMU.Persistence.Initialization.Properties.PlugInResources.AddFigurinesAndCharmsUpdatePlugIn_Description), ResourceType = typeof(MUnique.OpenMU.Persistence.Initialization.Properties.PlugInResources))] +[Guid("7EABF432-BC91-48E6-BDD0-5F1B7D7EFBC9")] +public class AddFigurinesAndCharmsUpdatePlugIn : UpdatePlugInBase +{ + /// + /// The items of the products of the cash shop script of the game client, by their product sequence. + /// + private static readonly IReadOnlyDictionary ProductItems = new Dictionary + { + { 459, (13, 128) }, + { 460, (13, 129) }, + { 461, (13, 130) }, + { 462, (13, 132) }, + }; + + /// + public override string DataInitializationKey => VersionSeasonSix.DataInitialization.Id; + + /// + public override string Name => PlugInResources.AddFigurinesAndCharmsUpdatePlugIn_Name; + + /// + public override string Description => PlugInResources.AddFigurinesAndCharmsUpdatePlugIn_Description; + + /// + public override bool IsMandatory => true; + + /// + public override DateTime CreatedAt => new(2026, 11, 09, 18, 0, 0, DateTimeKind.Utc); + + /// + protected override ValueTask ApplyAsync(IContext context, GameConfiguration gameConfiguration) + { + new CashShopItems(context, gameConfiguration).CreateFigurinesAndCharms(); + LinkCashShopProducts(gameConfiguration); + return ValueTask.CompletedTask; + } + + /// + /// Links the products of the cash shop to the figurines and charms. The cash shop was created before these items existed, + /// so its products of them have no item definition. Like other packages with products which can't be delivered, + /// their packages are not for sale; the administrator decides when to sell them. + /// + /// The game configuration. + private static void LinkCashShopProducts(GameConfiguration gameConfiguration) + { + if (gameConfiguration.CashShopConfiguration is not { } cashShop + || !CashShopInitializer.UsesClientScript(cashShop)) + { + return; + } + + var products = cashShop.Packages + .SelectMany(package => package.Products) + .Where(product => product.ItemDefinition is null && ProductItems.ContainsKey(product.ProductSequence)); + foreach (var product in products) + { + var (group, number) = ProductItems[product.ProductSequence]; + product.ItemDefinition = gameConfiguration.Items.FirstOrDefault(item => item.Group == group && item.Number == number); + } + } +} diff --git a/src/Persistence/Initialization/VersionSeasonSix/Items/CashShopItems.cs b/src/Persistence/Initialization/VersionSeasonSix/Items/CashShopItems.cs index 04f419e6c1..8bda6b1a52 100644 --- a/src/Persistence/Initialization/VersionSeasonSix/Items/CashShopItems.cs +++ b/src/Persistence/Initialization/VersionSeasonSix/Items/CashShopItems.cs @@ -4,8 +4,11 @@ namespace MUnique.OpenMU.Persistence.Initialization.VersionSeasonSix.Items; +using MUnique.OpenMU.AttributeSystem; +using MUnique.OpenMU.DataModel.Attributes; using MUnique.OpenMU.DataModel.Configuration; using MUnique.OpenMU.DataModel.Configuration.Items; +using MUnique.OpenMU.GameLogic.Attributes; using MUnique.OpenMU.Interfaces; using MUnique.OpenMU.Persistence.Initialization.Properties; @@ -37,6 +40,7 @@ public override void Initialize() this.CreateItem(14, 163, LocalizedString.FromResource(() => ItemNames.VaultExpansionCertificate)); this.CreateItem(14, 169, LocalizedString.FromResource(() => ItemNames.RageFighterCharacterCard)); this.CreateResetFruits(); + this.CreateFigurinesAndCharms(); this.CreateTalismanOfResurrection(); } @@ -76,6 +80,44 @@ internal IReadOnlyList CreateResetFruits() return fruits; } + /// + /// Creates the figurines and charms, which don't exist yet. They're used inside the inventory + /// with a right click, see . + /// Their durability is 1, so that they're not stackable; the game logic sets the durability of an item + /// to 255 when it's added to the inventory, which tells the client that it's not in use. + /// Their bonuses are the ones which the client shows. The worn horseshoe (13/134) increases the item drop rate, for which there's no attribute yet. + /// + /// The created items. + internal IReadOnlyList CreateFigurinesAndCharms() + { + const byte group = 13; + var items = new List(); + void Create(short number, LocalizedString name, byte height, params (AttributeDefinition Attribute, float Value)[] bonuses) + { + if (this.CreateItem(group, number, name) is not { } item) + { + return; + } + + item.Height = height; + item.Durability = 1; + foreach (var (attribute, value) in bonuses) + { + item.BasePowerUpAttributes.Add(this.CreateItemBasePowerUpDefinition(attribute, value, AggregateType.AddRaw)); + } + + items.Add(item); + } + + Create(128, LocalizedString.FromResource(() => ItemNames.HawkFigurine), 1, (Stats.CriticalDamageChance, 0.1f)); + Create(129, LocalizedString.FromResource(() => ItemNames.GoatFigurine), 1, (Stats.ExcellentDamageChance, 0.1f)); + Create(130, LocalizedString.FromResource(() => ItemNames.OakCharm), 1, (Stats.MaximumHealth, 50)); + Create(131, LocalizedString.FromResource(() => ItemNames.MapleCharm), 1, (Stats.MaximumMana, 50)); + Create(132, LocalizedString.FromResource(() => ItemNames.GoldenOakCharm), 2, (Stats.MaximumHealth, 100), (Stats.MaximumShield, 500)); + Create(133, LocalizedString.FromResource(() => ItemNames.GoldenMapleCharm), 2, (Stats.MaximumMana, 150), (Stats.MaximumAbility, 50)); + return items; + } + private ItemDefinition? CreateItem(byte group, short number, LocalizedString name) { if (this.GameConfiguration.Items.Any(item => item.Group == group && item.Number == number)) diff --git a/tests/MUnique.OpenMU.Persistence.Initialization.Tests/FigurinesAndCharmsDataTest.cs b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/FigurinesAndCharmsDataTest.cs new file mode 100644 index 0000000000..98483b2447 --- /dev/null +++ b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/FigurinesAndCharmsDataTest.cs @@ -0,0 +1,114 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.Persistence.Initialization.Tests; + +using Microsoft.Extensions.Logging.Abstractions; +using MUnique.OpenMU.AttributeSystem; +using MUnique.OpenMU.DataModel.Configuration; +using MUnique.OpenMU.DataModel.Configuration.Items; +using MUnique.OpenMU.GameLogic.Attributes; +using MUnique.OpenMU.Persistence.Initialization.Updates; +using MUnique.OpenMU.Persistence.InMemory; + +/// +/// Tests the data of the figurines and charms, which are used inside the inventory. +/// +[TestFixture] +internal class FigurinesAndCharmsDataTest +{ + private static readonly short[] Numbers = [128, 129, 130, 131, 132, 133]; + + /// + /// Tests that a new season 6 database contains the items. + /// + [Test] + public async Task NewDatabaseContainsItemsAsync() + { + var (context, gameConfiguration) = await CreateSeason6ConfigurationAsync().ConfigureAwait(false); + using var _ = context; + + AssertItemData(gameConfiguration); + } + + /// + /// Tests that the update adds the items to a database which was created before they existed. + /// Applying it twice doesn't add the items twice. + /// + [Test] + public async Task UpdateAddsItemsToExistingDatabaseAsync() + { + var (context, gameConfiguration) = await CreateSeason6ConfigurationAsync().ConfigureAwait(false); + using var _ = context; + gameConfiguration.Items.Where(IsFigurineOrCharm).ToList().ForEach(item => gameConfiguration.Items.Remove(item)); + + var update = new AddFigurinesAndCharmsUpdatePlugIn(); + await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + + AssertItemData(gameConfiguration); + } + + /// + /// Tests that the update links the products of the cash shop to the items, + /// which have no item definition in a database which was created before the items existed. + /// + [Test] + public async Task UpdateLinksCashShopProductsAsync() + { + var (context, gameConfiguration) = await CreateSeason6ConfigurationAsync().ConfigureAwait(false); + using var _ = context; + var products = gameConfiguration.CashShopConfiguration!.Packages + .SelectMany(package => package.Products) + .Where(product => product.ItemDefinition is { } definition && IsFigurineOrCharm(definition)) + .ToList(); + Assert.That(products.Select(product => product.ProductSequence).Distinct(), Is.EquivalentTo(new[] { 459, 460, 461, 462 })); + products.ForEach(product => product.ItemDefinition = null); + gameConfiguration.Items.Where(IsFigurineOrCharm).ToList().ForEach(item => gameConfiguration.Items.Remove(item)); + + await new AddFigurinesAndCharmsUpdatePlugIn().ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + + Assert.That(products, Has.All.Matches(product => product.ItemDefinition is { Group: 13 } definition && gameConfiguration.Items.Contains(definition))); + Assert.That(products.Where(product => product.ProductSequence == 459).Select(product => product.ItemDefinition!.Number), Has.All.EqualTo(128)); + Assert.That(products.Where(product => product.ProductSequence == 462).Select(product => product.ItemDefinition!.Number), Has.All.EqualTo(132)); + } + + private static bool IsFigurineOrCharm(ItemDefinition item) => item.Group == 13 && Numbers.Contains(item.Number); + + private static void AssertItemData(GameConfiguration gameConfiguration) + { + var items = gameConfiguration.Items.Where(IsFigurineOrCharm).ToList(); + Assert.That(items.Select(item => item.Number), Is.EquivalentTo(Numbers)); + Assert.That(items, Has.All.Matches(item => + item.Durability == 1 + && item.ItemSlot is null + && item.Name.ValueInNeutralLanguage.Length > 0)); + + Assert.That(PowerUp(items, 128, Stats.CriticalDamageChance), Is.EqualTo(0.1f)); + Assert.That(PowerUp(items, 129, Stats.ExcellentDamageChance), Is.EqualTo(0.1f)); + Assert.That(PowerUp(items, 130, Stats.MaximumHealth), Is.EqualTo(50)); + Assert.That(PowerUp(items, 131, Stats.MaximumMana), Is.EqualTo(50)); + Assert.That(PowerUp(items, 132, Stats.MaximumHealth), Is.EqualTo(100)); + Assert.That(PowerUp(items, 132, Stats.MaximumShield), Is.EqualTo(500)); + Assert.That(PowerUp(items, 133, Stats.MaximumMana), Is.EqualTo(150)); + Assert.That(PowerUp(items, 133, Stats.MaximumAbility), Is.EqualTo(50)); + } + + private static float? PowerUp(IEnumerable items, short number, AttributeDefinition attribute) + { + return items.Single(item => item.Number == number).BasePowerUpAttributes + .SingleOrDefault(powerUp => powerUp.TargetAttribute == attribute)?.BaseValue; + } + + private static async Task<(IContext Context, GameConfiguration GameConfiguration)> CreateSeason6ConfigurationAsync() + { + var contextProvider = new InMemoryPersistenceContextProvider(); + var dataInitialization = new VersionSeasonSix.DataInitialization(contextProvider, new NullLoggerFactory()); + await dataInitialization.CreateInitialDataAsync(1, true).ConfigureAwait(false); + + var context = contextProvider.CreateNewContext(); + var gameConfiguration = (await context.GetAsync().ConfigureAwait(false)).First(); + return (context, gameConfiguration); + } +} diff --git a/tests/MUnique.OpenMU.Persistence.Initialization.Tests/ItemFormulas/ItemFormulasEqualTodayTest.cs b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/ItemFormulas/ItemFormulasEqualTodayTest.cs index 46293bcbfc..6ffa981d9a 100644 --- a/tests/MUnique.OpenMU.Persistence.Initialization.Tests/ItemFormulas/ItemFormulasEqualTodayTest.cs +++ b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/ItemFormulas/ItemFormulasEqualTodayTest.cs @@ -626,7 +626,7 @@ private void ComparePowerUps(Item item, byte fullDurability, bool allDurabilitie $"{itemCase}, slot {slot}, durability {durability}", "power-ups", Capture(() => DescribePowerUps(item, this._legacyPowerUps.GetPowerUps)), - Capture(() => DescribePowerUps(item, this._powerUps.GetPowerUps))); + Capture(() => DescribePowerUps(item, (i, attributes) => this._powerUps.GetPowerUps(i, attributes)))); } } } diff --git a/tests/MUnique.OpenMU.Persistence.Initialization.Tests/ItemStatProfilesDataTest.cs b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/ItemStatProfilesDataTest.cs index ecd2f5c0c4..8505af2552 100644 --- a/tests/MUnique.OpenMU.Persistence.Initialization.Tests/ItemStatProfilesDataTest.cs +++ b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/ItemStatProfilesDataTest.cs @@ -204,7 +204,7 @@ public void Season6ItemCountsPerProfile() { "armor: 327", "book: 3", - "default: 246", + "default: 252", "firstTierWing: 4", "helper: 27", "orb: 12", diff --git a/tests/MUnique.OpenMU.Tests/BuyNpcItemActionTests.cs b/tests/MUnique.OpenMU.Tests/BuyNpcItemActionTests.cs index 239515c461..bbc6647dc3 100644 --- a/tests/MUnique.OpenMU.Tests/BuyNpcItemActionTests.cs +++ b/tests/MUnique.OpenMU.Tests/BuyNpcItemActionTests.cs @@ -117,6 +117,42 @@ public async ValueTask NormalPurchaseCallsBeforeAndAfterPlugInAsync() plugIn.Verify(p => p.AfterPurchaseAsync(player, player.OpenedNpc, It.IsAny(), bought), Times.Once); } + /// + /// Verifies that a bought item which is used inside the inventory is sent to the client + /// with the state which it got in the inventory, i.e. not in use, instead of the durability of the store item. + /// + [Test] + public async ValueTask BoughtInventoryUseItemIsSentWithItsInventoryStateAsync() + { + const byte notInUse = 255; + var player = await PlayerTestHelper.CreatePlayerAsync().ConfigureAwait(false); + player.GameContext.FeaturePlugIns.AddPlugIn(new InventoryItemUseFeaturePlugIn(), true); + player.Money = 1_000_000; + var charmDefinition = new ItemDefinition + { + Group = 13, + Number = 130, + Value = StorePrice, + PriceDefinition = new MUnique.OpenMU.Persistence.BasicModel.ItemPriceDefinition { BasePriceFormula = "value" }, + Width = 1, + Height = 1, + Durability = 1, + }; + var storeItem = CreateItem(charmDefinition, 1); + storeItem.ItemSlot = StoreSlot; + player.OpenedNpc = CreateMerchant(storeItem); + double? sentDurability = null; + Mock.Get(player.ViewPlugIns.GetPlugIn()!) + .Setup(p => p.NpcItemBoughtAsync(It.IsAny())) + .Callback(item => sentDurability = item.Durability) + .Returns(ValueTask.CompletedTask); + + await new BuyNpcItemAction().BuyItemAsync(player, StoreSlot).ConfigureAwait(false); + + Assert.That(player.Inventory!.Items.Single().Durability, Is.EqualTo(notInUse)); + Assert.That(sentDurability, Is.EqualTo(notInUse)); + } + /// /// Verifies that the price and the item chosen by the plug-in are used. /// diff --git a/tests/MUnique.OpenMU.Tests/UseInventoryItemActionTest.cs b/tests/MUnique.OpenMU.Tests/UseInventoryItemActionTest.cs new file mode 100644 index 0000000000..11135c45ed --- /dev/null +++ b/tests/MUnique.OpenMU.Tests/UseInventoryItemActionTest.cs @@ -0,0 +1,349 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.Tests; + +using Moq; +using MUnique.OpenMU.AttributeSystem; +using MUnique.OpenMU.DataModel; +using MUnique.OpenMU.DataModel.Configuration; +using MUnique.OpenMU.DataModel.Configuration.Items; +using MUnique.OpenMU.DataModel.Entities; +using MUnique.OpenMU.GameLogic; +using MUnique.OpenMU.GameLogic.Attributes; +using MUnique.OpenMU.GameLogic.NPC; +using MUnique.OpenMU.GameLogic.PlayerActions.Items; +using MUnique.OpenMU.GameLogic.Views.Inventory; +using BasicModel = MUnique.OpenMU.Persistence.BasicModel; + +/// +/// Tests for the . +/// +[TestFixture] +public class UseInventoryItemActionTest +{ + private const byte InUse = 254; + private const byte NotInUse = 255; + private const float CharmBonus = 50; + + private readonly UseInventoryItemAction _action = new(); + + /// + /// The bonus of a charm applies while it's in use. + /// + [Test] + public async Task BonusAppliesWhileInUseAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var charm = await AddCharmAsync(player).ConfigureAwait(false); + var view = Mock.Get(player.ViewPlugIns.GetPlugIn()!); + + // A new item, which isn't stackable because its definition has a durability of 1, starts without being in use. + Assert.That(charm.Durability, Is.EqualTo(NotInUse)); + + await this._action.SetItemInUseAsync(player, charm.ItemSlot, InUse).ConfigureAwait(false); + Assert.That(charm.Durability, Is.EqualTo(InUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health + CharmBonus)); + + await this._action.SetItemInUseAsync(player, charm.ItemSlot, NotInUse).ConfigureAwait(false); + Assert.That(charm.Durability, Is.EqualTo(NotInUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health)); + view.Verify(v => v.InventoryItemUseChangedAsync(charm), Times.Exactly(2)); + } + + /// + /// The same item can only be in use once. + /// + [Test] + public async Task SameItemCanOnlyBeInUseOnceAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var firstCharm = await AddCharmAsync(player).ConfigureAwait(false); + var secondCharm = await AddCharmAsync(player, firstCharm.Definition).ConfigureAwait(false); + + await this._action.SetItemInUseAsync(player, firstCharm.ItemSlot, InUse).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, secondCharm.ItemSlot, InUse).ConfigureAwait(false); + + Assert.That(secondCharm.Durability, Is.EqualTo(NotInUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health + CharmBonus)); + } + + /// + /// An item which leaves the inventory, e.g. when it's dropped, stops being in use. + /// When it's added again, it's not in use, so that it can't add its bonus twice. + /// + [Test] + public async Task RemovingStopsUseAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var charm = await AddCharmAsync(player).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, charm.ItemSlot, InUse).ConfigureAwait(false); + + var slot = charm.ItemSlot; + await player.Inventory!.RemoveItemAsync(charm).ConfigureAwait(false); + Assert.That(charm.Durability, Is.EqualTo(NotInUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health)); + + Assert.That(await player.Inventory.AddItemAsync(slot, charm).ConfigureAwait(false), Is.True); + Assert.That(charm.Durability, Is.EqualTo(NotInUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health)); + } + + /// + /// An item which is moved inside the inventory stays in use, and keeps its bonus during the move, + /// so that the current health isn't limited by a lower maximum health. + /// + [Test] + public async Task MovingInsideInventoryKeepsUseAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var charm = await AddCharmAsync(player).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, charm.ItemSlot, InUse).ConfigureAwait(false); + player.Attributes[Stats.CurrentHealth] = health + CharmBonus; + var toSlot = (byte)(charm.ItemSlot + 1); + + await new MoveItemAction().MoveItemAsync(player, charm.ItemSlot, Storages.Inventory, toSlot, Storages.Inventory).ConfigureAwait(false); + + Assert.That(charm.ItemSlot, Is.EqualTo(toSlot)); + Assert.That(charm.Durability, Is.EqualTo(InUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health + CharmBonus)); + Assert.That(player.Attributes[Stats.CurrentHealth], Is.EqualTo(health + CharmBonus)); + } + + /// + /// When an item is added which is in use, while another item of the same kind is in use, + /// it's not in use anymore. + /// + [Test] + public async Task AddedDuplicateIsNotInUseAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var firstCharm = await AddCharmAsync(player).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, firstCharm.ItemSlot, InUse).ConfigureAwait(false); + + var secondCharm = player.PersistenceContext.CreateNew(); + secondCharm.Definition = firstCharm.Definition; + secondCharm.Durability = InUse; + Assert.That(await player.Inventory!.AddItemAsync(secondCharm).ConfigureAwait(false), Is.True); + + Assert.That(secondCharm.Durability, Is.EqualTo(NotInUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health + CharmBonus)); + } + + /// + /// The items which can be used inside the inventory are configured at the feature plug-in. + /// + [Test] + public async Task UsableItemsAreConfiguredAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var charm = await AddCharmAsync(player).ConfigureAwait(false); + var plugIn = player.GameContext.FeaturePlugIns.GetPlugIn(); + Assert.That(plugIn, Is.Not.Null); + plugIn!.Configuration = new InventoryItemUseConfiguration { Items = [] }; + + await this._action.SetItemInUseAsync(player, charm.ItemSlot, InUse).ConfigureAwait(false); + + Assert.That(charm.Durability, Is.EqualTo(NotInUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health)); + } + + /// + /// An item which is moved out of the inventory, e.g. into the vault, stops being in use. + /// + [Test] + public async Task MovingOutOfInventoryStopsUseAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var charm = await AddCharmAsync(player).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, charm.ItemSlot, InUse).ConfigureAwait(false); + var vaultStorage = new Mock(); + vaultStorage.Setup(i => i.Items).Returns(new List()); + player.Vault = new Storage(InventoryConstants.WarehouseSize, vaultStorage.Object); + player.IsVaultLocked = false; + player.OpenedNpc = new NonPlayerCharacter(null!, new MonsterDefinition { NpcWindow = NpcWindow.VaultStorage }, null!); + Assert.That(await player.PlayerState.TryAdvanceToAsync(PlayerState.NpcDialogOpened).ConfigureAwait(false), Is.True); + + await new MoveItemAction().MoveItemAsync(player, charm.ItemSlot, Storages.Inventory, 0, Storages.Vault).ConfigureAwait(false); + + Assert.That(player.Vault!.Items, Does.Contain(charm)); + Assert.That(charm.Durability, Is.EqualTo(NotInUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health)); + } + + /// + /// Other items and other durability values can't be used inside the inventory. + /// + [Test] + public async Task OnlyCharmsCanBeUsedAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var charm = await AddCharmAsync(player).ConfigureAwait(false); + var otherDefinition = new BasicModel.ItemDefinition { Group = 13, Number = 20, Width = 1, Height = 1, Durability = 255 }; + otherDefinition.BasePowerUpAttributes.Add(new BasicModel.ItemBasePowerUpDefinition { TargetAttribute = Stats.MaximumHealth, BaseValue = CharmBonus, AggregateType = AggregateType.AddRaw }); + var other = await AddCharmAsync(player, otherDefinition).ConfigureAwait(false); + + await this._action.SetItemInUseAsync(player, other.ItemSlot, InUse).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, charm.ItemSlot, 100).ConfigureAwait(false); + + Assert.That(other.Durability, Is.EqualTo(NotInUse)); + Assert.That(charm.Durability, Is.EqualTo(NotInUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health)); + } + + /// + /// Requesting the use of an item which is already in use keeps its bonus, + /// so that the current health isn't lowered to a temporarily lower maximum. + /// + [Test] + public async Task RepeatedUseKeepsCurrentHealthAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var charm = await AddCharmAsync(player).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, charm.ItemSlot, InUse).ConfigureAwait(false); + var maximumHealth = player.Attributes![Stats.MaximumHealth]; + player.Attributes[Stats.CurrentHealth] = maximumHealth; + + await this._action.SetItemInUseAsync(player, charm.ItemSlot, InUse).ConfigureAwait(false); + + Assert.That(charm.Durability, Is.EqualTo(InUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(maximumHealth)); + Assert.That(player.Attributes[Stats.CurrentHealth], Is.EqualTo(maximumHealth)); + } + + /// + /// An item which leaves the inventory loses its bonus, even when it's no longer configured + /// to be used inside the inventory. + /// + [Test] + public async Task RemovedItemLosesBonusAfterConfigurationChangedAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var charm = await AddCharmAsync(player).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, charm.ItemSlot, InUse).ConfigureAwait(false); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health + CharmBonus)); + player.GameContext.FeaturePlugIns.GetPlugIn()!.Configuration = new InventoryItemUseConfiguration { Items = [] }; + + await player.Inventory!.RemoveItemAsync(charm).ConfigureAwait(false); + + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health)); + } + + /// + /// The durability values which tell whether an item is in use are configured at the feature plug-in. + /// + [Test] + public async Task InUseDurabilityIsConfiguredAsync() + { + const byte configuredInUse = 200; + const byte configuredNotInUse = 201; + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var configuration = new InventoryItemUseConfiguration { InUseDurability = configuredInUse, NotInUseDurability = configuredNotInUse }; + player.GameContext.FeaturePlugIns.GetPlugIn()!.Configuration = configuration; + var charm = await AddCharmAsync(player).ConfigureAwait(false); + Assert.That(charm.Durability, Is.EqualTo(configuredNotInUse)); + + await this._action.SetItemInUseAsync(player, charm.ItemSlot, InUse).ConfigureAwait(false); + Assert.That(charm.Durability, Is.EqualTo(configuredNotInUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health)); + + await this._action.SetItemInUseAsync(player, charm.ItemSlot, configuredInUse).ConfigureAwait(false); + Assert.That(charm.Durability, Is.EqualTo(configuredInUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health + CharmBonus)); + } + + /// + /// Only one item of the same exclusive group can be in use, e.g. either the Oak or the Golden Oak Charm. + /// Items of other groups can be used at the same time. + /// + [Test] + public async Task ItemOfSameExclusiveGroupCanOnlyBeInUseOnceAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var health = player.Attributes![Stats.MaximumHealth]; + var oakCharm = await AddCharmAsync(player).ConfigureAwait(false); + var goldenOakCharm = await AddCharmAsync(player, CreateCharmDefinition(132)).ConfigureAwait(false); + var mapleCharm = await AddCharmAsync(player, CreateCharmDefinition(131)).ConfigureAwait(false); + + await this._action.SetItemInUseAsync(player, oakCharm.ItemSlot, InUse).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, goldenOakCharm.ItemSlot, InUse).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, mapleCharm.ItemSlot, InUse).ConfigureAwait(false); + + Assert.That(oakCharm.Durability, Is.EqualTo(InUse)); + Assert.That(goldenOakCharm.Durability, Is.EqualTo(NotInUse)); + Assert.That(mapleCharm.Durability, Is.EqualTo(InUse)); + Assert.That(player.Attributes[Stats.MaximumHealth], Is.EqualTo(health + (2 * CharmBonus))); + } + + /// + /// An added item which is in use stops being in use, when an item of the same exclusive group is already in use. + /// + [Test] + public async Task AddedItemOfSameExclusiveGroupIsNotInUseAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var hawkFigurine = await AddCharmAsync(player, CreateCharmDefinition(128)).ConfigureAwait(false); + await this._action.SetItemInUseAsync(player, hawkFigurine.ItemSlot, InUse).ConfigureAwait(false); + + var goatFigurine = player.PersistenceContext.CreateNew(); + goatFigurine.Definition = CreateCharmDefinition(129); + goatFigurine.Durability = InUse; + Assert.That(await player.Inventory!.AddItemAsync(goatFigurine).ConfigureAwait(false), Is.True); + + Assert.That(hawkFigurine.Durability, Is.EqualTo(InUse)); + Assert.That(goatFigurine.Durability, Is.EqualTo(NotInUse)); + } + + /// + /// A picked up item, which is temporary until it's added to the inventory, tells the same durability + /// as the added item, because it's the one which is sent to the client. + /// + [Test] + public async Task PickedUpTemporaryItemHasDurabilityOfAddedItemAsync() + { + var player = await CreatePlayerAsync().ConfigureAwait(false); + var temporaryItem = new TemporaryItem { Definition = CreateCharmDefinition(130), Durability = 1 }; + var slot = player.Inventory!.CheckInvSpace(temporaryItem)!.Value; + + Assert.That(await player.Inventory.AddItemAsync(slot, temporaryItem).ConfigureAwait(false), Is.True); + + Assert.That(player.Inventory.GetItem(slot)!.Durability, Is.EqualTo(NotInUse)); + Assert.That(temporaryItem.Durability, Is.EqualTo(NotInUse)); + } + + private static async ValueTask CreatePlayerAsync() + { + var player = await PlayerTestHelper.CreatePlayerAsync().ConfigureAwait(false); + player.GameContext.FeaturePlugIns.AddPlugIn(new InventoryItemUseFeaturePlugIn(), true); + return player; + } + + private static async ValueTask AddCharmAsync(Player player, ItemDefinition? definition = null) + { + definition ??= CreateCharmDefinition(130); + + var item = player.PersistenceContext.CreateNew(); + item.Definition = definition; + item.Durability = definition.Durability; + Assert.That(await player.Inventory!.AddItemAsync(item).ConfigureAwait(false), Is.True); + return item; + } + + private static ItemDefinition CreateCharmDefinition(short number) + { + var definition = new BasicModel.ItemDefinition { Group = 13, Number = number, Width = 1, Height = 1, Durability = 1 }; + definition.BasePowerUpAttributes.Add(new BasicModel.ItemBasePowerUpDefinition { TargetAttribute = Stats.MaximumHealth, BaseValue = CharmBonus, AggregateType = AggregateType.AddRaw }); + return definition; + } +}