Inventory system
The inventory system lives in the PulseInventory module. It is a replicated inventory component with a grid layout, item definitions, stacking and moving rules, and a trait system that lets you add rules and data per inventory and per item without changing the layout.
It uses standard property replication and Fast Array serialization. It has no dependency on Iris and works with the classic net driver and with Iris.
Equipment slots and the hotbar are on their own page: Equipment; loot tables and random stats: Loot; consumables and stats while equipped: Item effects.
Overview
| Part | Class | Purpose |
|---|---|---|
| Inventory | UPulseInventoryComponent | Actor component that holds the items. Add it to any actor. |
| Item type | UPulseItemDefinition | Data asset that describes a kind of item. Derive from it to give items their own behavior. |
| Item stack | FPulseItemInstance | One stack of items in an inventory, with position, rotation and instance traits. |
| Layout | FPulseInventoryLayout | Grid size, grid or single-slot mode, rotation, cell size. |
| Preset | UPulseInventoryLayoutPreset | Data asset with a layout and default traits. |
| Traits | FPulseInventoryTrait, FPulseItemTrait | Extra rules and data for inventories and items. |
| Pickup | APulseItemPickup, UPulsePickupSubsystem | Items lying in the world, created when an item is dropped. |
| Access | UPulseInventoryAccessComponent | Component on the player controller that lets a client change inventories it does not own, such as chests. |
| ViewModels | UMVVMPulseInventory, UMVVMPulseInventoryItem, UMVVMPulseItemPickup | Expose an inventory, its items and pickups to UI. |
Quick start
- Create a data asset of class
UPulseItemDefinition(or a subclass) for each item type. SetSize(cells),MaxStackSize, and add traits such as Weight. - Add a
UPulseInventoryComponentto an actor. - Set
InitialPreset(aUPulseInventoryLayoutPresetasset) orInitialLayouton the component. Optionally addDefaultTraits, for example Weight Limit. - On the server, add items:
FPulseInventoryAddResult result = Inventory->TryAddItem(SwordDefinition, 1, {});
if (!result.WasFullyAdded())
{
// result.Result tells why (reason and text), result.Remaining how many were left over.
}
- Show the inventory in UI with a
UMVVMPulseInventoryViewModel: callSetInventoryand bind widgets to its fields.
The quick start as examples that you can create in your project from the Pulse Docs tab of the editor (Create in project…). The chest has the inventory component of Chests and other inventories without an owner with the preset below and fills it in BeginPlay on the authority with Try Add Item: 5 potions, a sword, and then 8 more swords, which do not fit (the result and the number of added items are printed). Creating the chest also creates the component, the preset and the items.
Item definitions
UPulseItemDefinition is a UPrimaryDataAsset that is Blueprintable.
| Property | Meaning |
|---|---|
DisplayName, Description, Icon | Presentation data. The icon is a soft pointer, the UI loads it. |
Tags | Gameplay tags, used for example by the item filter trait. |
Rarity | Rarity of the item type, a tier under Pulse.Rarity (such as Pulse.Rarity.Rare); empty by default. A rarity the instance rolled (FPulseItemTrait_RolledStats) comes first. Empty: the first Pulse.Rarity tag in Tags counts, so older content keeps its rarity. |
Size | Number of cells the item covers (width, height). Ignored in single cell mode. |
bCanRotate | Whether the item can be rotated by 90 degrees. |
MaxStackSize | Maximum items in one stack. 1 means the item does not stack. |
Traits | Item traits of the definition, for example the weight. |
Size and stacking are fixed properties because the grid needs them. Everything else is an item trait.
Rarity of an item: Pulse::Inventory::GetItemRarity(Definition, InstanceTraits) gives one rarity per item: the rolled rarity of FPulseItemTrait_RolledStats (of the instance, else of the definition), then Rarity of the definition, then the first Pulse.Rarity tag in its Tags. GetRarity (Blueprint pure) gives the last two, without an instance. The root Pulse.Rarity itself and tags outside it are no rarity. Data validation reports a Rarity outside Pulse.Rarity (or the root) as an error, and a Pulse.Rarity tag in Tags that differs from Rarity, or several of them without Rarity, as a warning: move the tag into Rarity. Spec: PulseInventory.TraitModifiers.
Example: a sword that covers 1 x 3 cells, can be rotated, does not stack and weighs 3 (Weight trait).
Behavior in subclasses
Derive from UPulseItemDefinition in C++ or Blueprint and override these events:
| Event | When it runs |
|---|---|
CanAddToInventory(Inventory, Count) | Before items are added. Return false to reject them. |
OnAddedToInventory(Inventory, Count) | On the authority after items were added. |
OnRemovedFromInventory(Inventory, Count) | On the authority after items were removed. |
UseItem(Inventory, ItemId, User) | On the authority when the item is used. Return true to consume one item. |
OnAddedToInventory and OnRemovedFromInventory are not called when stacks are only merged or moved inside one inventory, and not while importing saved data.
Example: a Blueprint item class with a HealAmount variable that overrides UseItem, prints who uses it and returns true, so one item is consumed. The potion is a data asset of this class (stacks up to 10, weight 0.5).
Layout and presets
FPulseInventoryLayout describes how the inventory is built:
| Property | Meaning |
|---|---|
GridMode | Grid: items cover their Size. SingleCell: every item takes exactly one slot, item size and rotation are ignored. |
GridSize | Cells horizontally (X) and vertically (Y). |
bAllowRotation | Allow rotating items by 90 degrees (grid mode only). |
CellSize | Size of one cell in UI units. Only a hint for the UI, the inventory logic does not use it. |
UPulseInventoryLibrary has Blueprint helpers to create layouts: MakeGridLayout(Columns, Rows, bAllowRotation, CellSize) and MakeSimpleSlotsLayout(SlotCount, CellSize).
Presets
UPulseInventoryLayoutPreset is a data asset with a Layout and a list of DefaultTraits. Create one asset per kind of inventory (backpack, chest, hotbar, …). Assign it to InitialPreset or apply it at runtime with ApplyPreset(Preset, bReplaceTraits).
Example: a grid of 6 x 4 cells with rotation and a Weight Limit of 20.
Changing the layout at runtime
SetLayout(NewLayout) and ApplyPreset run on the authority. If all items still fit at their current places, they stay where they are. Otherwise they are packed again (biggest items first, rotating them if allowed). If they still do not fit, nothing changes and the result is LayoutTooSmall. ApplyPreset changes the layout and the traits in one step (one OnInventoryChanged) and replaces the initial setup, also when it runs before BeginPlay.
InitialPreset, InitialLayout and DefaultTraits are applied in BeginPlay or by the first change. Code that reads the layout or the traits before the inventory began play (e.g. another component while loading) calls EnsureSetup() first; it does nothing on clients or when it already ran.
Placement rules
The inventory keeps a grid of cells. An item covers the cells of its footprint (Size, swapped when rotated). Items cannot overlap and cannot leave the grid.
For example, in a grid of 5 x 8 cells with a 4 x 4 item at the top left, a 4 x 2 item cannot be placed at (0, 3) because it would overlap. It fits at (0, 4).
TryAddItem fills existing stacks first and then places new stacks on the first free place, scanning row by row. It tries the rotated footprint only if the normal one does not fit anywhere. Only stacks without instance traits are merged.
Moving, merging and swapping
MoveItem(ItemId, Position, bRotated) handles the target place in this order:
- The target is free: the item moves there.
- The target holds exactly one other stack of the same item with room: the stacks are merged. The rest stays at the origin.
- The target holds exactly one other item and
bAllowSwapis set: the two items swap. The other item takes the old place of the moved item and is rotated if that is what makes it fit. This only happens if both fit afterwards. - Otherwise the action fails with
Occupiedand nothing changes.
TransferItem follows the same rules between two inventories. Swapping needs the whole stack. Both inventories check their traits before anything changes, each in the state it will have once the outgoing stack left (so a weight limit or your own trait judges the real result). A swap keeps the item ids of both stacks where the receiving inventory has no other stack with that id; a stack moved to a free place gets a new id. Both inventories are changed first, then the source fires its events, then the target.
MoveItemsTo(Target, Item, Count) moves a number of items of one type into another inventory, all or nothing, as an exchange of Pulse Foundation: the smallest stacks of the source first, onto stacks of the target first, then into free cells. Every stack keeps its instance traits (rolled stats, durability), and only stacks that may change their holder move: bound stacks (Bound without Can Transfer) and lent stacks stay. It returns InvalidCount when the source has fewer movable items, or the reason the target has no room.
For drag and drop feedback, CanMoveItem(ItemId, Position, bRotated) returns the result of MoveItem without changing anything. CanPlaceDefinitionAt checks whether an item that is not in the inventory yet would fit in free cells.
Results
The functions of the component, the pickups and the requests return an FPulseResult of PulseFoundation: success, or the reason as a gameplay tag with a text for the player (Get Display Text), the same as every other Pulse plugin. The rules underneath (planning, views, traits, Pulse Sim) work with the code EPulseInventoryResult; Pulse::Inventory::ToResult turns a code into a result and GetReason gives its tag. The names in this page are the codes; this is their reason and text (replace the texts in the Result Texts of the Pulse Foundation settings):
| Code | Reason | Text |
|---|---|---|
NoAuthority | Pulse.Result.Failure.Authority | of PulseFoundation |
InvalidItem | Pulse.Result.Failure.NotFound | of PulseFoundation |
InvalidDefinition, InvalidCount, InvalidTarget | Pulse.Result.Failure.Invalid | of PulseFoundation |
NoSpace | Pulse.Result.Failure.NoSpace | of PulseFoundation |
RateLimited | Pulse.Result.Failure.Busy | of PulseFoundation |
NotAllowed | Pulse.Result.Failure.Inventory.NotAllowed | You cannot change this inventory. |
OutOfBounds | Pulse.Result.Failure.Inventory.OutOfBounds | It does not fit there. |
Occupied | Pulse.Result.Failure.Inventory.Occupied | That place is taken. |
StackFull | Pulse.Result.Failure.Inventory.StackFull | The stack is full. |
WeightExceeded | Pulse.Result.Failure.Inventory.TooHeavy | That is too heavy. |
RejectedByTrait, RejectedByDefinition, RejectedByInventory | Pulse.Result.Failure.Inventory.Rejected.Trait, .Definition, .Inventory | This does not go in here. (text of Rejected) |
LayoutTooSmall | Pulse.Result.Failure.Inventory.LayoutTooSmall | The items do not fit into the new layout. |
CannotDrop | Pulse.Result.Failure.Inventory.CannotDrop | This cannot be dropped. |
SpawnFailed | Pulse.Result.Failure.Inventory.SpawnFailed | The item could not be dropped here. |
A missing stack, a wrong count and a missing authority are reasons of PulseFoundation, so the guard of the request subsystem counts them when a client sends many of them.
TryAddItem and TryAddItemAt return FPulseInventoryAddResult with Added, Remaining and the result for the remaining items (Result; Code for C++). They add as many items as possible.
Traits
Traits are how you add data and rules to an inventory or an item. They are similar to traits on a Mass entity: nothing is fixed in the layout, you add what you need. Traits can be changed at runtime.
FPulseInventoryTrait: a trait of an inventory. It can limit which items are accepted.FPulseItemTrait: a trait of an item.
Both derive from FPulseTrait, which has two flags:
| Flag | Meaning |
|---|---|
bReplicated (default true) | Replicate the trait to clients. When false the trait exists on the server only. |
bPersisted (default true) | Write the trait when the inventory is saved. |
There is at most one trait per struct type on the same holder. Setting a trait of the same type replaces the existing one. Traits are stored in a FPulseTraitContainer, which keeps replicated and server-only traits in separate lists. Changing bReplicated on a trait takes effect the next time you set it.
Inventory traits
Add them with DefaultTraits on the component, DefaultTraits of a preset, or at runtime with SetTrait / RemoveTrait on the authority. Read them with FindTrait<T>() (C++) or GetTrait / HasTrait (Blueprint). Clients only see replicated traits.
| Trait | Purpose |
|---|---|
FPulseInventoryTrait_WeightLimit | MaxWeight: the total weight of all items cannot exceed it. |
FPulseInventoryTrait_ItemFilter | RequiredTags (the item needs at least one) and BlockedTags (the item must have none). |
FPulseInventoryTrait_ItemModifiers | Item Modifiers: changes numbers of the items inside, e.g. ores weigh 10 % less (Trait modifiers). |
Item traits
Item traits can be on the definition and on the item instance. A trait on the instance overrides the trait of the same type on the definition. When all traits of an item are walked (Pulse::Inventory::ForEachEffectiveItemTrait, for example for stats), an instance trait also overrides a definition trait whose type derives from it or that it derives from (below FPulseItemTrait), so a stat counts once.
| Trait | Purpose |
|---|---|
FPulseItemTrait_Weight | Weight of one item. Items without it weigh nothing. |
FPulseItemTrait_Bound | Binds the item to its inventory, e.g. quest items or items lent by a skill. DropItem returns CannotDrop and TransferItem into another inventory returns NotAllowed, unless bCanDrop / bCanTransfer are set; a swap refuses a bound stack it would displace as well. Equipping from and unequipping into an inventory of another holder (a stash, a death bag, another player) returns NotAllowed too, for lent stacks as well; the inventories of the own player (same actor, or pawn, controller and player state of one player) are the same holder. Moving inside the inventory and RemoveItem still work. The rule is Pulse::Inventory::CanChangeHolder (Items/PulseItemRules.h). |
FPulseItemTrait_Perishable | Items that spoil on the game clock (Spoilage). |
FPulseItemTrait_Value | What one item is worth in the currency of a merchant (Merchants). |
FPulseItemTrait_WearerModifiers | Wearer Modifiers: while the item is equipped, it changes numbers of the items in the inventories of its wearer (Trait modifiers). |
Definition traits are part of a static asset and are not replicated: every machine reads them from the asset. Values that change at runtime, such as durability or a different weight, belong on the instance: SetItemTrait(ItemId, Trait) and RemoveItemTrait(ItemId, TraitType) on the authority. Instance traits are replicated according to bReplicated. FindItemTrait<T>(ItemId) and GetItemTrait return the trait as the item sees it, instance first and then definition.
Items with instance traits are not merged into other stacks, except perishable items (Spoilage).
Spoilage
Food, potions or bait spoil on the Pulse game clock with the item trait Perishable (FPulseItemTrait_Perishable) on the definition:
| Field | Meaning |
|---|---|
| Shelf Life Hours | Hours from fresh to spoiled (at rate 1): hours of the day by default, so 24 is one day of the PulseTime calendar; without a calendar hours of the game clock (Hour Unit) |
| On Spoiled | Replace with Spoiled Item (same count, in the place of the stack; without one the stack goes), Remove, or Keep at freshness 0 |
Every stack keeps its own state as an instance trait: how fresh it was when (Anchor Freshness at Anchor, a stamp of the game clock) and how fast it spoils (Rate). The inventory sets it when it makes a new stack. Items of different age still stack: the joined stack starts at the average freshness by count (Pulse::Inventory::Spoilage::MergeTraits), so ten fresh apples and one old apple make one stack of slightly older apples. Nothing ticks: freshness is a function of the game time (GetItemFreshness, also on clients), and the inventory sets one clock timer for the first stack that spoils (Replace, Remove). Stacks that spoiled while nobody looked (a stash in Pulse Sim, a saved game) go when the inventory starts. Set Item Spoil Rate changes the rate of a stack and keeps its freshness now (a cooler 0.5, salted 0.25, 0 stops it). Every spoiled stack sends Pulse.Message.Inventory.ItemSpoiled (authority).
Hours of the day. With Hour Unit Day Hour (the default, Settings) the hours of the shelf life follow the day rate of the Pulse Foundation clock (Pulse::Clock::GetSecondsPerDayHour, set by PulseTime): at a day rate of 60 an apple with 24 hours spoils in one day of the calendar, 24 game minutes. Without a calendar the day rate is 1 and nothing changes. Each stack keeps the game seconds of its hour in its state (Seconds Per Hour, 0 in data saved before counts as 3600); GetSecondsPerHour on the component gives the seconds of now. When the day rate changes, the authority moves the anchor of every stack (Reanchor with the new seconds per hour), so its freshness stays and the new hours count from then on; a load does the same for saved stacks. Skipping hours of the day in PulseTime (SkipHours, SkipToHour) moves only the day, not the game clock, so nothing spoils across a skip; a rest that moves the game clock does spoil. Set Hour Unit to Game Clock Hour to keep 3600 game seconds per hour.
The rules are plain functions (Items/PulseItemSpoilage.h): GetFreshness, GetSpoilTime, GetSecondsPerHour, Reanchor, Merge, CanStackTraits, StampTraits; the ones that set an anchor take the seconds per hour of now as a last parameter (0 counts as 3600). Plans stamp and join perishable stacks with FPulseInventoryView::Now (the game time) and FPulseInventoryView::SecondsPerHour; a view without a time (below 0) keeps perishable stacks apart. The tooltip section Freshness shows “75 %” or “Spoiled”. Equipped items keep their state and freshness, but spoil only in an inventory. Specs: PulseInventory.Spoilage.
GetTotalWeight() sums the weight of all items (weight of one item, with its trait modifiers, times the stack count).
Carry weight and overloaded
The weight limit is scaled by the tuning knob Pulse.Tuning.Inventory.CarryWeight for the owner of the inventory (GetCarryWeightFactor; per player, 1 without tuning). GetMaxWeight() is the limit as it counts now, negative without a weight limit trait.
When the limit drops below what is carried (a smaller carry weight, a harder difficulty, a smaller limit set at run time), the inventory is overloaded (IsOverloaded()): it keeps every item and refuses new ones until enough weight is gone. The inventory does nothing else; a game reads the state for slower movement or a HUD hint. The view model has bOverloaded, and Pulse.Message.Inventory.OverloadChanged (FPulseInventoryOverloadMessage: bOverloaded, Weight, MaxWeight) tells when it changes. The component checks after each change of its contents or traits and after each tuning change on every machine, so a new carry weight reaches the HUD by itself: a new limit fires OnInventoryChanged (the view model refreshes MaxWeight and bOverloaded). Call RefreshOverload() only when the factor changes another way (a rule of your own). Changes that OverloadChanged listeners make (dropping items to get under the limit) wait until the message has reached every listener, like those of an operation.
OverloadChanged catches up like the item messages: an inventory that a save, a Pulse Sim record or a client’s first replication (also its stacks whose item loads later) brings in overloaded sends it with CatchUp set (Load, Replication), so toasts and sounds leave it out; a change while playing has CatchUp None.
The pure rules are Pulse::Inventory::GetMaxWeight and IsOverloaded on a view (FPulseInventoryView::CarryWeight). A view of an unloaded stash record has no owner: Pulse::Inventory::Sim::MakeRecordView gives it the carry weight of the world (personal values need the owner), so an unloaded record takes no more than its loaded inventory would. Specs: PulseInventory.Tuning, PulseInventory.Messages.
Tuning: a new stack gets the spoil rate of the tuning knob Pulse.Tuning.Inventory.Spoilage for the owner of the inventory (GetSpoilRateFactor; a player may set it for themselves). A stack keeps the rate it got: a later change of the knob counts for new stacks, so saved freshness never jumps. SetItemSpoilRate sets a rate as it is given.
Trait modifiers
Numbers of an item can depend on where it is, without changing the item: a backpack whose ores weigh 10 % less, a cooler in which food spoils at half the rate, a hard difficulty that makes everything heavier, a talent that raises the value of gems. A trait modifier (FPulseItemTraitModifier, Traits/PulseItemModifier.h) has three parts:
- Filter:
Items(item types; empty: every type),Tags(a tag query on the tags of the definition and the rarity of the item; empty: every item) andRarities(the rarity of the item,GetItemRarity: the rolled rarity ofFPulseItemTrait_RolledStats, thenRarityof the definition, then aPulse.Raritytag of the definition; a child tag matches its parent, soPulse.Raritytakes every item with a rarity; empty: every rarity). An item without a rarity never passes a filledRarities. - Field (
FPulseItemTraitField): the number it changes. - Change:
OperationFactor (multiplies), Bonus (adds) or Set, withAmount.
| Field | Number | Read by |
|---|---|---|
Weight | FPulseItemTrait_Weight::Weight | GetTotalWeight, the weight limit, overloaded, TotalWeight of the item view model |
MaxDurability | FPulseItemTrait_Durability::Max | GetItemTrait<FPulseItemTrait_Durability> and the tooltip |
DurabilityLossPerUse | FPulseItemTrait_Durability::LossPerUse | Pulse::Inventory::Tuning::GetWearAmount without an amount (combat and gathering wear) |
MaxStackSize | UPulseItemDefinition::MaxStackSize (every item) | adds, moves and transfers; ValidatePlan and loading take the larger of it and the definition |
SpoilRate | a factor of how fast a perishable item spoils (starts at 1) | the rate a stack gets when it is made in the inventory or enters it |
Value | FPulseItemTrait_Value::Value | buy prices from the value and sell prices of merchants (the sources of the trader’s owner only) |
Custom | a float, double or integer property (Property) of an item trait of your own (Trait) | GetItemTraitValue, GetItemTrait<T> |
A modifier only changes a number the item has: Weight needs a weight trait, Value a value trait and so on (an item without a value stays unsold); MaxStackSize counts for every item.
Sources, applied in this order, each list in its order, one modifier after the other (a Set replaces what came before it, a later factor works on the set number):
- The inventory trait Item Modifiers (
FPulseInventoryTrait_ItemModifiers:Label,Modifiers) of the inventory: a backpack, a cooler, a quiver with larger stacks. It is part of the traits, so it counts in every view, also in planned states and in views without a component. - The item trait Wearer Modifiers (
FPulseItemTrait_WearerModifiers:Label,bOnlyWhileActive,Modifiers) of the items the owner wears: the worn backpack changes the inventories on the actors of its wearer. It counts while the item is in use (Pulse::Inventory::IsItemInUse: not broken, and in a hotbar slot only while active withbOnlyWhileActive). The inventory finds the equipment of its owner (UPulseEquipmentComponent::FindEquipmentComponent) inBeginPlay; while it has none (or the one it had is gone) it looks again when the modifiers are read, at most once a second or when the cache is rebuilt. - The adjustment Item Modifiers (
FPulseAdjustment_ItemModifier:Label,Modifiers) of the tuning: a difficulty, a zone, an event or a talent (Give Adjustments withbForPlayer). Its tags are checked with the owner of the inventory as the player; the filter of each modifier picks the items. Without aLabelthe tooltip names the tuning source (“Hard”). It takes no conditions (Validaterefuses them, the collection leaves such an adjustment out): the modifiers are collected once per tuning change and equipment change, so a condition would not be read again when its answer changes, and server and client could disagree. UseTags, or a tuning source of its own that the game sets and removes (a zone source while the player is in the zone). A client knows only the personal sources of its own players: the inventories of other players it computes without theirs (their weights and stack sizes in its view are the ones without personal sources; the server decides with them).
Reading. GetItemTraitValue(ItemId, Field) and GetDefinitionTraitValue(Definition, InstanceTraits, Field) (Blueprint) return an FPulseItemTraitValue: bValid, Base, Value and Sources (the names of the sources that changed it, each once). In C++ GetItemTrait<T>(ItemId) or GetItemTrait<T>(Definition, InstanceTraits) returns the whole trait as the inventory sees it, definition, instance and modifiers together (TOptional<T>); Blueprint has GetModifiedItemTrait. It is a copy: never write it back with SetItemTrait, the modifiers would count twice. The FindItemTrait and GetItemTrait functions of before still return the trait unmodified.
// Ores weigh 10 % less in this inventory
FPulseItemTraitModifier lighter;
lighter.Tags = FGameplayTagQuery::MakeQuery_MatchAnyTags(FGameplayTagContainer(OreTag));
lighter.Field = EPulseItemTraitField::Weight;
lighter.Operation = EPulseItemModifierOperation::Factor;
lighter.Amount = 0.9f;
FPulseInventoryTrait_ItemModifiers backpack;
backpack.Label = NSLOCTEXT("MyGame", "Backpack", "Backpack");
backpack.Modifiers.Add(lighter);
Inventory->SetTrait(backpack);
const FPulseItemTraitValue weight = Inventory->GetItemTraitValue(ItemId, EPulseItemTraitField::Weight);
const TOptional<FPulseItemTrait_Weight> trait = Inventory->GetItemTrait<FPulseItemTrait_Weight>(ItemId);
Pure rules. The view carries the modifiers from outside the traits (FPulseInventoryView::Modifiers); the component fills it in GetView and FPulseInventoryView::Of. Pulse::Inventory::GetItemTraitValue(View, ...), GetUnitWeight(View, ...), GetMaxStackSize, GetSpoilRateModifier, ModifyItemNumber (the modifiers on a number the caller has) and ApplyModifiersToTrait read the Item Modifiers trait of the view, then its Modifiers; ApplyModifiers is the rule itself (a number and a list of sources), ReadItemNumber the number without modifiers. GetModifierView() of the component is a view of its traits and modifiers without stacks.
Cache. The component collects the Wearer Modifiers of the equipment and the adjustments of the tuning once (GetItemModifiers) and again when the equipment of the owner equips, unequips, changes an item or the active slot, or when the tuning changes (its generation). Only when the collected sources differ from the last ones (labels and every property of the modifiers, Pulse::Inventory::AreSameModifierSources) it fires OnInventoryChanged (view models refresh their weights) and checks overloaded; a personal tuning source of another player is ignored. Call RefreshItemModifiers() when a source of your own changes. The Item Modifiers trait needs no cache: a new trait is a change of the inventory anyway.
Spoil rate. A new perishable stack gets the rate of the tuning times the SpoilRate modifiers of the inventory, and keeps that factor in its state (FPulseItemTrait_Perishable::ModifierFactor). A stack with a state that enters an inventory by any route (TransferItem and the other stack of a swap, an add with the traits of a dropped or unequipped stack, a pickup, an exchange, a Pulse Sim put: every new stack of PlanAdd) gets the rate of that inventory: its rate divided by the factor it was stamped with, times the factor of the inventory, and its anchor moves so its freshness now stays (Pulse::Inventory::EnterSpoilRate). Leaving a cooler by any route gives the rate without the cooler again, and equipping or unequipping between two moves never makes the rate drift. Stacks that stay where they are keep their rate when the modifiers change; a stack joining another takes the rate of that stack. Saved states without the factor read it as 1 (the save data is tagged properties, no new version). SetItemSpoilRate sets the whole rate, the factor stays.
Loading. A load never destroys items because of modifiers: the saved count is kept up to the larger of MaxStackSize of the definition and the modified size (with the traits of the import), and ValidatePlan checks the same limit (Pulse::Inventory::GetStackSizeLimit), so a lowered size or equipment that loads later cuts nothing. Items above that limit go to new stacks in free cells (the import report names them); planning keeps to the modified size.
Merchants. Prices read only the sources of the owner of the trader’s inventory (Wearer Modifiers and the tuning: GetModifierView(false)), not the Item Modifiers trait of the inventory itself: a bag with a value modifier would otherwise price an item one way inside it and another outside, and buying and selling through it would make money.
Hot path. The filter compares loaded item types by pointer and builds a path only for an entry that is not loaded; GetTotalWeight finds the Item Modifiers trait once (Pulse::Inventory::FindOwnModifiers, GetUnitWeight with it). GetWearAmount takes the instance traits of the item (InInstanceTraits, so rarity filters see the rolled rarity); without them the filter sees the definition only.
Tooltip. MakeItemTooltipRequest of PulseInventoryUI takes the inventory (Inventory, also on the payload FPulseItemTooltipPayload); the tooltip section Trait Modifiers (FPulseItemTooltipSection_Modifiers, in the default sections) shows one row per changed number, such as “Weight 2 -> 2.4 kg (Hard)”, in a color for raised and one for lowered numbers (Pulse::Inventory::FormatItemTraitValue writes the line).
Limits. The equipment of the owner is found in BeginPlay; an equipment on an actor the owner gets later (a pawn possessed afterwards) is not seen. Loading clamps a stack to the stack size the inventory has while it loads, so a stack that only fit with the modifiers of an equipment that loads after the inventory is cut to the size without them. IsBroken and the durability percent of equipped items read the durability trait as it is; a changed MaxDurability shows in GetItemTrait and in the tooltip. GetWearAmount uses the first inventory of the player of the context and the definition (Source of the context), not the rarity of the instance. Loot tables, pickups and the stack size of pickups do not read trait modifiers. Specs: PulseInventory.TraitModifiers.
Writing your own trait
Custom traits are C++ structs. (Blueprint structs cannot derive from a C++ struct.)
USTRUCT(BlueprintType, meta = (DisplayName = "Max Stacks"))
struct FMyTrait_MaxStacks : public FPulseInventoryTrait
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Trait")
int32 MaxStacks = 10;
virtual int32 GetMaxAcceptedCount(const FPulseInventoryView& InInventory, const FPulseInventoryAddContext& InContext, EPulseInventoryResult& OutBlockReason) const override
{
if (InInventory.Items.Num() < MaxStacks)
{
return InContext.Count;
}
OutBlockReason = EPulseInventoryResult::RejectedByTrait;
return 0;
}
};
GetMaxAcceptedCount returns how many of InContext.Count items the trait accepts. Returning less than InContext.Count lets TryAddItem add part of the items.
Read the inventory only from the view (FPulseInventoryView, State/PulseInventoryView.h): InInventory.Items (the stacks), InInventory.Layout, InInventory.FindTrait<T>() and the helpers in Pulse::Inventory (GetTotalWeight(InInventory), CountItems, FindFreePosition, …). The view is not always the live component: a swap between inventories asks each side with the planned state after the outgoing stack left, equipping asks with the inventory after the equipped stack left, and code without components (specs, later entities) asks with a plain FPulseInventoryState. So a trait that reads the view is right for all of them.
The context holds the definition, the instance traits and ExcludeItemId, a stack that is about to leave (the weight limit does not count it). The built-in moves and swaps do not set it: they remove the leaving stack from the planned state instead, so traits see the inventory as it will be; own code that checks an add against the live inventory can still set it. To read item data, use InContext.FindItemTrait<T>(), which returns the trait as the item sees it (instance first, then definition), for example InContext.FindItemTrait<FPulseItemTrait_Weight>().
The pure rule of the item type, UPulseItemDefinition::CanAddToInventoryView (C++), runs first for every view, also planned states and states without a component. The hooks of the definition (CanAddToInventory) and of the inventory (CanAcceptItem) run next and get the live component, also when a planned state is checked; states without a component skip them. Rules that must hold for planned states belong into CanAddToInventoryView or an inventory trait. Hooks must not change inventories: if one does, the check stops with InvalidItem and nothing is added.
An item trait is a struct that derives from FPulseItemTrait and only holds data. All non-transient properties of a persisted trait are saved, they do not need the SaveGame flag.
The item catalog
Items are known by their id: the kind PulseItem and the name of the definition (PulseItem:Sword, the primary asset id of the item asset). Stacks, equipment, pickups, item uses and saves keep the id; every machine finds the item behind it through the definitions of PulseFoundation (Pulse::Definitions): items the game registered at runtime first, then the catalog of the kind PulseItem. Without any setup that catalog reads the item data assets through the asset manager, so a project with item assets needs nothing. A studio with its own source of items (a database, a server, mod content) names a catalog class for the kind in Project Settings > Pulse > Foundation > Definitions > Definition Catalogs (see Definitions).
Pulse::Inventory::Items (Items/PulseItemCatalog.h) and the Blueprint library Pulse Item Catalog (Pulse|Inventory|Catalog):
| C++ | Blueprint | What it does |
|---|---|---|
GetItemId(Definition) | Get Item Id | The id of an item (no world needed). |
MakeItemId(Name) | PulseItem:<Name>. | |
FindItem(Context, Id) | Find Item | The item when it is ready now, without loading. |
LoadItemSynchronous(Context, Id) | Loads it at once (saves, cheats, server requests). | |
LoadItem(Context, Id, Done) | Load Pulse Definition (PulseFoundation, class Pulse Item Definition) | Loads it without a hitch. |
GetItemIds(Context) | Get All Item Ids | Every id of the catalog and the registered items, sorted. |
RegisterItem(Context, Definition) | Register Item | Adds an item made at runtime under its id. |
UnregisterItem(Context, Id) | Unregister Item | Removes it again. |
ParseItemId(Context, Text) | Reads Sword, PulseItem:Sword or an object path (cheats and tools). |
Items made at runtime. Make an object of an item class (Construct Object, NewObject), name it after its id, the same name on every machine, and register it with Register Item on the server and on every client that needs it. A registered item hides an asset with the same id. Registration refuses a class default object and an id that belongs to another registered object; an answer of a catalog whose object has another id is not used (a warning names the catalog). The cheat PulseInventoryMakeItem <Name> <Template> makes one from a template on the machine it runs on.
Lent items. An item trait on an instance can mark the stack as only lent to the player by overriding IsLent() (returns true), as the items that PulseSkillInventoryBridge gives while a skill is learned. Item costs and Take Items never take lent stacks, and Has Item counts them only with bIncludeLent (see Conditions, costs and rewards). Otherwise a player could pay with a lent item and get it again from the system that lent it. The lending system removes its items itself; Pulse::Inventory::IsLent(Traits) tells whether a stack is lent.
Effects of a use. An item trait can add its own effects when its item is used by overriding OnUsed(const FPulseItemUseContext&) (Items/PulseItemUseContext.h), for example a food trait that fills hunger when a consumable is eaten. The system that uses the item calls Pulse::Inventory::NotifyItemUsed(Context) on the authority once the use took effect: it calls OnUsed of every trait the item sees (instance traits first, then the definition traits they do not override), with bOnInstance set for each. The context holds the user (User, UserComponent), the item, where it came from (Inventory and ItemId, or Equipment and Slot; the stack may be gone when the use took the last item), Count and a copy of the instance traits from before the use, so Context.FindItemTrait<T>() still finds the freshness or rolled stats of the eaten stack. MakeContext() gives a FPulseContext for attribute changes and tuning (the user as player and instigator, the item as source, its tags, amount 1). Consumables of Item effects call it (spec PulseInventoryEffects.Trait hooks); the rule itself is in spec PulseInventory.ItemRules.NotifyItemUsed.
Replication and requests
All changes are made on the authority (server or standalone) and replicated to clients.
Items on the network
Stacks (FPulseItemInstance) and equipped items (FPulseEquippedItem) replicate the id of their item (DefinitionId), not the pointer; Definition is not replicated. A client finds the item through the catalog with an FPulseDefinitionResolver of PulseFoundation: at once when it is ready or loads at once (the default catalog loads the asset like a replicated pointer would), else asynchronously. While it loads the stack has no Definition (IsValidItem is false): it takes no cells, menus and the item messages leave it out, and when the item arrived the inventory announces it (OnItemAdded, OnInventoryChanged). An item that did not load (an id the client does not know) stays hidden until the item definitions change (NotifyDefinitionsChanged, a registration); a warning names the catalog. A stack or equipped item that gets the id of another item that still loads is announced as removed at once and as added when the new item arrived. A stack of the first replication whose item arrives later still catches up (CatchUp Replication, see Messages). GetItems still lists such stacks; read IsValidItem when you walk it. Pickups send the id once (a pickup whose item did not load asks again when the item definitions change), item uses (FPulseItemUseState) replicate it too; their started and finished events fire once when the item arrived.
Replication mode
The replication mode (EPulseReplicationMode of PulseFoundation) decides who receives the layout, the items and the replicated traits:
| Mode | Receivers |
|---|---|
Default | Follows Project Settings > Pulse > Inventory > Network: Player Inventory Replication (OwnerOnly) when a player owns the inventory (its pawn, controller or player state, or a pawn nobody possesses yet, see below), Other Inventory Replication (Everyone) for stashes, chests, shared containers, death bags and NPCs. |
Everyone | Everyone the owning actor is relevant to. |
OwnerOnly | Only the connection that owns the actor. Other clients see an empty inventory. |
The mode can only be set while the component is constructed, with SetReplicationMode. There are two places to do it:
// In the constructor of the inventory (or of a subclass):
UMyInventoryComponent::UMyInventoryComponent()
{
SetReplicationMode(EPulseReplicationMode::OwnerOnly);
}
// Or in the constructor of the owning actor, right after creating the component:
AMyCharacter::AMyCharacter()
{
Inventory = CreateDefaultSubobject<UPulseInventoryComponent>(TEXT("Inventory"));
Inventory->SetReplicationMode(EPulseReplicationMode::OwnerOnly);
}
The inventory of a player is private by default: other clients see it empty, which saves bandwidth with many players. Stashes and shared containers keep Everyone, so every player can look into them. GetEffectiveReplicationMode tells which mode applies (Pulse::Inventory::ResolveReplicationMode); like the mode it is read when the component starts to replicate, and from then on it returns the mode the inventory replicates with.
A player is found by Pulse::Inventory::IsPlayerInventoryOwner: a player controller, a player state that is no bot, a pawn a player controller possesses, and, only when the pawn replicates with Iris, a pawn nobody possesses yet unless the engine gives it an AI controller on its own (Auto Possess AI applies to it, placed or spawned, and it has an AI Controller Class). The last rule is for Iris: there an actor starts to replicate right before BeginPlay, inside SpawnActor, so a player pawn (also one with the automatic inventory) replicates before the game mode possesses it, and counting it as a player’s keeps its inventory private from the first replication. The classic net driver replicates after the possession, so there a pawn nobody possesses (a vehicle trunk, a saddlebag, turret ammunition, a pawn corpse) keeps Everyone. Under Iris an NPC that a spawner possesses only after SpawnActor (Auto Possess AI off) counts as a player’s and is OwnerOnly: let Auto Possess AI (Placed In World Or Spawned) possess it, set the mode in the constructor, or set Contents Replication to Everyone.
Contents Replication (ContentsReplication, a property) is the mode a Blueprint gives an inventory: in its class defaults, or in the details of an inventory added in a Blueprint. It counts when the C++ mode (SetReplicationMode) is Default; Default there follows the project settings. Like the C++ mode it is read once, when the inventory starts to replicate. When the controller of a pawn changes after its inventory started to replicate and the new controller would need another mode (an AI pawn a player takes over), the server logs a warning on LogPulseInventory: the mode stays, so set it in the constructor for such pawns.
A later call, for example at runtime or from BeginPlay, is ignored and logged as a warning. The C++ mode is not a property, so no saved asset overrides a constructor; a Blueprint sets Contents Replication instead, which counts while the C++ mode is Default. GetReplicationMode reads the C++ mode, GetEffectiveReplicationMode the one in use.
With OwnerOnly:
- The owner is found through the owner chain of the actor: pawn to controller, player state to controller.
- Clients that are not the owner receive no layout, items or traits. Do not bind UI or ViewModels to the inventory there.
The mode is implemented with a dynamic replication condition that is read once when the inventory starts to replicate. It works with the classic net driver and with Iris.
Requests
Clients ask for changes with the request functions: RequestMoveItem, RequestRemoveItem, RequestTransferItem, RequestUseItem and RequestDropItem, or with one FPulseInventoryRequest (action Move, Remove, Transfer, Use or Drop, the stack, a count, a cell and a target) in RequestInventoryChange (C++, with a callback) or the Blueprint node Request Inventory Change (On Success, On Failure with the result). Where a request goes depends on where it is called:
- On the authority the operation runs directly, without asking
CanRequesterModify. - On a client that owns the inventory’s actor (its pawn or controller), a reliable server RPC on the inventory is sent.
- On a client that does not own it (a chest), the request is sent through the
UPulseInventoryAccessComponentof the local player, see below.
A client request carries an id of the request subsystem of PulseFoundation (requests): the server lets it in with its guard (rate per kind Pulse.Request.Inventory.Move, .Remove, .Transfer, .Use, .Drop, open requests per player) and answers with the result. The callback or node gets it; a failure is also sent as Pulse.Message.Request.Failed on that client, so one widget can show the text of every failed request.
The server does a request only if CanRequesterModify(Requester) returns true. For a transfer, both inventories are asked. The default accepts the controller that owns the component. Then CanRequesterChangeItem(Requester, Request) (C++ virtual, asked on the inventory the stack lies in) may refuse a single request for its stack; the default allows all, a death bag gives bound and lent stacks back to their owner only. The requests of other components that take a stack out of an inventory ask it as well: the item user (UseFromInventory, as a Use of the stack) and the equipment (Equip, as a Transfer of the stack). A timed use from another holder’s inventory asks CanRequesterModify and CanRequesterChangeItem again when it takes the item, so a player who walked away from the bag or chest (or died) in the meantime gets nothing. HandleRequest(Requester, Request) runs the check and the operation. The RPCs call it, and you can call it from your own request paths.
CanAcceptItem(Definition, Count) lets the inventory itself refuse items. The default accepts everything.
Trait changes (SetTrait, SetItemTrait, …) are only possible on the authority.
Chests and other inventories without an owner
A client can only send a server RPC on an actor that its connection owns, and a chest belongs to nobody. Set it up like this:
- Add a
UPulseInventoryAccessComponentto the player controller (or the pawn). TheRequest...functions of every inventory the local player does not own are then sent through it, with the inventory as a parameter. Without it the request fails withNotAllowedand a warning is logged. With several local players the first local player is used. - Override
CanRequesterModifyon the chest inventory. The default only accepts the owner, so a chest refuses everyone until you decide who may use it, for example:
bool UMyChestInventory::CanRequesterModify_Implementation(AController* Requester) const
{
const APawn* Pawn = Requester ? Requester->GetPawn() : nullptr;
return Pawn && FVector::Dist(Pawn->GetActorLocation(), GetOwner()->GetActorLocation()) <= MaxUseDistance;
}
UPulseInventoryComponent is Blueprintable, so the same works in Blueprint: create a Blueprint class with Pulse Inventory Component as parent and override Can Requester Modify. Example: the requester’s pawn must be within MaxUseDistance (300 by default, editable per instance) of the chest.
- Choose who sees the contents:
- Everyone (default): The chest replicates like any actor, to every client it is relevant to (
NetCullDistance). Simple, and fine for small, public inventories. The contents are visible to every client in range. - Only the player who opened it: Give the chest the mode
OwnerOnlyand let the server callChest->SetOwner(PlayerController)when a player opens it andChest->SetOwner(nullptr)when it is closed. Only that player receives the contents, and only one player can use the chest at a time. The chest then also has a direct RPC connection to its owner. Verify this in your project with two clients, it depends on how the net driver handles a change of owner.
- Everyone (default): The chest replicates like any actor, to every client it is relevant to (
Moving items between the player’s inventory and a chest is a normal RequestTransferItem. Both inventories have to agree in CanRequesterModify.
Dropping and picking up items
DropItem puts items into the world as a APulseItemPickup. The pickup keeps the definition, the count and the item traits, and TryPickup turns it back into items.
Dropping
// On the server. Count 0 drops the whole stack.
Inventory->DropItem(ItemId, /*Count*/ 1, FPulseDropParams());
// On a client, or from UI: only the item and the count are sent.
Inventory->RequestDropItem(ItemId, 1);
The server decides where the item lands, so a client cannot drop items at arbitrary places. By default the item is placed in front of the requester’s pawn at DropDistance, on the ground below (GetDropTransform, overridable). For a drop from a chest the requester is the player, not the chest. FPulseDropParams can set a place (bOverrideTransform), physics, an impulse and a scatter radius.
A drop puts every item into the world or changes nothing. The order is: check everything, plan the removal right after the checks, check the drop budget of the requester (without taking from it), create the new pickup completely (spawn, Init, physics, BeginPlay) while nothing else changes, remove the items from the inventory, then merge into the planned pickups nearby and remove the oldest ones for the limit, and only then take one drop from the budget. If user code changes the inventory after the checks (GetDropTransform, the spawn of the pickup), the planned removal is stale: the drop fails with InvalidItem and nothing changes. OnItemDropped fires right after the removal events of the same drop. If the new pickup cannot be created (no class, a class that cannot be spawned, a pickup that is gone after BeginPlay), the result is SpawnFailed and nothing changed: the stack keeps its id and place, the pickups nearby keep their counts, no pickup was removed and the budget is untouched. Checks:
UPulseItemDefinition::bCanDropand the eventsCanDropon the definition andCanDropItemon the inventory. Otherwise the result isCannotDrop.- The drop rate of a requester (
MaxDropsPerSecond). Otherwise the result isRateLimited. The budget belongs to the player: it is keyed by the unique net id of the player state (so it survives a reconnect), else by the controller, else by the inventory. - A pickup class must exist (
SpawnFailed).
The pickup subsystem plans a drop in two steps that you can also call yourself: PreparePickup (plan the merges, create the new pickup) and CommitPickup (merge and evict; runs no user code). SpawnPickup does both. Until the commit the new pickup is inert (IsPendingCommit): it is not registered, cannot be picked up, takes no merges and fires its first OnPickupChanged at the commit. A merge target that changed in between (count, definition, physics) cancels the drop.
OnItemDropped fires with the dropped stack and the pickup. UPulseItemDefinition::OnDropped is called as well. DropAllItems drops everything, for example when the owner dies. It ignores the rate limit, use ScatterRadius to spread the items.
Pickups
APulseItemPickup is a replicated actor with a mesh. Set the mesh on the definition (WorldMesh) and, if you want another actor, PickupClass. Otherwise DefaultPickupClass from the settings is used. The pickup sends the id of its item once; clients resolve the item through the catalog, then OnDefinitionReady builds the visual. A pickup kept in Pulse Sim stores the id in its record (FPulseSimState_Pickup::DefinitionId), so a loaded record spawns its pickup with an item made at runtime too; records of older saves load by their item pointer.
TryPickup(Receiver, Requester)moves the items into an inventory. If everything fits, the pickup is destroyed. If not, it keeps the rest.CanBePickedUpcan refuse.- Items with instance traits are never merged and keep their traits through a drop and a pickup.
Pulse Sim: with bKeepPickupsInPulseSim (on by default) the server keeps every pickup as a Pulse Sim record (kind FPulseSimState_Pickup: item, count, traits, rotation and the game seconds left; id Pickup.<guid>, GetSimRecordId). Pulse Sim saves dropped items with the world. The lifetime runs in the record on the game clock (a paused game keeps its pickups), and when it is up the record removes itself and the pickup goes with it (notice Pulse.Inventory.Sim.PickupExpired). Picking up and evicting remove the record; the end of the world keeps it. After a load, UPulsePickupSubsystem spawns the pickup of every pickup record without one on the next frame (SpawnPickupForRecord does it by hand). Without Pulse Sim running the pickup counts its lifetime itself, also on the game clock.
Interaction: The module PulseInventoryInteract has APulseInteractablePickup, a pickup that works with the PulseAbility interaction. Use it as DefaultPickupClass. It finds the inventory on the interactor, its pawn, its controller or its player state. The interaction has to reach the server, so use UPulseRepInteractAbility (the pickup asks for replicated interaction). Without the interaction module, call TryPickup from your own code.
Settings
Project Settings under Pulse > Inventory (UPulseInventorySettings):
| Setting | Default | Meaning |
|---|---|---|
DefaultPickupClass | APulseItemPickup | Pickup class for definitions without their own PickupClass. |
PickupLifetime | 300 s | Seconds of the game clock until a pickup disappears. 0 keeps it. |
bKeepPickupsInPulseSim | on | Every pickup is a Pulse Sim record: saved with the world, back after a load, lifetime on the game clock. |
MaxWorldPickups | 500 | Limit of pickups in a world. The oldest is removed first; pickups a drop merges into are kept, so the limit can be exceeded for a moment. 0 means no limit. |
MergeRadius | 150 cm | Drops of the same item this close are merged into one stack. 0 turns it off. |
DropDistance | 120 cm | Distance in front of the requester. |
MaxDropsPerSecond | 5 | Drops per second and requester. 0 means no limit. |
bDefaultSimulatePhysics | off | Whether dropped items are thrown with physics. |
PhysicsSettleSpeed, PhysicsMaxTime | 10 cm/s, 4 s | When a simulated pickup counts as resting. |
PickupNetCullDistance | 5000 cm | Pickups are only relevant to clients this close. |
InventoryItemViewModelClass | UMVVMPulseInventoryItem | View model of one item stack, created by UMVVMPulseInventory (category View Models). A child (C++ or Blueprint) adds fields of its own; empty or a class that does not fit uses the base class. |
bAllowWornItemsToLeave | off | Whether worn stacks (durability below the maximum, broken included) may leave the inventory for good: sold to a merchant, paid in a trade or an Items cost, used up by crafting (Pulse::Inventory::CanLeaveInventory, CanWornItemsLeave). Off: they have to be repaired first. Lent and bound stacks never leave, whatever this says. Category Items. |
MaxPurchasesPerTrade | 999 | The most purchases of one offer a single buy may ask for (Request Buy, Buy). More are refused with Pulse.Result.Failure.Inventory.TooMany, and so is a buy whose price or item count does not fit a 32-bit number. Category Merchants. |
HourUnit | Day Hour | What the hours of Shelf Life Hours (Spoilage) and Restock Hours (Merchants) count. Day Hour: hours of the day, game clock hours times the day rate of the Pulse Foundation clock (Pulse::Clock::GetSecondsPerDayHour), so with PulseTime a shelf life of 24 hours is one day of the calendar; without a calendar (day rate 1) it is the same as Game Clock Hour. Game Clock Hour: 3600 game seconds, whatever the calendar does. UPulseInventorySettings::GetSecondsPerHour gives the seconds of one hour. |
Keeping the network cost low
The cost of pickups grows with the number of replicated actors, not with the bytes of one actor. So a pickup costs nothing while it lies still:
- Dormancy. A pickup replicates once, then goes dormant (
DORM_DormantAll, works with the classic net driver and with Iris). Clients that join later still get its state. Only a change of the count wakes it for one update (FlushNetDormancy). - No movement replication at rest. Without physics the item is placed and never replicates movement. With physics, movement is replicated only while it moves. When it rests, the simulation stops, the final position is sent once, then movement replication is turned off and the pickup goes dormant. A simulated item needs a
WorldMesh, otherwise it is placed instead. - Little data. The definition and the instance traits are sent once (
COND_InitialOnly). Only the count can change. - Relevance. A pickup is not always relevant, has a net cull distance and a low update frequency, and does not tick.
- Fewer actors. The limit of pickups, the lifetime and the merging of nearby drops keep the number of actors down.
- Abuse protection. The drop request carries only the item and the count, the server picks the place, and the drop rate is limited.
- No hitches on clients. The mesh of a pickup is loaded in the background.
Rule for your own pickup classes: a dormant actor does not send changes by itself. Change replicated state on the server only through the functions of APulseItemPickup. If you add replicated properties, call FlushNetDormancy() after changing them.
To check it in PIE, turn on net.DormancyValidate 1 and look at the dormant actors in stat net.
ViewModel
UMVVMPulseItemPickup exposes a pickup to UI, for example for an interaction prompt. Call SetPickup, or SetPickupFromActor with any actor, such as the SelectedInteractable of UMVVMPulseInteract. Fields: Pickup, Definition, DisplayName, Description, Icon, Count, MaxStackSize, UnitWeight, TotalWeight and bIsValid. The count follows the pickup on the server and on clients. On a client, bIsValid is false until the definition has arrived.
Events
UPulseInventoryComponent broadcasts these events, as Blueprint delegates and as native delegates with a Native suffix:
| Event | When |
|---|---|
OnItemAdded | An item stack was added. |
OnItemRemoved | An item stack was removed. On clients the stack is still listed in GetItems() while the event runs, but FindItem of its id returns null (or the new stack when one with the same id arrived in the same update): use the Item of the event, and IsItemPendingRemoval for code that walks GetItems(). |
OnItemChanged | A stack changed: count, place or traits. |
OnItemDropped | Items were dropped into the world (authority only). |
OnLayoutChanged | The layout changed. |
OnTraitsChanged | The traits of the inventory changed. |
OnInventoryChanged | Anything changed. Once per operation on the authority. |
On the authority they fire after the whole operation is applied: a TryAddItem that fills two stacks and opens a third fires its events once all three are changed, and every event carries the stack as it was right after its own step (a snapshot). So a listener of the first event already sees the final inventory. OnInventoryChanged fires once per operation. On clients they fire from the replication callbacks.
Order per change: a new stack calls the definition’s OnAddedToInventory first, then OnItemAdded; items added to or taken from a stack fire OnItemChanged first, then the definition hook; a removed stack calls OnRemovedFromInventory first, then OnItemRemoved. Then OnLayoutChanged, OnTraitsChanged and OnInventoryChanged.
A listener (or a hook) may change the inventory again, for example a quest objective that takes the items it counted. That change is applied at once, but its events wait until the events of the running operation are done (first in, first out per inventory). Operations on two inventories (transfers, equip, item costs) apply everything first and then fire the events of each holder in turn.
Messages
The same item events also go to the PulseFoundation message bus (UPulseMessageSubsystem), so anything can react without knowing the inventory component (a toast for a new item, a sound, a statistic, a quest objective):
| Channel | When | Payload |
|---|---|---|
Pulse.Message.Inventory.ItemAdded | OnItemAdded | FPulseInventoryItemMessage |
Pulse.Message.Inventory.ItemRemoved | OnItemRemoved | FPulseInventoryItemMessage |
Pulse.Message.Inventory.ItemChanged | OnItemChanged | FPulseInventoryItemMessage |
Pulse.Message.Inventory.ItemDropped | OnItemDropped (authority only) | FPulseInventoryItemMessage with Pickup |
Pulse.Message.Inventory.ItemSpoiled | a perishable stack spoiled and was replaced or removed (authority only) | FPulseInventoryItemMessage: the stack as it was |
Pulse.Message.Inventory.Bought, .Sold | items were bought from or sold to a merchant (authority only) | FPulseMerchantMessage: merchant, inventory, item, offer, count, price |
FPulseInventoryItemMessage has Inventory, Item (the stack after the change; for drops StackCount is the dropped amount), Pickup and Count: how many items were added or removed (also when they were merged into a stack or taken from one), the stack after a change, or the dropped amount. On the server, adding to an existing stack sends ItemAdded with the added amount and taking a part of a stack sends ItemRemoved; clients only see whole stacks, so there a merge arrives as ItemChanged.
The context of the messages has the owner of the inventory as Target and, when it is a player’s actor, as Player, the item definition as Source, its tags as Tags and Count as Amount, so quest objectives (“collect 5 wood”) and conditions of other plugins read them without the payload. Messages stay inside one game instance: the server and every client that receives the inventory send their own. Listen in Blueprint with Listen For Pulse Message (channel Pulse.Message.Inventory, match Partial for all of them). UI that shows one inventory binds to UMVVMPulseInventory instead.
Messages of items that only catch up carry a CatchUp in the context, so toasts and counters can leave them out: a client marks the stacks of the first replication (it joined, the actor became relevant again) Replication, the authority marks the stacks of a load (ImportSaveData, LoadFromBytes, a respawn carry) and of a Pulse Sim record that comes in when a stash is loaded Load. Changes made while the inventory is loaded are new events (None).
Rules as data (C++)
The rules of the inventory are plain functions on plain data in Pulse::Inventory (State/PulseInventoryState.h, State/PulseInventoryView.h), so they can be tested without a world and later run on entities:
FPulseInventoryStateis the contents as one value (layout, traits, stacks, next id, revision);UPulseInventoryComponent::GetStatecopies the component into it.FPulseInventoryViewis what rules read: pointers into a component (GetView) or a state (FPulseInventoryView::Of). On the authority plan againstGetSetUpView(it runs the setup first, which raises the revision).- Stacks carry their item type twice:
DefinitionId(PulseItem:<name>, replicated) andDefinition(the item, not replicated; clients resolve it).ValidatePlanrefuses aCreatewhose id does not match its definition. Plan...functions (PlanAdd,PlanRemove,PlanRemoveMany,PlanRestorewith whatRecordStackChangesrecorded, …) read a view and append steps to anFPulseInventoryPlan. A plan belongs to the revision of the view it was made from; several planners may fill one plan from the same view as long as they touch different stacks. A planner that fails appends nothing.ValidatePlanchecks a plan before anything changes;ApplyPlanapplies it in one step (all or nothing) and returns the changes with snapshots.UPulseInventoryComponent::ApplyPlandoes that for the component, marks replication and fires the events.
FPulseInventoryPlan plan;
FPulseInventoryAddRequest request;
request.Definition = Wood;
request.Count = 5;
const FPulseInventoryAddResult planned = Pulse::Inventory::PlanAdd(Inventory->GetSetUpView(), request, plan);
if (planned.Added > 0 && Inventory->ApplyPlan(plan) == EPulseInventoryResult::Success)
{
// planned.Added items are in the inventory now
}
The component functions (TryAddItem, RemoveItem, …) do exactly this. They report the planned result only when it was applied: if a hook changed the inventory while the plan was made, the plan is stale and nothing changes.
Exchanges
Inventories take part in exchanges of Pulse Foundation (trades, traders, crafting with costs), which change several holders all or nothing:
- The step Inventory Items (
FPulseExchangeStep_InventoryItems,State/PulseInventoryExchange.h) takes items of one type from an inventory component (Take) or puts them into it (Give). Its check plans the change on the inventory as it is. Undo puts back exactly what the step changed, relative to the inventory as it is at the undo (Pulse::Inventory::RecordStackChangesin Execute,Pulse::Inventory::PlanRestorein Undo): the stacks a take emptied come back with their id, place and instance traits, also when it took any stacks of the item, so a worn, bound or spoiling stack is never handed back as a new one; but only with the items the take took, and a stack it shrank gets only those back. A put takes only the items it added off the stacks it made or grew, as far as they are still there, and gives a grown stack its traits back (the freshness of a perishable stack) while its traits are still the ones the put left, also when some of it were used since (put 3 fresh onto 5 rotten, eat 1, undo: the 4 left are rotten again; after another join the traits stay). So a change between Execute and Undo never gives items back twice: when a take of 3 from a stack of 10 is undone after the player moved the 7 left into a chest (while an async step of the exchange waited, or in a listener of the change), the stack comes back with 3, not 10. What no longer fits onto its stack (the stack now holds other traits, the place is taken, a later undo failed) goes back where it fits, still with its traits; items a put added that were moved or used since are taken from other stacks of the item that are not lent, and what is not there any more is logged.ItemIdtakes from one stack only,InstanceTraitsgives the put items their traits,bOnlyLeavabletakes only stacks that may leave for good andbOnlyMovableonly stacks that may change their holder (not bound, not lent). Pulse::Inventory::MakeMoveExchange(Source, Target, Item, Count)builds the exchange ofMoveItemsTowithout changing anything and without a world: party 0 is the source (its owner as player), party 1 the target. It picks the movable stacks when it is built and adds one take and one put per stack, the put with the stack’s traits; run it right away (a stack that changed in between fails the exchange).MakeExchangeParty(Inventory)gives the party of an inventory,GetExchangeResult(Exchange, Result)theEPulseInventoryResultof a run.- The reward Give Items asks for room when it does not drop (
bDropWhenFulloff): an exchange with it gives nothing when the items would not fit. Its Revoke (the undo of an exchange) takes back as many as the player has, up to Count. - The cost Items pays and refunds items as before; the exchange calls them through its Costs step.
Warning: do not run an exchange with steps that finish later (Pulse::Exchange::RunAsync) on inventories a player can change while it waits. Nothing locks the inventories between the steps: when a player moves the items a put brought into one inventory out of it before a later step fails, the undo of the put cannot take them back, while the undo of the take gives them back to the other inventory, so they are duplicated. Run such exchanges with Pulse::Exchange::Run (one call, nothing changes in between), or only on inventories players cannot reach while the exchange runs (a stash in Pulse Sim, an inventory of the server). No Pulse plugin uses RunAsync on inventories today; a lock of the touched inventories is requested from PulseFoundation.
// A trade: 10 wood from the player for 3 coins of the trader, all or nothing
FPulseExchange trade = Pulse::Inventory::MakeMoveExchange(PlayerInventory, TraderInventory, Wood, 10);
FPulseExchangeStep_InventoryItems& coins = trade.AddStep<FPulseExchangeStep_InventoryItems>(1);
coins.Inventory = TraderInventory;
coins.Item = Coin;
coins.Count = 3;
FPulseExchangeStep_InventoryItems& paid = trade.AddStep<FPulseExchangeStep_InventoryItems>(0);
paid.Inventory = PlayerInventory;
paid.Item = Coin;
paid.Count = 3;
paid.bPutIn = true;
const EPulseInventoryResult result = Pulse::Inventory::GetExchangeResult(trade, Pulse::Exchange::Run(trade));
Merchants
A Pulse Merchant component on an NPC or a shop sells and buys items for a currency item (coins). Its asset Pulse Merchant (UPulseMerchantDefinition, Create entry Merchant) holds what it trades:
| Field | Meaning |
|---|---|
| Currency | The item that pays |
| Offers | What it sells: a stable Id (stock, saves and requests name it), the Item, Count per purchase, Price (below 0: the Value trait of the item times Count), Stock (below 0 unlimited), Restock Hours after the first purchase until the stock is full again (hours of the day by default, see below), Conditions for the buyer |
| Buys Items, Sell Factor, Buys Item Tags | Whether it buys items with a Value trait (FPulseItemTrait_Value), the share of the value it pays, and which items (empty: all with a value; never the currency) |
| Price Rules | Instanced structs whose factors multiply: Factor (the same factor on every price), Conditions (factors while Pulse conditions pass for the trader, a discount for friends of a faction), Item Tags (factors for items with tags); derive FPulseMerchantPriceRule for own rules |
Prices are rounded up per purchase when buying and down per item when selling. A purchase (Buy) and a sale (Sell) are all-or-nothing exchanges of PulseFoundation (Pulse::Merchant::MakeBuyExchange, MakeSellExchange): the buyer pays the currency, the stock goes down and the buyer gets the items, or nothing happens (sold out, not enough currency, no room, conditions). The merchant has no money of its own. A sale takes the items from the very stack the player names (MakeSellStackExchange, the take step with its item id) when that stack holds the count, so a sword with rolled stats is not swapped for another one of its kind; a count above the stack takes any stacks of the item that may leave.
The component holds only the stock (FPulseMerchantStock: an entry per limited offer that was bought from, with the purchases left, the restock time on the game clock and the game seconds of its hour), replicated as one struct with the push model and saved as bytes (IPulseByteSaveable, save identity Pulse.Inventory.Save.MerchantStock). Prices and restock are worked out when they are asked for (GetBuyPrice, GetSellPrice, GetRemaining on every machine). Restock Hours count like Shelf Life Hours (Hour Unit): with Day Hour they are hours of the day of the PulseTime calendar (24 is one day; at a day rate of 60 that is 24 game minutes), without a calendar hours of the game clock. When the day rate changes, the authority stretches the restock time left of every entry (Pulse::Merchant::RescaleRestock, also after a load and before every trade), so the share of the hours already gone stays. Skipping hours of the day in PulseTime moves only the day, not the game clock, so a skip does not refill a merchant; a rest that moves the game clock does. Clients trade with Request Buy (offer id and purchases) and Request Sell (stack and count) of the Pulse Inventory Access component, or with an FPulseMerchantTradeRequest in RequestTrade (C++, with a callback) or the node Request Merchant Trade (On Success, On Failure). A trade is a request with an id (Pulse.Request.Inventory.Buy, .Sell); the server checks that the requester owns the inventory and that its pawn stands within Max Trade Distance (600 cm to the bounds of the merchant’s owner, plus Reach Tolerance of the request guard of PulseFoundation) and, with Trade Line Of Sight, sees it (Visibility; Pulse::Requests::CheckReach and HasLineOfSight, where the pawn’s equipment and actors attached to the merchant’s owner do not block); a requester without a pawn (an inventory on the player state or controller) is too far. Then it works out the price itself, runs the exchange and answers with the result. Trades send Pulse.Message.Inventory.Bought and .Sold (FPulseMerchantMessage) and the events OnTrade / OnTradeNative. Refusals have reasons of their own with texts (Pulse.Result.Failure.Inventory.SoldOut, .NotWanted, .TooFar, .NotYours, .CannotSell, .Worn, .TooMany; replace the texts in the Result Texts of the Pulse Foundation settings). A buy asks for at most Max Purchases Per Trade purchases (999 by default, Settings); prices and counts are worked out in 64 bits (Pulse::Merchant::CheckPurchases), and a buy whose price or item count does not fit a 32-bit number is refused with .TooMany instead of wrapping into a few items for a negative price. GetBuyPrice and GetSellPrice stop at MAX_int32. Only stacks that may leave the inventory for good are sold or paid (Pulse::Inventory::CanLeaveInventory in Items/PulseItemRules.h: not lent, not bound by a Bound trait without Can Transfer, and not worn below their maximum durability unless Allow Worn Items To Leave is on, see Settings): a sale of a lent or bound stack is refused with .CannotSell, one of a worn stack with .Worn (“repair it first”), and the currency of a purchase comes only from leavable stacks. The rules are plain functions (Merchant/PulseMerchantTypes.h: GetBuyPrice, GetSellPrice, GetRemaining, Restock, TakeStock, ReturnStock). Specs: PulseInventory.Merchant.
Tuning: the tuning knobs Pulse.Tuning.Inventory.BuyPrice and Pulse.Tuning.Inventory.SellPrice of PulseFoundation multiply the prices after the price rules (rounded the same way: up for buying, down for selling). The trader is the player of the context, the item type the source and its tags the tags.
Merchant Price adjustment: a tuning source (a difficulty level, a zone, an event) changes prices by item tag with the adjustment Merchant Price (FPulseAdjustment_MerchantPrice): Merchant (empty: every merchant), Item Tag (child tags count; empty: every item), Buy Factor (what the trader pays) and Sell Factor (what the trader gets). Its factors multiply with the knobs and the price rules. The Item Modifiers adjustment of the trait modifiers changes the Value of items for everyone who trades with them; Merchant Price changes only what merchants ask and pay, per merchant and per direction, also for offers with an own price. Prices by the time of day need nothing new: a Conditions price rule with a time condition.
Assortment per level: a Swap Asset adjustment from the merchant to a variant (other offers; the same ids where it is the same offer). The component resolves its definition at BeginPlay and on every tuning change, on every machine (GetDefinition returns the variant); stock of offers the variant does not have leaves at the next restock. The save data stays the same.
The prices with an explicit tuning are pure: Pulse::Merchant::GetBuyPrice and GetSellPrice with an FPulseTuningData (the versions without call them with the tuning of the world), and Pulse::Merchant::GetTuningFactor(Data, Merchant, Item, bBuying, Context) (knob times adjustments).
In the editor: merchants open in the config workshop of the Pulse Editor Kit with the preview Prices:
- Assortment: a row per offer (id, item, count, stock and restock, base price) with a price column per difficulty level of Pulse Difficulty; changed prices are colored, “—” where the variant of a level does not sell the offer. A click on a row selects the offer in the graph, an offer selected in the graph is marked.
- Buys: every item of the project with a Value trait the merchant buys, with its value and what the merchant pays per level.
- Rules: Sell Factor and every price rule in one line (rules with conditions count as passed in the tables), then the Merchant Price adjustments of each level that hit the merchant, with their before and after (one merchant) or the merchants they hit (a rule).
- A line per level that swaps the merchant: “Level Hard uses DA_Smith_Hard”.
Offers are titled “Bread: Bread x2” in the graph, Price of an offer and Sell Factor are registered as tuned properties, a Merchant Price rule lists the merchants that sell items with its tag under Effect, and an item lists the merchants that sell it or pay with it under Where used. The pure rules: Pulse::Gameplay::Editor::Merchant::MakeOfferRows, MakeSellRows; specs PulseInventory.Merchant (Tuning) and PulseGameplay.Editor.MerchantWorkshop.
Stashes in Pulse Sim
A chest in a chunk that unloads, or a stash a crafting station takes from, can keep its contents in a Pulse Sim record of Pulse Foundation. The record lives on while the actor is gone, is saved with the world, and other systems change it whether the chest is loaded or not.
- Turn on Keep In Pulse Sim on the inventory component (category Sim). Sim Record Id names the record; without one the save key of the component is used (set an id for spawned actors, their names change). Not for player inventories.
- On the server the component adds the record in BeginPlay (kind
FPulseSimState_Inventory, relevancy None: the component replicates itself while it is loaded), or takes the contents of an existing record. Every change of the component is written into the record. A change of the record made by others (an exchange while unloaded, a crafting station, a load of Pulse Sim that replaces the record) replaces the contents of the component as one import, with the usual events. Pulse::Inventory::Sim::EditInventory(Sim, Id, Planner)changes a stash by its id: through the component while it is loaded (events, replication), else on the state of the record. The planner gets the matching view, so the plan applies to the right revision.PlanTakeItemsandPlanPutItemsplan the common changes;FindInventoryreads the contents andFindBoundInventorythe component.- The exchange step Stash Items (Pulse Sim) (
FPulseExchangeStep_SimInventoryItems) takes items from a stash record or puts them in, all or nothing with the other steps of an exchange. - A record keeps the id of every stack.
Pulse::Inventory::ResolveDefinitions(Context, State)fills the items of a state from the ids (the component andEditInventorycall it), so a record loaded from a region save finds items made at runtime by their id.
// Put 5 wood into the stash "Camp.North", loaded or not
Pulse::Inventory::Sim::EditInventory(*UPulseSimSubsystem::Get(this), TEXT("Camp.North"),
[Wood](const FPulseInventoryView& InView, FPulseInventoryPlan& OutPlan)
{
return Pulse::Inventory::Sim::PlanPutItems(InView, Wood, 5, OutPlan);
});
ViewModels
UMVVMPulseInventory exposes an inventory to UI. Call SetInventory with a component. The ViewModel listens to the events, so it works the same on the server and on clients.
Fields (FieldNotify): Inventory, GridSize, CellSize, GridMode, Items, TotalWeight, MaxWeight (from the weight limit trait, 0 if there is none) and UsedCells.
Functions: FindItemModel, CanMoveItemTo (drag and drop feedback: a result with the text why not), RequestMoveItem, RequestRemoveItem, RequestUseItem, RequestDropItem and Refresh.
Items holds one UMVVMPulseInventoryItem per item stack. The item ViewModels are kept for as long as the item exists and updated in place, so widgets stay bound while items change. Fields: ItemId, Definition, DisplayName, Icon, StackCount, Position, Size (with the current rotation), bRotated and TotalWeight.
There are no widgets in this module. Position and size are in cells, multiply them with CellSize to place a widget.
Saving and loading
Saving and loading run on the authority only. The functions return false on clients.
ExportSaveData(OutData)collects the layout, the persisted traits and all items into anFPulseInventorySaveData(a plain struct).ImportSaveData(Data, OutReport)replaces the state of the inventory. Items whose definition cannot be loaded, or that do not fit, are skipped and listed in theFPulseInventoryImportReport. An item that no longer fits at its saved place is moved to the first free place. Traits are not checked while importing, the saved state is trusted. Item ids are kept; a save with the same id twice gives the second item a new id and a message. The import is one step (Pulse::Inventory::PlanImport, planned against the saved layout only, so a save fits even when the current inventory is full) and fires its events afterwards: removed stacks, new stacks, layout, traits, oneOnInventoryChanged.SaveToBytes/LoadFromByteswrite and read the data as bytes (Pulse::Inventory::SaveDataToBytes/LoadDataFromBytes). Use them to embed the data in any save system. All non-transient properties are written, including trait properties.SaveToSlot/LoadFromSlotuse an engine save slot withUPulseInventorySaveGame.
The data has a Version (now 2). Data written by a newer version is refused; version 1 data still loads.
Items are saved by their id. Item definitions have the primary asset type PulseItem (every item class, Blueprint item classes included), so their id is PulseItem:<asset name>. A saved stack stores the id next to the path. Loading uses the id first, through the item catalog: an item registered at runtime, else the catalog of the kind (by default the asset manager, where a Primary Asset Id Redirect always wins), so a moved item loads also in a packaged build and an item made at runtime loads when the game registered it again before the load. A load needs the definition at once: a catalog used for saves must answer Load Definition Synchronous (the default catalog does). An id that does not load at once and whose path names nothing is left out of the loaded data (the next save no longer has it), with a warning that names the catalog of its kind; this holds for inventories, equipment, the crafting queue and unlocked recipes, and pickup records. The path is the fallback, for version 1 data (no id) and for an id nobody knows (an item outside the scanned content, or one whose asset registry data is older than the plugin). The plugin registers the type in code for /Game and the content of every plugin; nothing has to be set up. Two rules follow:
- Item asset names must be unique. Two items with the same asset name share one id: the editor shows a “Duplicate Asset ID” warning, packaged non-shipping builds report an ensure, and a save may load the other item. A copy of a plugin item under
/Game(Add Starter Content copies the examples to/Game/Pulse/PulseGameplay) may keep its name: the item catalog takes the project asset (two assets with one id), and only two items under/Gameor two items of plugins with one name are an error. The setup step “Give every item, recipe and recipe book its own asset name” and the data validation of items, recipes and recipe books list duplicates (the same rule holds for recipes and recipe books within their type). - Renaming an item changes its id. For items that are already in saves, add a redirect in Project Settings > Asset Manager > Primary Asset Id Redirects, for example
PulseItem:SwordtoPulseItem:IronSword.
Pulse::Inventory::ResolveSavedItem(Context, Id, Path) / ResolveSavedAsset(Context, Id, Path, Class) (Save/PulseInventorySave.h) do this lookup for your own save data; the world context names the game instance whose definitions are asked (without one: the asset manager). Specs that need other answers give the kind a catalog of their own (UPulseDefinitionSubsystem::SetCatalogClass).
The inventory saves itself as bytes (IPulseByteSaveable of PulseFoundation): PulseSave keeps every inventory in its general model without a save bridge (Collector Classes of the save settings with the byte collector, the default), and a respawn keeps or resets it by its tag (Carry Rules of the respawn settings). The save identity is Pulse.Inventory.Save.Inventory (Save Identity of the component): an actor with a second inventory gives it its own Key, otherwise both would save into one record (a warning on BeginPlay). An inventory with Keep In Pulse Sim is saved with its record and leaves the bytes out. Reset (ResetToDefaults) removes every stack and puts back the layout and traits of the setup. PulseInventory does not depend on a save plugin.
Items in the editor
Item definitions (and their subclasses) open in the config workshop of the Pulse Editor Kit: the traits as cards in the graph, details, validation and notes, and a preview of PulseGameplay on the right. The preview has a button per difficulty level of Pulse Difficulty (Base is the asset as it is); a level applies its Item Modifiers adjustments (the trait modifiers of the tuning) without a world, with an empty owner: adjustments that need the tags of a player do not count, and the Item Modifiers trait of an inventory and the Wearer Modifiers of equipment are not part of it.
Item (tab of an item):
- Header: the icon, the name, the grid size with the cells it covers drawn as squares, whether it can be turned, the stack size on the level (in the warning color when the level changes it) and the tags.
- Traits: one chip per trait of the item.
- Value per level: one row per number of the item (weight, stack size, value, durability, spoil rate, and the numbers of own traits a modifier of a level names), a column for Base and one per level. A number a level changes is in the warning color; its tooltip shows the change and the level (“1.5 -> 3 (Hard)”).
- Tooltip: the tooltip widget of the game (Item Tooltip Class and Tooltip Sections of the Inventory UI settings) filled by Make Item Tooltip Request. The widget lives in a transient widget tree, not in a world. The numbers of the level are given to it as the traits of the stack, so its rows show the values of the level. The exception is the stack size: it is a property of the definition, not a trait, so the tooltip keeps the base value (the header shows the stack size of the level). The “a -> b (level)” rows of the Trait Modifiers section need an inventory and do not show here. The widget has no player, world or game clock in the editor: Construct logic of the tooltip Blueprint that needs them does not run in the preview, so keep such logic player-free. The widget is made again after a compile of the tooltip Blueprint or a replaced class. Without a tooltip class the rows of the sections are shown as text, with a hint that says whether no Item Tooltip Class is set or the class could not be created (abstract, not a Pulse item tooltip, or not loadable).
- Where used: the assets that name the item (as the plugins find them: recipes, presets and others), with a button that opens them.
- Open in Pulse Tables lists every item definition of the project in Pulse Tables.
Demo Inventory (the live test tab next to the details): an empty grid inventory (6 x 4 cells to start, columns and rows can be changed) filled with the item by the rules of the game (PlanAdd, as TryAddItem: stacks on the first free places, turned if that helps), with the trait modifiers and the carry weight knob (Pulse.Tuning.Inventory.CarryWeight) of the level. Pick the count (two stacks to start) and an optional weight limit (a Weight Limit trait on the demo inventory, scaled by the carry weight of the level); the result names the stack size, the stacks needed, the stacks and cells placed, the items that did not fit and why, and the weight against the limit. The grid is drawn by the editor: PulseGameplay has no inventory grid widget. Instance traits, item filters and the hooks of item classes are not part of the demo.
The rules behind the preview are pure functions of the editor module (Pulse::Inventory::Editor: CollectLevelModifiers, GetItemFields, GetLevelValue, MakeLevelNumbers, MakeLevelTraits, GetCarryWeightFactor, GetStacksNeeded, MakeDemoInventory). Spec: PulseGameplay.Editor.ItemWorkshop.
Tests
The module has Automation specs in Source/PulseInventory/Private/Tests:
PulseInventory.Grid: the occupancy grid.PulseInventory.View: the view rules and traits read, acceptance with hooks, the grid with pending removals.PulseInventory.State: plans (add, remove, move, transfer, layout, import),ValidatePlan/ApplyPlan, events after the whole operation.PulseInventory.Pickups: the merge plan of drops, the drop budget and its key.PulseInventory.ItemRules: in use, stats of equipped items, wear and repair data.PulseInventory.Ids: primary asset ids of items and the resolver of saved assets (id through the catalog, path as fallback).PulseInventory.Catalog: item ids, registration rules andParseItemId; replicated stacks by id with a registered item and with a catalog that loads asynchronously (hidden, then announced); equipped items and pickups by id (at once, asynchronously, a new id that loads, a pickup that asks again after a registration);ResolveDefinitions; inventory bytes and a pickup record of an item made at runtime loaded by its id.PulseInventory.Equipment,PulseInventory.Conditions,PulseInventory.Loot: equipment plans, item costs as one take, loot.PulseInventory.Traits: the trait container and item weights.PulseInventory.TraitModifiers: trait modifiers in order and their filter, views with the Item Modifiers trait (weight, stack size, the spoil rate of a stack that enters and leaves a cooler by a transfer or an add, without drift), loads that keep stacks above a lowered size, merchant values without the inventory’s own trait, adjustments that refuse conditions, the comparison of collected sources and a component whose weight limit takes more of a lighter item.PulseInventory.Drop: dropping, rate limit, merging, limit of pickups, dormancy and physics settling, picking up, pickup ViewModel.PulseInventoryInteract.Pickup: finding the inventory of an interactor and picking up through the interaction.PulseInventory.Component: placement, stacking, weight limit, moving, swapping, transfers, layout changes, events, replication mode (constructor rules), save and load.PulseInventory.Messages: the item messages on the message bus.PulseInventory.ViewModels: the item view models take the class of the settings, the base class when it is empty.PulseInventory.Exchange:MoveItemsToand the move exchange all or nothing, a stale exchange that runs only while the items last, the undo when a later step fails (the very stacks a take of an item took come back with their id, place and wear; puts take back exactly what they added), bound and lent stacks that stay, traits that move with their stack, the room check of Give Items (no world).
Run them with the Automation RunTests PulseInventory command.
Debugging
Every inventory component is a snapshot provider of PulseFoundation (category Inventory): Tools > Debug > Pulse Debugger > Live (pick the server or a client to compare) and the gameplay debugger category Pulse for the selected actor show authority, replication mode, grid, used cells, total weight, inventory traits, the sources of trait modifiers from outside the traits and every item with id, definition, stack count, position and rotation. The save bytes are written with Pulse::Serialization.
Cheats (console, development builds; on a client they run on the server):
| Cheat | Does |
|---|---|
PulseInventoryGive <item> [count] | Adds items to the player’s inventory (found on controller, player state or pawn). <item> is the asset name (DA_Stone) or path of a UPulseItemDefinition. |
PulseInventoryClear | Removes all items from the player’s inventory. |
Known limitations
- Only rectangular items are supported.
- Changing inventories that the player does not own needs a
UPulseInventoryAccessComponenton the local player controller, and aCanRequesterModifyoverride on the inventory. - Pickups are one replicated actor per stack. That is meant for some hundreds of pickups. Thousands would need an aggregated replication actor.
- Pickups are not saved with the inventory. Saving dropped items in the world needs its own solution.
- The replication mode is fixed at construction. There is no per-connection filter: contents go to everyone in range or only to the owner.
- Swapping has no partial mode: it needs the whole stack.
- Traits defined in Blueprint structs are not possible, custom traits are C++ structs.